From a40ee7424f59aafd3f9e187a95bbb5cb91ec5697 Mon Sep 17 00:00:00 2001 From: Raven Szewczyk Date: Thu, 1 Sep 2022 12:27:40 +0100 Subject: [PATCH] Update buildscript, apply spotless (#175) --- .gitattributes | 41 + build.gradle | 435 +- dependencies.gradle | 20 +- settings.gradle | 10 + src/main/java/appeng/api/AEApi.java | 69 +- src/main/java/appeng/api/IAppEngApi.java | 117 +- .../appeng/api/config/AccessRestriction.java | 76 +- .../java/appeng/api/config/ActionItems.java | 30 +- .../java/appeng/api/config/Actionable.java | 20 +- .../appeng/api/config/CondenserOutput.java | 16 +- src/main/java/appeng/api/config/CopyMode.java | 7 +- .../java/appeng/api/config/FullnessMode.java | 10 +- .../java/appeng/api/config/FuzzyMode.java | 35 +- .../appeng/api/config/IncludeExclude.java | 9 +- .../java/appeng/api/config/InsertionMode.java | 7 +- .../appeng/api/config/ItemSubstitution.java | 7 +- .../appeng/api/config/LevelEmitterMode.java | 12 +- .../java/appeng/api/config/LevelType.java | 12 +- .../java/appeng/api/config/ModSettings.java | 6 +- .../appeng/api/config/NetworkEmitterMode.java | 14 +- .../java/appeng/api/config/OperationMode.java | 9 +- .../java/appeng/api/config/OutputMode.java | 8 +- .../appeng/api/config/PatternSlotConfig.java | 3 +- .../appeng/api/config/PowerMultiplier.java | 29 +- .../java/appeng/api/config/PowerUnits.java | 69 +- .../java/appeng/api/config/RedstoneMode.java | 11 +- .../appeng/api/config/RelativeDirection.java | 11 +- .../appeng/api/config/SchedulingMode.java | 8 +- .../java/appeng/api/config/SearchBoxMode.java | 14 +- .../api/config/SecurityPermissions.java | 65 +- src/main/java/appeng/api/config/Settings.java | 75 +- src/main/java/appeng/api/config/SortDir.java | 9 +- .../java/appeng/api/config/SortOrder.java | 11 +- .../java/appeng/api/config/StorageFilter.java | 10 +- .../java/appeng/api/config/TerminalStyle.java | 14 +- .../java/appeng/api/config/TunnelType.java | 26 +- src/main/java/appeng/api/config/Upgrades.java | 182 +- .../java/appeng/api/config/ViewItems.java | 10 +- src/main/java/appeng/api/config/YesNo.java | 8 +- .../java/appeng/api/definitions/Blocks.java | 101 +- .../api/definitions/IBlockDefinition.java | 41 +- .../java/appeng/api/definitions/IBlocks.java | 176 +- .../definitions/IComparableDefinition.java | 43 +- .../appeng/api/definitions/IDefinitions.java | 36 +- .../api/definitions/IItemDefinition.java | 29 +- .../java/appeng/api/definitions/IItems.java | 81 +- .../appeng/api/definitions/IMaterials.java | 116 +- .../java/appeng/api/definitions/IParts.java | 91 +- .../api/definitions/ITileDefinition.java | 13 +- .../java/appeng/api/definitions/Items.java | 79 +- .../appeng/api/definitions/Materials.java | 113 +- .../java/appeng/api/definitions/Parts.java | 81 +- .../api/events/LocatableEventAnnounce.java | 27 +- .../api/exceptions/AppEngException.java | 13 +- .../exceptions/CoreInaccessibleException.java | 11 +- .../ExistingConnectionException.java | 24 +- .../api/exceptions/FailedConnection.java | 18 +- .../api/exceptions/MissingDefinition.java | 11 +- .../exceptions/MissingIngredientError.java | 13 +- .../api/exceptions/ModNotInstalled.java | 13 +- .../NullNodeConnectionException.java | 23 +- .../appeng/api/exceptions/RecipeError.java | 13 +- .../api/exceptions/RegistrationError.java | 13 +- .../SecurityConnectionException.java | 23 +- .../appeng/api/features/IGrinderEntry.java | 177 +- .../appeng/api/features/IGrinderRegistry.java | 101 +- .../appeng/api/features/IInscriberRecipe.java | 88 +- .../api/features/IInscriberRecipeBuilder.java | 126 +- .../api/features/IInscriberRegistry.java | 103 +- .../appeng/api/features/IItemComparison.java | 8 +- .../api/features/IItemComparisonProvider.java | 37 +- .../java/appeng/api/features/ILocatable.java | 15 +- .../api/features/ILocatableRegistry.java | 40 +- .../features/IMatterCannonAmmoRegistry.java | 33 +- .../api/features/INetworkEncodable.java | 35 +- .../api/features/IP2PTunnelRegistry.java | 46 +- .../appeng/api/features/IPlayerRegistry.java | 46 +- .../api/features/IRecipeHandlerRegistry.java | 78 +- .../api/features/IRegistryContainer.java | 147 +- .../features/ISpecialComparisonRegistry.java | 33 +- .../api/features/IWirelessTermHandler.java | 63 +- .../api/features/IWirelessTermRegistry.java | 57 +- .../java/appeng/api/features/IWorldGen.java | 22 +- .../api/features/InscriberProcessType.java | 20 +- .../implementations/ICraftingPatternItem.java | 21 +- .../implementations/IPowerChannelState.java | 24 +- .../api/implementations/IUpgradeableHost.java | 25 +- .../api/implementations/TransitionResult.java | 17 +- .../implementations/guiobjects/IGuiItem.java | 7 +- .../guiobjects/IGuiItemObject.java | 7 +- .../guiobjects/INetworkTool.java | 7 +- .../guiobjects/IPortableCell.java | 7 +- .../items/IAEItemPowerStorage.java | 67 +- .../api/implementations/items/IAEWrench.java | 25 +- .../implementations/items/IBiometricCard.java | 92 +- .../items/IGrowableCrystal.java | 9 +- .../api/implementations/items/IItemGroup.java | 22 +- .../implementations/items/IMemoryCard.java | 71 +- .../items/ISpatialStorageCell.java | 101 +- .../implementations/items/IStorageCell.java | 136 +- .../items/IStorageComponent.java | 37 +- .../implementations/items/IUpgradeModule.java | 15 +- .../items/MemoryCardMessages.java | 9 +- .../api/implementations/parts/IPartCable.java | 76 +- .../implementations/parts/IPartMonitor.java | 15 +- .../parts/IPartStorageMonitor.java | 27 +- .../implementations/tiles/IChestOrDrive.java | 65 +- .../implementations/tiles/IColorableTile.java | 9 +- .../tiles/ICraftingMachine.java | 38 +- .../api/implementations/tiles/ICrankable.java | 39 +- .../tiles/ICrystalGrowthAccelerator.java | 6 +- .../api/implementations/tiles/IMEChest.java | 7 +- .../tiles/ISegmentedInventory.java | 21 +- .../tiles/ITileStorageMonitorable.java | 7 +- .../tiles/IViewCellStorage.java | 17 +- .../tiles/IWirelessAccessPoint.java | 37 +- .../api/integration/IBeeComparison.java | 14 +- .../appeng/api/movable/IMovableHandler.java | 73 +- .../appeng/api/movable/IMovableRegistry.java | 113 +- .../java/appeng/api/movable/IMovableTile.java | 26 +- .../java/appeng/api/networking/GridFlags.java | 74 +- .../api/networking/GridNotification.java | 12 +- .../java/appeng/api/networking/IGrid.java | 101 +- .../appeng/api/networking/IGridBlock.java | 150 +- .../appeng/api/networking/IGridCache.java | 102 +- .../api/networking/IGridCacheRegistry.java | 31 +- .../api/networking/IGridConnection.java | 77 +- .../networking/IGridConnectionVisitor.java | 16 +- .../java/appeng/api/networking/IGridHost.java | 55 +- .../api/networking/IGridMultiblock.java | 17 +- .../java/appeng/api/networking/IGridNode.java | 242 +- .../appeng/api/networking/IGridStorage.java | 21 +- .../appeng/api/networking/IGridVisitor.java | 22 +- .../appeng/api/networking/IMachineSet.java | 13 +- .../networking/crafting/CraftingItemList.java | 9 +- .../api/networking/crafting/ICraftingCPU.java | 54 +- .../crafting/ICraftingCallback.java | 16 +- .../networking/crafting/ICraftingGrid.java | 121 +- .../api/networking/crafting/ICraftingJob.java | 53 +- .../networking/crafting/ICraftingLink.java | 69 +- .../networking/crafting/ICraftingMedium.java | 31 +- .../crafting/ICraftingPatternDetails.java | 137 +- .../crafting/ICraftingProvider.java | 17 +- .../crafting/ICraftingProviderHelper.java | 21 +- .../crafting/ICraftingRequester.java | 55 +- .../networking/crafting/ICraftingWatcher.java | 8 +- .../crafting/ICraftingWatcherHost.java | 33 +- .../networking/energy/IAEPowerStorage.java | 65 +- .../api/networking/energy/IEnergyGrid.java | 123 +- .../energy/IEnergyGridProvider.java | 34 +- .../api/networking/energy/IEnergySource.java | 21 +- .../api/networking/energy/IEnergyWatcher.java | 7 +- .../networking/energy/IEnergyWatcherHost.java | 30 +- .../events/MENetworkBootingStatusChange.java | 7 +- .../events/MENetworkCellArrayUpdate.java | 6 +- .../events/MENetworkChannelChanged.java | 14 +- .../events/MENetworkChannelsChanged.java | 7 +- .../events/MENetworkControllerChange.java | 6 +- .../events/MENetworkCraftingCpuChange.java | 14 +- .../MENetworkCraftingPatternChange.java | 18 +- .../api/networking/events/MENetworkEvent.java | 73 +- .../events/MENetworkEventSubscribe.java | 10 +- .../MENetworkPostCacheConstruction.java | 6 +- .../events/MENetworkPowerIdleChange.java | 14 +- .../events/MENetworkPowerStatusChange.java | 7 +- .../events/MENetworkPowerStorage.java | 47 +- .../events/MENetworkSecurityChange.java | 6 +- .../events/MENetworkSpatialEvent.java | 26 +- .../events/MENetworkStorageEvent.java | 18 +- .../networking/pathing/ControllerState.java | 28 +- .../api/networking/pathing/IPathingGrid.java | 33 +- .../networking/security/BaseActionSource.java | 18 +- .../api/networking/security/IActionHost.java | 23 +- .../networking/security/ISecurityGrid.java | 61 +- .../security/ISecurityProvider.java | 54 +- .../security/ISecurityRegistry.java | 20 +- .../networking/security/MachineSource.java | 22 +- .../api/networking/security/PlayerSource.java | 27 +- .../api/networking/spatial/ISpatialCache.java | 65 +- .../api/networking/storage/IBaseMonitor.java | 21 +- .../api/networking/storage/IStackWatcher.java | 8 +- .../networking/storage/IStackWatcherHost.java | 39 +- .../api/networking/storage/IStorageGrid.java | 53 +- .../api/networking/ticking/IGridTickable.java | 81 +- .../api/networking/ticking/ITickManager.java | 57 +- .../ticking/TickRateModulation.java | 62 +- .../networking/ticking/TickingRequest.java | 69 +- src/main/java/appeng/api/package-info.java | 4 +- .../java/appeng/api/parts/BusSupport.java | 10 +- .../appeng/api/parts/CableRenderMode.java | 21 +- .../java/appeng/api/parts/IAlphaPassItem.java | 19 +- .../java/appeng/api/parts/IBoxProvider.java | 16 +- .../appeng/api/parts/IFacadeContainer.java | 106 +- .../java/appeng/api/parts/IFacadePart.java | 129 +- src/main/java/appeng/api/parts/IPart.java | 492 ++- .../api/parts/IPartCollisionHelper.java | 73 +- .../java/appeng/api/parts/IPartHelper.java | 101 +- src/main/java/appeng/api/parts/IPartHost.java | 272 +- src/main/java/appeng/api/parts/IPartItem.java | 26 +- .../appeng/api/parts/IPartRenderHelper.java | 339 +- .../appeng/api/parts/ISimplifiedBundle.java | 6 +- src/main/java/appeng/api/parts/LayerBase.java | 68 +- .../java/appeng/api/parts/LayerFlags.java | 8 +- .../java/appeng/api/parts/PartItemStack.java | 14 +- .../java/appeng/api/parts/SelectedPart.java | 62 +- .../appeng/api/recipes/ICraftHandler.java | 40 +- .../java/appeng/api/recipes/IIngredient.java | 99 +- .../appeng/api/recipes/IRecipeHandler.java | 26 +- .../appeng/api/recipes/IRecipeLoader.java | 19 +- .../appeng/api/recipes/ISubItemResolver.java | 16 +- .../appeng/api/recipes/ResolverResult.java | 33 +- .../appeng/api/recipes/ResolverResultSet.java | 21 +- .../appeng/api/storage/ICellContainer.java | 17 +- .../java/appeng/api/storage/ICellHandler.java | 153 +- .../appeng/api/storage/ICellInventory.java | 179 +- .../api/storage/ICellInventoryHandler.java | 19 +- .../appeng/api/storage/ICellProvider.java | 35 +- .../appeng/api/storage/ICellRegistry.java | 67 +- .../api/storage/ICellWorkbenchItem.java | 87 +- .../api/storage/IExternalStorageHandler.java | 51 +- .../api/storage/IExternalStorageRegistry.java | 36 +- .../java/appeng/api/storage/IMEInventory.java | 61 +- .../api/storage/IMEInventoryHandler.java | 93 +- .../java/appeng/api/storage/IMEMonitor.java | 29 +- .../storage/IMEMonitorHandlerReceiver.java | 45 +- .../appeng/api/storage/ISaveProvider.java | 6 +- .../appeng/api/storage/IStorageHelper.java | 162 +- .../api/storage/IStorageMonitorable.java | 21 +- .../appeng/api/storage/ITerminalHost.java | 7 +- .../appeng/api/storage/MEMonitorHandler.java | 310 +- .../appeng/api/storage/StorageChannel.java | 56 +- .../api/storage/data/IAEFluidStack.java | 57 +- .../appeng/api/storage/data/IAEItemStack.java | 115 +- .../appeng/api/storage/data/IAEStack.java | 336 +- .../api/storage/data/IAETagCompound.java | 45 +- .../api/storage/data/IItemContainer.java | 58 +- .../appeng/api/storage/data/IItemList.java | 81 +- .../java/appeng/api/util/AECableType.java | 68 +- src/main/java/appeng/api/util/AEColor.java | 115 +- .../api/util/AEColoredItemDefinition.java | 63 +- .../appeng/api/util/AEItemDefinition.java | 106 +- .../appeng/api/util/DimensionalCoord.java | 140 +- .../java/appeng/api/util/ICommonTile.java | 32 +- .../java/appeng/api/util/IConfigManager.java | 88 +- .../appeng/api/util/IConfigurableObject.java | 12 +- .../appeng/api/util/INetworkToolAgent.java | 7 +- .../java/appeng/api/util/IOrientable.java | 53 +- .../appeng/api/util/IOrientableBlock.java | 31 +- .../appeng/api/util/IReadOnlyCollection.java | 28 +- src/main/java/appeng/api/util/WorldCoord.java | 291 +- src/main/java/appeng/block/AEBaseBlock.java | 1057 +++-- .../java/appeng/block/AEBaseItemBlock.java | 337 +- .../block/AEBaseItemBlockChargeable.java | 211 +- .../appeng/block/AEBaseItemBlockSlab.java | 16 +- .../java/appeng/block/AEBaseSlabBlock.java | 196 +- .../java/appeng/block/AEBaseStairBlock.java | 41 +- .../java/appeng/block/AEBaseTileBlock.java | 571 ++- .../java/appeng/block/AEDecorativeBlock.java | 30 +- .../block/crafting/BlockCraftingMonitor.java | 76 +- .../block/crafting/BlockCraftingStorage.java | 117 +- .../block/crafting/BlockCraftingUnit.java | 231 +- .../crafting/BlockMolecularAssembler.java | 99 +- .../block/crafting/ItemCraftingStorage.java | 50 +- .../appeng/block/grindstone/BlockCrank.java | 234 +- .../appeng/block/grindstone/BlockGrinder.java | 56 +- .../appeng/block/misc/BlockCellWorkbench.java | 60 +- .../java/appeng/block/misc/BlockCharger.java | 289 +- .../appeng/block/misc/BlockCondenser.java | 60 +- .../appeng/block/misc/BlockInscriber.java | 75 +- .../appeng/block/misc/BlockInterface.java | 94 +- .../appeng/block/misc/BlockLightDetector.java | 260 +- .../java/appeng/block/misc/BlockPaint.java | 190 +- .../misc/BlockQuartzGrowthAccelerator.java | 215 +- .../appeng/block/misc/BlockQuartzTorch.java | 248 +- .../java/appeng/block/misc/BlockSecurity.java | 73 +- .../appeng/block/misc/BlockSkyCompass.java | 295 +- .../java/appeng/block/misc/BlockTinyTNT.java | 277 +- .../block/misc/BlockVibrationChamber.java | 186 +- .../block/networking/BlockCableBus.java | 899 ++-- .../block/networking/BlockController.java | 54 +- .../networking/BlockCreativeEnergyCell.java | 17 +- .../networking/BlockDenseEnergyCell.java | 78 +- .../block/networking/BlockEnergyAcceptor.java | 19 +- .../block/networking/BlockEnergyCell.java | 115 +- .../block/networking/BlockWireless.java | 338 +- .../appeng/block/qnb/BlockQuantumBase.java | 74 +- .../block/qnb/BlockQuantumLinkChamber.java | 120 +- .../appeng/block/qnb/BlockQuantumRing.java | 79 +- .../java/appeng/block/solids/BlockFluix.java | 17 +- .../java/appeng/block/solids/BlockQuartz.java | 17 +- .../block/solids/BlockQuartzChiseled.java | 17 +- .../appeng/block/solids/BlockQuartzGlass.java | 59 +- .../appeng/block/solids/BlockQuartzLamp.java | 52 +- .../block/solids/BlockQuartzPillar.java | 35 +- .../appeng/block/solids/BlockSkyStone.java | 317 +- .../java/appeng/block/solids/OreQuartz.java | 255 +- .../appeng/block/solids/OreQuartzCharged.java | 141 +- .../block/spatial/BlockMatrixFrame.java | 132 +- .../block/spatial/BlockSpatialIOPort.java | 76 +- .../block/spatial/BlockSpatialPylon.java | 72 +- .../block/stair/ChiseledQuartzStairBlock.java | 15 +- .../appeng/block/stair/FluixStairBlock.java | 15 +- .../block/stair/QuartzPillarStairBlock.java | 15 +- .../appeng/block/stair/QuartzStairBlock.java | 15 +- .../block/stair/SkyStoneBlockStairBlock.java | 15 +- .../block/stair/SkyStoneBrickStairBlock.java | 17 +- .../stair/SkyStoneSmallBrickStairBlock.java | 17 +- .../block/stair/SkyStoneStairBlock.java | 15 +- .../java/appeng/block/storage/BlockChest.java | 92 +- .../java/appeng/block/storage/BlockDrive.java | 71 +- .../appeng/block/storage/BlockIOPort.java | 76 +- .../appeng/block/storage/BlockSkyChest.java | 267 +- src/main/java/appeng/client/ActionKey.java | 15 +- src/main/java/appeng/client/ClientHelper.java | 750 ++-- src/main/java/appeng/client/EffectType.java | 11 +- .../java/appeng/client/gui/AEBaseGui.java | 1800 ++++---- .../java/appeng/client/gui/AEBaseMEGui.java | 208 +- src/main/java/appeng/client/gui/GuiNull.java | 25 +- .../appeng/client/gui/config/AEConfigGui.java | 64 +- .../client/gui/config/AEConfigGuiFactory.java | 42 +- .../gui/implementations/GuiCellWorkbench.java | 315 +- .../client/gui/implementations/GuiChest.java | 71 +- .../gui/implementations/GuiCondenser.java | 124 +- .../gui/implementations/GuiCraftAmount.java | 406 +- .../gui/implementations/GuiCraftConfirm.java | 971 +++-- .../gui/implementations/GuiCraftingCPU.java | 862 ++-- .../implementations/GuiCraftingStatus.java | 287 +- .../gui/implementations/GuiCraftingTerm.java | 96 +- .../client/gui/implementations/GuiDrive.java | 71 +- .../implementations/GuiFormationPlane.java | 127 +- .../gui/implementations/GuiGrinder.java | 46 +- .../client/gui/implementations/GuiIOPort.java | 173 +- .../gui/implementations/GuiInscriber.java | 117 +- .../gui/implementations/GuiInterface.java | 185 +- .../implementations/GuiInterfaceTerminal.java | 1234 +++--- .../gui/implementations/GuiLevelEmitter.java | 451 +- .../client/gui/implementations/GuiMAC.java | 87 +- .../gui/implementations/GuiMEMonitorable.java | 1124 +++-- .../implementations/GuiMEPortableCell.java | 28 +- .../gui/implementations/GuiNetworkStatus.java | 531 ++- .../gui/implementations/GuiNetworkTool.java | 118 +- .../gui/implementations/GuiOreFilter.java | 87 +- .../gui/implementations/GuiPatternTerm.java | 293 +- .../gui/implementations/GuiPatternTermEx.java | 192 +- .../GuiPatternValueAmount.java | 205 +- .../gui/implementations/GuiPriority.java | 462 +-- .../client/gui/implementations/GuiQNB.java | 49 +- .../gui/implementations/GuiQuartzKnife.java | 141 +- .../gui/implementations/GuiRenamer.java | 70 +- .../gui/implementations/GuiSecurity.java | 239 +- .../gui/implementations/GuiSkyChest.java | 57 +- .../gui/implementations/GuiSpatialIOPort.java | 106 +- .../gui/implementations/GuiStorageBus.java | 193 +- .../gui/implementations/GuiUpgradeable.java | 381 +- .../implementations/GuiVibrationChamber.java | 85 +- .../gui/implementations/GuiWireless.java | 123 +- .../gui/implementations/GuiWirelessTerm.java | 21 +- .../gui/widgets/GuiCraftingCPUTable.java | 338 +- .../client/gui/widgets/GuiImgButton.java | 1103 +++-- .../client/gui/widgets/GuiNumberBox.java | 71 +- .../client/gui/widgets/GuiProgressBar.java | 233 +- .../client/gui/widgets/GuiScrollbar.java | 269 +- .../client/gui/widgets/GuiTabButton.java | 256 +- .../client/gui/widgets/GuiToggleButton.java | 228 +- .../gui/widgets/ICraftingCPUTableHolder.java | 3 +- .../gui/widgets/IDropToFillTextField.java | 4 +- .../client/gui/widgets/IScrollSource.java | 6 +- .../client/gui/widgets/ISortSource.java | 29 +- .../appeng/client/gui/widgets/ITooltip.java | 72 +- .../client/gui/widgets/MEGuiTextField.java | 383 +- .../appeng/client/me/ClientDCInternalInv.java | 77 +- .../java/appeng/client/me/InternalSlotME.java | 61 +- src/main/java/appeng/client/me/ItemRepo.java | 479 +-- .../appeng/client/me/SlotDisconnected.java | 146 +- src/main/java/appeng/client/me/SlotME.java | 144 +- .../client/render/AppEngRenderItem.java | 250 +- .../appeng/client/render/BaseBlockRender.java | 1660 ++++---- .../client/render/BlockPosHighlighter.java | 3 +- .../appeng/client/render/BlockRenderInfo.java | 215 +- .../appeng/client/render/BusRenderHelper.java | 1157 +++--- .../appeng/client/render/BusRenderer.java | 280 +- .../client/render/CableRenderHelper.java | 462 +-- .../appeng/client/render/ItemRenderer.java | 81 +- .../client/render/RenderBlocksWorkaround.java | 1447 ++++--- .../client/render/SpatialSkyRender.java | 303 +- .../appeng/client/render/TESRWrapper.java | 79 +- .../appeng/client/render/WorldRender.java | 149 +- .../render/blocks/RenderBlockAssembler.java | 492 ++- .../render/blocks/RenderBlockCharger.java | 225 +- .../render/blocks/RenderBlockController.java | 282 +- .../render/blocks/RenderBlockCraftingCPU.java | 649 +-- .../blocks/RenderBlockCraftingCPUMonitor.java | 269 +- .../render/blocks/RenderBlockCrank.java | 164 +- .../render/blocks/RenderBlockEnergyCube.java | 75 +- .../render/blocks/RenderBlockInscriber.java | 539 +-- .../render/blocks/RenderBlockInterface.java | 45 +- .../render/blocks/RenderBlockPaint.java | 290 +- .../blocks/RenderBlockQuartzAccelerator.java | 52 +- .../render/blocks/RenderBlockSkyChest.java | 217 +- .../render/blocks/RenderBlockSkyCompass.java | 389 +- .../render/blocks/RenderBlockWireless.java | 534 +-- .../client/render/blocks/RenderDrive.java | 607 +-- .../client/render/blocks/RenderMEChest.java | 279 +- .../client/render/blocks/RenderNull.java | 45 +- .../client/render/blocks/RenderQNB.java | 435 +- .../render/blocks/RenderQuartzGlass.java | 407 +- .../client/render/blocks/RenderQuartzOre.java | 67 +- .../render/blocks/RenderQuartzTorch.java | 394 +- .../render/blocks/RenderSpatialPylon.java | 368 +- .../client/render/blocks/RenderTinyTNT.java | 57 +- .../render/blocks/RendererCableBus.java | 82 +- .../render/blocks/RendererSecurity.java | 150 +- .../client/render/effects/AssemblerFX.java | 111 +- .../client/render/effects/ChargedOreFX.java | 49 +- .../client/render/effects/CraftingFx.java | 183 +- .../client/render/effects/EnergyFx.java | 162 +- .../client/render/effects/LightningArcFX.java | 74 +- .../client/render/effects/LightningFX.java | 403 +- .../client/render/effects/MatterCannonFX.java | 113 +- .../client/render/effects/VibrantFX.java | 92 +- .../items/ItemEncodedPatternRenderer.java | 71 +- .../client/render/items/PaintBallRender.java | 197 +- .../render/items/ToolBiometricCardRender.java | 241 +- .../items/ToolColorApplicatorRender.java | 246 +- .../client/render/model/ModelCompass.java | 184 +- .../client/texture/CableBusTextures.java | 311 +- .../client/texture/ExtraBlockTextures.java | 185 +- .../client/texture/ExtraItemTextures.java | 63 +- .../appeng/client/texture/FlippableIcon.java | 257 +- .../java/appeng/client/texture/FullIcon.java | 154 +- .../appeng/client/texture/MissingIcon.java | 131 +- .../appeng/client/texture/OffsetIcon.java | 168 +- .../appeng/client/texture/TaughtIcon.java | 192 +- .../client/texture/TmpFlippableIcon.java | 59 +- .../appeng/container/AEBaseContainer.java | 2289 +++++------ .../java/appeng/container/ContainerNull.java | 14 +- .../container/ContainerOpenContext.java | 136 +- .../appeng/container/guisync/GuiSync.java | 8 +- .../appeng/container/guisync/SyncData.java | 223 +- .../implementations/ContainerCPUTable.java | 115 +- .../ContainerCellWorkbench.java | 573 ++- .../implementations/ContainerChest.java | 21 +- .../implementations/ContainerCondenser.java | 125 +- .../implementations/ContainerCraftAmount.java | 83 +- .../ContainerCraftConfirm.java | 609 ++- .../implementations/ContainerCraftingCPU.java | 458 +-- .../ContainerCraftingStatus.java | 49 +- .../ContainerCraftingTerm.java | 155 +- .../implementations/ContainerDrive.java | 38 +- .../ContainerFormationPlane.java | 197 +- .../implementations/ContainerGrinder.java | 31 +- .../implementations/ContainerIOPort.java | 211 +- .../implementations/ContainerInscriber.java | 348 +- .../implementations/ContainerInterface.java | 294 +- .../ContainerInterfaceTerminal.java | 187 +- .../ContainerLevelEmitter.java | 265 +- .../implementations/ContainerMAC.java | 256 +- .../ContainerMEMonitorable.java | 691 ++-- .../ContainerMEPortableCell.java | 125 +- .../ContainerNetworkStatus.java | 271 +- .../implementations/ContainerNetworkTool.java | 143 +- .../implementations/ContainerOreFilter.java | 37 +- .../implementations/ContainerPatternTerm.java | 1116 +++-- .../ContainerPatternTermEx.java | 303 +- .../ContainerPatternValueAmount.java | 40 +- .../implementations/ContainerPriority.java | 82 +- .../implementations/ContainerQNB.java | 23 +- .../implementations/ContainerQuartzKnife.java | 376 +- .../implementations/ContainerRenamer.java | 37 +- .../implementations/ContainerSecurity.java | 288 +- .../implementations/ContainerSkyChest.java | 55 +- .../ContainerSpatialIOPort.java | 188 +- .../implementations/ContainerStorageBus.java | 302 +- .../implementations/ContainerUpgradeable.java | 530 ++- .../ContainerVibrationChamber.java | 79 +- .../implementations/ContainerWireless.java | 80 +- .../ContainerWirelessTerm.java | 53 +- .../implementations/CraftingCPURecord.java | 89 +- .../implementations/CraftingCPUStatus.java | 146 +- .../ICraftingCPUSelectorContainer.java | 3 +- .../interfaces/IInventorySlotAware.java | 70 +- .../interfaces/IProgressProvider.java | 97 +- .../container/slot/AppEngCraftingSlot.java | 304 +- .../appeng/container/slot/AppEngSlot.java | 405 +- .../container/slot/IOptionalSlotHost.java | 6 +- .../java/appeng/container/slot/NullSlot.java | 103 +- .../container/slot/OptionalSlotFake.java | 132 +- .../slot/OptionalSlotFakeTypeOnly.java | 55 +- .../container/slot/OptionalSlotNormal.java | 50 +- .../slot/OptionalSlotRestrictedInput.java | 52 +- .../container/slot/QuartzKnifeOutput.java | 12 +- .../container/slot/SlotCraftingMatrix.java | 73 +- .../container/slot/SlotCraftingTerm.java | 575 ++- .../appeng/container/slot/SlotDisabled.java | 30 +- .../java/appeng/container/slot/SlotFake.java | 67 +- .../container/slot/SlotFakeBlacklist.java | 54 +- .../slot/SlotFakeCraftingMatrix.java | 12 +- .../container/slot/SlotFakeTypeOnly.java | 47 +- .../container/slot/SlotInaccessible.java | 78 +- .../container/slot/SlotInaccessibleHD.java | 12 +- .../appeng/container/slot/SlotMACPattern.java | 25 +- .../appeng/container/slot/SlotNormal.java | 12 +- .../appeng/container/slot/SlotOutput.java | 23 +- .../container/slot/SlotPatternOutputs.java | 44 +- .../container/slot/SlotPatternTerm.java | 80 +- .../container/slot/SlotPlayerHotBar.java | 14 +- .../appeng/container/slot/SlotPlayerInv.java | 14 +- .../container/slot/SlotRestrictedInput.java | 511 ++- src/main/java/appeng/core/AEConfig.java | 987 ++--- src/main/java/appeng/core/AELog.java | 669 ++- src/main/java/appeng/core/Api.java | 171 +- src/main/java/appeng/core/ApiDefinitions.java | 86 +- src/main/java/appeng/core/AppEng.java | 368 +- src/main/java/appeng/core/CommonHelper.java | 59 +- src/main/java/appeng/core/CreativeTab.java | 76 +- .../java/appeng/core/CreativeTabFacade.java | 51 +- src/main/java/appeng/core/FacadeConfig.java | 79 +- .../appeng/core/FeatureHandlerRegistry.java | 22 +- .../java/appeng/core/FeatureRegistry.java | 22 +- src/main/java/appeng/core/IMCHandler.java | 100 +- src/main/java/appeng/core/RecipeLoader.java | 130 +- src/main/java/appeng/core/Registration.java | 1310 +++--- src/main/java/appeng/core/api/ApiPart.java | 563 ++- src/main/java/appeng/core/api/ApiStorage.java | 126 +- .../java/appeng/core/api/IIMCProcessor.java | 7 +- .../core/api/definitions/ApiBlocks.java | 1097 +++-- .../appeng/core/api/definitions/ApiItems.java | 676 ++- .../core/api/definitions/ApiMaterials.java | 938 ++--- .../appeng/core/api/definitions/ApiParts.java | 675 ++- .../definitions/DefinitionConstructor.java | 111 +- .../core/api/imc/IMCBlackListSpatial.java | 32 +- .../java/appeng/core/api/imc/IMCGrinder.java | 130 +- .../appeng/core/api/imc/IMCMatterCannon.java | 43 +- .../appeng/core/api/imc/IMCP2PAttunement.java | 68 +- .../java/appeng/core/api/imc/IMCSpatial.java | 31 +- .../core/crash/BaseCrashEnhancement.java | 36 +- .../java/appeng/core/crash/CrashInfo.java | 7 +- .../crash/IntegrationCrashEnhancement.java | 12 +- .../core/crash/ModCrashEnhancement.java | 23 +- .../core/features/AEBlockFeatureHandler.java | 76 +- .../features/AECableBusFeatureHandler.java | 91 +- .../java/appeng/core/features/AEFeature.java | 327 +- .../features/AETileBlockFeatureHandler.java | 89 +- .../appeng/core/features/ActivityState.java | 26 +- .../appeng/core/features/BlockDefinition.java | 256 +- .../appeng/core/features/BlockStackSrc.java | 71 +- .../core/features/ColoredItemDefinition.java | 130 +- .../core/features/DamagedItemDefinition.java | 152 +- .../core/features/DefinitionConverter.java | 266 +- .../core/features/FeatureNameExtractor.java | 93 +- .../core/features/FeaturedActiveChecker.java | 34 +- .../java/appeng/core/features/IAEFeature.java | 8 +- .../appeng/core/features/IFeatureHandler.java | 11 +- .../java/appeng/core/features/IStackSrc.java | 13 +- .../appeng/core/features/ItemDefinition.java | 122 +- .../core/features/ItemFeatureHandler.java | 99 +- .../appeng/core/features/ItemStackSrc.java | 85 +- .../core/features/MaterialStackSrc.java | 62 +- .../appeng/core/features/NameResolver.java | 75 +- .../features/SlabBlockFeatureHandler.java | 77 +- .../features/StairBlockFeatureHandler.java | 72 +- .../appeng/core/features/TileDefinition.java | 72 +- .../features/WrappedDamageItemDefinition.java | 172 +- .../features/registries/CellRegistry.java | 116 +- .../registries/ExternalStorageRegistry.java | 59 +- .../registries/GridCacheRegistry.java | 91 +- .../registries/GrinderRecipeManager.java | 490 +-- .../registries/InscriberRegistry.java | 296 +- .../registries/LocatableRegistry.java | 72 +- .../registries/MatterCannonAmmoRegistry.java | 213 +- .../registries/MovableTileRegistry.java | 250 +- .../registries/P2PTunnelRegistry.java | 272 +- .../features/registries/PlayerRegistry.java | 44 +- .../registries/RecipeHandlerRegistry.java | 135 +- .../registries/RegistryContainer.java | 185 +- .../registries/SpecialComparisonRegistry.java | 57 +- .../features/registries/WirelessRegistry.java | 138 +- .../features/registries/WorldGenRegistry.java | 160 +- .../entries/AppEngGrinderRecipe.java | 232 +- .../registries/entries/BasicCellHandler.java | 102 +- .../entries/CreativeCellHandler.java | 91 +- .../registries/entries/ExternalIInv.java | 34 +- .../entries/InscriberInscribeRecipe.java | 21 +- .../registries/entries/InscriberRecipe.java | 213 +- .../core/localization/ButtonToolTips.java | 262 +- .../appeng/core/localization/GuiColors.java | 290 +- .../appeng/core/localization/GuiText.java | 302 +- .../core/localization/PlayerMessages.java | 55 +- .../appeng/core/localization/WailaText.java | 55 +- .../java/appeng/core/settings/TickRates.java | 87 +- .../stats/AchievementCraftingHandler.java | 66 +- .../core/stats/AchievementHierarchy.java | 41 +- .../core/stats/AchievementPickupHandler.java | 55 +- .../appeng/core/stats/AchievementType.java | 11 +- .../java/appeng/core/stats/Achievements.java | 221 +- .../core/stats/PlayerDifferentiator.java | 32 +- .../core/stats/PlayerStatsRegistration.java | 135 +- src/main/java/appeng/core/stats/Stats.java | 48 +- .../java/appeng/core/sync/AppEngPacket.java | 73 +- .../core/sync/AppEngPacketHandlerBase.java | 134 +- src/main/java/appeng/core/sync/GuiBridge.java | 824 ++-- .../java/appeng/core/sync/GuiHostType.java | 22 +- .../network/AppEngClientPacketHandler.java | 60 +- .../network/AppEngServerPacketHandler.java | 56 +- .../core/sync/network/INetworkInfo.java | 6 +- .../core/sync/network/IPacketHandler.java | 7 +- .../core/sync/network/NetworkHandler.java | 195 +- .../packets/PacketAssemblerAnimation.java | 79 +- .../appeng/core/sync/packets/PacketClick.java | 133 +- .../sync/packets/PacketCompassRequest.java | 75 +- .../sync/packets/PacketCompassResponse.java | 71 +- .../sync/packets/PacketCompressedNBT.java | 137 +- .../core/sync/packets/PacketConfigButton.java | 71 +- .../core/sync/packets/PacketCraftRequest.java | 160 +- .../packets/PacketCraftingCPUsUpdate.java | 51 +- .../sync/packets/PacketInventoryAction.java | 257 +- .../core/sync/packets/PacketLightning.java | 77 +- .../sync/packets/PacketMEInventoryUpdate.java | 319 +- .../core/sync/packets/PacketMatterCannon.java | 122 +- .../sync/packets/PacketMockExplosion.java | 62 +- .../core/sync/packets/PacketMultiPart.java | 42 +- .../core/sync/packets/PacketNEIDragClick.java | 45 +- .../core/sync/packets/PacketNEIRecipe.java | 411 +- .../packets/PacketNewStorageDimension.java | 55 +- .../sync/packets/PacketPaintedEntity.java | 54 +- .../sync/packets/PacketPartPlacement.java | 81 +- .../core/sync/packets/PacketPartialItem.java | 78 +- .../core/sync/packets/PacketPatternSlot.java | 117 +- .../sync/packets/PacketPatternValueSet.java | 43 +- .../core/sync/packets/PacketProgressBar.java | 73 +- .../core/sync/packets/PacketSwapSlots.java | 51 +- .../core/sync/packets/PacketSwitchGuis.java | 76 +- .../sync/packets/PacketTransitionEffect.java | 161 +- .../core/sync/packets/PacketValueConfig.java | 453 +- .../appeng/core/worlddata/CompassData.java | 49 +- .../appeng/core/worlddata/DimensionData.java | 240 +- .../core/worlddata/IOnWorldStartable.java | 6 +- .../core/worlddata/IOnWorldStoppable.java | 6 +- .../core/worlddata/IWorldCompassData.java | 7 +- .../appeng/core/worlddata/IWorldData.java | 29 +- .../core/worlddata/IWorldDimensionData.java | 16 +- .../core/worlddata/IWorldGridStorageData.java | 20 +- .../core/worlddata/IWorldPlayerData.java | 14 +- .../core/worlddata/IWorldPlayerMapping.java | 42 +- .../core/worlddata/IWorldSpawnData.java | 16 +- .../core/worlddata/MeteorDataNameEncoder.java | 95 +- .../appeng/core/worlddata/PlayerData.java | 184 +- .../appeng/core/worlddata/PlayerMapping.java | 67 +- .../worlddata/PlayerMappingsInitializer.java | 101 +- .../java/appeng/core/worlddata/SpawnData.java | 316 +- .../appeng/core/worlddata/StorageData.java | 243 +- .../java/appeng/core/worlddata/WorldData.java | 318 +- .../appeng/crafting/CraftBranchFailure.java | 20 +- .../crafting/CraftingCalculationFailure.java | 20 +- .../java/appeng/crafting/CraftingJob.java | 657 ++- .../java/appeng/crafting/CraftingLink.java | 341 +- .../appeng/crafting/CraftingLinkNexus.java | 263 +- .../appeng/crafting/CraftingTreeNode.java | 679 ++- .../appeng/crafting/CraftingTreeProcess.java | 530 ++- .../java/appeng/crafting/CraftingWatcher.java | 308 +- .../appeng/crafting/MECraftingInventory.java | 586 ++- .../java/appeng/debug/BlockChunkloader.java | 39 +- .../java/appeng/debug/BlockCubeGenerator.java | 63 +- src/main/java/appeng/debug/BlockItemGen.java | 28 +- .../java/appeng/debug/BlockPhantomNode.java | 56 +- .../java/appeng/debug/TileChunkLoader.java | 87 +- .../java/appeng/debug/TileCubeGenerator.java | 170 +- src/main/java/appeng/debug/TileItemGen.java | 209 +- .../java/appeng/debug/TilePhantomNode.java | 67 +- src/main/java/appeng/debug/ToolDebugCard.java | 332 +- src/main/java/appeng/debug/ToolEraser.java | 156 +- .../appeng/debug/ToolMeteoritePlacer.java | 64 +- .../java/appeng/debug/ToolReplicatorCard.java | 259 +- .../java/appeng/entity/AEBaseEntityItem.java | 31 +- .../appeng/entity/EntityChargedQuartz.java | 231 +- .../appeng/entity/EntityFloatingItem.java | 82 +- .../appeng/entity/EntityGrowingCrystal.java | 294 +- src/main/java/appeng/entity/EntityIds.java | 58 +- .../java/appeng/entity/EntitySingularity.java | 210 +- .../appeng/entity/EntityTinyTNTPrimed.java | 302 +- .../appeng/entity/RenderFloatingItem.java | 63 +- .../appeng/entity/RenderTinyTNTPrimed.java | 137 +- .../java/appeng/facade/FacadeContainer.java | 375 +- src/main/java/appeng/facade/FacadePart.java | 1130 ++--- src/main/java/appeng/facade/IFacadeItem.java | 13 +- src/main/java/appeng/fmp/CableBusPart.java | 1153 +++--- src/main/java/appeng/fmp/FMPEvent.java | 222 +- .../java/appeng/fmp/FMPPlacementHelper.java | 509 +-- src/main/java/appeng/fmp/PartRegistry.java | 89 +- src/main/java/appeng/fmp/QuartzTorchPart.java | 145 +- .../java/appeng/helpers/AEGlassMaterial.java | 23 +- src/main/java/appeng/helpers/AEMultiTile.java | 7 +- .../java/appeng/helpers/DualityInterface.java | 2307 +++++------ .../appeng/helpers/HighlighterHandler.java | 65 +- .../helpers/IContainerCraftingPacket.java | 57 +- .../java/appeng/helpers/ICustomCollision.java | 12 +- .../appeng/helpers/ICustomNameObject.java | 10 +- .../java/appeng/helpers/IInterfaceHost.java | 16 +- .../java/appeng/helpers/IMouseWheelItem.java | 7 +- .../java/appeng/helpers/IOreFilterable.java | 3 +- .../java/appeng/helpers/IPriorityHost.java | 20 +- .../java/appeng/helpers/InventoryAction.java | 28 +- .../java/appeng/helpers/LocationRotation.java | 81 +- .../java/appeng/helpers/MetaRotation.java | 80 +- .../appeng/helpers/MultiCraftingTracker.java | 455 +- .../appeng/helpers/NonNullArrayIterator.java | 57 +- .../java/appeng/helpers/NullRotation.java | 44 +- .../java/appeng/helpers/PatternHelper.java | 744 ++-- .../appeng/helpers/PlayerSecurityWrapper.java | 24 +- src/main/java/appeng/helpers/Reflected.java | 11 +- src/main/java/appeng/helpers/Splotch.java | 163 +- .../helpers/WirelessTerminalGuiObject.java | 611 ++- src/main/java/appeng/hooks/AETrading.java | 180 +- .../java/appeng/hooks/CompassManager.java | 177 +- src/main/java/appeng/hooks/CompassResult.java | 85 +- .../hooks/DispenserBehaviorTinyTNT.java | 31 +- .../java/appeng/hooks/DispenserBlockTool.java | 56 +- .../appeng/hooks/DispenserMatterCannon.java | 60 +- src/main/java/appeng/hooks/IBlockTool.java | 17 +- src/main/java/appeng/hooks/TickHandler.java | 518 ++- .../integration/IIntegrationModule.java | 8 +- .../appeng/integration/IntegrationHelper.java | 11 +- .../appeng/integration/IntegrationNode.java | 277 +- .../integration/IntegrationRegistry.java | 163 +- .../appeng/integration/IntegrationSide.java | 8 +- .../appeng/integration/IntegrationStage.java | 13 +- .../appeng/integration/IntegrationType.java | 75 +- .../abstraction/IBetterStorage.java | 9 +- .../abstraction/IBuildCraftCore.java | 62 +- .../abstraction/IBuildCraftTransport.java | 124 +- .../integration/abstraction/ICLApi.java | 7 +- .../appeng/integration/abstraction/IDSU.java | 9 +- .../appeng/integration/abstraction/IFMP.java | 13 +- .../appeng/integration/abstraction/IFZ.java | 21 +- .../integration/abstraction/IForestry.java | 9 +- .../appeng/integration/abstraction/IGT.java | 9 +- .../appeng/integration/abstraction/IIC2.java | 13 +- .../abstraction/IImmibisMicroblocks.java | 17 +- .../integration/abstraction/IInvTweaks.java | 7 +- .../appeng/integration/abstraction/ILP.java | 26 +- .../integration/abstraction/IMekanism.java | 9 +- .../appeng/integration/abstraction/INEI.java | 9 +- .../appeng/integration/abstraction/IRC.java | 7 +- .../appeng/integration/abstraction/ITE.java | 13 +- .../BCHelpers/AECableSchematicTile.java | 233 +- .../BCHelpers/AEGenericSchematicTile.java | 72 +- .../BCHelpers/AERotatableBlockSchematic.java | 21 +- .../modules/BCHelpers/BCPipeHandler.java | 50 +- .../modules/BCHelpers/BCPipeInventory.java | 83 +- .../integration/modules/BetterStorage.java | 68 +- .../modules/BuildCraftBuilder.java | 128 +- .../integration/modules/BuildCraftCore.java | 82 +- .../modules/BuildCraftTransport.java | 456 +- .../appeng/integration/modules/CLApi.java | 20 +- .../appeng/integration/modules/Chisel.java | 24 +- .../integration/modules/CraftGuide.java | 125 +- .../java/appeng/integration/modules/DSU.java | 51 +- .../java/appeng/integration/modules/FMP.java | 306 +- .../java/appeng/integration/modules/FZ.java | 300 +- .../java/appeng/integration/modules/GT.java | 20 +- .../java/appeng/integration/modules/IC2.java | 123 +- .../modules/ImmibisMicroblocks.java | 198 +- .../appeng/integration/modules/InvTweaks.java | 63 +- .../appeng/integration/modules/Jabba.java | 24 +- .../java/appeng/integration/modules/MFR.java | 31 +- .../appeng/integration/modules/Mekanism.java | 74 +- .../java/appeng/integration/modules/NEI.java | 346 +- .../NEIHelpers/NEIAEShapedRecipeHandler.java | 393 +- .../NEIAEShapelessRecipeHandler.java | 398 +- .../NEIHelpers/NEICraftingHandler.java | 167 +- .../NEIHelpers/NEIFacadeRecipeHandler.java | 378 +- .../NEIHelpers/NEIGrinderRecipeHandler.java | 379 +- .../modules/NEIHelpers/NEIGuiHandler.java | 28 +- .../NEIHelpers/NEIInscriberRecipeHandler.java | 297 +- .../NEIHelpers/NEIWorldCraftingHandler.java | 370 +- .../TerminalCraftingSlotFinder.java | 29 +- .../integration/modules/OpenComputers.java | 72 +- .../integration/modules/PneumaticCraft.java | 75 +- .../java/appeng/integration/modules/RC.java | 43 +- .../java/appeng/integration/modules/RF.java | 97 +- .../appeng/integration/modules/RFItem.java | 30 +- .../appeng/integration/modules/Waila.java | 60 +- .../integration/modules/helpers/BSCrate.java | 86 +- .../modules/helpers/BSCrateHandler.java | 32 +- .../helpers/BSCrateStorageAdaptor.java | 334 +- .../modules/helpers/FMPPacketEvent.java | 21 +- .../modules/helpers/FactorizationBarrel.java | 257 +- .../modules/helpers/FactorizationHandler.java | 32 +- .../modules/helpers/JabbaBarrel.java | 103 +- .../modules/helpers/JabbaStorageHandler.java | 18 +- .../modules/helpers/MFRDSUHandler.java | 32 +- .../MinefactoryReloadedDeepStorageUnit.java | 171 +- .../modules/helpers/NullRFHandler.java | 41 +- .../modules/waila/BaseWailaDataProvider.java | 72 +- .../modules/waila/PartWailaDataProvider.java | 300 +- .../modules/waila/TileWailaDataProvider.java | 151 +- .../waila/part/BasePartWailaDataProvider.java | 73 +- .../waila/part/ChannelWailaDataProvider.java | 220 +- .../waila/part/IPartWailaDataProvider.java | 22 +- .../waila/part/P2PStateWailaDataProvider.java | 273 +- .../modules/waila/part/PartAccessor.java | 50 +- .../part/PartStackWailaDataProvider.java | 17 +- .../part/PowerStateWailaDataProvider.java | 96 +- .../part/StorageMonitorWailaDataProvider.java | 73 +- .../modules/waila/part/Tracer.java | 103 +- .../waila/tile/ChargerWailaDataProvider.java | 65 +- .../CraftingMonitorWailaDataProvider.java | 59 +- .../tile/PowerStateWailaDataProvider.java | 81 +- .../tile/PowerStorageWailaDataProvider.java | 241 +- src/main/java/appeng/items/AEBaseItem.java | 122 +- .../appeng/items/contents/CellConfig.java | 29 +- .../appeng/items/contents/CellUpgrades.java | 29 +- .../items/contents/NetworkToolViewer.java | 203 +- .../items/contents/PortableCellViewer.java | 137 +- .../appeng/items/contents/QuartzKnifeObj.java | 23 +- .../contents/WirelessTerminalViewCells.java | 29 +- .../items/materials/ItemMultiMaterial.java | 769 ++-- .../appeng/items/materials/MaterialType.java | 408 +- .../appeng/items/misc/ItemCrystalSeed.java | 529 ++- .../appeng/items/misc/ItemEncodedPattern.java | 368 +- .../java/appeng/items/misc/ItemPaintBall.java | 130 +- .../java/appeng/items/parts/ItemFacade.java | 446 +- .../appeng/items/parts/ItemMultiPart.java | 678 ++- .../java/appeng/items/parts/PartType.java | 453 +- .../items/storage/ItemBasicStorageCell.java | 541 ++- .../storage/ItemCreativeStorageCell.java | 73 +- .../items/storage/ItemSpatialStorageCell.java | 317 +- .../appeng/items/storage/ItemViewCell.java | 264 +- .../appeng/items/tools/ToolBiometricCard.java | 304 +- .../appeng/items/tools/ToolMemoryCard.java | 272 +- .../appeng/items/tools/ToolNetworkTool.java | 351 +- .../items/tools/powered/ToolChargedStaff.java | 60 +- .../tools/powered/ToolColorApplicator.java | 937 ++--- .../tools/powered/ToolEntropyManipulator.java | 679 +-- .../items/tools/powered/ToolMassCannon.java | 929 ++--- .../items/tools/powered/ToolPortableCell.java | 276 +- .../tools/powered/ToolWirelessTerminal.java | 192 +- .../powered/powersink/AEBasePoweredItem.java | 14 +- .../powered/powersink/AERootPoweredItem.java | 318 +- .../items/tools/powered/powersink/IC2.java | 211 +- .../tools/powered/powersink/RedstoneFlux.java | 58 +- .../powersink/UniversalElectricity.java | 66 +- .../items/tools/quartz/ToolQuartzAxe.java | 57 +- .../tools/quartz/ToolQuartzCuttingKnife.java | 152 +- .../items/tools/quartz/ToolQuartzHoe.java | 63 +- .../items/tools/quartz/ToolQuartzPickaxe.java | 51 +- .../items/tools/quartz/ToolQuartzSpade.java | 49 +- .../items/tools/quartz/ToolQuartzSword.java | 57 +- .../items/tools/quartz/ToolQuartzWrench.java | 151 +- src/main/java/appeng/me/Grid.java | 539 ++- .../java/appeng/me/GridAccessException.java | 6 +- src/main/java/appeng/me/GridCacheWrapper.java | 86 +- src/main/java/appeng/me/GridConnection.java | 477 +-- src/main/java/appeng/me/GridException.java | 13 +- src/main/java/appeng/me/GridNode.java | 1238 +++--- .../java/appeng/me/GridNodeCollection.java | 95 +- src/main/java/appeng/me/GridNodeIterator.java | 80 +- src/main/java/appeng/me/GridPropagator.java | 34 +- .../java/appeng/me/GridSplitDetector.java | 46 +- src/main/java/appeng/me/GridStorage.java | 224 +- .../java/appeng/me/GridStorageSearch.java | 89 +- src/main/java/appeng/me/MachineSet.java | 26 +- src/main/java/appeng/me/NetworkEventBus.java | 330 +- src/main/java/appeng/me/NetworkList.java | 152 +- .../appeng/me/cache/CraftingGridCache.java | 1091 +++-- .../java/appeng/me/cache/EnergyGridCache.java | 1076 +++-- .../appeng/me/cache/GridStorageCache.java | 659 ++- .../java/appeng/me/cache/NetworkMonitor.java | 555 ++- src/main/java/appeng/me/cache/P2PCache.java | 344 +- .../java/appeng/me/cache/PathGridCache.java | 808 ++-- .../java/appeng/me/cache/SecurityCache.java | 315 +- .../appeng/me/cache/SpatialPylonCache.java | 392 +- .../appeng/me/cache/TickManagerCache.java | 414 +- .../me/cache/helpers/ConnectionWrapper.java | 30 +- .../appeng/me/cache/helpers/Connections.java | 87 +- .../appeng/me/cache/helpers/TickTracker.java | 209 +- .../me/cache/helpers/TunnelCollection.java | 63 +- .../me/cache/helpers/TunnelConnection.java | 34 +- .../me/cache/helpers/TunnelIterator.java | 87 +- .../java/appeng/me/cluster/IAECluster.java | 12 +- .../java/appeng/me/cluster/IAEMultiBlock.java | 10 +- .../java/appeng/me/cluster/MBCalculator.java | 381 +- .../CraftingCPUCalculator.java | 204 +- .../implementations/CraftingCPUCluster.java | 2345 +++++------ .../implementations/QuantumCalculator.java | 248 +- .../implementations/QuantumCluster.java | 489 +-- .../SpatialPylonCalculator.java | 142 +- .../implementations/SpatialPylonCluster.java | 200 +- .../appeng/me/energy/EnergyThreshold.java | 65 +- .../java/appeng/me/energy/EnergyWatcher.java | 315 +- .../appeng/me/helpers/AENetworkProxy.java | 717 ++-- .../me/helpers/AENetworkProxyMultiblock.java | 39 +- .../appeng/me/helpers/ChannelPowerSrc.java | 34 +- .../me/helpers/GenericInterestManager.java | 171 +- .../appeng/me/helpers/IGridProxyable.java | 11 +- .../me/pathfinding/AdHocChannelUpdater.java | 54 +- .../me/pathfinding/BackbonePathSegment.java | 71 +- .../pathfinding/ControllerChannelUpdater.java | 29 +- .../me/pathfinding/ControllerValidator.java | 135 +- .../java/appeng/me/pathfinding/IPathItem.java | 54 +- .../appeng/me/pathfinding/PathSegment.java | 226 +- .../appeng/me/pathfinding/TopologyStage.java | 9 +- .../appeng/me/storage/AEExternalHandler.java | 87 +- .../java/appeng/me/storage/CellInventory.java | 1061 +++-- .../me/storage/CellInventoryHandler.java | 208 +- .../me/storage/CreativeCellInventory.java | 183 +- .../java/appeng/me/storage/DriveWatcher.java | 78 +- .../java/appeng/me/storage/ItemWatcher.java | 300 +- .../me/storage/MEIInventoryWrapper.java | 344 +- .../appeng/me/storage/MEInventoryHandler.java | 300 +- .../me/storage/MEMonitorIInventory.java | 575 ++- .../me/storage/MEMonitorPassThrough.java | 244 +- .../java/appeng/me/storage/MEPassThrough.java | 159 +- .../me/storage/NetworkInventoryHandler.java | 542 ++- .../java/appeng/me/storage/NullInventory.java | 95 +- .../appeng/me/storage/SecurityInventory.java | 294 +- .../appeng/me/storage/VoidFluidInventory.java | 144 +- .../appeng/me/storage/VoidItemInventory.java | 144 +- src/main/java/appeng/parts/AEBasePart.java | 966 ++--- .../java/appeng/parts/BusCollisionHelper.java | 291 +- .../java/appeng/parts/CableBusContainer.java | 1949 ++++----- .../java/appeng/parts/CableBusStorage.java | 208 +- .../java/appeng/parts/ICableBusContainer.java | 38 +- .../appeng/parts/NullCableBusContainer.java | 147 +- .../java/appeng/parts/PartBasicState.java | 268 +- src/main/java/appeng/parts/PartPlacement.java | 899 ++-- .../automation/BlockUpgradeInventory.java | 43 +- .../DefinitionUpgradeInventory.java | 41 +- .../automation/PartAnnihilationPlane.java | 1045 +++-- .../parts/automation/PartExportBus.java | 638 ++- .../parts/automation/PartFormationPlane.java | 1098 ++--- .../PartIdentityAnnihilationPlane.java | 111 +- .../parts/automation/PartImportBus.java | 580 ++- .../parts/automation/PartLevelEmitter.java | 1413 ++++--- .../parts/automation/PartSharedItemBus.java | 327 +- .../parts/automation/PartUpgradeable.java | 253 +- .../automation/StackUpgradeInventory.java | 41 +- .../parts/automation/UpgradeInventory.java | 310 +- .../appeng/parts/layers/InvLayerData.java | 215 +- src/main/java/appeng/parts/layers/InvSot.java | 60 +- .../parts/layers/LayerIEnergyConnected.java | 90 +- .../parts/layers/LayerIEnergyHandler.java | 95 +- .../appeng/parts/layers/LayerIEnergySink.java | 301 +- .../parts/layers/LayerIEnergySource.java | 308 +- .../parts/layers/LayerIFluidHandler.java | 115 +- .../parts/layers/LayerIPipeConnection.java | 23 +- .../parts/layers/LayerISidedInventory.java | 408 +- .../layers/LayerITileStorageMonitorable.java | 23 +- .../appeng/parts/layers/LayerPressure.java | 29 +- .../parts/layers/LayerSidedEnvironment.java | 46 +- .../appeng/parts/misc/PartCableAnchor.java | 400 +- .../java/appeng/parts/misc/PartInterface.java | 692 ++-- .../parts/misc/PartInvertedToggleBus.java | 31 +- .../appeng/parts/misc/PartStorageBus.java | 981 +++-- .../java/appeng/parts/misc/PartToggleBus.java | 418 +- .../appeng/parts/networking/PartCable.java | 1999 +++++---- .../parts/networking/PartCableCovered.java | 404 +- .../parts/networking/PartCableGlass.java | 14 +- .../parts/networking/PartCableSmart.java | 663 +-- .../parts/networking/PartDenseCable.java | 941 +++-- .../networking/PartDenseCableCovered.java | 684 ++- .../parts/networking/PartQuartzFiber.java | 354 +- .../PartUltraDenseCableCovered.java | 34 +- .../networking/PartUltraDenseCableSmart.java | 31 +- .../appeng/parts/p2p/PartP2PGT5Power.java | 70 +- .../appeng/parts/p2p/PartP2PIC2Power.java | 412 +- .../java/appeng/parts/p2p/PartP2PItems.java | 603 ++- .../java/appeng/parts/p2p/PartP2PLight.java | 342 +- .../java/appeng/parts/p2p/PartP2PLiquids.java | 520 ++- .../parts/p2p/PartP2POpenComputers.java | 259 +- .../appeng/parts/p2p/PartP2PPressure.java | 261 +- .../java/appeng/parts/p2p/PartP2PRFPower.java | 430 +- .../appeng/parts/p2p/PartP2PRedstone.java | 315 +- .../java/appeng/parts/p2p/PartP2PTunnel.java | 946 ++--- .../appeng/parts/p2p/PartP2PTunnelME.java | 381 +- .../parts/reporting/AbstractPartDisplay.java | 214 +- .../parts/reporting/AbstractPartMonitor.java | 673 ++- .../parts/reporting/AbstractPartPanel.java | 169 +- .../reporting/AbstractPartReporting.java | 490 +-- .../parts/reporting/AbstractPartTerminal.java | 227 +- .../reporting/PartConversionMonitor.java | 277 +- .../parts/reporting/PartCraftingTerminal.java | 168 +- .../appeng/parts/reporting/PartDarkPanel.java | 23 +- .../reporting/PartInterfaceTerminal.java | 75 +- .../appeng/parts/reporting/PartPanel.java | 24 +- .../parts/reporting/PartPatternTerminal.java | 354 +- .../reporting/PartPatternTerminalEx.java | 143 +- .../parts/reporting/PartSemiDarkPanel.java | 29 +- .../parts/reporting/PartStorageMonitor.java | 58 +- .../appeng/parts/reporting/PartTerminal.java | 45 +- .../java/appeng/recipes/AEItemResolver.java | 325 +- .../appeng/recipes/CustomRecipeConfig.java | 6 +- .../CustomRecipeForgeConfiguration.java | 29 +- .../java/appeng/recipes/GroupIngredient.java | 233 +- src/main/java/appeng/recipes/Ingredient.java | 431 +- .../java/appeng/recipes/IngredientSet.java | 177 +- .../appeng/recipes/MissedIngredientSet.java | 23 +- src/main/java/appeng/recipes/RecipeData.java | 20 +- .../java/appeng/recipes/RecipeHandler.java | 1253 +++--- .../recipes/game/DisassembleRecipe.java | 256 +- .../appeng/recipes/game/FacadeRecipe.java | 105 +- .../appeng/recipes/game/IRecipeBakeable.java | 7 +- .../appeng/recipes/game/ShapedRecipe.java | 529 ++- .../appeng/recipes/game/ShapelessRecipe.java | 270 +- .../java/appeng/recipes/handlers/Crusher.java | 89 +- .../java/appeng/recipes/handlers/Grind.java | 78 +- .../java/appeng/recipes/handlers/GrindFZ.java | 89 +- .../appeng/recipes/handlers/HCCrusher.java | 120 +- .../recipes/handlers/IWebsiteSerializer.java | 9 +- .../appeng/recipes/handlers/Inscribe.java | 49 +- .../recipes/handlers/InscriberProcess.java | 190 +- .../appeng/recipes/handlers/Macerator.java | 89 +- .../appeng/recipes/handlers/MekCrusher.java | 89 +- .../recipes/handlers/MekEnrichment.java | 89 +- .../recipes/handlers/OreRegistration.java | 47 +- .../java/appeng/recipes/handlers/Press.java | 49 +- .../appeng/recipes/handlers/Pulverizer.java | 83 +- .../java/appeng/recipes/handlers/Shaped.java | 246 +- .../appeng/recipes/handlers/Shapeless.java | 183 +- .../java/appeng/recipes/handlers/Smelt.java | 84 +- .../appeng/recipes/loader/ConfigLoader.java | 51 +- .../java/appeng/recipes/loader/JarLoader.java | 31 +- .../recipes/loader/RecipeResourceCopier.java | 404 +- .../appeng/recipes/ores/IOreListener.java | 21 +- .../recipes/ores/OreDictionaryHandler.java | 163 +- src/main/java/appeng/server/AECommand.java | 176 +- src/main/java/appeng/server/AccessType.java | 62 +- src/main/java/appeng/server/Commands.java | 38 +- src/main/java/appeng/server/ISubCommand.java | 9 +- src/main/java/appeng/server/ServerHelper.java | 300 +- .../server/subcommands/ChunkLogger.java | 105 +- .../appeng/server/subcommands/Profile.java | 50 +- .../appeng/server/subcommands/Supporters.java | 28 +- .../subcommands/ToggleDebugPathfinding.java | 4 +- .../server/subcommands/ToggleDebugTiming.java | 8 +- .../server/subcommands/ToggleFullAccess.java | 24 +- .../java/appeng/services/CompassService.java | 602 ++- .../java/appeng/services/VersionChecker.java | 266 +- .../services/compass/CompassException.java | 15 +- .../services/compass/CompassReader.java | 83 +- .../services/compass/CompassRegion.java | 319 +- .../compass/CompassThreadFactory.java | 19 +- .../services/compass/ICompassCallback.java | 22 +- .../appeng/services/export/CheckType.java | 20 +- .../java/appeng/services/export/Checker.java | 19 +- .../appeng/services/export/ExportConfig.java | 93 +- .../appeng/services/export/ExportMode.java | 20 +- .../appeng/services/export/ExportProcess.java | 160 +- .../java/appeng/services/export/Exporter.java | 12 +- .../services/export/ForgeExportConfig.java | 195 +- .../export/MinecraftItemCSVExporter.java | 468 +-- .../services/export/ModListChecker.java | 86 +- .../appeng/services/export/package-info.java | 3 +- .../appeng/services/version/BaseVersion.java | 174 +- .../java/appeng/services/version/Channel.java | 10 +- .../services/version/DefaultVersion.java | 46 +- .../services/version/DoNotCheckVersion.java | 29 +- .../services/version/MissingVersion.java | 37 +- .../services/version/ModVersionFetcher.java | 69 +- .../java/appeng/services/version/Version.java | 62 +- .../version/VersionCheckerConfig.java | 208 +- .../services/version/VersionFetcher.java | 6 +- .../services/version/VersionParser.java | 287 +- .../exceptions/InvalidBuildException.java | 13 +- .../exceptions/InvalidChannelException.java | 14 +- .../exceptions/InvalidRevisionException.java | 13 +- .../exceptions/InvalidVersionException.java | 13 +- .../exceptions/MissingSeparatorException.java | 13 +- .../exceptions/VersionCheckerException.java | 14 +- .../github/DefaultFormattedRelease.java | 48 +- .../version/github/FormattedRelease.java | 21 +- .../github/MissingFormattedRelease.java | 53 +- .../services/version/github/Release.java | 20 +- .../version/github/ReleaseFetcher.java | 149 +- .../java/appeng/spatial/BiomeGenStorage.java | 32 +- src/main/java/appeng/spatial/CachedPlane.java | 786 ++-- .../appeng/spatial/DefaultSpatialHandler.java | 66 +- .../java/appeng/spatial/ISpatialVisitor.java | 6 +- .../appeng/spatial/StorageChunkProvider.java | 129 +- .../java/appeng/spatial/StorageHelper.java | 651 ++- .../appeng/spatial/StorageWorldProvider.java | 224 +- src/main/java/appeng/tile/AEBaseInvTile.java | 265 +- src/main/java/appeng/tile/AEBaseTile.java | 984 ++--- src/main/java/appeng/tile/TileEvent.java | 10 +- .../crafting/TileCraftingMonitorTile.java | 263 +- .../crafting/TileCraftingStorageTile.java | 116 +- .../tile/crafting/TileCraftingTile.java | 607 ++- .../tile/crafting/TileMolecularAssembler.java | 1095 +++-- .../tile/events/AETileEventHandler.java | 191 +- .../appeng/tile/events/TileEventType.java | 19 +- .../appeng/tile/grid/AENetworkInvTile.java | 126 +- .../appeng/tile/grid/AENetworkPowerTile.java | 148 +- .../java/appeng/tile/grid/AENetworkTile.java | 156 +- .../appeng/tile/grindstone/TileCrank.java | 279 +- .../appeng/tile/grindstone/TileGrinder.java | 307 +- .../inventory/AppEngInternalAEInventory.java | 434 +- .../inventory/AppEngInternalInventory.java | 494 +-- .../tile/inventory/AppEngNullInventory.java | 148 +- .../tile/inventory/BiggerAppEngInventory.java | 53 +- .../tile/inventory/IAEAppEngInventory.java | 9 +- .../appeng/tile/inventory/InvOperation.java | 9 +- .../appeng/tile/misc/TileCellWorkbench.java | 451 +- .../java/appeng/tile/misc/TileCharger.java | 483 ++- .../java/appeng/tile/misc/TileCondenser.java | 449 +- .../java/appeng/tile/misc/TileInscriber.java | 939 ++--- .../java/appeng/tile/misc/TileInterface.java | 598 ++- .../appeng/tile/misc/TileLightDetector.java | 71 +- src/main/java/appeng/tile/misc/TilePaint.java | 424 +- .../misc/TileQuartzGrowthAccelerator.java | 149 +- .../java/appeng/tile/misc/TileSecurity.java | 544 ++- .../java/appeng/tile/misc/TileSkyCompass.java | 14 +- .../tile/misc/TileVibrationChamber.java | 515 ++- .../appeng/tile/networking/TileCableBus.java | 624 ++- .../tile/networking/TileCableBusTESR.java | 33 +- .../tile/networking/TileController.java | 335 +- .../networking/TileCreativeEnergyCell.java | 75 +- .../tile/networking/TileDenseEnergyCell.java | 11 +- .../tile/networking/TileEnergyAcceptor.java | 194 +- .../tile/networking/TileEnergyCell.java | 382 +- .../appeng/tile/networking/TileWireless.java | 328 +- .../tile/powersink/AEBasePoweredTile.java | 6 +- .../tile/powersink/AERootPoweredTile.java | 362 +- .../appeng/tile/powersink/GTPowerSink.java | 21 +- src/main/java/appeng/tile/powersink/IC2.java | 166 +- .../java/appeng/tile/powersink/MekJoules.java | 22 +- .../appeng/tile/powersink/RedstoneFlux.java | 64 +- .../appeng/tile/powersink/RotaryCraft.java | 41 +- .../tile/powersink/UniversalElectricity.java | 3 +- .../appeng/tile/qnb/TileQuantumBridge.java | 571 ++- .../tile/spatial/TileSpatialIOPort.java | 289 +- .../appeng/tile/spatial/TileSpatialPylon.java | 384 +- .../java/appeng/tile/storage/TileChest.java | 1627 ++++---- .../java/appeng/tile/storage/TileDrive.java | 669 ++- .../java/appeng/tile/storage/TileIOPort.java | 949 ++--- .../appeng/tile/storage/TileSkyChest.java | 247 +- .../java/appeng/transformer/AppEngCore.java | 168 +- .../appeng/transformer/MissingCoreMod.java | 183 +- .../transformer/annotations/Integration.java | 48 +- .../transformer/asm/ASMIntegration.java | 387 +- .../appeng/transformer/asm/ASMTweaker.java | 248 +- .../appeng/transformer/asm/ApiRepairer.java | 89 +- src/main/java/appeng/util/BlockUpdate.java | 38 +- .../java/appeng/util/ClassInstantiation.java | 180 +- src/main/java/appeng/util/ConfigManager.java | 182 +- .../java/appeng/util/IConfigManagerHost.java | 7 +- .../util/ISlimReadableNumberConverter.java | 31 +- .../util/IWideReadableNumberConverter.java | 31 +- src/main/java/appeng/util/IWorldCallable.java | 32 +- .../util/InWorldToolOperationResult.java | 89 +- .../java/appeng/util/InventoryAdaptor.java | 159 +- src/main/java/appeng/util/ItemSorters.java | 259 +- src/main/java/appeng/util/LookDirection.java | 32 +- src/main/java/appeng/util/Platform.java | 3658 ++++++++--------- .../java/appeng/util/ReadOnlyCollection.java | 51 +- .../appeng/util/ReadableNumberConverter.java | 171 +- src/main/java/appeng/util/SettingsFrom.java | 12 +- src/main/java/appeng/util/UUIDMatcher.java | 40 +- .../appeng/util/calculators/ArithHelper.java | 4 +- .../appeng/util/calculators/Calculator.java | 17 +- .../java/appeng/util/inv/AdaptorBCPipe.java | 178 +- .../appeng/util/inv/AdaptorIInventory.java | 707 ++-- .../java/appeng/util/inv/AdaptorList.java | 347 +- .../appeng/util/inv/AdaptorPlayerHand.java | 380 +- .../util/inv/AdaptorPlayerInventory.java | 180 +- .../util/inv/IInventoryDestination.java | 7 +- .../appeng/util/inv/IInventoryWrapper.java | 7 +- src/main/java/appeng/util/inv/IMEAdaptor.java | 308 +- .../appeng/util/inv/IMEAdaptorIterator.java | 84 +- .../util/inv/IMEInventoryDestination.java | 39 +- .../util/inv/ItemListIgnoreCrafting.java | 151 +- src/main/java/appeng/util/inv/ItemSlot.java | 79 +- .../java/appeng/util/inv/WrapperBCPipe.java | 168 +- .../util/inv/WrapperChainedInventory.java | 377 +- .../java/appeng/util/inv/WrapperInvSlot.java | 203 +- .../util/inv/WrapperInventoryRange.java | 277 +- .../util/inv/WrapperMCISidedInventory.java | 75 +- .../java/appeng/util/item/AEFluidStack.java | 652 ++- src/main/java/appeng/util/item/AEItemDef.java | 357 +- .../java/appeng/util/item/AEItemStack.java | 1289 +++--- .../java/appeng/util/item/AESharedNBT.java | 341 +- src/main/java/appeng/util/item/AEStack.java | 311 +- src/main/java/appeng/util/item/FluidList.java | 311 +- .../appeng/util/item/HashBasedItemList.java | 293 +- src/main/java/appeng/util/item/ItemList.java | 366 +- .../java/appeng/util/item/ItemModList.java | 91 +- .../util/item/MeaningfulFluidIterator.java | 87 +- .../util/item/MeaningfulItemIterator.java | 73 +- src/main/java/appeng/util/item/OreHelper.java | 278 +- .../java/appeng/util/item/OreReference.java | 61 +- .../appeng/util/item/SharedSearchObject.java | 93 +- .../appeng/util/iterators/AEInvIterator.java | 52 +- .../util/iterators/ChainedIterator.java | 55 +- .../appeng/util/iterators/InvIterator.java | 54 +- .../appeng/util/iterators/NullIterator.java | 30 +- .../util/iterators/ProxyNodeIterator.java | 46 +- .../util/iterators/StackToSlotIterator.java | 64 +- .../util/prioitylist/DefaultPriorityList.java | 35 +- .../util/prioitylist/FuzzyPriorityList.java | 56 +- .../util/prioitylist/IPartitionList.java | 11 +- .../util/prioitylist/MergedPriorityList.java | 86 +- .../util/prioitylist/OreFilteredList.java | 87 +- .../util/prioitylist/PrecisePriorityList.java | 41 +- .../java/appeng/worldgen/MeteoritePlacer.java | 998 +++-- .../appeng/worldgen/MeteoriteWorldGen.java | 229 +- .../java/appeng/worldgen/QuartzWorldGen.java | 91 +- .../appeng/worldgen/meteorite/ChunkOnly.java | 173 +- .../appeng/worldgen/meteorite/Fallout.java | 115 +- .../worldgen/meteorite/FalloutCopy.java | 103 +- .../worldgen/meteorite/FalloutSand.java | 49 +- .../worldgen/meteorite/FalloutSnow.java | 57 +- .../worldgen/meteorite/IMeteoriteWorld.java | 33 +- .../meteorite/MeteoriteBlockPutter.java | 37 +- .../worldgen/meteorite/StandardWorld.java | 206 +- .../worlddata/MeteorDataNameEncoderTest.java | 63 +- .../version/ModVersionFetcherTest.java | 65 +- .../services/version/VersionParserTest.java | 169 +- .../appeng/services/version/VersionTest.java | 154 +- .../util/SlimReadableNumberConverterTest.java | 213 +- .../java/appeng/util/UUIDMatcherTest.java | 59 +- .../util/WideReadableNumberConverterTest.java | 213 +- 1220 files changed, 105610 insertions(+), 120307 deletions(-) create mode 100644 .gitattributes create mode 100644 settings.gradle diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000000..6f227db1e44 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,41 @@ +* text eol=lf + +*.[jJ][aA][rR] binary + +*.[pP][nN][gG] binary +*.[jJ][pP][gG] binary +*.[jJ][pP][eE][gG] binary +*.[gG][iI][fF] binary +*.[tT][iI][fF] binary +*.[tT][iI][fF][fF] binary +*.[iI][cC][oO] binary +*.[sS][vV][gG] text +*.[eE][pP][sS] binary + +*.[kK][aA][rR] binary +*.[mM]4[aA] binary +*.[mM][iI][dD] binary +*.[mM][iI][dD][iI] binary +*.[mM][pP]3 binary +*.[oO][gG][gG] binary +*.[rR][aA] binary + +*.7[zZ] binary +*.[gG][zZ] binary +*.[tT][aA][rR] binary +*.[tT][gG][zZ] binary +*.[zZ][iI][pP] binary + +*.[tT][cC][nN] binary +*.[sS][oO] binary +*.[dD][lL][lL] binary +*.[dD][yY][lL][iI][bB] binary +*.[pP][sS][dD] binary + +*.[pP][aA][tT][cC][hH] -text + +*.[bB][aA][tT] text eol=crlf +*.[cC][mM][dD] text eol=crlf +*.[pP][sS]1 text eol=crlf + +*[aA][uU][tT][oO][gG][eE][nN][eE][rR][aA][tT][eE][dD]* binary \ No newline at end of file diff --git a/build.gradle b/build.gradle index 5e787403a3d..997b94dc308 100644 --- a/build.gradle +++ b/build.gradle @@ -1,10 +1,9 @@ -//version: 1650343995 +//version: 1661114848 /* -DO NOT CHANGE THIS FILE! - -Also, you may replace this file at any time if there is an update available. -Please check https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/main/build.gradle for updates. -*/ + DO NOT CHANGE THIS FILE! + Also, you may replace this file at any time if there is an update available. + Please check https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/main/build.gradle for updates. + */ import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation @@ -12,14 +11,26 @@ import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar import org.gradle.internal.logging.text.StyledTextOutput.Style import org.gradle.internal.logging.text.StyledTextOutputFactory +import java.nio.file.Files +import java.nio.file.Paths import java.util.concurrent.TimeUnit +import java.util.zip.ZipEntry +import java.util.zip.ZipInputStream +import java.util.zip.ZipOutputStream buildscript { repositories { + mavenCentral() + maven { name 'forge' url 'https://maven.minecraftforge.net' } + maven { + // GTNH ForgeGradle Fork + name = "GTNH Maven" + url = "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" + } maven { name 'sonatype' url 'https://oss.sonatype.org/content/repositories/snapshots/' @@ -28,31 +39,38 @@ buildscript { name 'Scala CI dependencies' url 'https://repo1.maven.org/maven2/' } - maven { - name 'jitpack' - url 'https://jitpack.io' - } } dependencies { - classpath 'com.github.GTNewHorizons:ForgeGradle:1.2.7' + classpath 'net.minecraftforge.gradle:ForgeGradle:1.2.9' } } - plugins { id 'java-library' id 'idea' id 'eclipse' id 'scala' id 'maven-publish' - id 'org.jetbrains.kotlin.jvm' version '1.5.30' apply false - id 'org.jetbrains.kotlin.kapt' version '1.5.30' apply false - id 'org.ajoberstar.grgit' version '4.1.1' + id 'org.jetbrains.kotlin.jvm' version '1.5.30' apply false + id 'org.jetbrains.kotlin.kapt' version '1.5.30' apply false + id 'com.google.devtools.ksp' version '1.5.30-1.0.0' apply false + id 'org.ajoberstar.grgit' version '4.1.1' id 'com.github.johnrengelman.shadow' version '4.0.4' - id 'com.palantir.git-version' version '0.13.0' apply false - id 'de.undercouch.download' version '5.0.1' - id 'com.github.gmazzo.buildconfig' version '3.0.3' apply false + id 'com.palantir.git-version' version '0.13.0' apply false + id 'de.undercouch.download' version '5.0.1' + id 'com.github.gmazzo.buildconfig' version '3.0.3' apply false + id 'com.diffplug.spotless' version '6.7.2' apply false +} +boolean settingsupdated = verifySettingsGradle() +settingsupdated = verifyGitAttributes() || settingsupdated +if (settingsupdated) + throw new GradleException("Settings has been updated, please re-run task.") + +dependencies { + implementation 'com.diffplug:blowdryer:1.6.0' } +apply plugin: 'com.diffplug.blowdryer' + if (project.file('.git/HEAD').isFile()) { apply plugin: 'com.palantir.git-version' } @@ -77,7 +95,14 @@ idea { } } -if(JavaVersion.current() != JavaVersion.VERSION_1_8) { +boolean disableSpotless = project.hasProperty("disableSpotless") ? project.disableSpotless.toBoolean() : false + +if (!disableSpotless) { + apply plugin: 'com.diffplug.spotless' + apply from: Blowdryer.file('spotless.gradle') +} + +if (JavaVersion.current() != JavaVersion.VERSION_1_8) { throw new GradleException("This project requires Java 8, but it's running on " + JavaVersion.current()) } @@ -102,9 +127,11 @@ checkPropertyExists("containsMixinsAndOrCoreModOnly") checkPropertyExists("usesShadowedDependencies") checkPropertyExists("developmentEnvironmentUserName") -boolean noPublishedSources = project.findProperty("noPublishedSources") ? project.noPublishedSources.toBoolean() : false -boolean usesMixinDebug = project.findProperty('usesMixinDebug') ?: project.usesMixins.toBoolean() - +boolean noPublishedSources = project.hasProperty("noPublishedSources") ? project.noPublishedSources.toBoolean() : false +boolean usesMixinDebug = project.hasProperty('usesMixinDebug') ?: project.usesMixins.toBoolean() +boolean forceEnableMixins = project.hasProperty('forceEnableMixins') ? project.forceEnableMixins.toBoolean() : false +String channel = project.hasProperty('channel') ? project.channel : 'stable' +String mappingsVersion = project.hasProperty('mappingsVersion') ? project.mappingsVersion : '12' String javaSourceDir = "src/main/java/" String scalaSourceDir = "src/main/scala/" String kotlinSourceDir = "src/main/kotlin/" @@ -112,53 +139,53 @@ String kotlinSourceDir = "src/main/kotlin/" String targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") String targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") String targetPackageKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") -if(!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { +if (!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { throw new GradleException("Could not resolve \"modGroup\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin) } -if(apiPackage) { +if (apiPackage) { targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") targetPackageKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") - if(!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { + if (!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { throw new GradleException("Could not resolve \"apiPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin) } } -if(accessTransformersFile) { +if (accessTransformersFile) { String targetFile = "src/main/resources/META-INF/" + accessTransformersFile - if(!getFile(targetFile).exists()) { + if (!getFile(targetFile).exists()) { throw new GradleException("Could not resolve \"accessTransformersFile\"! Could not find " + targetFile) } } -if(usesMixins.toBoolean()) { - if(mixinsPackage.isEmpty() || mixinPlugin.isEmpty()) { +if (usesMixins.toBoolean()) { + if (mixinsPackage.isEmpty() || mixinPlugin.isEmpty()) { throw new GradleException("\"mixinPlugin\" requires \"mixinsPackage\" and \"mixinPlugin\" to be set!") } targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/") targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/") targetPackageKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/") - if(!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { - throw new GradleException("Could not resolve \"mixinsPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin) + if (!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { + throw new GradleException("Could not resolve \"mixinsPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin) } String targetFileJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".java" String targetFileScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".scala" String targetFileScalaJava = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".java" String targetFileKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".kt" - if(!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) { + if (!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) { throw new GradleException("Could not resolve \"mixinPlugin\"! Could not find " + targetFileJava + " or " + targetFileScala + " or " + targetFileScalaJava + " or " + targetFileKotlin) } } -if(coreModClass) { +if (coreModClass) { String targetFileJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".java" String targetFileScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".scala" String targetFileScalaJava = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".java" String targetFileKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".kt" - if(!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) { + if (!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) { throw new GradleException("Could not resolve \"coreModClass\"! Could not find " + targetFileJava + " or " + targetFileScala + " or " + targetFileScalaJava + " or " + targetFileKotlin) } } @@ -188,7 +215,7 @@ try { catch (Exception ignored) { out.style(Style.Failure).text( 'This mod must be version controlled by Git AND the repository must provide at least one tag,\n' + - 'or the VERSION override must be set! ').style(Style.SuccessHeader).text('(Do NOT download from GitHub using the ZIP option, instead\n' + + 'or the VERSION override must be set! ').style(Style.SuccessHeader).text('(Do NOT download from GitHub using the ZIP option, instead\n' + 'clone the repository, see ').style(Style.Info).text('https://gtnh.miraheze.org/wiki/Development').style(Style.SuccessHeader).println(' for details.)' ) versionOverride = 'NO-GIT-TAG-SET' @@ -199,22 +226,21 @@ ext { modVersion = identifiedVersion } -if(identifiedVersion == versionOverride) { +if (identifiedVersion == versionOverride) { out.style(Style.Failure).text('Override version to ').style(Style.Identifier).text(modVersion).style(Style.Failure).println('!\7') } group = modGroup -if(project.hasProperty("customArchiveBaseName") && customArchiveBaseName) { +if (project.hasProperty("customArchiveBaseName") && customArchiveBaseName) { archivesBaseName = customArchiveBaseName -} -else { +} else { archivesBaseName = modId } def arguments = [] def jvmArguments = [] -if (usesMixins.toBoolean()) { +if (usesMixins.toBoolean() || forceEnableMixins) { arguments += [ "--tweakClass org.spongepowered.asm.launch.MixinTweaker" ] @@ -233,16 +259,16 @@ minecraft { if (replaceGradleTokenInFile) { replaceIn replaceGradleTokenInFile - if(gradleTokenModId) { + if (gradleTokenModId) { replace gradleTokenModId, modId } - if(gradleTokenModName) { + if (gradleTokenModName) { replace gradleTokenModName, modName } - if(gradleTokenVersion) { + if (gradleTokenVersion) { replace gradleTokenVersion, modVersion } - if(gradleTokenGroupName) { + if (gradleTokenGroupName) { replace gradleTokenGroupName, modGroup } } @@ -251,7 +277,7 @@ minecraft { args(arguments) jvmArgs(jvmArguments) - if(developmentEnvironmentUserName) { + if (developmentEnvironmentUserName) { args("--username", developmentEnvironmentUserName) } } @@ -262,7 +288,7 @@ minecraft { } } -if(file('addon.gradle').exists()) { +if (file('addon.gradle').exists()) { apply from: 'addon.gradle' } @@ -279,7 +305,7 @@ repositories { name 'Overmind forge repo mirror' url 'https://gregtech.overminddl1.com/' } - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean() || forceEnableMixins) { maven { name 'sponge' url 'https://repo.spongepowered.org/repository/maven-public' @@ -291,11 +317,13 @@ repositories { } dependencies { - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean()) { annotationProcessor('org.ow2.asm:asm-debug-all:5.0.3') annotationProcessor('com.google.guava:guava:24.1.1-jre') annotationProcessor('com.google.code.gson:gson:2.8.6') annotationProcessor('org.spongepowered:mixin:0.8-SNAPSHOT') + } + if (usesMixins.toBoolean() || forceEnableMixins) { // using 0.8 to workaround a issue in 0.7 which fails mixin application compile('com.github.GTNewHorizons:SpongePoweredMixin:0.7.12-GTNH') { // Mixin includes a lot of dependencies that are too up-to-date @@ -353,7 +381,10 @@ shadowJar { } minimize() // This will only allow shading for actually used classes - configurations = [project.configurations.shadowImplementation, project.configurations.shadowCompile] + configurations = [ + project.configurations.shadowImplementation, + project.configurations.shadowCompile + ] dependsOn(relocateShadowJar) } @@ -368,38 +399,38 @@ jar { attributes(getManifestAttributes()) } - if(usesShadowedDependencies.toBoolean()) { + if (usesShadowedDependencies.toBoolean()) { dependsOn(shadowJar) enabled = false } } reobf { - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean()) { addExtraSrgFile mixinSrg } } afterEvaluate { - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean()) { tasks.compileJava { options.compilerArgs += [ - "-AreobfSrgFile=${tasks.reobf.srg}", - "-AoutSrgFile=${mixinSrg}", - "-AoutRefMapFile=${refMap}", - // Elan: from what I understand they are just some linter configs so you get some warning on how to properly code - "-XDenableSunApiLintControl", - "-XDignore.symbol.file" + "-AreobfSrgFile=${tasks.reobf.srg}", + "-AoutSrgFile=${mixinSrg}", + "-AoutRefMapFile=${refMap}", + // Elan: from what I understand they are just some linter configs so you get some warning on how to properly code + "-XDenableSunApiLintControl", + "-XDignore.symbol.file" ] } } } runClient { - if(developmentEnvironmentUserName) { + if (developmentEnvironmentUserName) { arguments += [ - "--username", - developmentEnvironmentUserName + "--username", + developmentEnvironmentUserName ] } @@ -414,9 +445,9 @@ runServer { tasks.withType(JavaExec).configureEach { javaLauncher.set( - javaToolchains.launcherFor { - languageVersion = projectJavaVersion - } + javaToolchains.launcherFor { + languageVersion = projectJavaVersion + } ) } @@ -424,6 +455,7 @@ processResources { // this will ensure that this task is redone when the versions change. inputs.property "version", project.version inputs.property "mcversion", project.minecraft.version + exclude("spotless.gradle") // replace stuff in mcmod.info, nothing else from(sourceSets.main.resources.srcDirs) { @@ -436,43 +468,44 @@ processResources { "modName": modName } - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean()) { from refMap } // copy everything else that's not the mcmod.info from(sourceSets.main.resources.srcDirs) { exclude 'mcmod.info' + exclude 'spotless.gradle' } } def getManifestAttributes() { def manifestAttributes = [:] - if(!containsMixinsAndOrCoreModOnly.toBoolean() && (usesMixins.toBoolean() || coreModClass)) { + if (!containsMixinsAndOrCoreModOnly.toBoolean() && (usesMixins.toBoolean() || coreModClass)) { manifestAttributes += ["FMLCorePluginContainsFMLMod": true] } - if(accessTransformersFile) { - manifestAttributes += ["FMLAT" : accessTransformersFile.toString()] + if (accessTransformersFile) { + manifestAttributes += ["FMLAT": accessTransformersFile.toString()] } - if(coreModClass) { + if (coreModClass) { manifestAttributes += ["FMLCorePlugin": modGroup + "." + coreModClass] } - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean()) { manifestAttributes += [ - "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", - "MixinConfigs" : "mixins." + modId + ".json", - "ForceLoadAsMod" : !containsMixinsAndOrCoreModOnly.toBoolean() + "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", + "MixinConfigs" : "mixins." + modId + ".json", + "ForceLoadAsMod": !containsMixinsAndOrCoreModOnly.toBoolean() ] } return manifestAttributes } task sourcesJar(type: Jar) { - from (sourceSets.main.allSource) - from (file("$projectDir/LICENSE")) + from(sourceSets.main.allSource) + from(file("$projectDir/LICENSE")) getArchiveClassifier().set('sources') } @@ -491,7 +524,10 @@ task shadowDevJar(type: ShadowJar) { } minimize() // This will only allow shading for actually used classes - configurations = [project.configurations.shadowImplementation, project.configurations.shadowCompile] + configurations = [ + project.configurations.shadowImplementation, + project.configurations.shadowCompile + ] } task relocateShadowDevJar(type: ConfigureShadowRelocation) { @@ -519,22 +555,22 @@ task devJar(type: Jar) { attributes(getManifestAttributes()) } - if(usesShadowedDependencies.toBoolean()) { + if (usesShadowedDependencies.toBoolean()) { dependsOn(circularResolverJar) enabled = false } } task apiJar(type: Jar) { - from (sourceSets.main.allSource) { + from(sourceSets.main.allSource) { include modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") + '/**' } - from (sourceSets.main.output) { + from(sourceSets.main.output) { include modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") + '/**' } - from (sourceSets.main.resources.srcDirs) { + from(sourceSets.main.resources.srcDirs) { include("LICENSE") } @@ -542,11 +578,11 @@ task apiJar(type: Jar) { } artifacts { - if(!noPublishedSources) { + if (!noPublishedSources) { archives sourcesJar } archives devJar - if(apiPackage) { + if (apiPackage) { archives apiJar } } @@ -564,10 +600,10 @@ publishing { publications { maven(MavenPublication) { from components.java - if(usesShadowedDependencies.toBoolean()) { + if (usesShadowedDependencies.toBoolean()) { artifact source: shadowJar, classifier: "" } - if(!noPublishedSources) { + if (!noPublishedSources) { artifact source: sourcesJar, classifier: "sources" } artifact source: usesShadowedDependencies.toBoolean() ? shadowDevJar : devJar, classifier: "dev" @@ -582,8 +618,11 @@ publishing { // remove extra garbage from minecraft and minecraftDeps configuration pom.withXml { - def badArtifacts = [:].withDefault {[] as Set} - for (configuration in [projectConfigs.minecraft, projectConfigs.minecraftDeps]) { + def badArtifacts = [:].withDefault { [] as Set } + for (configuration in [ + projectConfigs.minecraft, + projectConfigs.minecraftDeps + ]) { for (dependency in configuration.allDependencies) { badArtifacts[dependency.group == null ? "" : dependency.group] += dependency.name } @@ -621,7 +660,7 @@ task updateBuildScript { } } -if (isNewBuildScriptVersionAvailable(projectDir.toString())) { +if (!project.getGradle().startParameter.isOffline() && isNewBuildScriptVersionAvailable(projectDir.toString())) { if (autoUpdateBuildScript.toBoolean()) { performBuildScriptUpdate(projectDir.toString()) } else { @@ -630,7 +669,40 @@ if (isNewBuildScriptVersionAvailable(projectDir.toString())) { } static URL availableBuildScriptUrl() { - new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/main/build.gradle") + new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/master/build.gradle") +} + +static URL exampleSettingsGradleUrl() { + new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/master/settings.gradle.example") +} + +static URL exampleGitAttributesUrl() { + new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/master/.gitattributes") +} + + +boolean verifyGitAttributes() { + def gitattributesFile = getFile(".gitattributes") + if (!gitattributesFile.exists()) { + println("Downloading default .gitattributes") + exampleGitAttributesUrl().withInputStream { i -> gitattributesFile.withOutputStream { it << i } } + exec { + workingDir '.' + commandLine 'git', 'add', '--renormalize', '.' + } + return true + } + return false +} + +boolean verifySettingsGradle() { + def settingsFile = getFile("settings.gradle") + if (!settingsFile.exists()) { + println("Downloading default settings.gradle") + exampleSettingsGradleUrl().withInputStream { i -> settingsFile.withOutputStream { it << i } } + return true + } + return false } boolean performBuildScriptUpdate(String projectDir) { @@ -638,6 +710,10 @@ boolean performBuildScriptUpdate(String projectDir) { def buildscriptFile = getFile("build.gradle") availableBuildScriptUrl().withInputStream { i -> buildscriptFile.withOutputStream { it << i } } out.style(Style.Success).print("Build script updated. Please REIMPORT the project or RESTART your IDE!") + boolean settingsupdated = verifySettingsGradle() + settingsupdated = verifyGitAttributes() || settingsupdated + if (settingsupdated) + throw new GradleException("Settings has been updated, please re-run task.") return true } return false @@ -657,7 +733,7 @@ boolean isNewBuildScriptVersionAvailable(String projectDir) { static String getVersionHash(String buildScriptContent) { String versionLine = buildScriptContent.find("^//version: [a-z0-9]*") - if(versionLine != null) { + if (versionLine != null) { return versionLine.split(": ").last() } return "" @@ -668,7 +744,103 @@ configure(updateBuildScript) { description = 'Updates the build script to the latest version' } -// Deobfuscation +// Parameter Deobfuscation + +task deobfParams { + doLast { + + String mcpDir = "$project.gradle.gradleUserHomeDir/caches/minecraft/de/oceanlabs/mcp/mcp_$channel/$mappingsVersion" + String mcpZIP = "$mcpDir/mcp_$channel-$mappingsVersion-${minecraftVersion}.zip" + String paramsCSV = "$mcpDir/params.csv" + + download.run { + src "https://maven.minecraftforge.net/de/oceanlabs/mcp/mcp_$channel/$mappingsVersion-$minecraftVersion/mcp_$channel-$mappingsVersion-${minecraftVersion}.zip" + dest mcpZIP + overwrite false + } + + if (!file(paramsCSV).exists()) { + println("Extracting MCP archive ...") + unzip(mcpZIP, mcpDir) + } + + println("Parsing params.csv ...") + Map params = new HashMap<>() + Files.lines(Paths.get(paramsCSV)).forEach { line -> + String[] cells = line.split(",") + if (cells.length > 2 && cells[0].matches("p_i?\\d+_\\d+_")) { + params.put(cells[0], cells[1]) + } + } + + out.style(Style.Success).println("Modified ${replaceParams(file("$projectDir/src/main/java"), params)} files!") + out.style(Style.Failure).println("Don't forget to verify that the code still works as before!\n It could be broken due to duplicate variables existing now\n or parameters taking priority over other variables.") + } +} + +static int replaceParams(File file, Map params) { + int fileCount = 0 + + if (file.isDirectory()) { + for (File f : file.listFiles()) { + fileCount += replaceParams(f, params) + } + return fileCount + } + println("Visiting ${file.getName()} ...") + try { + String content = new String(Files.readAllBytes(file.toPath())) + int hash = content.hashCode() + params.forEach { key, value -> + content = content.replaceAll(key, value) + } + if (hash != content.hashCode()) { + Files.write(file.toPath(), content.getBytes("UTF-8")) + return 1 + } + } catch (Exception e) { + e.printStackTrace() + } + return 0 +} + +// Credit: bitsnaps (https://gist.github.com/bitsnaps/00947f2dce66f4bbdabc67d7e7b33681) +static unzip(String zipFileName, String outputDir) { + byte[] buffer = new byte[16384] + ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName)) + ZipEntry zipEntry = zis.getNextEntry() + while (zipEntry != null) { + File newFile = new File(outputDir + File.separator, zipEntry.name) + if (zipEntry.isDirectory()) { + if (!newFile.isDirectory() && !newFile.mkdirs()) { + throw new IOException("Failed to create directory $newFile") + } + } else { + // fix for Windows-created archives + File parent = newFile.parentFile + if (!parent.isDirectory() && !parent.mkdirs()) { + throw new IOException("Failed to create directory $parent") + } + // write file content + FileOutputStream fos = new FileOutputStream(newFile) + int len = 0 + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len) + } + fos.close() + } + zipEntry = zis.getNextEntry() + } + zis.closeEntry() + zis.close() +} + +configure(deobfParams) { + group = 'forgegradle' + description = 'Rename all obfuscated parameter names inherited from Minecraft classes' +} + +// Dependency Deobfuscation def deobf(String sourceURL) { try { @@ -677,42 +849,57 @@ def deobf(String sourceURL) { //get rid of directories: int lastSlash = fileName.lastIndexOf("/") - if(lastSlash > 0) { + if (lastSlash > 0) { fileName = fileName.substring(lastSlash + 1) } //get rid of extension: - if(fileName.endsWith(".jar")) { + if (fileName.endsWith(".jar") || fileName.endsWith(".litemod")) { fileName = fileName.substring(0, fileName.lastIndexOf(".")) } String hostName = url.getHost() - if(hostName.startsWith("www.")) { + if (hostName.startsWith("www.")) { hostName = hostName.substring(4) } List parts = Arrays.asList(hostName.split("\\.")) Collections.reverse(parts) hostName = String.join(".", parts) - return deobf(sourceURL, hostName + "/" + fileName) - } catch(Exception e) { - return deobf(sourceURL, "deobf/" + String.valueOf(sourceURL.hashCode())) + return deobf(sourceURL, "$hostName/$fileName") + } catch (Exception e) { + return deobf(sourceURL, "deobf/${sourceURL.hashCode()}") } } // The method above is to be preferred. Use this method if the filename is not at the end of the URL. -def deobf(String sourceURL, String fileName) { - String cacheDir = System.getProperty("user.home") + "/.gradle/caches/" - String bon2Dir = cacheDir + "forge_gradle/deobf" - String bon2File = bon2Dir + "/BON2-2.5.0.jar" - String obfFile = cacheDir + "modules-2/files-2.1/" + fileName + ".jar" - String deobfFile = cacheDir + "modules-2/files-2.1/" + fileName + "-deobf.jar" - - if(file(deobfFile).exists()) { +def deobf(String sourceURL, String rawFileName) { + String bon2Version = "2.5.1" + String fileName = URLDecoder.decode(rawFileName, "UTF-8") + String cacheDir = "$project.gradle.gradleUserHomeDir/caches" + String bon2Dir = "$cacheDir/forge_gradle/deobf" + String bon2File = "$bon2Dir/BON2-${bon2Version}.jar" + String obfFile = "$cacheDir/modules-2/files-2.1/${fileName}.jar" + String deobfFile = "$cacheDir/modules-2/files-2.1/${fileName}-deobf.jar" + + if (file(deobfFile).exists()) { return files(deobfFile) } + String mappingsVer + String remoteMappings = project.hasProperty('remoteMappings') ? project.remoteMappings : 'https://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/conf/' + if (remoteMappings) { + String id = "${forgeVersion.split("\\.")[3]}-$minecraftVersion" + String mappingsZIP = "$cacheDir/forge_gradle/maven_downloader/de/oceanlabs/mcp/mcp_snapshot_nodoc/$id/mcp_snapshot_nodoc-${id}.zip" + + zipMappings(mappingsZIP, remoteMappings, bon2Dir) + + mappingsVer = "snapshot_$id" + } else { + mappingsVer = "${channel}_$mappingsVersion" + } + download.run { - src 'https://github.com/GTNewHorizons/BON2/releases/download/2.5.0/BON2-2.5.0.CUSTOM-all.jar' + src "http://jenkins.usrv.eu:8081/nexus/content/repositories/releases/com/github/parker8283/BON2/$bon2Version-CUSTOM/BON2-$bon2Version-CUSTOM-all.jar" dest bon2File quiet true overwrite false @@ -726,14 +913,48 @@ def deobf(String sourceURL, String fileName) { } exec { - commandLine 'java', '-jar', bon2File, '--inputJar', obfFile, '--outputJar', deobfFile, '--mcVer', '1.7.10', '--mappingsVer', 'stable_12', '--notch' + commandLine 'java', '-jar', bon2File, '--inputJar', obfFile, '--outputJar', deobfFile, '--mcVer', minecraftVersion, '--mappingsVer', mappingsVer, '--notch' workingDir bon2Dir - standardOutput = new ByteArrayOutputStream() + standardOutput = new FileOutputStream("${deobfFile}.log") } return files(deobfFile) } +def zipMappings(String zipPath, String url, String bon2Dir) { + File zipFile = new File(zipPath) + if (zipFile.exists()) { + return + } + + String fieldsCache = "$bon2Dir/data/fields.csv" + String methodsCache = "$bon2Dir/data/methods.csv" + + download.run { + src "${url}fields.csv" + dest fieldsCache + quiet true + } + download.run { + src "${url}methods.csv" + dest methodsCache + quiet true + } + + zipFile.getParentFile().mkdirs() + ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)) + + zos.putNextEntry(new ZipEntry("fields.csv")) + Files.copy(Paths.get(fieldsCache), zos) + zos.closeEntry() + + zos.putNextEntry(new ZipEntry("methods.csv")) + Files.copy(Paths.get(methodsCache), zos) + zos.closeEntry() + + zos.close() +} + // Helper methods def checkPropertyExists(String propertyName) { diff --git a/dependencies.gradle b/dependencies.gradle index 4381c66044e..e086ce83e2a 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -1,18 +1,18 @@ // Add your dependencies here dependencies { - compile('com.github.GTNewHorizons:CodeChickenLib:1.1.5.3:dev') - compile('com.github.GTNewHorizons:NotEnoughItems:2.2.12-GTNH:dev') - compile('curse.maven:cofh-core-69162:2388751') + compile('com.github.GTNewHorizons:CodeChickenLib:1.1.5.5:dev') + compile('com.github.GTNewHorizons:NotEnoughItems:2.2.33-GTNH:dev') + compile('curse.maven:cofh-core-69162:2388751') compileOnly('com.github.GTNewHorizons:BuildCraft:7.1.27:dev') {transitive = false} - compileOnly('com.github.GTNewHorizons:ForgeMultipart:1.2.7:dev') {transitive = false} - compileOnly('com.github.GTNewHorizons:GT5-Unofficial:5.09.40.34:dev') {transitive = false} - compileOnly('com.github.GTNewHorizons:Jabba:1.2.13:dev') {transitive = false} - compileOnly('com.github.GTNewHorizons:inventory-tweaks:1.5.14:api') {transitive = false} - compileOnly('com.github.GTNewHorizons:OpenComputers:1.7.5.23-GTNH:api') {transitive = false} - compileOnly('com.github.GTNewHorizons:waila:1.5.19:api') {transitive = false} - compileOnly('com.github.GTNewHorizons:Railcraft:9.13.6:api') {transitive = false} + compileOnly('com.github.GTNewHorizons:ForgeMultipart:1.2.8:dev') {transitive = false} + compileOnly('com.github.GTNewHorizons:GT5-Unofficial:5.09.41.18:dev') {transitive = false} + compileOnly('com.github.GTNewHorizons:Jabba:1.2.21:dev') {transitive = false} + compileOnly('com.github.GTNewHorizons:inventory-tweaks:1.5.15:api') {transitive = false} + compileOnly('com.github.GTNewHorizons:OpenComputers:1.7.5.32-GTNH:api') {transitive = false} + compileOnly('com.github.GTNewHorizons:waila:1.5.21:api') {transitive = false} + compileOnly('com.github.GTNewHorizons:Railcraft:9.13.10:api') {transitive = false} compileOnly('net.industrial-craft:industrialcraft-2:2.2.828-experimental:api') compileOnly('curse.maven:minefactory-reloaded-66672:2366150') diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000000..93c852a12ca --- /dev/null +++ b/settings.gradle @@ -0,0 +1,10 @@ +plugins { + id 'com.diffplug.blowdryerSetup' version '1.6.0' +} + +apply plugin: 'com.diffplug.blowdryerSetup' + +blowdryerSetup { + github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.1.5') + //devLocal '.' // Use this when testing config updates locally +} diff --git a/src/main/java/appeng/api/AEApi.java b/src/main/java/appeng/api/AEApi.java index dd5005f43e4..a0407609161 100644 --- a/src/main/java/appeng/api/AEApi.java +++ b/src/main/java/appeng/api/AEApi.java @@ -23,56 +23,45 @@ package appeng.api; - import appeng.api.exceptions.CoreInaccessibleException; - import java.lang.reflect.Field; - /** * Entry point for api. *

* Available IMCs: */ -public enum AEApi -{ - ; - - private static final String CORE_API_FQN = "appeng.core.Api"; - private static final String CORE_API_FIELD = "INSTANCE"; - private static final IAppEngApi HELD_API; +public enum AEApi { + ; - static - { - try - { - final Class apiClass = Class.forName( CORE_API_FQN ); - final Field apiField = apiClass.getField( CORE_API_FIELD ); + private static final String CORE_API_FQN = "appeng.core.Api"; + private static final String CORE_API_FIELD = "INSTANCE"; + private static final IAppEngApi HELD_API; - HELD_API = (IAppEngApi) apiField.get( apiClass ); - } - catch( final ClassNotFoundException e ) - { - throw new CoreInaccessibleException( "AE2 API tried to access the " + CORE_API_FQN + " class, without it being declared." ); - } - catch( final NoSuchFieldException e ) - { - throw new CoreInaccessibleException( "AE2 API tried to access the " + CORE_API_FIELD + " field in " + CORE_API_FQN + " without it being declared." ); - } - catch( final IllegalAccessException e ) - { - throw new CoreInaccessibleException( "AE2 API tried to access the " + CORE_API_FIELD + " field in " + CORE_API_FQN + " without enough access permissions." ); - } - } + static { + try { + final Class apiClass = Class.forName(CORE_API_FQN); + final Field apiField = apiClass.getField(CORE_API_FIELD); - /** - * API Entry Point. - * - * @return the {@link IAppEngApi} - */ - public static IAppEngApi instance() - { - return HELD_API; - } + HELD_API = (IAppEngApi) apiField.get(apiClass); + } catch (final ClassNotFoundException e) { + throw new CoreInaccessibleException( + "AE2 API tried to access the " + CORE_API_FQN + " class, without it being declared."); + } catch (final NoSuchFieldException e) { + throw new CoreInaccessibleException("AE2 API tried to access the " + CORE_API_FIELD + " field in " + + CORE_API_FQN + " without it being declared."); + } catch (final IllegalAccessException e) { + throw new CoreInaccessibleException("AE2 API tried to access the " + CORE_API_FIELD + " field in " + + CORE_API_FQN + " without enough access permissions."); + } + } + /** + * API Entry Point. + * + * @return the {@link IAppEngApi} + */ + public static IAppEngApi instance() { + return HELD_API; + } } diff --git a/src/main/java/appeng/api/IAppEngApi.java b/src/main/java/appeng/api/IAppEngApi.java index 453ec979fcd..d9808c413de 100644 --- a/src/main/java/appeng/api/IAppEngApi.java +++ b/src/main/java/appeng/api/IAppEngApi.java @@ -23,7 +23,6 @@ package appeng.api; - import appeng.api.definitions.*; import appeng.api.exceptions.FailedConnection; import appeng.api.features.IRegistryContainer; @@ -33,72 +32,70 @@ import appeng.api.parts.IPartHelper; import appeng.api.storage.IStorageHelper; +public interface IAppEngApi { -public interface IAppEngApi -{ - - /** - * @return Registry Container for the numerous registries in AE2. - */ - IRegistryContainer registries(); + /** + * @return Registry Container for the numerous registries in AE2. + */ + IRegistryContainer registries(); - /** - * @return helper for working with storage data types. - */ - IStorageHelper storage(); + /** + * @return helper for working with storage data types. + */ + IStorageHelper storage(); - /** - * @return helper for working with grids, and buses. - */ - IPartHelper partHelper(); + /** + * @return helper for working with grids, and buses. + */ + IPartHelper partHelper(); - /** - * @return an accessible list of all of AE's Items - * @deprecated use {@link appeng.api.definitions.IDefinitions#items()} - */ - @Deprecated - Items items(); + /** + * @return an accessible list of all of AE's Items + * @deprecated use {@link appeng.api.definitions.IDefinitions#items()} + */ + @Deprecated + Items items(); - /** - * @return an accessible list of all of AE's materials; materials are items - * @deprecated use {@link appeng.api.definitions.IDefinitions#materials()} - */ - @Deprecated - Materials materials(); + /** + * @return an accessible list of all of AE's materials; materials are items + * @deprecated use {@link appeng.api.definitions.IDefinitions#materials()} + */ + @Deprecated + Materials materials(); - /** - * @return an accessible list of all of AE's blocks - * @deprecated use {@link appeng.api.definitions.IDefinitions#blocks()} - */ - @Deprecated - Blocks blocks(); + /** + * @return an accessible list of all of AE's blocks + * @deprecated use {@link appeng.api.definitions.IDefinitions#blocks()} + */ + @Deprecated + Blocks blocks(); - /** - * @return an accessible list of all of AE's parts, parts are items - * @deprecated use {@link appeng.api.definitions.IDefinitions#parts()} - */ - @Deprecated - Parts parts(); + /** + * @return an accessible list of all of AE's parts, parts are items + * @deprecated use {@link appeng.api.definitions.IDefinitions#parts()} + */ + @Deprecated + Parts parts(); - /** - * @return an accessible list of all AE definitions - */ - IDefinitions definitions(); + /** + * @return an accessible list of all AE definitions + */ + IDefinitions definitions(); - /** - * create a grid node for your {@link appeng.api.networking.IGridHost} - * - * @param block grid block - * @return grid node of block - */ - IGridNode createGridNode( IGridBlock block ); + /** + * create a grid node for your {@link appeng.api.networking.IGridHost} + * + * @param block grid block + * @return grid node of block + */ + IGridNode createGridNode(IGridBlock block); - /** - * create a connection between two {@link appeng.api.networking.IGridNode} - * - * @param a to be connected gridnode - * @param b to be connected gridnode - * @throws appeng.api.exceptions.FailedConnection - */ - IGridConnection createGridConnection( IGridNode a, IGridNode b ) throws FailedConnection; -} \ No newline at end of file + /** + * create a connection between two {@link appeng.api.networking.IGridNode} + * + * @param a to be connected gridnode + * @param b to be connected gridnode + * @throws appeng.api.exceptions.FailedConnection + */ + IGridConnection createGridConnection(IGridNode a, IGridNode b) throws FailedConnection; +} diff --git a/src/main/java/appeng/api/config/AccessRestriction.java b/src/main/java/appeng/api/config/AccessRestriction.java index 6788d744e91..8385c82e6a4 100644 --- a/src/main/java/appeng/api/config/AccessRestriction.java +++ b/src/main/java/appeng/api/config/AccessRestriction.java @@ -23,51 +23,45 @@ package appeng.api.config; +public enum AccessRestriction { + NO_ACCESS(0), + READ(1), + WRITE(2), + READ_WRITE(3); -public enum AccessRestriction -{ - NO_ACCESS( 0 ), READ( 1 ), WRITE( 2 ), READ_WRITE( 3 ); + private final int permissionBit; - private final int permissionBit; + AccessRestriction(final int v) { + this.permissionBit = v; + } - AccessRestriction( final int v ) - { - this.permissionBit = v; - } + public boolean hasPermission(final AccessRestriction ar) { + return (this.permissionBit & ar.permissionBit) == ar.permissionBit; + } - public boolean hasPermission( final AccessRestriction ar ) - { - return ( this.permissionBit & ar.permissionBit ) == ar.permissionBit; - } + public AccessRestriction restrictPermissions(final AccessRestriction ar) { + return this.getPermByBit(this.permissionBit & ar.permissionBit); + } - public AccessRestriction restrictPermissions( final AccessRestriction ar ) - { - return this.getPermByBit( this.permissionBit & ar.permissionBit ); - } + private AccessRestriction getPermByBit(final int bit) { + switch (bit) { + default: + case 0: + return NO_ACCESS; + case 1: + return READ; + case 2: + return WRITE; + case 3: + return READ_WRITE; + } + } - private AccessRestriction getPermByBit( final int bit ) - { - switch( bit ) - { - default: - case 0: - return NO_ACCESS; - case 1: - return READ; - case 2: - return WRITE; - case 3: - return READ_WRITE; - } - } + public AccessRestriction addPermissions(final AccessRestriction ar) { + return this.getPermByBit(this.permissionBit | ar.permissionBit); + } - public AccessRestriction addPermissions( final AccessRestriction ar ) - { - return this.getPermByBit( this.permissionBit | ar.permissionBit ); - } - - public AccessRestriction removePermissions( final AccessRestriction ar ) - { - return this.getPermByBit( this.permissionBit & ( ~ar.permissionBit ) ); - } -} \ No newline at end of file + public AccessRestriction removePermissions(final AccessRestriction ar) { + return this.getPermByBit(this.permissionBit & (~ar.permissionBit)); + } +} diff --git a/src/main/java/appeng/api/config/ActionItems.java b/src/main/java/appeng/api/config/ActionItems.java index 39cf1e3c123..9961e9df7e4 100644 --- a/src/main/java/appeng/api/config/ActionItems.java +++ b/src/main/java/appeng/api/config/ActionItems.java @@ -23,16 +23,20 @@ package appeng.api.config; - -public enum ActionItems -{ - WRENCH, CLOSE, STASH, ENCODE, SUBSTITUTION, SLOT_CONFIG, ORE_FILTER, DOUBLE, - MOLECULAR_ASSEMBLEERS_ON, - MOLECULAR_ASSEMBLEERS_OFF, - TOGGLE_SHOW_FULL_INTERFACES_ON, - TOGGLE_SHOW_FULL_INTERFACES_OFF, - TOGGLE_SHOW_ONLY_INVALID_PATTERN_ON, - TOGGLE_SHOW_ONLY_INVALID_PATTERN_OFF, - HIGHLIGHT_INTERFACE - -} \ No newline at end of file +public enum ActionItems { + WRENCH, + CLOSE, + STASH, + ENCODE, + SUBSTITUTION, + SLOT_CONFIG, + ORE_FILTER, + DOUBLE, + MOLECULAR_ASSEMBLEERS_ON, + MOLECULAR_ASSEMBLEERS_OFF, + TOGGLE_SHOW_FULL_INTERFACES_ON, + TOGGLE_SHOW_FULL_INTERFACES_OFF, + TOGGLE_SHOW_ONLY_INVALID_PATTERN_ON, + TOGGLE_SHOW_ONLY_INVALID_PATTERN_OFF, + HIGHLIGHT_INTERFACE +} diff --git a/src/main/java/appeng/api/config/Actionable.java b/src/main/java/appeng/api/config/Actionable.java index 8e5f1f5422b..93835e62ade 100644 --- a/src/main/java/appeng/api/config/Actionable.java +++ b/src/main/java/appeng/api/config/Actionable.java @@ -23,16 +23,14 @@ package appeng.api.config; +public enum Actionable { + /** + * Perform the intended action. + */ + MODULATE, -public enum Actionable -{ - /** - * Perform the intended action. - */ - MODULATE, - - /** - * Pretend to perform the action. - */ - SIMULATE + /** + * Pretend to perform the action. + */ + SIMULATE } diff --git a/src/main/java/appeng/api/config/CondenserOutput.java b/src/main/java/appeng/api/config/CondenserOutput.java index cb9efae00b2..03483eb4d27 100644 --- a/src/main/java/appeng/api/config/CondenserOutput.java +++ b/src/main/java/appeng/api/config/CondenserOutput.java @@ -23,16 +23,12 @@ package appeng.api.config; +public enum CondenserOutput { + TRASH, // 0 -public enum CondenserOutput -{ + MATTER_BALLS, // 256 - TRASH, // 0 + SINGULARITY; // 250,000 - MATTER_BALLS, // 256 - - SINGULARITY; // 250,000 - - public int requiredPower = 0; - -} \ No newline at end of file + public int requiredPower = 0; +} diff --git a/src/main/java/appeng/api/config/CopyMode.java b/src/main/java/appeng/api/config/CopyMode.java index 7f2f39969cc..b55d70df6c7 100644 --- a/src/main/java/appeng/api/config/CopyMode.java +++ b/src/main/java/appeng/api/config/CopyMode.java @@ -23,8 +23,7 @@ package appeng.api.config; - -public enum CopyMode -{ - CLEAR_ON_REMOVE, KEEP_ON_REMOVE +public enum CopyMode { + CLEAR_ON_REMOVE, + KEEP_ON_REMOVE } diff --git a/src/main/java/appeng/api/config/FullnessMode.java b/src/main/java/appeng/api/config/FullnessMode.java index c52d4228f33..423c9cd5ff2 100644 --- a/src/main/java/appeng/api/config/FullnessMode.java +++ b/src/main/java/appeng/api/config/FullnessMode.java @@ -23,8 +23,8 @@ package appeng.api.config; - -public enum FullnessMode -{ - EMPTY, HALF, FULL -} \ No newline at end of file +public enum FullnessMode { + EMPTY, + HALF, + FULL +} diff --git a/src/main/java/appeng/api/config/FuzzyMode.java b/src/main/java/appeng/api/config/FuzzyMode.java index 665dd551aa5..1d403a4fa75 100644 --- a/src/main/java/appeng/api/config/FuzzyMode.java +++ b/src/main/java/appeng/api/config/FuzzyMode.java @@ -23,24 +23,23 @@ package appeng.api.config; +public enum FuzzyMode { + // Note that percentage damaged, is the inverse of percentage durability. + IGNORE_ALL(-1), + PERCENT_99(0), + PERCENT_75(25), + PERCENT_50(50), + PERCENT_25(75); -public enum FuzzyMode -{ - // Note that percentage damaged, is the inverse of percentage durability. - IGNORE_ALL( -1 ), PERCENT_99( 0 ), PERCENT_75( 25 ), PERCENT_50( 50 ), PERCENT_25( 75 ); + public final float breakPoint; + public final float percentage; - public final float breakPoint; - public final float percentage; + FuzzyMode(final float p) { + this.percentage = p; + this.breakPoint = p / 100.0f; + } - FuzzyMode( final float p ) - { - this.percentage = p; - this.breakPoint = p / 100.0f; - } - - public int calculateBreakPoint( final int maxDamage ) - { - return (int) ( ( this.percentage * maxDamage ) / 100.0f ); - } - -} \ No newline at end of file + public int calculateBreakPoint(final int maxDamage) { + return (int) ((this.percentage * maxDamage) / 100.0f); + } +} diff --git a/src/main/java/appeng/api/config/IncludeExclude.java b/src/main/java/appeng/api/config/IncludeExclude.java index 53f0bbeb761..7aae32b7996 100644 --- a/src/main/java/appeng/api/config/IncludeExclude.java +++ b/src/main/java/appeng/api/config/IncludeExclude.java @@ -23,8 +23,7 @@ package appeng.api.config; - -public enum IncludeExclude -{ - WHITELIST, BLACKLIST -} \ No newline at end of file +public enum IncludeExclude { + WHITELIST, + BLACKLIST +} diff --git a/src/main/java/appeng/api/config/InsertionMode.java b/src/main/java/appeng/api/config/InsertionMode.java index 085ef407389..b34f8b6885a 100644 --- a/src/main/java/appeng/api/config/InsertionMode.java +++ b/src/main/java/appeng/api/config/InsertionMode.java @@ -1,6 +1,7 @@ package appeng.api.config; -public enum InsertionMode -{ - DEFAULT, PREFER_EMPTY, ONLY_EMPTY; +public enum InsertionMode { + DEFAULT, + PREFER_EMPTY, + ONLY_EMPTY; } diff --git a/src/main/java/appeng/api/config/ItemSubstitution.java b/src/main/java/appeng/api/config/ItemSubstitution.java index 9c4b4706a61..e32ec6ea6c1 100644 --- a/src/main/java/appeng/api/config/ItemSubstitution.java +++ b/src/main/java/appeng/api/config/ItemSubstitution.java @@ -23,8 +23,7 @@ package appeng.api.config; - -public enum ItemSubstitution -{ - ENABLED, DISABLED +public enum ItemSubstitution { + ENABLED, + DISABLED } diff --git a/src/main/java/appeng/api/config/LevelEmitterMode.java b/src/main/java/appeng/api/config/LevelEmitterMode.java index dcdd0ef88c1..03ac44971f4 100644 --- a/src/main/java/appeng/api/config/LevelEmitterMode.java +++ b/src/main/java/appeng/api/config/LevelEmitterMode.java @@ -23,12 +23,8 @@ package appeng.api.config; +public enum LevelEmitterMode { + STORED_AMOUNT, -public enum LevelEmitterMode -{ - - STORED_AMOUNT, - - STORABLE_AMOUNT - -} \ No newline at end of file + STORABLE_AMOUNT +} diff --git a/src/main/java/appeng/api/config/LevelType.java b/src/main/java/appeng/api/config/LevelType.java index 0787abb750c..8f07398473b 100644 --- a/src/main/java/appeng/api/config/LevelType.java +++ b/src/main/java/appeng/api/config/LevelType.java @@ -23,12 +23,8 @@ package appeng.api.config; +public enum LevelType { + ITEM_LEVEL, -public enum LevelType -{ - - ITEM_LEVEL, - - ENERGY_LEVEL - -} \ No newline at end of file + ENERGY_LEVEL +} diff --git a/src/main/java/appeng/api/config/ModSettings.java b/src/main/java/appeng/api/config/ModSettings.java index b1225844600..097053603e1 100644 --- a/src/main/java/appeng/api/config/ModSettings.java +++ b/src/main/java/appeng/api/config/ModSettings.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum ModSettings -{ - -} +public enum ModSettings {} diff --git a/src/main/java/appeng/api/config/NetworkEmitterMode.java b/src/main/java/appeng/api/config/NetworkEmitterMode.java index 03efd7c9821..73178902e76 100644 --- a/src/main/java/appeng/api/config/NetworkEmitterMode.java +++ b/src/main/java/appeng/api/config/NetworkEmitterMode.java @@ -23,14 +23,10 @@ package appeng.api.config; +public enum NetworkEmitterMode { + POWER_LEVEL, -public enum NetworkEmitterMode -{ + BOOTING, - POWER_LEVEL, - - BOOTING, - - CHANNEL_ERROR - -} \ No newline at end of file + CHANNEL_ERROR +} diff --git a/src/main/java/appeng/api/config/OperationMode.java b/src/main/java/appeng/api/config/OperationMode.java index f2c8ff30e0e..4a4cccaaac1 100644 --- a/src/main/java/appeng/api/config/OperationMode.java +++ b/src/main/java/appeng/api/config/OperationMode.java @@ -23,8 +23,7 @@ package appeng.api.config; - -public enum OperationMode -{ - FILL, EMPTY -} \ No newline at end of file +public enum OperationMode { + FILL, + EMPTY +} diff --git a/src/main/java/appeng/api/config/OutputMode.java b/src/main/java/appeng/api/config/OutputMode.java index f9bcffa5792..252dc0a078f 100644 --- a/src/main/java/appeng/api/config/OutputMode.java +++ b/src/main/java/appeng/api/config/OutputMode.java @@ -23,8 +23,8 @@ package appeng.api.config; - -public enum OutputMode -{ - EXPORT_ONLY, EXPORT_OR_CRAFT, CRAFT_ONLY +public enum OutputMode { + EXPORT_ONLY, + EXPORT_OR_CRAFT, + CRAFT_ONLY } diff --git a/src/main/java/appeng/api/config/PatternSlotConfig.java b/src/main/java/appeng/api/config/PatternSlotConfig.java index 3d18b13ce58..02b2d98f0fe 100644 --- a/src/main/java/appeng/api/config/PatternSlotConfig.java +++ b/src/main/java/appeng/api/config/PatternSlotConfig.java @@ -1,5 +1,6 @@ package appeng.api.config; public enum PatternSlotConfig { - C_16_4, C_4_16 + C_16_4, + C_4_16 } diff --git a/src/main/java/appeng/api/config/PowerMultiplier.java b/src/main/java/appeng/api/config/PowerMultiplier.java index dd50e79eb53..3f2bc4721cb 100644 --- a/src/main/java/appeng/api/config/PowerMultiplier.java +++ b/src/main/java/appeng/api/config/PowerMultiplier.java @@ -23,23 +23,20 @@ package appeng.api.config; +public enum PowerMultiplier { + ONE, + CONFIG; -public enum PowerMultiplier -{ - ONE, CONFIG; + /** + * please do not edit this value, it is set when AE loads its config files. + */ + public double multiplier = 1.0; - /** - * please do not edit this value, it is set when AE loads its config files. - */ - public double multiplier = 1.0; + public double multiply(final double in) { + return in * this.multiplier; + } - public double multiply( final double in ) - { - return in * this.multiplier; - } - - public double divide( final double in ) - { - return in / this.multiplier; - } + public double divide(final double in) { + return in / this.multiplier; + } } diff --git a/src/main/java/appeng/api/config/PowerUnits.java b/src/main/java/appeng/api/config/PowerUnits.java index b6389413ae6..e5125ea5c0a 100644 --- a/src/main/java/appeng/api/config/PowerUnits.java +++ b/src/main/java/appeng/api/config/PowerUnits.java @@ -23,43 +23,38 @@ package appeng.api.config; +public enum PowerUnits { + AE("gui.appliedenergistics2.units.appliedenergstics"), // Native Units - AE Energy + EU("gui.appliedenergistics2.units.ic2"), // IndustrialCraft 2 - Energy Units + WA("gui.appliedenergistics2.units.rotarycraft"), // RotaryCraft - Watts + RF("gui.appliedenergistics2.units.thermalexpansion"), // ThermalExpansion - Redstone Flux + MK("gui.appliedenergistics2.units.mekanism"); // Mekanism - Joules -public enum PowerUnits -{ - AE( "gui.appliedenergistics2.units.appliedenergstics" ), // Native Units - AE Energy - EU( "gui.appliedenergistics2.units.ic2" ), // IndustrialCraft 2 - Energy Units - WA( "gui.appliedenergistics2.units.rotarycraft" ), // RotaryCraft - Watts - RF( "gui.appliedenergistics2.units.thermalexpansion" ), // ThermalExpansion - Redstone Flux - MK( "gui.appliedenergistics2.units.mekanism" ); // Mekanism - Joules + /** + * unlocalized name for the power unit. + */ + public final String unlocalizedName; + /** + * please do not edit this value, it is set when AE loads its config files. + */ + public double conversionRatio = 1.0; - /** - * unlocalized name for the power unit. - */ - public final String unlocalizedName; - /** - * please do not edit this value, it is set when AE loads its config files. - */ - public double conversionRatio = 1.0; + PowerUnits(final String un) { + this.unlocalizedName = un; + } - PowerUnits( final String un ) - { - this.unlocalizedName = un; - } - - /** - * do power conversion using AE's conversion rates. - *

- * Example: PowerUnits.EU.convertTo( PowerUnits.AE, 32 ); - *

- * will normally returns 64, as it will convert the EU, to AE with AE's power settings. - * - * @param target target power unit - * @param value value - * @return value converted to target units, from this units. - */ - public double convertTo( final PowerUnits target, final double value ) - { - return ( value * this.conversionRatio ) / target.conversionRatio; - } - -} \ No newline at end of file + /** + * do power conversion using AE's conversion rates. + *

+ * Example: PowerUnits.EU.convertTo( PowerUnits.AE, 32 ); + *

+ * will normally returns 64, as it will convert the EU, to AE with AE's power settings. + * + * @param target target power unit + * @param value value + * @return value converted to target units, from this units. + */ + public double convertTo(final PowerUnits target, final double value) { + return (value * this.conversionRatio) / target.conversionRatio; + } +} diff --git a/src/main/java/appeng/api/config/RedstoneMode.java b/src/main/java/appeng/api/config/RedstoneMode.java index 0bb5a54da7d..bd4b0073e0d 100644 --- a/src/main/java/appeng/api/config/RedstoneMode.java +++ b/src/main/java/appeng/api/config/RedstoneMode.java @@ -23,8 +23,9 @@ package appeng.api.config; - -public enum RedstoneMode -{ - IGNORE, LOW_SIGNAL, HIGH_SIGNAL, SIGNAL_PULSE -} \ No newline at end of file +public enum RedstoneMode { + IGNORE, + LOW_SIGNAL, + HIGH_SIGNAL, + SIGNAL_PULSE +} diff --git a/src/main/java/appeng/api/config/RelativeDirection.java b/src/main/java/appeng/api/config/RelativeDirection.java index a81d20473ff..7c598a0bc25 100644 --- a/src/main/java/appeng/api/config/RelativeDirection.java +++ b/src/main/java/appeng/api/config/RelativeDirection.java @@ -23,8 +23,9 @@ package appeng.api.config; - -public enum RelativeDirection -{ - LEFT, RIGHT, UP, DOW -} \ No newline at end of file +public enum RelativeDirection { + LEFT, + RIGHT, + UP, + DOW +} diff --git a/src/main/java/appeng/api/config/SchedulingMode.java b/src/main/java/appeng/api/config/SchedulingMode.java index 395bf1ece8c..ee3ad2a99c6 100644 --- a/src/main/java/appeng/api/config/SchedulingMode.java +++ b/src/main/java/appeng/api/config/SchedulingMode.java @@ -23,8 +23,8 @@ package appeng.api.config; - -public enum SchedulingMode -{ - DEFAULT, ROUNDROBIN, RANDOM +public enum SchedulingMode { + DEFAULT, + ROUNDROBIN, + RANDOM } diff --git a/src/main/java/appeng/api/config/SearchBoxMode.java b/src/main/java/appeng/api/config/SearchBoxMode.java index 6711b895da1..275f873882e 100644 --- a/src/main/java/appeng/api/config/SearchBoxMode.java +++ b/src/main/java/appeng/api/config/SearchBoxMode.java @@ -23,13 +23,9 @@ package appeng.api.config; - -public enum SearchBoxMode -{ - - MANUAL_SEARCH, // ------- - AUTOSEARCH, // autofocus - NEI_AUTOSEARCH, // autofocus + NEISync - NEI_MANUAL_SEARCH // NEISync - +public enum SearchBoxMode { + MANUAL_SEARCH, // ------- + AUTOSEARCH, // autofocus + NEI_AUTOSEARCH, // autofocus + NEISync + NEI_MANUAL_SEARCH // NEISync } diff --git a/src/main/java/appeng/api/config/SecurityPermissions.java b/src/main/java/appeng/api/config/SecurityPermissions.java index c3e69062a2a..8174d4e3fdb 100644 --- a/src/main/java/appeng/api/config/SecurityPermissions.java +++ b/src/main/java/appeng/api/config/SecurityPermissions.java @@ -23,49 +23,46 @@ package appeng.api.config; - /** * Represent the security systems basic permissions, these are not for anti-griefing, they are part of the mod as a * gameplay feature. */ -public enum SecurityPermissions -{ - /** - * required to insert items into the network via terminal ( also used for machines based on the owner of the - * network, which is determined by its Security Block. ) - */ - INJECT, +public enum SecurityPermissions { + /** + * required to insert items into the network via terminal ( also used for machines based on the owner of the + * network, which is determined by its Security Block. ) + */ + INJECT, - /** - * required to extract items from the network via terminal ( also used for machines based on the owner of the - * network, which is determined by its Security Block. ) - */ - EXTRACT, + /** + * required to extract items from the network via terminal ( also used for machines based on the owner of the + * network, which is determined by its Security Block. ) + */ + EXTRACT, - /** - * required to request crafting from the network via terminal. - */ - CRAFT, + /** + * required to request crafting from the network via terminal. + */ + CRAFT, - /** - * required to modify automation, and make modifications to the networks physical layout. - */ - BUILD, + /** + * required to modify automation, and make modifications to the networks physical layout. + */ + BUILD, - /** - * required to modify the security blocks settings. - */ - SECURITY; + /** + * required to modify the security blocks settings. + */ + SECURITY; - private final String unlocalizedName = "gui.appliedenergistics2.security." + this.name().toLowerCase(); + private final String unlocalizedName = + "gui.appliedenergistics2.security." + this.name().toLowerCase(); - public String getUnlocalizedName() - { - return this.unlocalizedName + ".name"; - } + public String getUnlocalizedName() { + return this.unlocalizedName + ".name"; + } - public String getUnlocalizedTip() - { - return this.unlocalizedName + ".tip"; - } + public String getUnlocalizedTip() { + return this.unlocalizedName + ".tip"; + } } diff --git a/src/main/java/appeng/api/config/Settings.java b/src/main/java/appeng/api/config/Settings.java index 0cb35b84496..c1e7f209893 100644 --- a/src/main/java/appeng/api/config/Settings.java +++ b/src/main/java/appeng/api/config/Settings.java @@ -23,58 +23,65 @@ package appeng.api.config; - -import javax.annotation.Nonnull; import java.util.EnumSet; +import javax.annotation.Nonnull; +public enum Settings { + LEVEL_EMITTER_MODE(EnumSet.allOf(LevelEmitterMode.class)), -public enum Settings -{ - LEVEL_EMITTER_MODE( EnumSet.allOf( LevelEmitterMode.class ) ), - - REDSTONE_EMITTER( EnumSet.of( RedstoneMode.HIGH_SIGNAL, RedstoneMode.LOW_SIGNAL ) ), REDSTONE_CONTROLLED( EnumSet.allOf( RedstoneMode.class ) ), - - CONDENSER_OUTPUT( EnumSet.allOf( CondenserOutput.class ) ), + REDSTONE_EMITTER(EnumSet.of(RedstoneMode.HIGH_SIGNAL, RedstoneMode.LOW_SIGNAL)), + REDSTONE_CONTROLLED(EnumSet.allOf(RedstoneMode.class)), - POWER_UNITS( EnumSet.allOf( PowerUnits.class ) ), ACCESS( EnumSet.of( AccessRestriction.READ_WRITE, AccessRestriction.READ, AccessRestriction.WRITE ) ), + CONDENSER_OUTPUT(EnumSet.allOf(CondenserOutput.class)), - SORT_DIRECTION( EnumSet.allOf( SortDir.class ) ), SORT_BY( EnumSet.allOf( SortOrder.class ) ), + POWER_UNITS(EnumSet.allOf(PowerUnits.class)), + ACCESS(EnumSet.of(AccessRestriction.READ_WRITE, AccessRestriction.READ, AccessRestriction.WRITE)), - SEARCH_TOOLTIPS( EnumSet.of( YesNo.YES, YesNo.NO ) ), VIEW_MODE( EnumSet.allOf( ViewItems.class ) ), SEARCH_MODE( EnumSet.allOf( SearchBoxMode.class ) ), + SORT_DIRECTION(EnumSet.allOf(SortDir.class)), + SORT_BY(EnumSet.allOf(SortOrder.class)), - ACTIONS( EnumSet.allOf( ActionItems.class ) ), IO_DIRECTION( EnumSet.of( RelativeDirection.LEFT, RelativeDirection.RIGHT ) ), + SEARCH_TOOLTIPS(EnumSet.of(YesNo.YES, YesNo.NO)), + VIEW_MODE(EnumSet.allOf(ViewItems.class)), + SEARCH_MODE(EnumSet.allOf(SearchBoxMode.class)), - BLOCK( EnumSet.of( YesNo.YES, YesNo.NO ) ), OPERATION_MODE( EnumSet.allOf( OperationMode.class ) ), + ACTIONS(EnumSet.allOf(ActionItems.class)), + IO_DIRECTION(EnumSet.of(RelativeDirection.LEFT, RelativeDirection.RIGHT)), - FULLNESS_MODE( EnumSet.allOf( FullnessMode.class ) ), CRAFT_ONLY( EnumSet.of( YesNo.YES, YesNo.NO ) ), + BLOCK(EnumSet.of(YesNo.YES, YesNo.NO)), + OPERATION_MODE(EnumSet.allOf(OperationMode.class)), - FUZZY_MODE( EnumSet.allOf( FuzzyMode.class ) ), LEVEL_TYPE( EnumSet.allOf( LevelType.class ) ), + FULLNESS_MODE(EnumSet.allOf(FullnessMode.class)), + CRAFT_ONLY(EnumSet.of(YesNo.YES, YesNo.NO)), - TERMINAL_STYLE( EnumSet.of( TerminalStyle.TALL, TerminalStyle.SMALL ) ), COPY_MODE( EnumSet.allOf( CopyMode.class ) ), + FUZZY_MODE(EnumSet.allOf(FuzzyMode.class)), + LEVEL_TYPE(EnumSet.allOf(LevelType.class)), - INTERFACE_TERMINAL( EnumSet.of( YesNo.YES, YesNo.NO ) ), CRAFT_VIA_REDSTONE( EnumSet.of( YesNo.YES, YesNo.NO ) ), + TERMINAL_STYLE(EnumSet.of(TerminalStyle.TALL, TerminalStyle.SMALL)), + COPY_MODE(EnumSet.allOf(CopyMode.class)), - STORAGE_FILTER( EnumSet.allOf( StorageFilter.class ) ), PLACE_BLOCK( EnumSet.of( YesNo.YES, YesNo.NO ) ), + INTERFACE_TERMINAL(EnumSet.of(YesNo.YES, YesNo.NO)), + CRAFT_VIA_REDSTONE(EnumSet.of(YesNo.YES, YesNo.NO)), - SCHEDULING_MODE( EnumSet.allOf( SchedulingMode.class ) ), SAVE_SEARCH( EnumSet.of( YesNo.YES, YesNo.NO ) ), CRAFTING_STATUS( EnumSet.allOf( CraftingStatus.class ) ), + STORAGE_FILTER(EnumSet.allOf(StorageFilter.class)), + PLACE_BLOCK(EnumSet.of(YesNo.YES, YesNo.NO)), - INSERTION_MODE( EnumSet.allOf( InsertionMode.class ) ); + SCHEDULING_MODE(EnumSet.allOf(SchedulingMode.class)), + SAVE_SEARCH(EnumSet.of(YesNo.YES, YesNo.NO)), + CRAFTING_STATUS(EnumSet.allOf(CraftingStatus.class)), - private final EnumSet> values; + INSERTION_MODE(EnumSet.allOf(InsertionMode.class)); - Settings( @Nonnull final EnumSet> possibleOptions ) - { - if( possibleOptions.isEmpty() ) - { - throw new IllegalArgumentException( "Tried to instantiate an empty setting." ); - } + private final EnumSet> values; - this.values = possibleOptions; - } + Settings(@Nonnull final EnumSet> possibleOptions) { + if (possibleOptions.isEmpty()) { + throw new IllegalArgumentException("Tried to instantiate an empty setting."); + } - public EnumSet> getPossibleValues() - { - return this.values; - } + this.values = possibleOptions; + } + public EnumSet> getPossibleValues() { + return this.values; + } } diff --git a/src/main/java/appeng/api/config/SortDir.java b/src/main/java/appeng/api/config/SortDir.java index 654fda0dc23..3227e7a2233 100644 --- a/src/main/java/appeng/api/config/SortDir.java +++ b/src/main/java/appeng/api/config/SortDir.java @@ -23,8 +23,7 @@ package appeng.api.config; - -public enum SortDir -{ - ASCENDING, DESCENDING -} \ No newline at end of file +public enum SortDir { + ASCENDING, + DESCENDING +} diff --git a/src/main/java/appeng/api/config/SortOrder.java b/src/main/java/appeng/api/config/SortOrder.java index 51cde4e64b2..bbf7f9cf74e 100644 --- a/src/main/java/appeng/api/config/SortOrder.java +++ b/src/main/java/appeng/api/config/SortOrder.java @@ -23,8 +23,9 @@ package appeng.api.config; - -public enum SortOrder -{ - NAME, AMOUNT, MOD, INVTWEAKS -} \ No newline at end of file +public enum SortOrder { + NAME, + AMOUNT, + MOD, + INVTWEAKS +} diff --git a/src/main/java/appeng/api/config/StorageFilter.java b/src/main/java/appeng/api/config/StorageFilter.java index 64f63f704ce..158fb3e7067 100644 --- a/src/main/java/appeng/api/config/StorageFilter.java +++ b/src/main/java/appeng/api/config/StorageFilter.java @@ -23,12 +23,8 @@ package appeng.api.config; +public enum StorageFilter { + NONE, -public enum StorageFilter -{ - - NONE, - - EXTRACTABLE_ONLY - + EXTRACTABLE_ONLY } diff --git a/src/main/java/appeng/api/config/TerminalStyle.java b/src/main/java/appeng/api/config/TerminalStyle.java index d8687e1a30d..646ae69c343 100644 --- a/src/main/java/appeng/api/config/TerminalStyle.java +++ b/src/main/java/appeng/api/config/TerminalStyle.java @@ -23,14 +23,10 @@ package appeng.api.config; +public enum TerminalStyle { + TALL, -public enum TerminalStyle -{ + FULL, - TALL, - - FULL, - - SMALL - -} \ No newline at end of file + SMALL +} diff --git a/src/main/java/appeng/api/config/TunnelType.java b/src/main/java/appeng/api/config/TunnelType.java index 0323f0dd273..116b3e5242c 100644 --- a/src/main/java/appeng/api/config/TunnelType.java +++ b/src/main/java/appeng/api/config/TunnelType.java @@ -23,18 +23,16 @@ package appeng.api.config; - -public enum TunnelType -{ - ME, // Network Tunnel - IC2_POWER, // EU Tunnel - RF_POWER, // RF Tunnel - REDSTONE, // Redstone Tunnel - FLUID, // Fluid Tunnel - ITEM, // Item Tunnel - LIGHT, // Light Tunnel - BUNDLED_REDSTONE, // Bundled Redstone Tunnel - COMPUTER_MESSAGE, // Computer Message Tunnel - PRESSURE, // PneumaticCraft Tunnel - GT_POWER // GregTech EU Tunnel +public enum TunnelType { + ME, // Network Tunnel + IC2_POWER, // EU Tunnel + RF_POWER, // RF Tunnel + REDSTONE, // Redstone Tunnel + FLUID, // Fluid Tunnel + ITEM, // Item Tunnel + LIGHT, // Light Tunnel + BUNDLED_REDSTONE, // Bundled Redstone Tunnel + COMPUTER_MESSAGE, // Computer Message Tunnel + PRESSURE, // PneumaticCraft Tunnel + GT_POWER // GregTech EU Tunnel } diff --git a/src/main/java/appeng/api/config/Upgrades.java b/src/main/java/appeng/api/config/Upgrades.java index c4b7f9794f6..e889852cd14 100644 --- a/src/main/java/appeng/api/config/Upgrades.java +++ b/src/main/java/appeng/api/config/Upgrades.java @@ -23,105 +23,97 @@ package appeng.api.config; - import appeng.api.definitions.IItemDefinition; import appeng.api.util.AEItemDefinition; import com.google.common.base.Optional; -import net.minecraft.item.ItemStack; - import java.util.HashMap; import java.util.Map; +import net.minecraft.item.ItemStack; - -public enum Upgrades -{ - /** - * Gold Tier Upgrades. - */ - CAPACITY( 0 ), REDSTONE( 0 ), CRAFTING( 0 ), - - /** - * Diamond Tier Upgrades. - */ - FUZZY( 1 ), SPEED( 1 ), INVERTER( 1 ), PATTERN_CAPACITY(1), ORE_FILTER(1); - - /** - * @deprecated use {@link Upgrades#getTier()} - */ - @Deprecated - public final int tier; - - /** - * @deprecated use {@link Upgrades#getSupported()} - */ - @Deprecated - private final Map supportedMax = new HashMap(); - - Upgrades( final int tier ) - { - this.tier = tier; - } - - /** - * @return list of Items/Blocks that support this upgrade, and how many it supports. - */ - public Map getSupported() - { - return this.supportedMax; - } - - /** - * Registers a specific amount of this upgrade into a specific machine - * - * @param item machine in which this upgrade can be installed - * @param maxSupported amount how many upgrades can be installed - */ - public void registerItem( final IItemDefinition item, final int maxSupported ) - { - final Optional maybeStack = item.maybeStack( 1 ); - for( final ItemStack stack : maybeStack.asSet() ) - { - this.registerItem( stack, maxSupported ); - } - } - - /** - * Registers a specific amount of this upgrade into a specific machine - * - * @param stack machine in which this upgrade can be installed - * @param maxSupported amount how many upgrades can be installed - */ - public void registerItem( final ItemStack stack, final int maxSupported ) - { - if( stack != null ) - { - this.supportedMax.put( stack, maxSupported ); - } - } - - /** - * Registers a specific amount of this upgrade into a specific machine - * - * @param item machine in which this upgrade can be installed - * @param maxSupported amount how many upgrades can be installed - * @deprecated use {@link Upgrades#registerItem(IItemDefinition, int)} - */ - @Deprecated - public void registerItem( final AEItemDefinition item, final int maxSupported ) - { - if( item != null ) - { - final ItemStack stack = item.stack( 1 ); - - if( stack != null ) - { - this.registerItem( stack, maxSupported ); - } - } - } - - public int getTier() - { - return this.tier; - } +public enum Upgrades { + /** + * Gold Tier Upgrades. + */ + CAPACITY(0), + REDSTONE(0), + CRAFTING(0), + + /** + * Diamond Tier Upgrades. + */ + FUZZY(1), + SPEED(1), + INVERTER(1), + PATTERN_CAPACITY(1), + ORE_FILTER(1); + + /** + * @deprecated use {@link Upgrades#getTier()} + */ + @Deprecated + public final int tier; + + /** + * @deprecated use {@link Upgrades#getSupported()} + */ + @Deprecated + private final Map supportedMax = new HashMap(); + + Upgrades(final int tier) { + this.tier = tier; + } + + /** + * @return list of Items/Blocks that support this upgrade, and how many it supports. + */ + public Map getSupported() { + return this.supportedMax; + } + + /** + * Registers a specific amount of this upgrade into a specific machine + * + * @param item machine in which this upgrade can be installed + * @param maxSupported amount how many upgrades can be installed + */ + public void registerItem(final IItemDefinition item, final int maxSupported) { + final Optional maybeStack = item.maybeStack(1); + for (final ItemStack stack : maybeStack.asSet()) { + this.registerItem(stack, maxSupported); + } + } + + /** + * Registers a specific amount of this upgrade into a specific machine + * + * @param stack machine in which this upgrade can be installed + * @param maxSupported amount how many upgrades can be installed + */ + public void registerItem(final ItemStack stack, final int maxSupported) { + if (stack != null) { + this.supportedMax.put(stack, maxSupported); + } + } + + /** + * Registers a specific amount of this upgrade into a specific machine + * + * @param item machine in which this upgrade can be installed + * @param maxSupported amount how many upgrades can be installed + * @deprecated use {@link Upgrades#registerItem(IItemDefinition, int)} + */ + @Deprecated + public void registerItem(final AEItemDefinition item, final int maxSupported) { + if (item != null) { + final ItemStack stack = item.stack(1); + + if (stack != null) { + this.registerItem(stack, maxSupported); + } + } + } + + public int getTier() { + return this.tier; + } } diff --git a/src/main/java/appeng/api/config/ViewItems.java b/src/main/java/appeng/api/config/ViewItems.java index a87e0aa2197..4658a083c65 100644 --- a/src/main/java/appeng/api/config/ViewItems.java +++ b/src/main/java/appeng/api/config/ViewItems.java @@ -23,8 +23,8 @@ package appeng.api.config; - -public enum ViewItems -{ - ALL, STORED, CRAFTABLE -} \ No newline at end of file +public enum ViewItems { + ALL, + STORED, + CRAFTABLE +} diff --git a/src/main/java/appeng/api/config/YesNo.java b/src/main/java/appeng/api/config/YesNo.java index c6bfcd60287..79830d9608c 100644 --- a/src/main/java/appeng/api/config/YesNo.java +++ b/src/main/java/appeng/api/config/YesNo.java @@ -23,8 +23,8 @@ package appeng.api.config; - -public enum YesNo -{ - YES, NO, UNDECIDED +public enum YesNo { + YES, + NO, + UNDECIDED } diff --git a/src/main/java/appeng/api/definitions/Blocks.java b/src/main/java/appeng/api/definitions/Blocks.java index 8e398cb1e32..9b147a127e0 100644 --- a/src/main/java/appeng/api/definitions/Blocks.java +++ b/src/main/java/appeng/api/definitions/Blocks.java @@ -23,113 +23,110 @@ package appeng.api.definitions; - import appeng.api.util.AEItemDefinition; - /** * @deprecated use {@link IBlocks} now */ @Deprecated -public class Blocks -{ - public AEItemDefinition blockQuartzOre; +public class Blocks { + public AEItemDefinition blockQuartzOre; - public AEItemDefinition blockQuartzOreCharged; + public AEItemDefinition blockQuartzOreCharged; - public AEItemDefinition blockMatrixFrame; + public AEItemDefinition blockMatrixFrame; - public AEItemDefinition blockQuartz; + public AEItemDefinition blockQuartz; - public AEItemDefinition blockQuartzPillar; + public AEItemDefinition blockQuartzPillar; - public AEItemDefinition blockQuartzChiseled; + public AEItemDefinition blockQuartzChiseled; - public AEItemDefinition blockQuartzGlass; + public AEItemDefinition blockQuartzGlass; - public AEItemDefinition blockQuartzVibrantGlass; + public AEItemDefinition blockQuartzVibrantGlass; - public AEItemDefinition blockQuartzTorch; + public AEItemDefinition blockQuartzTorch; - public AEItemDefinition blockFluix; + public AEItemDefinition blockFluix; - public AEItemDefinition blockSkyStone; + public AEItemDefinition blockSkyStone; - public AEItemDefinition blockSkyChest; + public AEItemDefinition blockSkyChest; - public AEItemDefinition blockSkyCompass; + public AEItemDefinition blockSkyCompass; - public AEItemDefinition blockGrindStone; + public AEItemDefinition blockGrindStone; - public AEItemDefinition blockCrankHandle; + public AEItemDefinition blockCrankHandle; - public AEItemDefinition blockInscriber; + public AEItemDefinition blockInscriber; - public AEItemDefinition blockWireless; + public AEItemDefinition blockWireless; - public AEItemDefinition blockCharger; + public AEItemDefinition blockCharger; - public AEItemDefinition blockTinyTNT; + public AEItemDefinition blockTinyTNT; - public AEItemDefinition blockSecurity; + public AEItemDefinition blockSecurity; - public AEItemDefinition blockQuantumRing; + public AEItemDefinition blockQuantumRing; - public AEItemDefinition blockQuantumLink; + public AEItemDefinition blockQuantumLink; - public AEItemDefinition blockSpatialPylon; + public AEItemDefinition blockSpatialPylon; - public AEItemDefinition blockSpatialIOPort; + public AEItemDefinition blockSpatialIOPort; - public AEItemDefinition blockMultiPart; + public AEItemDefinition blockMultiPart; - public AEItemDefinition blockController; + public AEItemDefinition blockController; - public AEItemDefinition blockDrive; + public AEItemDefinition blockDrive; - public AEItemDefinition blockChest; + public AEItemDefinition blockChest; - public AEItemDefinition blockInterface; + public AEItemDefinition blockInterface; - public AEItemDefinition blockCellWorkbench; + public AEItemDefinition blockCellWorkbench; - public AEItemDefinition blockIOPort; + public AEItemDefinition blockIOPort; - public AEItemDefinition blockCondenser; + public AEItemDefinition blockCondenser; - public AEItemDefinition blockEnergyAcceptor; + public AEItemDefinition blockEnergyAcceptor; - public AEItemDefinition blockVibrationChamber; + public AEItemDefinition blockVibrationChamber; - public AEItemDefinition blockQuartzGrowthAccelerator; + public AEItemDefinition blockQuartzGrowthAccelerator; - public AEItemDefinition blockEnergyCell; + public AEItemDefinition blockEnergyCell; - public AEItemDefinition blockEnergyCellDense; + public AEItemDefinition blockEnergyCellDense; - public AEItemDefinition blockEnergyCellCreative; + public AEItemDefinition blockEnergyCellCreative; - public AEItemDefinition blockCraftingUnit; + public AEItemDefinition blockCraftingUnit; - public AEItemDefinition blockCraftingAccelerator; + public AEItemDefinition blockCraftingAccelerator; public AEItemDefinition blockCraftingAccelerator4x; public AEItemDefinition blockCraftingAccelerator16x; - public AEItemDefinition blockCraftingStorage1k; + public AEItemDefinition blockCraftingStorage1k; - public AEItemDefinition blockCraftingStorage4k; + public AEItemDefinition blockCraftingStorage4k; - public AEItemDefinition blockCraftingStorage16k; + public AEItemDefinition blockCraftingStorage16k; - public AEItemDefinition blockCraftingStorage64k; + public AEItemDefinition blockCraftingStorage64k; - public AEItemDefinition blockCraftingMonitor; + public AEItemDefinition blockCraftingMonitor; - public AEItemDefinition blockMolecularAssembler; + public AEItemDefinition blockMolecularAssembler; - public AEItemDefinition blockLightDetector; + public AEItemDefinition blockLightDetector; - public AEItemDefinition blockPaint; + public AEItemDefinition blockPaint; } diff --git a/src/main/java/appeng/api/definitions/IBlockDefinition.java b/src/main/java/appeng/api/definitions/IBlockDefinition.java index a08795e1a45..f5ef67705fc 100644 --- a/src/main/java/appeng/api/definitions/IBlockDefinition.java +++ b/src/main/java/appeng/api/definitions/IBlockDefinition.java @@ -1,32 +1,29 @@ package appeng.api.definitions; - import com.google.common.base.Optional; import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; import net.minecraft.world.IBlockAccess; +public interface IBlockDefinition extends IItemDefinition { + /** + * @return the {@link Block} implementation if applicable + */ + Optional maybeBlock(); -public interface IBlockDefinition extends IItemDefinition -{ - /** - * @return the {@link Block} implementation if applicable - */ - Optional maybeBlock(); - - /** - * @return the {@link ItemBlock} implementation if applicable - */ - Optional maybeItemBlock(); + /** + * @return the {@link ItemBlock} implementation if applicable + */ + Optional maybeItemBlock(); - /** - * Compare Block with world. - * - * @param world world of block - * @param x x pos of block - * @param y y pos of block - * @param z z pos of block - * @return if the block is placed in the world at the specific location. - */ - boolean isSameAs( IBlockAccess world, int x, int y, int z ); + /** + * Compare Block with world. + * + * @param world world of block + * @param x x pos of block + * @param y y pos of block + * @param z z pos of block + * @return if the block is placed in the world at the specific location. + */ + boolean isSameAs(IBlockAccess world, int x, int y, int z); } diff --git a/src/main/java/appeng/api/definitions/IBlocks.java b/src/main/java/appeng/api/definitions/IBlocks.java index 2d71430957a..923ac806d3e 100644 --- a/src/main/java/appeng/api/definitions/IBlocks.java +++ b/src/main/java/appeng/api/definitions/IBlocks.java @@ -23,163 +23,161 @@ package appeng.api.definitions; - /** * A list of all blocks in AE */ -public interface IBlocks -{ - /* - * world gen - */ - IBlockDefinition quartzOre(); +public interface IBlocks { + /* + * world gen + */ + IBlockDefinition quartzOre(); - IBlockDefinition quartzOreCharged(); + IBlockDefinition quartzOreCharged(); - IBlockDefinition matrixFrame(); + IBlockDefinition matrixFrame(); - /* - * decorative - */ - IBlockDefinition quartz(); + /* + * decorative + */ + IBlockDefinition quartz(); - IBlockDefinition quartzPillar(); + IBlockDefinition quartzPillar(); - IBlockDefinition quartzChiseled(); + IBlockDefinition quartzChiseled(); - IBlockDefinition quartzGlass(); + IBlockDefinition quartzGlass(); - IBlockDefinition quartzVibrantGlass(); + IBlockDefinition quartzVibrantGlass(); - IBlockDefinition quartzTorch(); + IBlockDefinition quartzTorch(); - IBlockDefinition fluix(); + IBlockDefinition fluix(); - IBlockDefinition skyStone(); + IBlockDefinition skyStone(); - IBlockDefinition skyChest(); + IBlockDefinition skyChest(); - IBlockDefinition skyCompass(); + IBlockDefinition skyCompass(); - IBlockDefinition skyStoneStair(); + IBlockDefinition skyStoneStair(); - IBlockDefinition skyStoneBlockStair(); + IBlockDefinition skyStoneBlockStair(); - IBlockDefinition skyStoneBrickStair(); + IBlockDefinition skyStoneBrickStair(); - IBlockDefinition skyStoneSmallBrickStair(); + IBlockDefinition skyStoneSmallBrickStair(); - IBlockDefinition fluixStair(); + IBlockDefinition fluixStair(); - IBlockDefinition quartzStair(); + IBlockDefinition quartzStair(); - IBlockDefinition chiseledQuartzStair(); + IBlockDefinition chiseledQuartzStair(); - IBlockDefinition quartzPillarStair(); + IBlockDefinition quartzPillarStair(); - IBlockDefinition skyStoneSlab(); + IBlockDefinition skyStoneSlab(); - IBlockDefinition skyStoneBlockSlab(); + IBlockDefinition skyStoneBlockSlab(); - IBlockDefinition skyStoneBrickSlab(); + IBlockDefinition skyStoneBrickSlab(); - IBlockDefinition skyStoneSmallBrickSlab(); + IBlockDefinition skyStoneSmallBrickSlab(); - IBlockDefinition fluixSlab(); + IBlockDefinition fluixSlab(); - IBlockDefinition quartzSlab(); + IBlockDefinition quartzSlab(); - IBlockDefinition chiseledQuartzSlab(); + IBlockDefinition chiseledQuartzSlab(); - IBlockDefinition quartzPillarSlab(); + IBlockDefinition quartzPillarSlab(); - /* - * misc - */ - ITileDefinition grindStone(); + /* + * misc + */ + ITileDefinition grindStone(); - ITileDefinition crankHandle(); + ITileDefinition crankHandle(); - ITileDefinition inscriber(); + ITileDefinition inscriber(); - ITileDefinition wireless(); + ITileDefinition wireless(); - ITileDefinition charger(); + ITileDefinition charger(); - IBlockDefinition tinyTNT(); + IBlockDefinition tinyTNT(); - ITileDefinition security(); + ITileDefinition security(); - /* - * quantum Network Bridge - */ - ITileDefinition quantumRing(); + /* + * quantum Network Bridge + */ + ITileDefinition quantumRing(); - ITileDefinition quantumLink(); + ITileDefinition quantumLink(); - /* - * spatial iO - */ - ITileDefinition spatialPylon(); + /* + * spatial iO + */ + ITileDefinition spatialPylon(); - ITileDefinition spatialIOPort(); + ITileDefinition spatialIOPort(); - /* - * Bus / cables - */ - ITileDefinition multiPart(); + /* + * Bus / cables + */ + ITileDefinition multiPart(); - /* - * machines - */ - ITileDefinition controller(); + /* + * machines + */ + ITileDefinition controller(); - ITileDefinition drive(); + ITileDefinition drive(); - ITileDefinition chest(); + ITileDefinition chest(); - ITileDefinition iface(); + ITileDefinition iface(); - ITileDefinition cellWorkbench(); + ITileDefinition cellWorkbench(); - ITileDefinition iOPort(); + ITileDefinition iOPort(); - ITileDefinition condenser(); + ITileDefinition condenser(); - ITileDefinition energyAcceptor(); + ITileDefinition energyAcceptor(); - ITileDefinition vibrationChamber(); + ITileDefinition vibrationChamber(); - ITileDefinition quartzGrowthAccelerator(); + ITileDefinition quartzGrowthAccelerator(); - ITileDefinition energyCell(); + ITileDefinition energyCell(); - ITileDefinition energyCellDense(); + ITileDefinition energyCellDense(); - ITileDefinition energyCellCreative(); + ITileDefinition energyCellCreative(); - // rv1 - ITileDefinition craftingUnit(); + // rv1 + ITileDefinition craftingUnit(); - ITileDefinition craftingAccelerator(); + ITileDefinition craftingAccelerator(); ITileDefinition craftingAccelerator4x(); ITileDefinition craftingAccelerator16x(); - ITileDefinition craftingStorage1k(); + ITileDefinition craftingStorage1k(); - ITileDefinition craftingStorage4k(); + ITileDefinition craftingStorage4k(); - ITileDefinition craftingStorage16k(); + ITileDefinition craftingStorage16k(); - ITileDefinition craftingStorage64k(); + ITileDefinition craftingStorage64k(); - ITileDefinition craftingMonitor(); + ITileDefinition craftingMonitor(); - ITileDefinition molecularAssembler(); + ITileDefinition molecularAssembler(); - ITileDefinition lightDetector(); + ITileDefinition lightDetector(); - ITileDefinition paint(); + ITileDefinition paint(); } diff --git a/src/main/java/appeng/api/definitions/IComparableDefinition.java b/src/main/java/appeng/api/definitions/IComparableDefinition.java index c172c5ef924..f30db6eff87 100644 --- a/src/main/java/appeng/api/definitions/IComparableDefinition.java +++ b/src/main/java/appeng/api/definitions/IComparableDefinition.java @@ -1,10 +1,8 @@ package appeng.api.definitions; - import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; - /** * Interface to compare a definition with an itemstack or a block * @@ -12,26 +10,25 @@ * @version rv2 * @since rv2 */ -public interface IComparableDefinition -{ - /** - * Compare {@link ItemStack} with this - * - * @param comparableStack compared item - * @return true if the item stack is a matching item. - */ - boolean isSameAs( ItemStack comparableStack ); +public interface IComparableDefinition { + /** + * Compare {@link ItemStack} with this + * + * @param comparableStack compared item + * @return true if the item stack is a matching item. + */ + boolean isSameAs(ItemStack comparableStack); - /** - * Compare Block with world. - * - * @param world world of block - * @param x x pos of block - * @param y y pos of block - * @param z z pos of block - * @return if the block is placed in the world at the specific location. - * @deprecated moved to {@link IBlockDefinition}. Is removed in the next major release rv3 - */ - @Deprecated - boolean isSameAs( IBlockAccess world, int x, int y, int z ); + /** + * Compare Block with world. + * + * @param world world of block + * @param x x pos of block + * @param y y pos of block + * @param z z pos of block + * @return if the block is placed in the world at the specific location. + * @deprecated moved to {@link IBlockDefinition}. Is removed in the next major release rv3 + */ + @Deprecated + boolean isSameAs(IBlockAccess world, int x, int y, int z); } diff --git a/src/main/java/appeng/api/definitions/IDefinitions.java b/src/main/java/appeng/api/definitions/IDefinitions.java index 354f8899f01..c07968abe97 100644 --- a/src/main/java/appeng/api/definitions/IDefinitions.java +++ b/src/main/java/appeng/api/definitions/IDefinitions.java @@ -23,29 +23,27 @@ package appeng.api.definitions; - /** * All definitions in AE */ -public interface IDefinitions -{ - /** - * @return an accessible list of all of AE's blocks - */ - IBlocks blocks(); +public interface IDefinitions { + /** + * @return an accessible list of all of AE's blocks + */ + IBlocks blocks(); - /** - * @return an accessible list of all of AE's Items - */ - IItems items(); + /** + * @return an accessible list of all of AE's Items + */ + IItems items(); - /** - * @return an accessible list of all of AE's materials; materials are items - */ - IMaterials materials(); + /** + * @return an accessible list of all of AE's materials; materials are items + */ + IMaterials materials(); - /** - * @return an accessible list of all of AE's parts, parts are items - */ - IParts parts(); + /** + * @return an accessible list of all of AE's parts, parts are items + */ + IParts parts(); } diff --git a/src/main/java/appeng/api/definitions/IItemDefinition.java b/src/main/java/appeng/api/definitions/IItemDefinition.java index 80ca2d7daa5..10c6834515b 100644 --- a/src/main/java/appeng/api/definitions/IItemDefinition.java +++ b/src/main/java/appeng/api/definitions/IItemDefinition.java @@ -23,26 +23,23 @@ package appeng.api.definitions; - import com.google.common.base.Optional; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +public interface IItemDefinition extends IComparableDefinition { + /** + * @return the {@link Item} Implementation if applicable + */ + Optional maybeItem(); -public interface IItemDefinition extends IComparableDefinition -{ - /** - * @return the {@link Item} Implementation if applicable - */ - Optional maybeItem(); - - /** - * @return an {@link ItemStack} with specified quantity of this item. - */ - Optional maybeStack( int stackSize ); + /** + * @return an {@link ItemStack} with specified quantity of this item. + */ + Optional maybeStack(int stackSize); - /** - * @return true if definition is enabled - */ - boolean isEnabled(); + /** + * @return true if definition is enabled + */ + boolean isEnabled(); } diff --git a/src/main/java/appeng/api/definitions/IItems.java b/src/main/java/appeng/api/definitions/IItems.java index 5ea20f2ad5c..d8486a29c91 100644 --- a/src/main/java/appeng/api/definitions/IItems.java +++ b/src/main/java/appeng/api/definitions/IItems.java @@ -23,87 +23,84 @@ package appeng.api.definitions; - import appeng.api.util.AEColoredItemDefinition; - /** * A list of all items in AE */ -public interface IItems -{ - IItemDefinition certusQuartzAxe(); +public interface IItems { + IItemDefinition certusQuartzAxe(); - IItemDefinition certusQuartzHoe(); + IItemDefinition certusQuartzHoe(); - IItemDefinition certusQuartzShovel(); + IItemDefinition certusQuartzShovel(); - IItemDefinition certusQuartzPick(); + IItemDefinition certusQuartzPick(); - IItemDefinition certusQuartzSword(); + IItemDefinition certusQuartzSword(); - IItemDefinition certusQuartzWrench(); + IItemDefinition certusQuartzWrench(); - IItemDefinition certusQuartzKnife(); + IItemDefinition certusQuartzKnife(); - IItemDefinition netherQuartzAxe(); + IItemDefinition netherQuartzAxe(); - IItemDefinition netherQuartzHoe(); + IItemDefinition netherQuartzHoe(); - IItemDefinition netherQuartzShovel(); + IItemDefinition netherQuartzShovel(); - IItemDefinition netherQuartzPick(); + IItemDefinition netherQuartzPick(); - IItemDefinition netherQuartzSword(); + IItemDefinition netherQuartzSword(); - IItemDefinition netherQuartzWrench(); + IItemDefinition netherQuartzWrench(); - IItemDefinition netherQuartzKnife(); + IItemDefinition netherQuartzKnife(); - IItemDefinition entropyManipulator(); + IItemDefinition entropyManipulator(); - IItemDefinition wirelessTerminal(); + IItemDefinition wirelessTerminal(); - IItemDefinition biometricCard(); + IItemDefinition biometricCard(); - IItemDefinition chargedStaff(); + IItemDefinition chargedStaff(); - IItemDefinition massCannon(); + IItemDefinition massCannon(); - IItemDefinition memoryCard(); + IItemDefinition memoryCard(); - IItemDefinition networkTool(); + IItemDefinition networkTool(); - IItemDefinition portableCell(); + IItemDefinition portableCell(); - IItemDefinition cellCreative(); + IItemDefinition cellCreative(); - IItemDefinition viewCell(); + IItemDefinition viewCell(); - IItemDefinition cell1k(); + IItemDefinition cell1k(); - IItemDefinition cell4k(); + IItemDefinition cell4k(); - IItemDefinition cell16k(); + IItemDefinition cell16k(); - IItemDefinition cell64k(); + IItemDefinition cell64k(); - IItemDefinition spatialCell2(); + IItemDefinition spatialCell2(); - IItemDefinition spatialCell16(); + IItemDefinition spatialCell16(); - IItemDefinition spatialCell128(); + IItemDefinition spatialCell128(); - IItemDefinition facade(); + IItemDefinition facade(); - IItemDefinition crystalSeed(); + IItemDefinition crystalSeed(); - // rv1 - IItemDefinition encodedPattern(); + // rv1 + IItemDefinition encodedPattern(); - IItemDefinition colorApplicator(); + IItemDefinition colorApplicator(); - AEColoredItemDefinition coloredPaintBall(); + AEColoredItemDefinition coloredPaintBall(); - AEColoredItemDefinition coloredLumenPaintBall(); + AEColoredItemDefinition coloredLumenPaintBall(); } diff --git a/src/main/java/appeng/api/definitions/IMaterials.java b/src/main/java/appeng/api/definitions/IMaterials.java index 262c03908a5..b14515c5cd4 100644 --- a/src/main/java/appeng/api/definitions/IMaterials.java +++ b/src/main/java/appeng/api/definitions/IMaterials.java @@ -23,121 +23,119 @@ package appeng.api.definitions; - /** * A list of all materials in AE */ -public interface IMaterials -{ - IItemDefinition cell2SpatialPart(); +public interface IMaterials { + IItemDefinition cell2SpatialPart(); - IItemDefinition cell16SpatialPart(); + IItemDefinition cell16SpatialPart(); - IItemDefinition cell128SpatialPart(); + IItemDefinition cell128SpatialPart(); - IItemDefinition silicon(); + IItemDefinition silicon(); - IItemDefinition skyDust(); + IItemDefinition skyDust(); - IItemDefinition calcProcessorPress(); + IItemDefinition calcProcessorPress(); - IItemDefinition engProcessorPress(); + IItemDefinition engProcessorPress(); - IItemDefinition logicProcessorPress(); + IItemDefinition logicProcessorPress(); - IItemDefinition calcProcessorPrint(); + IItemDefinition calcProcessorPrint(); - IItemDefinition engProcessorPrint(); + IItemDefinition engProcessorPrint(); - IItemDefinition logicProcessorPrint(); + IItemDefinition logicProcessorPrint(); - IItemDefinition siliconPress(); + IItemDefinition siliconPress(); - IItemDefinition siliconPrint(); + IItemDefinition siliconPrint(); - IItemDefinition namePress(); + IItemDefinition namePress(); - IItemDefinition logicProcessor(); + IItemDefinition logicProcessor(); - IItemDefinition calcProcessor(); + IItemDefinition calcProcessor(); - IItemDefinition engProcessor(); + IItemDefinition engProcessor(); - IItemDefinition basicCard(); + IItemDefinition basicCard(); - IItemDefinition advCard(); + IItemDefinition advCard(); - IItemDefinition purifiedCertusQuartzCrystal(); + IItemDefinition purifiedCertusQuartzCrystal(); - IItemDefinition purifiedNetherQuartzCrystal(); + IItemDefinition purifiedNetherQuartzCrystal(); - IItemDefinition purifiedFluixCrystal(); + IItemDefinition purifiedFluixCrystal(); - IItemDefinition cell1kPart(); + IItemDefinition cell1kPart(); - IItemDefinition cell4kPart(); + IItemDefinition cell4kPart(); - IItemDefinition cell16kPart(); + IItemDefinition cell16kPart(); - IItemDefinition cell64kPart(); + IItemDefinition cell64kPart(); - IItemDefinition emptyStorageCell(); + IItemDefinition emptyStorageCell(); - IItemDefinition cardRedstone(); + IItemDefinition cardRedstone(); - IItemDefinition cardSpeed(); + IItemDefinition cardSpeed(); - IItemDefinition cardCapacity(); + IItemDefinition cardCapacity(); - IItemDefinition cardFuzzy(); + IItemDefinition cardFuzzy(); - IItemDefinition cardInverter(); + IItemDefinition cardInverter(); - IItemDefinition cardCrafting(); + IItemDefinition cardCrafting(); - IItemDefinition enderDust(); + IItemDefinition enderDust(); - IItemDefinition flour(); + IItemDefinition flour(); - IItemDefinition goldDust(); + IItemDefinition goldDust(); - IItemDefinition ironDust(); + IItemDefinition ironDust(); - IItemDefinition fluixDust(); + IItemDefinition fluixDust(); - IItemDefinition certusQuartzDust(); + IItemDefinition certusQuartzDust(); - IItemDefinition netherQuartzDust(); + IItemDefinition netherQuartzDust(); - IItemDefinition matterBall(); + IItemDefinition matterBall(); - IItemDefinition ironNugget(); + IItemDefinition ironNugget(); - IItemDefinition certusQuartzCrystal(); + IItemDefinition certusQuartzCrystal(); - IItemDefinition certusQuartzCrystalCharged(); + IItemDefinition certusQuartzCrystalCharged(); - IItemDefinition fluixCrystal(); + IItemDefinition fluixCrystal(); - IItemDefinition fluixPearl(); + IItemDefinition fluixPearl(); - IItemDefinition woodenGear(); + IItemDefinition woodenGear(); - IItemDefinition wireless(); + IItemDefinition wireless(); - IItemDefinition wirelessBooster(); + IItemDefinition wirelessBooster(); - IItemDefinition annihilationCore(); + IItemDefinition annihilationCore(); - IItemDefinition formationCore(); + IItemDefinition formationCore(); - IItemDefinition singularity(); + IItemDefinition singularity(); - IItemDefinition qESingularity(); + IItemDefinition qESingularity(); - IItemDefinition blankPattern(); + IItemDefinition blankPattern(); - IItemDefinition cardPatternCapacity(); + IItemDefinition cardPatternCapacity(); - IItemDefinition cardOreFilter(); + IItemDefinition cardOreFilter(); } diff --git a/src/main/java/appeng/api/definitions/IParts.java b/src/main/java/appeng/api/definitions/IParts.java index 65f84711c84..673b8652de2 100644 --- a/src/main/java/appeng/api/definitions/IParts.java +++ b/src/main/java/appeng/api/definitions/IParts.java @@ -23,98 +23,95 @@ package appeng.api.definitions; - import appeng.api.util.AEColoredItemDefinition; - /** * A list of all parts in AE */ -public interface IParts -{ - AEColoredItemDefinition cableSmart(); +public interface IParts { + AEColoredItemDefinition cableSmart(); - AEColoredItemDefinition cableCovered(); + AEColoredItemDefinition cableCovered(); - AEColoredItemDefinition cableGlass(); + AEColoredItemDefinition cableGlass(); - AEColoredItemDefinition cableDense(); + AEColoredItemDefinition cableDense(); - AEColoredItemDefinition cableDenseCovered(); + AEColoredItemDefinition cableDenseCovered(); - AEColoredItemDefinition cableUltraDenseCovered(); + AEColoredItemDefinition cableUltraDenseCovered(); - AEColoredItemDefinition cableUltraDenseSmart(); + AEColoredItemDefinition cableUltraDenseSmart(); - AEColoredItemDefinition lumenCableSmart(); + AEColoredItemDefinition lumenCableSmart(); - AEColoredItemDefinition lumenCableCovered(); + AEColoredItemDefinition lumenCableCovered(); - AEColoredItemDefinition lumenCableGlass(); + AEColoredItemDefinition lumenCableGlass(); - AEColoredItemDefinition lumenCableDense(); + AEColoredItemDefinition lumenCableDense(); - IItemDefinition quartzFiber(); + IItemDefinition quartzFiber(); - IItemDefinition toggleBus(); + IItemDefinition toggleBus(); - IItemDefinition invertedToggleBus(); + IItemDefinition invertedToggleBus(); - IItemDefinition storageBus(); + IItemDefinition storageBus(); - IItemDefinition importBus(); + IItemDefinition importBus(); - IItemDefinition exportBus(); + IItemDefinition exportBus(); - IItemDefinition iface(); + IItemDefinition iface(); - IItemDefinition levelEmitter(); + IItemDefinition levelEmitter(); - IItemDefinition annihilationPlane(); + IItemDefinition annihilationPlane(); - IItemDefinition identityAnnihilationPlane(); + IItemDefinition identityAnnihilationPlane(); - IItemDefinition formationPlane(); + IItemDefinition formationPlane(); - IItemDefinition p2PTunnelME(); + IItemDefinition p2PTunnelME(); - IItemDefinition p2PTunnelRedstone(); + IItemDefinition p2PTunnelRedstone(); - IItemDefinition p2PTunnelItems(); + IItemDefinition p2PTunnelItems(); - IItemDefinition p2PTunnelLiquids(); + IItemDefinition p2PTunnelLiquids(); - IItemDefinition p2PTunnelEU(); + IItemDefinition p2PTunnelEU(); - IItemDefinition p2PTunnelRF(); + IItemDefinition p2PTunnelRF(); - IItemDefinition p2PTunnelLight(); + IItemDefinition p2PTunnelLight(); - IItemDefinition p2PTunnelOpenComputers(); + IItemDefinition p2PTunnelOpenComputers(); - IItemDefinition p2PTunnelPneumaticCraft(); + IItemDefinition p2PTunnelPneumaticCraft(); - IItemDefinition cableAnchor(); + IItemDefinition cableAnchor(); - IItemDefinition monitor(); + IItemDefinition monitor(); - IItemDefinition semiDarkMonitor(); + IItemDefinition semiDarkMonitor(); - IItemDefinition darkMonitor(); + IItemDefinition darkMonitor(); - IItemDefinition interfaceTerminal(); + IItemDefinition interfaceTerminal(); - IItemDefinition patternTerminal(); + IItemDefinition patternTerminal(); - IItemDefinition craftingTerminal(); + IItemDefinition craftingTerminal(); - IItemDefinition terminal(); + IItemDefinition terminal(); - IItemDefinition storageMonitor(); + IItemDefinition storageMonitor(); - IItemDefinition conversionMonitor(); + IItemDefinition conversionMonitor(); - IItemDefinition patternTerminalEx(); + IItemDefinition patternTerminalEx(); - IItemDefinition p2PTunnelGregtech(); + IItemDefinition p2PTunnelGregtech(); } diff --git a/src/main/java/appeng/api/definitions/ITileDefinition.java b/src/main/java/appeng/api/definitions/ITileDefinition.java index 8660fa60c11..794c20ce9ca 100644 --- a/src/main/java/appeng/api/definitions/ITileDefinition.java +++ b/src/main/java/appeng/api/definitions/ITileDefinition.java @@ -1,14 +1,11 @@ package appeng.api.definitions; - import com.google.common.base.Optional; import net.minecraft.tileentity.TileEntity; - -public interface ITileDefinition extends IBlockDefinition -{ - /** - * @return the {@link TileEntity} Class if applicable. - */ - Optional> maybeEntity(); +public interface ITileDefinition extends IBlockDefinition { + /** + * @return the {@link TileEntity} Class if applicable. + */ + Optional> maybeEntity(); } diff --git a/src/main/java/appeng/api/definitions/Items.java b/src/main/java/appeng/api/definitions/Items.java index 09c242629bc..d0061338859 100644 --- a/src/main/java/appeng/api/definitions/Items.java +++ b/src/main/java/appeng/api/definitions/Items.java @@ -23,88 +23,85 @@ package appeng.api.definitions; - import appeng.api.util.AEColoredItemDefinition; import appeng.api.util.AEItemDefinition; - /** * @deprecated use {@link IItems} */ @Deprecated -public class Items -{ - public AEItemDefinition itemCertusQuartzAxe; +public class Items { + public AEItemDefinition itemCertusQuartzAxe; - public AEItemDefinition itemCertusQuartzHoe; + public AEItemDefinition itemCertusQuartzHoe; - public AEItemDefinition itemCertusQuartzShovel; + public AEItemDefinition itemCertusQuartzShovel; - public AEItemDefinition itemCertusQuartzPick; + public AEItemDefinition itemCertusQuartzPick; - public AEItemDefinition itemCertusQuartzSword; + public AEItemDefinition itemCertusQuartzSword; - public AEItemDefinition itemCertusQuartzWrench; + public AEItemDefinition itemCertusQuartzWrench; - public AEItemDefinition itemCertusQuartzKnife; + public AEItemDefinition itemCertusQuartzKnife; - public AEItemDefinition itemNetherQuartzAxe; + public AEItemDefinition itemNetherQuartzAxe; - public AEItemDefinition itemNetherQuartzHoe; + public AEItemDefinition itemNetherQuartzHoe; - public AEItemDefinition itemNetherQuartzShovel; + public AEItemDefinition itemNetherQuartzShovel; - public AEItemDefinition itemNetherQuartzPick; + public AEItemDefinition itemNetherQuartzPick; - public AEItemDefinition itemNetherQuartzSword; + public AEItemDefinition itemNetherQuartzSword; - public AEItemDefinition itemNetherQuartzWrench; + public AEItemDefinition itemNetherQuartzWrench; - public AEItemDefinition itemNetherQuartzKnife; + public AEItemDefinition itemNetherQuartzKnife; - public AEItemDefinition itemEntropyManipulator; + public AEItemDefinition itemEntropyManipulator; - public AEItemDefinition itemWirelessTerminal; + public AEItemDefinition itemWirelessTerminal; - public AEItemDefinition itemBiometricCard; + public AEItemDefinition itemBiometricCard; - public AEItemDefinition itemChargedStaff; + public AEItemDefinition itemChargedStaff; - public AEItemDefinition itemMassCannon; + public AEItemDefinition itemMassCannon; - public AEItemDefinition itemMemoryCard; + public AEItemDefinition itemMemoryCard; - public AEItemDefinition itemNetworkTool; + public AEItemDefinition itemNetworkTool; - public AEItemDefinition itemPortableCell; + public AEItemDefinition itemPortableCell; - public AEItemDefinition itemCellCreative; + public AEItemDefinition itemCellCreative; - public AEItemDefinition itemViewCell; + public AEItemDefinition itemViewCell; - public AEItemDefinition itemCell1k; + public AEItemDefinition itemCell1k; - public AEItemDefinition itemCell4k; + public AEItemDefinition itemCell4k; - public AEItemDefinition itemCell16k; + public AEItemDefinition itemCell16k; - public AEItemDefinition itemCell64k; + public AEItemDefinition itemCell64k; - public AEItemDefinition itemSpatialCell2; + public AEItemDefinition itemSpatialCell2; - public AEItemDefinition itemSpatialCell16; + public AEItemDefinition itemSpatialCell16; - public AEItemDefinition itemSpatialCell128; + public AEItemDefinition itemSpatialCell128; - public AEItemDefinition itemFacade; + public AEItemDefinition itemFacade; - public AEItemDefinition itemCrystalSeed; + public AEItemDefinition itemCrystalSeed; - public AEItemDefinition itemEncodedPattern; + public AEItemDefinition itemEncodedPattern; - public AEItemDefinition itemColorApplicator; + public AEItemDefinition itemColorApplicator; - public AEColoredItemDefinition itemPaintBall; + public AEColoredItemDefinition itemPaintBall; - public AEColoredItemDefinition itemLumenPaintBall; + public AEColoredItemDefinition itemLumenPaintBall; } diff --git a/src/main/java/appeng/api/definitions/Materials.java b/src/main/java/appeng/api/definitions/Materials.java index 88696474205..e47827cbf92 100644 --- a/src/main/java/appeng/api/definitions/Materials.java +++ b/src/main/java/appeng/api/definitions/Materials.java @@ -23,121 +23,118 @@ package appeng.api.definitions; - import appeng.api.util.AEItemDefinition; - /** * @deprecated use {@link IMaterials} */ @Deprecated -public class Materials -{ - public AEItemDefinition materialCell2SpatialPart; +public class Materials { + public AEItemDefinition materialCell2SpatialPart; - public AEItemDefinition materialCell16SpatialPart; + public AEItemDefinition materialCell16SpatialPart; - public AEItemDefinition materialCell128SpatialPart; + public AEItemDefinition materialCell128SpatialPart; - public AEItemDefinition materialSilicon; + public AEItemDefinition materialSilicon; - public AEItemDefinition materialSkyDust; + public AEItemDefinition materialSkyDust; - public AEItemDefinition materialCalcProcessorPress; + public AEItemDefinition materialCalcProcessorPress; - public AEItemDefinition materialEngProcessorPress; + public AEItemDefinition materialEngProcessorPress; - public AEItemDefinition materialLogicProcessorPress; + public AEItemDefinition materialLogicProcessorPress; - public AEItemDefinition materialCalcProcessorPrint; + public AEItemDefinition materialCalcProcessorPrint; - public AEItemDefinition materialEngProcessorPrint; + public AEItemDefinition materialEngProcessorPrint; - public AEItemDefinition materialLogicProcessorPrint; + public AEItemDefinition materialLogicProcessorPrint; - public AEItemDefinition materialSiliconPress; + public AEItemDefinition materialSiliconPress; - public AEItemDefinition materialSiliconPrint; + public AEItemDefinition materialSiliconPrint; - public AEItemDefinition materialNamePress; + public AEItemDefinition materialNamePress; - public AEItemDefinition materialLogicProcessor; + public AEItemDefinition materialLogicProcessor; - public AEItemDefinition materialCalcProcessor; + public AEItemDefinition materialCalcProcessor; - public AEItemDefinition materialEngProcessor; + public AEItemDefinition materialEngProcessor; - public AEItemDefinition materialBasicCard; + public AEItemDefinition materialBasicCard; - public AEItemDefinition materialAdvCard; + public AEItemDefinition materialAdvCard; - public AEItemDefinition materialPurifiedCertusQuartzCrystal; + public AEItemDefinition materialPurifiedCertusQuartzCrystal; - public AEItemDefinition materialPurifiedNetherQuartzCrystal; + public AEItemDefinition materialPurifiedNetherQuartzCrystal; - public AEItemDefinition materialPurifiedFluixCrystal; + public AEItemDefinition materialPurifiedFluixCrystal; - public AEItemDefinition materialCell1kPart; + public AEItemDefinition materialCell1kPart; - public AEItemDefinition materialCell4kPart; + public AEItemDefinition materialCell4kPart; - public AEItemDefinition materialCell16kPart; + public AEItemDefinition materialCell16kPart; - public AEItemDefinition materialCell64kPart; + public AEItemDefinition materialCell64kPart; - public AEItemDefinition materialEmptyStorageCell; + public AEItemDefinition materialEmptyStorageCell; - public AEItemDefinition materialCardRedstone; + public AEItemDefinition materialCardRedstone; - public AEItemDefinition materialCardSpeed; + public AEItemDefinition materialCardSpeed; - public AEItemDefinition materialCardCapacity; + public AEItemDefinition materialCardCapacity; - public AEItemDefinition materialCardFuzzy; + public AEItemDefinition materialCardFuzzy; - public AEItemDefinition materialCardInverter; + public AEItemDefinition materialCardInverter; - public AEItemDefinition materialCardCrafting; + public AEItemDefinition materialCardCrafting; - public AEItemDefinition materialEnderDust; + public AEItemDefinition materialEnderDust; - public AEItemDefinition materialFlour; + public AEItemDefinition materialFlour; - public AEItemDefinition materialGoldDust; + public AEItemDefinition materialGoldDust; - public AEItemDefinition materialIronDust; + public AEItemDefinition materialIronDust; - public AEItemDefinition materialFluixDust; + public AEItemDefinition materialFluixDust; - public AEItemDefinition materialCertusQuartzDust; + public AEItemDefinition materialCertusQuartzDust; - public AEItemDefinition materialNetherQuartzDust; + public AEItemDefinition materialNetherQuartzDust; - public AEItemDefinition materialMatterBall; + public AEItemDefinition materialMatterBall; - public AEItemDefinition materialIronNugget; + public AEItemDefinition materialIronNugget; - public AEItemDefinition materialCertusQuartzCrystal; + public AEItemDefinition materialCertusQuartzCrystal; - public AEItemDefinition materialCertusQuartzCrystalCharged; + public AEItemDefinition materialCertusQuartzCrystalCharged; - public AEItemDefinition materialFluixCrystal; + public AEItemDefinition materialFluixCrystal; - public AEItemDefinition materialFluixPearl; + public AEItemDefinition materialFluixPearl; - public AEItemDefinition materialWoodenGear; + public AEItemDefinition materialWoodenGear; - public AEItemDefinition materialWireless; + public AEItemDefinition materialWireless; - public AEItemDefinition materialWirelessBooster; + public AEItemDefinition materialWirelessBooster; - public AEItemDefinition materialAnnihilationCore; + public AEItemDefinition materialAnnihilationCore; - public AEItemDefinition materialFormationCore; + public AEItemDefinition materialFormationCore; - public AEItemDefinition materialSingularity; + public AEItemDefinition materialSingularity; - public AEItemDefinition materialQESingularity; + public AEItemDefinition materialQESingularity; - public AEItemDefinition materialBlankPattern; + public AEItemDefinition materialBlankPattern; } diff --git a/src/main/java/appeng/api/definitions/Parts.java b/src/main/java/appeng/api/definitions/Parts.java index 94665453e9a..bd441bea59d 100644 --- a/src/main/java/appeng/api/definitions/Parts.java +++ b/src/main/java/appeng/api/definitions/Parts.java @@ -23,90 +23,87 @@ package appeng.api.definitions; - import appeng.api.util.AEColoredItemDefinition; import appeng.api.util.AEItemDefinition; - /** * @deprecated use {@link IParts} */ @Deprecated -public class Parts -{ - public AEColoredItemDefinition partCableSmart; +public class Parts { + public AEColoredItemDefinition partCableSmart; - public AEColoredItemDefinition partCableCovered; + public AEColoredItemDefinition partCableCovered; - public AEColoredItemDefinition partCableGlass; + public AEColoredItemDefinition partCableGlass; - public AEColoredItemDefinition partCableDense; + public AEColoredItemDefinition partCableDense; - public AEColoredItemDefinition partCableDenseCovered; + public AEColoredItemDefinition partCableDenseCovered; - public AEColoredItemDefinition partCableUltraDenseCovered; + public AEColoredItemDefinition partCableUltraDenseCovered; - public AEColoredItemDefinition partCableUltraDenseSmart; + public AEColoredItemDefinition partCableUltraDenseSmart; - public AEColoredItemDefinition partLumenCableSmart; + public AEColoredItemDefinition partLumenCableSmart; - public AEColoredItemDefinition partLumenCableCovered; + public AEColoredItemDefinition partLumenCableCovered; - public AEColoredItemDefinition partLumenCableGlass; + public AEColoredItemDefinition partLumenCableGlass; - public AEColoredItemDefinition partLumenCableDense; + public AEColoredItemDefinition partLumenCableDense; - public AEItemDefinition partQuartzFiber; + public AEItemDefinition partQuartzFiber; - public AEItemDefinition partToggleBus; + public AEItemDefinition partToggleBus; - public AEItemDefinition partInvertedToggleBus; + public AEItemDefinition partInvertedToggleBus; - public AEItemDefinition partStorageBus; + public AEItemDefinition partStorageBus; - public AEItemDefinition partImportBus; + public AEItemDefinition partImportBus; - public AEItemDefinition partExportBus; + public AEItemDefinition partExportBus; - public AEItemDefinition partInterface; + public AEItemDefinition partInterface; - public AEItemDefinition partLevelEmitter; + public AEItemDefinition partLevelEmitter; - public AEItemDefinition partAnnihilationPlane; + public AEItemDefinition partAnnihilationPlane; - public AEItemDefinition partFormationPlane; + public AEItemDefinition partFormationPlane; - public AEItemDefinition partP2PTunnelME; + public AEItemDefinition partP2PTunnelME; - public AEItemDefinition partP2PTunnelRedstone; + public AEItemDefinition partP2PTunnelRedstone; - public AEItemDefinition partP2PTunnelItems; + public AEItemDefinition partP2PTunnelItems; - public AEItemDefinition partP2PTunnelLiquids; + public AEItemDefinition partP2PTunnelLiquids; - public AEItemDefinition partP2PTunnelEU; + public AEItemDefinition partP2PTunnelEU; - public AEItemDefinition partP2PTunnelRF; + public AEItemDefinition partP2PTunnelRF; - public AEItemDefinition partP2PTunnelLight; + public AEItemDefinition partP2PTunnelLight; - public AEItemDefinition partCableAnchor; + public AEItemDefinition partCableAnchor; - public AEItemDefinition partMonitor; + public AEItemDefinition partMonitor; - public AEItemDefinition partSemiDarkMonitor; + public AEItemDefinition partSemiDarkMonitor; - public AEItemDefinition partDarkMonitor; + public AEItemDefinition partDarkMonitor; - public AEItemDefinition partInterfaceTerminal; + public AEItemDefinition partInterfaceTerminal; - public AEItemDefinition partPatternTerminal; + public AEItemDefinition partPatternTerminal; - public AEItemDefinition partCraftingTerminal; + public AEItemDefinition partCraftingTerminal; - public AEItemDefinition partTerminal; + public AEItemDefinition partTerminal; - public AEItemDefinition partStorageMonitor; + public AEItemDefinition partStorageMonitor; - public AEItemDefinition partConversionMonitor; + public AEItemDefinition partConversionMonitor; } diff --git a/src/main/java/appeng/api/events/LocatableEventAnnounce.java b/src/main/java/appeng/api/events/LocatableEventAnnounce.java index af641544881..8024762a063 100644 --- a/src/main/java/appeng/api/events/LocatableEventAnnounce.java +++ b/src/main/java/appeng/api/events/LocatableEventAnnounce.java @@ -23,31 +23,26 @@ package appeng.api.events; - import appeng.api.features.ILocatable; import cpw.mods.fml.common.eventhandler.Event; - /** * Input Event: *

* Used to Notify the Location Registry of objects, and their availability. */ -public class LocatableEventAnnounce extends Event -{ +public class LocatableEventAnnounce extends Event { - public final ILocatable target; - public final LocatableEvent change; + public final ILocatable target; + public final LocatableEvent change; - public LocatableEventAnnounce( final ILocatable o, final LocatableEvent ev ) - { - this.target = o; - this.change = ev; - } + public LocatableEventAnnounce(final ILocatable o, final LocatableEvent ev) { + this.target = o; + this.change = ev; + } - public enum LocatableEvent - { - Register, // Adds the locatable to the registry - Unregister // Removes the locatable from the registry - } + public enum LocatableEvent { + Register, // Adds the locatable to the registry + Unregister // Removes the locatable from the registry + } } diff --git a/src/main/java/appeng/api/exceptions/AppEngException.java b/src/main/java/appeng/api/exceptions/AppEngException.java index 478cfd77e4e..0ab4c99ff3e 100644 --- a/src/main/java/appeng/api/exceptions/AppEngException.java +++ b/src/main/java/appeng/api/exceptions/AppEngException.java @@ -23,14 +23,11 @@ package appeng.api.exceptions; +public class AppEngException extends Exception { -public class AppEngException extends Exception -{ + private static final long serialVersionUID = -9051434206368465494L; - private static final long serialVersionUID = -9051434206368465494L; - - public AppEngException( final String t ) - { - super( t ); - } + public AppEngException(final String t) { + super(t); + } } diff --git a/src/main/java/appeng/api/exceptions/CoreInaccessibleException.java b/src/main/java/appeng/api/exceptions/CoreInaccessibleException.java index 88a5725f031..ed8480e4f92 100644 --- a/src/main/java/appeng/api/exceptions/CoreInaccessibleException.java +++ b/src/main/java/appeng/api/exceptions/CoreInaccessibleException.java @@ -1,10 +1,7 @@ package appeng.api.exceptions; - -public class CoreInaccessibleException extends RuntimeException -{ - public CoreInaccessibleException( final String message ) - { - super( message ); - } +public class CoreInaccessibleException extends RuntimeException { + public CoreInaccessibleException(final String message) { + super(message); + } } diff --git a/src/main/java/appeng/api/exceptions/ExistingConnectionException.java b/src/main/java/appeng/api/exceptions/ExistingConnectionException.java index 4d2cb082de3..e1dc89e9dbe 100644 --- a/src/main/java/appeng/api/exceptions/ExistingConnectionException.java +++ b/src/main/java/appeng/api/exceptions/ExistingConnectionException.java @@ -23,10 +23,8 @@ package appeng.api.exceptions; - import appeng.api.networking.IGridNode; - /** * Exception occurred because of an already existing connection between the two {@link IGridNode}s *

@@ -37,20 +35,16 @@ * @version rv3 * @since rv3 */ -public class ExistingConnectionException extends FailedConnection -{ - - private static final long serialVersionUID = 2975450379720353182L; - private static final String DEFAULT_MESSAGE = "Connection between both nodes already exists."; +public class ExistingConnectionException extends FailedConnection { - public ExistingConnectionException() - { - super( DEFAULT_MESSAGE ); - } + private static final long serialVersionUID = 2975450379720353182L; + private static final String DEFAULT_MESSAGE = "Connection between both nodes already exists."; - public ExistingConnectionException( String message ) - { - super( message ); - } + public ExistingConnectionException() { + super(DEFAULT_MESSAGE); + } + public ExistingConnectionException(String message) { + super(message); + } } diff --git a/src/main/java/appeng/api/exceptions/FailedConnection.java b/src/main/java/appeng/api/exceptions/FailedConnection.java index 65072eea0a2..5fe968c6a1d 100644 --- a/src/main/java/appeng/api/exceptions/FailedConnection.java +++ b/src/main/java/appeng/api/exceptions/FailedConnection.java @@ -23,10 +23,8 @@ package appeng.api.exceptions; - import appeng.api.networking.IGridNode; - /** * Exception indicating a failed connection between two {@link IGridNode}s. *

@@ -40,17 +38,13 @@ * @version rv3 * @since rv0 */ -public class FailedConnection extends Exception -{ +public class FailedConnection extends Exception { - private static final long serialVersionUID = -2544208090248293753L; + private static final long serialVersionUID = -2544208090248293753L; - public FailedConnection() - { - } + public FailedConnection() {} - public FailedConnection( String message ) - { - super( message ); - } + public FailedConnection(String message) { + super(message); + } } diff --git a/src/main/java/appeng/api/exceptions/MissingDefinition.java b/src/main/java/appeng/api/exceptions/MissingDefinition.java index f920a9e9db1..c7bcba3ca39 100644 --- a/src/main/java/appeng/api/exceptions/MissingDefinition.java +++ b/src/main/java/appeng/api/exceptions/MissingDefinition.java @@ -1,10 +1,7 @@ package appeng.api.exceptions; - -public class MissingDefinition extends RuntimeException -{ - public MissingDefinition( final String message ) - { - super( message ); - } +public class MissingDefinition extends RuntimeException { + public MissingDefinition(final String message) { + super(message); + } } diff --git a/src/main/java/appeng/api/exceptions/MissingIngredientError.java b/src/main/java/appeng/api/exceptions/MissingIngredientError.java index 81fe40d371b..655d6f4bafe 100644 --- a/src/main/java/appeng/api/exceptions/MissingIngredientError.java +++ b/src/main/java/appeng/api/exceptions/MissingIngredientError.java @@ -23,14 +23,11 @@ package appeng.api.exceptions; +public class MissingIngredientError extends Exception { -public class MissingIngredientError extends Exception -{ + private static final long serialVersionUID = -998858343831371697L; - private static final long serialVersionUID = -998858343831371697L; - - public MissingIngredientError( final String n ) - { - super( n ); - } + public MissingIngredientError(final String n) { + super(n); + } } diff --git a/src/main/java/appeng/api/exceptions/ModNotInstalled.java b/src/main/java/appeng/api/exceptions/ModNotInstalled.java index a3c5eb0566b..59d6432b304 100644 --- a/src/main/java/appeng/api/exceptions/ModNotInstalled.java +++ b/src/main/java/appeng/api/exceptions/ModNotInstalled.java @@ -23,14 +23,11 @@ package appeng.api.exceptions; +public class ModNotInstalled extends Exception { -public class ModNotInstalled extends Exception -{ + private static final long serialVersionUID = -9052435206368425494L; - private static final long serialVersionUID = -9052435206368425494L; - - public ModNotInstalled( final String t ) - { - super( t ); - } + public ModNotInstalled(final String t) { + super(t); + } } diff --git a/src/main/java/appeng/api/exceptions/NullNodeConnectionException.java b/src/main/java/appeng/api/exceptions/NullNodeConnectionException.java index 30f3fe0cac0..11c9c108d0d 100644 --- a/src/main/java/appeng/api/exceptions/NullNodeConnectionException.java +++ b/src/main/java/appeng/api/exceptions/NullNodeConnectionException.java @@ -23,7 +23,6 @@ package appeng.api.exceptions; - /** * Exception due to trying to connect one or more null values. *

@@ -34,20 +33,16 @@ * @version rv3 * @since rv3 */ -public class NullNodeConnectionException extends FailedConnection -{ - - private static final long serialVersionUID = -2143719383495321764L; - private static final String DEFAULT_MESSAGE = "Connection forged between null entities."; +public class NullNodeConnectionException extends FailedConnection { - public NullNodeConnectionException() - { - super( DEFAULT_MESSAGE ); - } + private static final long serialVersionUID = -2143719383495321764L; + private static final String DEFAULT_MESSAGE = "Connection forged between null entities."; - public NullNodeConnectionException( String message ) - { - super( message ); - } + public NullNodeConnectionException() { + super(DEFAULT_MESSAGE); + } + public NullNodeConnectionException(String message) { + super(message); + } } diff --git a/src/main/java/appeng/api/exceptions/RecipeError.java b/src/main/java/appeng/api/exceptions/RecipeError.java index d4d6f90a4c7..dc5d2db6f5a 100644 --- a/src/main/java/appeng/api/exceptions/RecipeError.java +++ b/src/main/java/appeng/api/exceptions/RecipeError.java @@ -23,14 +23,11 @@ package appeng.api.exceptions; +public class RecipeError extends Exception { -public class RecipeError extends Exception -{ + private static final long serialVersionUID = -6602870588617670262L; - private static final long serialVersionUID = -6602870588617670262L; - - public RecipeError( final String n ) - { - super( n ); - } + public RecipeError(final String n) { + super(n); + } } diff --git a/src/main/java/appeng/api/exceptions/RegistrationError.java b/src/main/java/appeng/api/exceptions/RegistrationError.java index 205df3e9ac5..4d92f77fbcd 100644 --- a/src/main/java/appeng/api/exceptions/RegistrationError.java +++ b/src/main/java/appeng/api/exceptions/RegistrationError.java @@ -23,14 +23,11 @@ package appeng.api.exceptions; +public class RegistrationError extends Exception { -public class RegistrationError extends Exception -{ + private static final long serialVersionUID = -6602870588617670263L; - private static final long serialVersionUID = -6602870588617670263L; - - public RegistrationError( final String n ) - { - super( n ); - } + public RegistrationError(final String n) { + super(n); + } } diff --git a/src/main/java/appeng/api/exceptions/SecurityConnectionException.java b/src/main/java/appeng/api/exceptions/SecurityConnectionException.java index 267377da3f0..2f6f46027d7 100644 --- a/src/main/java/appeng/api/exceptions/SecurityConnectionException.java +++ b/src/main/java/appeng/api/exceptions/SecurityConnectionException.java @@ -23,7 +23,6 @@ package appeng.api.exceptions; - /** * Exception due to trying to connect different security realms. *

@@ -34,19 +33,15 @@ * @version rv3 * @since rv3 */ -public class SecurityConnectionException extends FailedConnection -{ - private static final long serialVersionUID = 5048714900434215426L; - private static final String DEFAULT_MESSAGE = "Connection failed due to different security realms."; - - public SecurityConnectionException() - { - super( DEFAULT_MESSAGE ); - } +public class SecurityConnectionException extends FailedConnection { + private static final long serialVersionUID = 5048714900434215426L; + private static final String DEFAULT_MESSAGE = "Connection failed due to different security realms."; - public SecurityConnectionException( String message ) - { - super( message ); - } + public SecurityConnectionException() { + super(DEFAULT_MESSAGE); + } + public SecurityConnectionException(String message) { + super(message); + } } diff --git a/src/main/java/appeng/api/features/IGrinderEntry.java b/src/main/java/appeng/api/features/IGrinderEntry.java index 1667f12cc26..27b12b7b950 100644 --- a/src/main/java/appeng/api/features/IGrinderEntry.java +++ b/src/main/java/appeng/api/features/IGrinderEntry.java @@ -23,99 +23,96 @@ package appeng.api.features; - import net.minecraft.item.ItemStack; - /** * Registration Records for {@link IGrinderRegistry} */ -public interface IGrinderEntry -{ - - /** - * the current input - * - * @return input that the grinder will accept. - */ - ItemStack getInput(); - - /** - * lets you change the grinder recipe by changing its input. - * - * @param input input item - */ - void setInput( ItemStack input ); - - /** - * gets the current output - * - * @return output that the grinder will produce - */ - ItemStack getOutput(); - - /** - * allows you to change the output. - * - * @param output output item - */ - void setOutput( ItemStack output ); - - /** - * gets the current output - * - * @return output that the grinder will produce - */ - ItemStack getOptionalOutput(); - - /** - * gets the current output - * - * @return output that the grinder will produce - */ - ItemStack getSecondOptionalOutput(); - - /** - * stack, and 0.0-1.0 chance that it will be generated. - * - * @param output output item - * @param chance generation chance - */ - void setOptionalOutput( ItemStack output, float chance ); - - /** - * 0.0 - 1.0 the chance that the optional output will be generated. - * - * @return chance of optional output - */ - float getOptionalChance(); - - /** - * stack, and 0.0-1.0 chance that it will be generated. - * - * @param output second optional output item - * @param chance second optional output chance - */ - void setSecondOptionalOutput( ItemStack output, float chance ); - - /** - * 0.0 - 1.0 the chance that the optional output will be generated. - * - * @return second optional output chance - */ - float getSecondOptionalChance(); - - /** - * Energy cost, in turns. - * - * @return number of turns it takes to produce the output from the input. - */ - int getEnergyCost(); - - /** - * Allows you to adjust the number of turns - * - * @param c number of turns to produce output. - */ - void setEnergyCost( int c ); +public interface IGrinderEntry { + + /** + * the current input + * + * @return input that the grinder will accept. + */ + ItemStack getInput(); + + /** + * lets you change the grinder recipe by changing its input. + * + * @param input input item + */ + void setInput(ItemStack input); + + /** + * gets the current output + * + * @return output that the grinder will produce + */ + ItemStack getOutput(); + + /** + * allows you to change the output. + * + * @param output output item + */ + void setOutput(ItemStack output); + + /** + * gets the current output + * + * @return output that the grinder will produce + */ + ItemStack getOptionalOutput(); + + /** + * gets the current output + * + * @return output that the grinder will produce + */ + ItemStack getSecondOptionalOutput(); + + /** + * stack, and 0.0-1.0 chance that it will be generated. + * + * @param output output item + * @param chance generation chance + */ + void setOptionalOutput(ItemStack output, float chance); + + /** + * 0.0 - 1.0 the chance that the optional output will be generated. + * + * @return chance of optional output + */ + float getOptionalChance(); + + /** + * stack, and 0.0-1.0 chance that it will be generated. + * + * @param output second optional output item + * @param chance second optional output chance + */ + void setSecondOptionalOutput(ItemStack output, float chance); + + /** + * 0.0 - 1.0 the chance that the optional output will be generated. + * + * @return second optional output chance + */ + float getSecondOptionalChance(); + + /** + * Energy cost, in turns. + * + * @return number of turns it takes to produce the output from the input. + */ + int getEnergyCost(); + + /** + * Allows you to adjust the number of turns + * + * @param c number of turns to produce output. + */ + void setEnergyCost(int c); } diff --git a/src/main/java/appeng/api/features/IGrinderRegistry.java b/src/main/java/appeng/api/features/IGrinderRegistry.java index 9fc9f74dcb3..7336131ea32 100644 --- a/src/main/java/appeng/api/features/IGrinderRegistry.java +++ b/src/main/java/appeng/api/features/IGrinderRegistry.java @@ -23,63 +23,66 @@ package appeng.api.features; - -import net.minecraft.item.ItemStack; - import java.util.List; - +import net.minecraft.item.ItemStack; /** * Lets you manipulate Grinder Recipes, by adding or editing existing ones. */ -public interface IGrinderRegistry -{ +public interface IGrinderRegistry { - /** - * Current list of registered recipes, you can modify this if you want too. - * - * @return currentlyRegisteredRecipes - */ - List getRecipes(); + /** + * Current list of registered recipes, you can modify this if you want too. + * + * @return currentlyRegisteredRecipes + */ + List getRecipes(); - /** - * add a new recipe the easy way, in → out, how many turns., duplicates will not be added. - * - * @param in input - * @param out output - * @param turns amount of turns to turn the input into the output - */ - void addRecipe( ItemStack in, ItemStack out, int turns ); + /** + * add a new recipe the easy way, in → out, how many turns., duplicates will not be added. + * + * @param in input + * @param out output + * @param turns amount of turns to turn the input into the output + */ + void addRecipe(ItemStack in, ItemStack out, int turns); - /** - * add a new recipe with optional outputs, duplicates will not be added. - * - * @param in input - * @param out output - * @param optional optional output - * @param chance chance to get the optional output within 0.0 - 1.0 - * @param turns amount of turns to turn the input into the outputs - */ - void addRecipe( ItemStack in, ItemStack out, ItemStack optional, float chance, int turns ); + /** + * add a new recipe with optional outputs, duplicates will not be added. + * + * @param in input + * @param out output + * @param optional optional output + * @param chance chance to get the optional output within 0.0 - 1.0 + * @param turns amount of turns to turn the input into the outputs + */ + void addRecipe(ItemStack in, ItemStack out, ItemStack optional, float chance, int turns); - /** - * add a new recipe with optional outputs, duplicates will not be added. - * - * @param in input - * @param out output - * @param optional optional output - * @param chance chance to get the optional output within 0.0 - 1.0 - * @param optional2 second optional output - * @param chance2 chance to get the second optional output within 0.0 - 1.0 - * @param turns amount of turns to turn the input into the outputs - */ - void addRecipe( ItemStack in, ItemStack out, ItemStack optional, float chance, ItemStack optional2, float chance2, int turns ); + /** + * add a new recipe with optional outputs, duplicates will not be added. + * + * @param in input + * @param out output + * @param optional optional output + * @param chance chance to get the optional output within 0.0 - 1.0 + * @param optional2 second optional output + * @param chance2 chance to get the second optional output within 0.0 - 1.0 + * @param turns amount of turns to turn the input into the outputs + */ + void addRecipe( + ItemStack in, + ItemStack out, + ItemStack optional, + float chance, + ItemStack optional2, + float chance2, + int turns); - /** - * Searches for a recipe for a given input, and returns it. - * - * @param input input - * @return identified recipe or null - */ - IGrinderEntry getRecipeForInput( ItemStack input ); + /** + * Searches for a recipe for a given input, and returns it. + * + * @param input input + * @return identified recipe or null + */ + IGrinderEntry getRecipeForInput(ItemStack input); } diff --git a/src/main/java/appeng/api/features/IInscriberRecipe.java b/src/main/java/appeng/api/features/IInscriberRecipe.java index 1137436d9fc..78f48a9067b 100644 --- a/src/main/java/appeng/api/features/IInscriberRecipe.java +++ b/src/main/java/appeng/api/features/IInscriberRecipe.java @@ -1,12 +1,9 @@ package appeng.api.features; - import com.google.common.base.Optional; -import net.minecraft.item.ItemStack; - -import javax.annotation.Nonnull; import java.util.List; - +import javax.annotation.Nonnull; +import net.minecraft.item.ItemStack; /** * Registration Records for {@link IInscriberRegistry} @@ -20,45 +17,44 @@ * @version rv2 * @since rv2 */ -public interface IInscriberRecipe -{ - /** - * the current inputs - * - * @return inputs the inscriber will accept - */ - @Nonnull - List getInputs(); - - /** - * gets the current output - * - * @return output that the recipe will produce - */ - @Nonnull - ItemStack getOutput(); - - /** - * gets the top optional - * - * @return item which is used top - */ - @Nonnull - Optional getTopOptional(); - - /** - * gets the bottom optional - * - * @return item which is used bottom - */ - @Nonnull - Optional getBottomOptional(); - - /** - * type of inscriber process - * - * @return type of process the inscriber is doing - */ - @Nonnull - InscriberProcessType getProcessType(); +public interface IInscriberRecipe { + /** + * the current inputs + * + * @return inputs the inscriber will accept + */ + @Nonnull + List getInputs(); + + /** + * gets the current output + * + * @return output that the recipe will produce + */ + @Nonnull + ItemStack getOutput(); + + /** + * gets the top optional + * + * @return item which is used top + */ + @Nonnull + Optional getTopOptional(); + + /** + * gets the bottom optional + * + * @return item which is used bottom + */ + @Nonnull + Optional getBottomOptional(); + + /** + * type of inscriber process + * + * @return type of process the inscriber is doing + */ + @Nonnull + InscriberProcessType getProcessType(); } diff --git a/src/main/java/appeng/api/features/IInscriberRecipeBuilder.java b/src/main/java/appeng/api/features/IInscriberRecipeBuilder.java index 99e2fdafb61..4fe34421b3d 100644 --- a/src/main/java/appeng/api/features/IInscriberRecipeBuilder.java +++ b/src/main/java/appeng/api/features/IInscriberRecipeBuilder.java @@ -1,11 +1,8 @@ package appeng.api.features; - -import net.minecraft.item.ItemStack; - -import javax.annotation.Nonnull; import java.util.Collection; - +import javax.annotation.Nonnull; +import net.minecraft.item.ItemStack; /** * Builder for an inscriber recipe @@ -14,69 +11,68 @@ * @version rv2 * @since rv2 */ -public interface IInscriberRecipeBuilder -{ - /** - * Creates an inscriber recipe with inputs. - * Needs to be invoked. - * - * @param inputs new inputs for the recipe - * @return currently used builder - */ - @Nonnull - IInscriberRecipeBuilder withInputs( @Nonnull Collection inputs ); +public interface IInscriberRecipeBuilder { + /** + * Creates an inscriber recipe with inputs. + * Needs to be invoked. + * + * @param inputs new inputs for the recipe + * @return currently used builder + */ + @Nonnull + IInscriberRecipeBuilder withInputs(@Nonnull Collection inputs); - /** - * Creates an inscriber recipe with output. - * Needs to be invoked. - * - * @param output new output for the recipe - * @return currently used builder - */ - @Nonnull - IInscriberRecipeBuilder withOutput( @Nonnull ItemStack output ); + /** + * Creates an inscriber recipe with output. + * Needs to be invoked. + * + * @param output new output for the recipe + * @return currently used builder + */ + @Nonnull + IInscriberRecipeBuilder withOutput(@Nonnull ItemStack output); - /** - * Creates an inscriber recipe with top. - * Either this or bot needs to be invoked. - * - * @param topOptional new top for the recipe - * @return currently used builder - */ - @Nonnull - IInscriberRecipeBuilder withTopOptional( @Nonnull ItemStack topOptional ); + /** + * Creates an inscriber recipe with top. + * Either this or bot needs to be invoked. + * + * @param topOptional new top for the recipe + * @return currently used builder + */ + @Nonnull + IInscriberRecipeBuilder withTopOptional(@Nonnull ItemStack topOptional); - /** - * Creates an inscriber recipe with bot. - * Either this or top needs to be invoked. - * - * @param bottomOptional new bot for the recipe - * @return currently used builder - */ - @Nonnull - IInscriberRecipeBuilder withBottomOptional( @Nonnull ItemStack bottomOptional ); + /** + * Creates an inscriber recipe with bot. + * Either this or top needs to be invoked. + * + * @param bottomOptional new bot for the recipe + * @return currently used builder + */ + @Nonnull + IInscriberRecipeBuilder withBottomOptional(@Nonnull ItemStack bottomOptional); - /** - * Creates an inscriber recipe with type. - * Needs to be invoked. - * - * @param type new type for the recipe - * @return currently used builder - */ - @Nonnull - IInscriberRecipeBuilder withProcessType( @Nonnull InscriberProcessType type ); + /** + * Creates an inscriber recipe with type. + * Needs to be invoked. + * + * @param type new type for the recipe + * @return currently used builder + */ + @Nonnull + IInscriberRecipeBuilder withProcessType(@Nonnull InscriberProcessType type); - /** - * Finalizes the process of making the recipe. - * Needs to be invoked to fetch inscriber recipe. - * - * @return legal inscriber recipe - * @throws IllegalStateException when input is not defined - * @throws IllegalStateException when input has no size - * @throws IllegalStateException when output is not defined - * @throws IllegalStateException when both optionals are not defined - * @throws IllegalStateException when process type is not defined - */ - @Nonnull - IInscriberRecipe build(); + /** + * Finalizes the process of making the recipe. + * Needs to be invoked to fetch inscriber recipe. + * + * @return legal inscriber recipe + * @throws IllegalStateException when input is not defined + * @throws IllegalStateException when input has no size + * @throws IllegalStateException when output is not defined + * @throws IllegalStateException when both optionals are not defined + * @throws IllegalStateException when process type is not defined + */ + @Nonnull + IInscriberRecipe build(); } diff --git a/src/main/java/appeng/api/features/IInscriberRegistry.java b/src/main/java/appeng/api/features/IInscriberRegistry.java index c4337332f5d..4aed5044da2 100644 --- a/src/main/java/appeng/api/features/IInscriberRegistry.java +++ b/src/main/java/appeng/api/features/IInscriberRegistry.java @@ -1,12 +1,9 @@ package appeng.api.features; - -import net.minecraft.item.ItemStack; - -import javax.annotation.Nonnull; import java.util.Collection; import java.util.Set; - +import javax.annotation.Nonnull; +import net.minecraft.item.ItemStack; /** * Lets you manipulate Inscriber Recipes, by adding or editing existing ones. @@ -15,58 +12,56 @@ * @version rv3 * @since rv2 */ -public interface IInscriberRegistry -{ - /** - * An immutable copy of currently registered recipes. - *

- * Use the provided methods to actually modify the inscriber recipes. - * - * @return currentlyRegisteredRecipes - * @see IInscriberRegistry#addRecipe(IInscriberRecipe) - * @see IInscriberRegistry#removeRecipe(IInscriberRecipe) - */ - @Nonnull - Collection getRecipes(); - - /** - * Optional items which are used in the top or bottom slot. - * - * @return set of all optional items - */ - @Nonnull - Set getOptionals(); +public interface IInscriberRegistry { + /** + * An immutable copy of currently registered recipes. + *

+ * Use the provided methods to actually modify the inscriber recipes. + * + * @return currentlyRegisteredRecipes + * @see IInscriberRegistry#addRecipe(IInscriberRecipe) + * @see IInscriberRegistry#removeRecipe(IInscriberRecipe) + */ + @Nonnull + Collection getRecipes(); - /** - * Get all registered items which are valid inputs. - * - * @return set of all input items - */ - @Nonnull - Set getInputs(); + /** + * Optional items which are used in the top or bottom slot. + * + * @return set of all optional items + */ + @Nonnull + Set getOptionals(); - /** - * Extensible way to create an inscriber recipe. - * - * @return builder for inscriber recipes - */ - @Nonnull - IInscriberRecipeBuilder builder(); + /** + * Get all registered items which are valid inputs. + * + * @return set of all input items + */ + @Nonnull + Set getInputs(); - /** - * add a new recipe the easy way, duplicates will not be added. - * Added recipes will be automatically added to the optionals and inputs. - * - * @param recipe new recipe - * @throws IllegalArgumentException if null is added - */ - void addRecipe( IInscriberRecipe recipe ); + /** + * Extensible way to create an inscriber recipe. + * + * @return builder for inscriber recipes + */ + @Nonnull + IInscriberRecipeBuilder builder(); - /** - * Removes all equal recipes from the registry. - * - * @param toBeRemovedRecipe to be removed recipe, can be null, makes just no sense. - */ - void removeRecipe( IInscriberRecipe toBeRemovedRecipe ); + /** + * add a new recipe the easy way, duplicates will not be added. + * Added recipes will be automatically added to the optionals and inputs. + * + * @param recipe new recipe + * @throws IllegalArgumentException if null is added + */ + void addRecipe(IInscriberRecipe recipe); + /** + * Removes all equal recipes from the registry. + * + * @param toBeRemovedRecipe to be removed recipe, can be null, makes just no sense. + */ + void removeRecipe(IInscriberRecipe toBeRemovedRecipe); } diff --git a/src/main/java/appeng/api/features/IItemComparison.java b/src/main/java/appeng/api/features/IItemComparison.java index b7d2b982b8d..ce2ef184d4b 100644 --- a/src/main/java/appeng/api/features/IItemComparison.java +++ b/src/main/java/appeng/api/features/IItemComparison.java @@ -23,10 +23,8 @@ package appeng.api.features; +public interface IItemComparison { + boolean sameAsPrecise(IItemComparison comp); -public interface IItemComparison -{ - boolean sameAsPrecise( IItemComparison comp ); - - boolean sameAsFuzzy( IItemComparison comp ); + boolean sameAsFuzzy(IItemComparison comp); } diff --git a/src/main/java/appeng/api/features/IItemComparisonProvider.java b/src/main/java/appeng/api/features/IItemComparisonProvider.java index 4c21c3a883b..5d9c4b99d0e 100644 --- a/src/main/java/appeng/api/features/IItemComparisonProvider.java +++ b/src/main/java/appeng/api/features/IItemComparisonProvider.java @@ -23,32 +23,29 @@ package appeng.api.features; - import net.minecraft.item.ItemStack; - /** * Provider for special comparisons. when an item is encountered AE Will request * if the comparison function handles the item, by trying to request a * IItemComparison class. */ -public interface IItemComparisonProvider -{ +public interface IItemComparisonProvider { - /** - * should return a new IItemComparison, or return null if it doesn't handle - * the supplied item. - * - * @param is item - * @return IItemComparison, or null - */ - IItemComparison getComparison( ItemStack is ); + /** + * should return a new IItemComparison, or return null if it doesn't handle + * the supplied item. + * + * @param is item + * @return IItemComparison, or null + */ + IItemComparison getComparison(ItemStack is); - /** - * Simple test for support ( AE generally skips this and calls the above function. ) - * - * @param stack item - * @return true, if getComparison will return a valid IItemComparison Object - */ - boolean canHandle( ItemStack stack ); -} \ No newline at end of file + /** + * Simple test for support ( AE generally skips this and calls the above function. ) + * + * @param stack item + * @return true, if getComparison will return a valid IItemComparison Object + */ + boolean canHandle(ItemStack stack); +} diff --git a/src/main/java/appeng/api/features/ILocatable.java b/src/main/java/appeng/api/features/ILocatable.java index c64a937fc0b..b8abd4f3e59 100644 --- a/src/main/java/appeng/api/features/ILocatable.java +++ b/src/main/java/appeng/api/features/ILocatable.java @@ -23,19 +23,16 @@ package appeng.api.features; - import appeng.api.events.LocatableEventAnnounce; - /** * A registration record for the {@link ILocatableRegistry} use the {@link LocatableEventAnnounce} event on the Forge * Event bus to update the registry. */ -public interface ILocatable -{ +public interface ILocatable { - /** - * @return the serial for a locatable object - */ - long getLocatableSerial(); -} \ No newline at end of file + /** + * @return the serial for a locatable object + */ + long getLocatableSerial(); +} diff --git a/src/main/java/appeng/api/features/ILocatableRegistry.java b/src/main/java/appeng/api/features/ILocatableRegistry.java index 853638b882f..79d943a4a17 100644 --- a/src/main/java/appeng/api/features/ILocatableRegistry.java +++ b/src/main/java/appeng/api/features/ILocatableRegistry.java @@ -23,28 +23,26 @@ package appeng.api.features; - /** * A Registry for locatable items, works based on serial numbers. */ -public interface ILocatableRegistry -{ - /** - * Attempts to find the object with the serial specified, if it can it - * returns the object. - * - * @param serial serial - * @return requestedObject, or null - * @deprecated use {@link ILocatableRegistry#getLocatableBy(long)} - */ - @Deprecated - Object findLocatableBySerial( long serial ); +public interface ILocatableRegistry { + /** + * Attempts to find the object with the serial specified, if it can it + * returns the object. + * + * @param serial serial + * @return requestedObject, or null + * @deprecated use {@link ILocatableRegistry#getLocatableBy(long)} + */ + @Deprecated + Object findLocatableBySerial(long serial); - /** - * Gets the {@link ILocatable} with the registered serial, if available - * - * @param serial serial - * @return requestedObject, or null, if the object does not exist anymore - */ - ILocatable getLocatableBy( long serial ); -} \ No newline at end of file + /** + * Gets the {@link ILocatable} with the registered serial, if available + * + * @param serial serial + * @return requestedObject, or null, if the object does not exist anymore + */ + ILocatable getLocatableBy(long serial); +} diff --git a/src/main/java/appeng/api/features/IMatterCannonAmmoRegistry.java b/src/main/java/appeng/api/features/IMatterCannonAmmoRegistry.java index c73eff5022c..368c88baef1 100644 --- a/src/main/java/appeng/api/features/IMatterCannonAmmoRegistry.java +++ b/src/main/java/appeng/api/features/IMatterCannonAmmoRegistry.java @@ -23,26 +23,23 @@ package appeng.api.features; - import net.minecraft.item.ItemStack; +public interface IMatterCannonAmmoRegistry { -public interface IMatterCannonAmmoRegistry -{ - - /** - * register a new ammo, generally speaking this is based off of atomic weight to make it easier to guess at - * - * @param ammo new ammo - * @param weight atomic weight - */ - void registerAmmo( ItemStack ammo, double weight ); + /** + * register a new ammo, generally speaking this is based off of atomic weight to make it easier to guess at + * + * @param ammo new ammo + * @param weight atomic weight + */ + void registerAmmo(ItemStack ammo, double weight); - /** - * get the penetration value for a particular ammo, 0 indicates a non-ammo. - * - * @param is ammo - * @return 0 or a valid penetration value. - */ - float getPenetration( ItemStack is ); + /** + * get the penetration value for a particular ammo, 0 indicates a non-ammo. + * + * @param is ammo + * @return 0 or a valid penetration value. + */ + float getPenetration(ItemStack is); } diff --git a/src/main/java/appeng/api/features/INetworkEncodable.java b/src/main/java/appeng/api/features/INetworkEncodable.java index 91dc8cebf28..62d675113f6 100644 --- a/src/main/java/appeng/api/features/INetworkEncodable.java +++ b/src/main/java/appeng/api/features/INetworkEncodable.java @@ -23,27 +23,24 @@ package appeng.api.features; - import net.minecraft.item.ItemStack; +public interface INetworkEncodable { -public interface INetworkEncodable -{ - - /** - * Used to get the current key from the item. - * - * @param item item - * @return string key of item - */ - String getEncryptionKey( ItemStack item ); + /** + * Used to get the current key from the item. + * + * @param item item + * @return string key of item + */ + String getEncryptionKey(ItemStack item); - /** - * Encode the wireless frequency via the Controller. - * - * @param item the wireless terminal. - * @param encKey the wireless encryption key. - * @param name null for now. - */ - void setEncryptionKey( ItemStack item, String encKey, String name ); + /** + * Encode the wireless frequency via the Controller. + * + * @param item the wireless terminal. + * @param encKey the wireless encryption key. + * @param name null for now. + */ + void setEncryptionKey(ItemStack item, String encKey, String name); } diff --git a/src/main/java/appeng/api/features/IP2PTunnelRegistry.java b/src/main/java/appeng/api/features/IP2PTunnelRegistry.java index 137d731bd83..d1e6e4f3ab0 100644 --- a/src/main/java/appeng/api/features/IP2PTunnelRegistry.java +++ b/src/main/java/appeng/api/features/IP2PTunnelRegistry.java @@ -23,34 +23,30 @@ package appeng.api.features; - import appeng.api.config.TunnelType; -import net.minecraft.item.ItemStack; - import javax.annotation.Nullable; - +import net.minecraft.item.ItemStack; /** * A Registry for how p2p Tunnels are attuned */ -public interface IP2PTunnelRegistry -{ - - /** - * Allows third parties to register items from their mod as potential - * attunements for AE's P2P Tunnels - * - * @param trigger - the item which triggers attunement. Nullable, but then ignored - * @param type - the type of tunnel. Nullable, but then ignored - */ - void addNewAttunement( @Nullable ItemStack trigger, @Nullable TunnelType type ); - - /** - * returns null if no attunement can be found. - * - * @param trigger attunement trigger - * @return null if no attunement can be found or attunement - */ - @Nullable - TunnelType getTunnelTypeByItem( ItemStack trigger ); -} \ No newline at end of file +public interface IP2PTunnelRegistry { + + /** + * Allows third parties to register items from their mod as potential + * attunements for AE's P2P Tunnels + * + * @param trigger - the item which triggers attunement. Nullable, but then ignored + * @param type - the type of tunnel. Nullable, but then ignored + */ + void addNewAttunement(@Nullable ItemStack trigger, @Nullable TunnelType type); + + /** + * returns null if no attunement can be found. + * + * @param trigger attunement trigger + * @return null if no attunement can be found or attunement + */ + @Nullable + TunnelType getTunnelTypeByItem(ItemStack trigger); +} diff --git a/src/main/java/appeng/api/features/IPlayerRegistry.java b/src/main/java/appeng/api/features/IPlayerRegistry.java index 18219b76ab6..c818bb5565a 100644 --- a/src/main/java/appeng/api/features/IPlayerRegistry.java +++ b/src/main/java/appeng/api/features/IPlayerRegistry.java @@ -23,36 +23,32 @@ package appeng.api.features; - import com.mojang.authlib.GameProfile; -import net.minecraft.entity.player.EntityPlayer; - import javax.annotation.Nullable; - +import net.minecraft.entity.player.EntityPlayer; /** * Maintains a save specific list of userids and username combinations this greatly simplifies storage internally and * gives a common place to look up and get IDs for the security framework. */ -public interface IPlayerRegistry -{ - - /** - * @param gameProfile user game profile - * @return user id of a username. - */ - int getID( GameProfile gameProfile ); - - /** - * @param player player - * @return user id of a player entity. - */ - int getID( EntityPlayer player ); - - /** - * @param playerID to be found player id - * @return PlayerEntity, or null if the player could not be found. - */ - @Nullable - EntityPlayer findPlayer( int playerID ); +public interface IPlayerRegistry { + + /** + * @param gameProfile user game profile + * @return user id of a username. + */ + int getID(GameProfile gameProfile); + + /** + * @param player player + * @return user id of a player entity. + */ + int getID(EntityPlayer player); + + /** + * @param playerID to be found player id + * @return PlayerEntity, or null if the player could not be found. + */ + @Nullable + EntityPlayer findPlayer(int playerID); } diff --git a/src/main/java/appeng/api/features/IRecipeHandlerRegistry.java b/src/main/java/appeng/api/features/IRecipeHandlerRegistry.java index 1e225c225f2..e1b304867c4 100644 --- a/src/main/java/appeng/api/features/IRecipeHandlerRegistry.java +++ b/src/main/java/appeng/api/features/IRecipeHandlerRegistry.java @@ -23,61 +23,57 @@ package appeng.api.features; - import appeng.api.recipes.ICraftHandler; import appeng.api.recipes.IRecipeHandler; import appeng.api.recipes.ISubItemResolver; - import javax.annotation.Nullable; - /** * @author AlgorithmX2 * @author thatsIch * @version rv3 - 10.08.2015 * @since rv0 */ -public interface IRecipeHandlerRegistry -{ +public interface IRecipeHandlerRegistry { - /** - * Add a new Recipe Handler to the parser. - *

- * MUST BE CALLED IN PRE-INIT - * - * @param name name of crafthandler - * @param handler class of crafthandler - */ - void addNewCraftHandler( String name, Class handler ); + /** + * Add a new Recipe Handler to the parser. + *

+ * MUST BE CALLED IN PRE-INIT + * + * @param name name of crafthandler + * @param handler class of crafthandler + */ + void addNewCraftHandler(String name, Class handler); - /** - * Add a new resolver to the parser. - *

- * MUST BE CALLED IN PRE-INIT - * - * @param sir sub item resolver - */ - void addNewSubItemResolver( ISubItemResolver sir ); + /** + * Add a new resolver to the parser. + *

+ * MUST BE CALLED IN PRE-INIT + * + * @param sir sub item resolver + */ + void addNewSubItemResolver(ISubItemResolver sir); - /** - * @param name name of crafting handler - * @return A recipe handler by name, returns null on failure. - */ - @Nullable - ICraftHandler getCraftHandlerFor( String name ); + /** + * @param name name of crafting handler + * @return A recipe handler by name, returns null on failure. + */ + @Nullable + ICraftHandler getCraftHandlerFor(String name); - /** - * @return a new recipe handler, which can be used to parse, and read recipe files. - */ - IRecipeHandler createNewRecipehandler(); + /** + * @return a new recipe handler, which can be used to parse, and read recipe files. + */ + IRecipeHandler createNewRecipehandler(); - /** - * resolve sub items by name. - * - * @param nameSpace namespace of item - * @param itemName full name of item - * @return ResolverResult or ResolverResultSet or null if could not resolve - */ - @Nullable - Object resolveItem( String nameSpace, String itemName ); + /** + * resolve sub items by name. + * + * @param nameSpace namespace of item + * @param itemName full name of item + * @return ResolverResult or ResolverResultSet or null if could not resolve + */ + @Nullable + Object resolveItem(String nameSpace, String itemName); } diff --git a/src/main/java/appeng/api/features/IRegistryContainer.java b/src/main/java/appeng/api/features/IRegistryContainer.java index 9b3a7e10348..73929529ea5 100644 --- a/src/main/java/appeng/api/features/IRegistryContainer.java +++ b/src/main/java/appeng/api/features/IRegistryContainer.java @@ -23,90 +23,87 @@ package appeng.api.features; - import appeng.api.movable.IMovableRegistry; import appeng.api.networking.IGridCacheRegistry; import appeng.api.storage.ICellRegistry; import appeng.api.storage.IExternalStorageRegistry; - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public interface IRegistryContainer -{ - - /** - * Use the movable registry to white list your tiles. - */ - IMovableRegistry movable(); - - /** - * Add new Grid Caches for use during run time, only use during loading phase. - */ - IGridCacheRegistry gridCache(); - - /** - * Add additional storage bus handlers to improve interplay with mod blocks that contains special inventories that - * function unlike vanilla chests. AE uses this internally for barrels, DSU's, quantum chests, AE Networks and more. - */ - IExternalStorageRegistry externalStorage(); - - /** - * Add additional special comparison functionality, AE Uses this internally for Bees. - */ - ISpecialComparisonRegistry specialComparison(); - - /** - * Lets you register your items as wireless terminals - */ - IWirelessTermRegistry wireless(); - - /** - * Allows you to register new cell types, these will function in drives - */ - ICellRegistry cell(); - - /** - * Manage grinder recipes via API - */ - IGrinderRegistry grinder(); - - /** - * Manage inscriber recipes via API - */ - IInscriberRegistry inscriber(); - - /** - * get access to the locatable registry - */ - ILocatableRegistry locatable(); - - /** - * get access to the p2p tunnel registry. - */ - IP2PTunnelRegistry p2pTunnel(); - - /** - * get access to the ammo registry. - */ - IMatterCannonAmmoRegistry matterCannon(); - - /** - * get access to the player registry - */ - IPlayerRegistry players(); - - /** - * get access to the ae2 recipe api - */ - IRecipeHandlerRegistry recipes(); - - /** - * get access to the world-gen api. - */ - IWorldGen worldgen(); +public interface IRegistryContainer { + + /** + * Use the movable registry to white list your tiles. + */ + IMovableRegistry movable(); + + /** + * Add new Grid Caches for use during run time, only use during loading phase. + */ + IGridCacheRegistry gridCache(); + + /** + * Add additional storage bus handlers to improve interplay with mod blocks that contains special inventories that + * function unlike vanilla chests. AE uses this internally for barrels, DSU's, quantum chests, AE Networks and more. + */ + IExternalStorageRegistry externalStorage(); + + /** + * Add additional special comparison functionality, AE Uses this internally for Bees. + */ + ISpecialComparisonRegistry specialComparison(); + + /** + * Lets you register your items as wireless terminals + */ + IWirelessTermRegistry wireless(); + + /** + * Allows you to register new cell types, these will function in drives + */ + ICellRegistry cell(); + + /** + * Manage grinder recipes via API + */ + IGrinderRegistry grinder(); + + /** + * Manage inscriber recipes via API + */ + IInscriberRegistry inscriber(); + + /** + * get access to the locatable registry + */ + ILocatableRegistry locatable(); + + /** + * get access to the p2p tunnel registry. + */ + IP2PTunnelRegistry p2pTunnel(); + + /** + * get access to the ammo registry. + */ + IMatterCannonAmmoRegistry matterCannon(); + + /** + * get access to the player registry + */ + IPlayerRegistry players(); + + /** + * get access to the ae2 recipe api + */ + IRecipeHandlerRegistry recipes(); + + /** + * get access to the world-gen api. + */ + IWorldGen worldgen(); } diff --git a/src/main/java/appeng/api/features/ISpecialComparisonRegistry.java b/src/main/java/appeng/api/features/ISpecialComparisonRegistry.java index 43fdf6eb3c6..5484f36e749 100644 --- a/src/main/java/appeng/api/features/ISpecialComparisonRegistry.java +++ b/src/main/java/appeng/api/features/ISpecialComparisonRegistry.java @@ -23,28 +23,25 @@ package appeng.api.features; - import net.minecraft.item.ItemStack; - /** * A Registry of any special comparison handlers for AE To use. */ -public interface ISpecialComparisonRegistry -{ +public interface ISpecialComparisonRegistry { - /** - * return TheHandler or null. - * - * @param stack item - * @return a handler it found for a specific item - */ - IItemComparison getSpecialComparison( ItemStack stack ); + /** + * return TheHandler or null. + * + * @param stack item + * @return a handler it found for a specific item + */ + IItemComparison getSpecialComparison(ItemStack stack); - /** - * Register a new special comparison function with AE. - * - * @param prov comparison provider - */ - void addComparisonProvider( IItemComparisonProvider prov ); -} \ No newline at end of file + /** + * Register a new special comparison function with AE. + * + * @param prov comparison provider + */ + void addComparisonProvider(IItemComparisonProvider prov); +} diff --git a/src/main/java/appeng/api/features/IWirelessTermHandler.java b/src/main/java/appeng/api/features/IWirelessTermHandler.java index b1da6d726cc..09613eef5da 100644 --- a/src/main/java/appeng/api/features/IWirelessTermHandler.java +++ b/src/main/java/appeng/api/features/IWirelessTermHandler.java @@ -23,47 +23,44 @@ package appeng.api.features; - import appeng.api.util.IConfigManager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; - /** * A handler for a wireless terminal. */ -public interface IWirelessTermHandler extends INetworkEncodable -{ +public interface IWirelessTermHandler extends INetworkEncodable { - /** - * @param is wireless terminal - * @return true, if usePower, hasPower, etc... can be called for the provided item - */ - boolean canHandle( ItemStack is ); + /** + * @param is wireless terminal + * @return true, if usePower, hasPower, etc... can be called for the provided item + */ + boolean canHandle(ItemStack is); - /** - * use an amount of power, in AE units - * - * @param amount is in AE units ( 5 per MJ ), if you return false, the item should be dead and return false for - * hasPower - * @param is wireless terminal - * @return true if wireless terminal uses power - */ - boolean usePower( EntityPlayer player, double amount, ItemStack is ); + /** + * use an amount of power, in AE units + * + * @param amount is in AE units ( 5 per MJ ), if you return false, the item should be dead and return false for + * hasPower + * @param is wireless terminal + * @return true if wireless terminal uses power + */ + boolean usePower(EntityPlayer player, double amount, ItemStack is); - /** - * gets the power status of the item. - * - * @param is wireless terminal - * @return returns true if there is any power left. - */ - boolean hasPower( EntityPlayer player, double amount, ItemStack is ); + /** + * gets the power status of the item. + * + * @param is wireless terminal + * @return returns true if there is any power left. + */ + boolean hasPower(EntityPlayer player, double amount, ItemStack is); - /** - * Return the config manager for the wireless terminal. - * - * @param is wireless terminal - * @return config manager of wireless terminal - */ - IConfigManager getConfigManager( ItemStack is ); -} \ No newline at end of file + /** + * Return the config manager for the wireless terminal. + * + * @param is wireless terminal + * @return config manager of wireless terminal + */ + IConfigManager getConfigManager(ItemStack is); +} diff --git a/src/main/java/appeng/api/features/IWirelessTermRegistry.java b/src/main/java/appeng/api/features/IWirelessTermRegistry.java index aea2b71c05b..d42864efd86 100644 --- a/src/main/java/appeng/api/features/IWirelessTermRegistry.java +++ b/src/main/java/appeng/api/features/IWirelessTermRegistry.java @@ -23,41 +23,38 @@ package appeng.api.features; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; - /** * Registration record for a Custom Cell handler. */ -public interface IWirelessTermRegistry -{ - - /** - * add this handler to the list of other wireless handler. - * - * @param handler wireless handler - */ - void registerWirelessHandler( IWirelessTermHandler handler ); - - /** - * @param is item which might have a handler - * @return true if there is a handler for this item - */ - boolean isWirelessTerminal( ItemStack is ); - - /** - * @param is item with handler - * @return a register handler for the item in question, or null if there - * isn't one - */ - IWirelessTermHandler getWirelessTerminalHandler( ItemStack is ); - - /** - * opens the wireless terminal gui, the wireless terminal item, must be in - * the active slot on the tool bar. - */ - void openWirelessTerminalGui( ItemStack item, World w, EntityPlayer player ); +public interface IWirelessTermRegistry { + + /** + * add this handler to the list of other wireless handler. + * + * @param handler wireless handler + */ + void registerWirelessHandler(IWirelessTermHandler handler); + + /** + * @param is item which might have a handler + * @return true if there is a handler for this item + */ + boolean isWirelessTerminal(ItemStack is); + + /** + * @param is item with handler + * @return a register handler for the item in question, or null if there + * isn't one + */ + IWirelessTermHandler getWirelessTerminalHandler(ItemStack is); + + /** + * opens the wireless terminal gui, the wireless terminal item, must be in + * the active slot on the tool bar. + */ + void openWirelessTerminalGui(ItemStack item, World w, EntityPlayer player); } diff --git a/src/main/java/appeng/api/features/IWorldGen.java b/src/main/java/appeng/api/features/IWorldGen.java index 8e5a9c7363d..633047e4233 100644 --- a/src/main/java/appeng/api/features/IWorldGen.java +++ b/src/main/java/appeng/api/features/IWorldGen.java @@ -23,24 +23,22 @@ package appeng.api.features; - import net.minecraft.world.World; import net.minecraft.world.WorldProvider; +public interface IWorldGen { -public interface IWorldGen -{ - - void disableWorldGenForProviderID( WorldGenType type, Class provider ); + void disableWorldGenForProviderID(WorldGenType type, Class provider); - void enableWorldGenForDimension( WorldGenType type, int dimID ); + void enableWorldGenForDimension(WorldGenType type, int dimID); - void disableWorldGenForDimension( WorldGenType type, int dimID ); + void disableWorldGenForDimension(WorldGenType type, int dimID); - boolean isWorldGenEnabled( WorldGenType type, World w ); + boolean isWorldGenEnabled(WorldGenType type, World w); - enum WorldGenType - { - CertusQuartz, ChargedCertusQuartz, Meteorites - } + enum WorldGenType { + CertusQuartz, + ChargedCertusQuartz, + Meteorites + } } diff --git a/src/main/java/appeng/api/features/InscriberProcessType.java b/src/main/java/appeng/api/features/InscriberProcessType.java index 70aaa9f7a04..bf505861432 100644 --- a/src/main/java/appeng/api/features/InscriberProcessType.java +++ b/src/main/java/appeng/api/features/InscriberProcessType.java @@ -1,15 +1,13 @@ package appeng.api.features; +public enum InscriberProcessType { + /** + * uses the optionals as catalyst + */ + Inscribe, -public enum InscriberProcessType -{ - /** - * uses the optionals as catalyst - */ - Inscribe, - - /** - * spends the optionals - */ - Press + /** + * spends the optionals + */ + Press } diff --git a/src/main/java/appeng/api/implementations/ICraftingPatternItem.java b/src/main/java/appeng/api/implementations/ICraftingPatternItem.java index 132a5ef08e2..6fef18e9ebc 100644 --- a/src/main/java/appeng/api/implementations/ICraftingPatternItem.java +++ b/src/main/java/appeng/api/implementations/ICraftingPatternItem.java @@ -23,25 +23,22 @@ package appeng.api.implementations; - import appeng.api.networking.crafting.ICraftingPatternDetails; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; - /** * Implemented on {@link Item} */ -public interface ICraftingPatternItem -{ +public interface ICraftingPatternItem { - /** - * Access Details about a pattern - * - * @param is pattern - * @param w crafting world - * @return details of pattern - */ - ICraftingPatternDetails getPatternForItem( ItemStack is, World w ); + /** + * Access Details about a pattern + * + * @param is pattern + * @param w crafting world + * @return details of pattern + */ + ICraftingPatternDetails getPatternForItem(ItemStack is, World w); } diff --git a/src/main/java/appeng/api/implementations/IPowerChannelState.java b/src/main/java/appeng/api/implementations/IPowerChannelState.java index 48e620cf781..964fc3f27ed 100644 --- a/src/main/java/appeng/api/implementations/IPowerChannelState.java +++ b/src/main/java/appeng/api/implementations/IPowerChannelState.java @@ -23,22 +23,22 @@ package appeng.api.implementations; - /** * This is intended for use on the client side to provide details to WAILA. */ -public interface IPowerChannelState -{ +public interface IPowerChannelState { - /** - * @return true if the part/tile is powered. - */ - boolean isPowered(); + /** + * @return true if the part/tile is powered. + */ + boolean isPowered(); - /** - * @return true if the part/tile isActive - */ - boolean isActive(); + /** + * @return true if the part/tile isActive + */ + boolean isActive(); - default boolean isBooting(){ return false; } + default boolean isBooting() { + return false; + } } diff --git a/src/main/java/appeng/api/implementations/IUpgradeableHost.java b/src/main/java/appeng/api/implementations/IUpgradeableHost.java index 7abc93f970c..2da8c4d0fd1 100644 --- a/src/main/java/appeng/api/implementations/IUpgradeableHost.java +++ b/src/main/java/appeng/api/implementations/IUpgradeableHost.java @@ -23,25 +23,22 @@ package appeng.api.implementations; - import appeng.api.config.Upgrades; import appeng.api.implementations.tiles.ISegmentedInventory; import appeng.api.util.IConfigurableObject; import net.minecraft.tileentity.TileEntity; +public interface IUpgradeableHost extends IConfigurableObject, ISegmentedInventory { -public interface IUpgradeableHost extends IConfigurableObject, ISegmentedInventory -{ - - /** - * determine how many of an upgrade are installed. - */ - int getInstalledUpgrades( Upgrades u ); + /** + * determine how many of an upgrade are installed. + */ + int getInstalledUpgrades(Upgrades u); - /** - * the tile... - * - * @return tile entity - */ - TileEntity getTile(); + /** + * the tile... + * + * @return tile entity + */ + TileEntity getTile(); } diff --git a/src/main/java/appeng/api/implementations/TransitionResult.java b/src/main/java/appeng/api/implementations/TransitionResult.java index 9eec763e898..b83357777cc 100644 --- a/src/main/java/appeng/api/implementations/TransitionResult.java +++ b/src/main/java/appeng/api/implementations/TransitionResult.java @@ -23,19 +23,16 @@ package appeng.api.implementations; - /** * Defines the result of performing a transition from the world into a storage * cell, if its possible, and what the energy usage is. */ -public class TransitionResult -{ - public final boolean success; - public final double energyUsage; +public class TransitionResult { + public final boolean success; + public final double energyUsage; - public TransitionResult( final boolean _success, final double power ) - { - this.success = _success; - this.energyUsage = power; - } + public TransitionResult(final boolean _success, final double power) { + this.success = _success; + this.energyUsage = power; + } } diff --git a/src/main/java/appeng/api/implementations/guiobjects/IGuiItem.java b/src/main/java/appeng/api/implementations/guiobjects/IGuiItem.java index 269eea2a24d..fa02992132f 100644 --- a/src/main/java/appeng/api/implementations/guiobjects/IGuiItem.java +++ b/src/main/java/appeng/api/implementations/guiobjects/IGuiItem.java @@ -23,17 +23,14 @@ package appeng.api.implementations.guiobjects; - import net.minecraft.item.ItemStack; import net.minecraft.world.World; - /** * Implemented on Item objects, to return objects used to manage, and interact * with the contents. */ -public interface IGuiItem -{ +public interface IGuiItem { - IGuiItemObject getGuiObject( ItemStack is, World world, int x, int y, int z ); + IGuiItemObject getGuiObject(ItemStack is, World world, int x, int y, int z); } diff --git a/src/main/java/appeng/api/implementations/guiobjects/IGuiItemObject.java b/src/main/java/appeng/api/implementations/guiobjects/IGuiItemObject.java index 3421873946a..5d08fb530aa 100644 --- a/src/main/java/appeng/api/implementations/guiobjects/IGuiItemObject.java +++ b/src/main/java/appeng/api/implementations/guiobjects/IGuiItemObject.java @@ -23,12 +23,9 @@ package appeng.api.implementations.guiobjects; - import net.minecraft.item.ItemStack; +public interface IGuiItemObject { -public interface IGuiItemObject -{ - - ItemStack getItemStack(); + ItemStack getItemStack(); } diff --git a/src/main/java/appeng/api/implementations/guiobjects/INetworkTool.java b/src/main/java/appeng/api/implementations/guiobjects/INetworkTool.java index 931b5234d8e..1fc7231f1e0 100644 --- a/src/main/java/appeng/api/implementations/guiobjects/INetworkTool.java +++ b/src/main/java/appeng/api/implementations/guiobjects/INetworkTool.java @@ -23,16 +23,13 @@ package appeng.api.implementations.guiobjects; - import appeng.api.networking.IGridHost; import net.minecraft.inventory.IInventory; - /** * Obtained via {@link IGuiItem} getGuiObject */ -public interface INetworkTool extends IInventory, IGuiItemObject -{ +public interface INetworkTool extends IInventory, IGuiItemObject { - IGridHost getGridHost(); // null for most purposes. + IGridHost getGridHost(); // null for most purposes. } diff --git a/src/main/java/appeng/api/implementations/guiobjects/IPortableCell.java b/src/main/java/appeng/api/implementations/guiobjects/IPortableCell.java index 7a80a00b565..a4f85901c59 100644 --- a/src/main/java/appeng/api/implementations/guiobjects/IPortableCell.java +++ b/src/main/java/appeng/api/implementations/guiobjects/IPortableCell.java @@ -23,17 +23,12 @@ package appeng.api.implementations.guiobjects; - import appeng.api.networking.energy.IEnergySource; import appeng.api.storage.IMEMonitor; import appeng.api.storage.ITerminalHost; import appeng.api.storage.data.IAEItemStack; - /** * Obtained via {@link IGuiItem} getGuiObject */ -public interface IPortableCell extends ITerminalHost, IMEMonitor, IEnergySource, IGuiItemObject -{ - -} +public interface IPortableCell extends ITerminalHost, IMEMonitor, IEnergySource, IGuiItemObject {} diff --git a/src/main/java/appeng/api/implementations/items/IAEItemPowerStorage.java b/src/main/java/appeng/api/implementations/items/IAEItemPowerStorage.java index fe7daf0bedf..15ca18d9a56 100644 --- a/src/main/java/appeng/api/implementations/items/IAEItemPowerStorage.java +++ b/src/main/java/appeng/api/implementations/items/IAEItemPowerStorage.java @@ -23,50 +23,47 @@ package appeng.api.implementations.items; - import appeng.api.config.AccessRestriction; import appeng.api.networking.energy.IAEPowerStorage; import net.minecraft.item.ItemStack; - /** * Basically the same as {@link IAEPowerStorage}, but for items. */ -public interface IAEItemPowerStorage -{ +public interface IAEItemPowerStorage { - /** - * Inject amt, power into the device, it will store what it can, and return - * the amount unable to be stored. - * - * @return amount unable to be stored - */ - double injectAEPower( ItemStack is, double amt ); + /** + * Inject amt, power into the device, it will store what it can, and return + * the amount unable to be stored. + * + * @return amount unable to be stored + */ + double injectAEPower(ItemStack is, double amt); - /** - * Attempt to extract power from the device, it will extract what it can and - * return it. - * - * @param amt to be extracted power from device - * @return what it could extract - */ - double extractAEPower( ItemStack is, double amt ); + /** + * Attempt to extract power from the device, it will extract what it can and + * return it. + * + * @param amt to be extracted power from device + * @return what it could extract + */ + double extractAEPower(ItemStack is, double amt); - /** - * @return the current maximum power ( this can change :P ) - */ - double getAEMaxPower( ItemStack is ); + /** + * @return the current maximum power ( this can change :P ) + */ + double getAEMaxPower(ItemStack is); - /** - * @return the current AE Power Level, this may exceed getMEMaxPower() - */ - double getAECurrentPower( ItemStack is ); + /** + * @return the current AE Power Level, this may exceed getMEMaxPower() + */ + double getAECurrentPower(ItemStack is); - /** - * Control the power flow by telling what the network can do, either add? or - * subtract? or both! - * - * @return access restriction of network - */ - AccessRestriction getPowerFlow( ItemStack is ); -} \ No newline at end of file + /** + * Control the power flow by telling what the network can do, either add? or + * subtract? or both! + * + * @return access restriction of network + */ + AccessRestriction getPowerFlow(ItemStack is); +} diff --git a/src/main/java/appeng/api/implementations/items/IAEWrench.java b/src/main/java/appeng/api/implementations/items/IAEWrench.java index 48bedac6255..79c60b97f60 100644 --- a/src/main/java/appeng/api/implementations/items/IAEWrench.java +++ b/src/main/java/appeng/api/implementations/items/IAEWrench.java @@ -23,26 +23,23 @@ package appeng.api.implementations.items; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; - /** * Implemented on AE's wrench(s) as a substitute for if BC's API is not * available. */ -public interface IAEWrench -{ +public interface IAEWrench { - /** - * Check if the wrench can be used. - * - * @param player wrenching player - * @param x x pos of wrenched block - * @param y y pos of wrenched block - * @param z z pos of wrenched block - * @return true if wrench can be used - */ - boolean canWrench( ItemStack wrench, EntityPlayer player, int x, int y, int z ); + /** + * Check if the wrench can be used. + * + * @param player wrenching player + * @param x x pos of wrenched block + * @param y y pos of wrenched block + * @param z z pos of wrenched block + * @return true if wrench can be used + */ + boolean canWrench(ItemStack wrench, EntityPlayer player, int x, int y, int z); } diff --git a/src/main/java/appeng/api/implementations/items/IBiometricCard.java b/src/main/java/appeng/api/implementations/items/IBiometricCard.java index 3a06b9e711a..79e4a782ac7 100644 --- a/src/main/java/appeng/api/implementations/items/IBiometricCard.java +++ b/src/main/java/appeng/api/implementations/items/IBiometricCard.java @@ -23,65 +23,61 @@ package appeng.api.implementations.items; - import appeng.api.config.SecurityPermissions; import appeng.api.features.IPlayerRegistry; import appeng.api.networking.security.ISecurityRegistry; import com.mojang.authlib.GameProfile; -import net.minecraft.item.ItemStack; - import java.util.EnumSet; +import net.minecraft.item.ItemStack; +public interface IBiometricCard { -public interface IBiometricCard -{ - - /** - * Set the {@link GameProfile} to null, to clear it. - */ - void setProfile( ItemStack itemStack, GameProfile username ); + /** + * Set the {@link GameProfile} to null, to clear it. + */ + void setProfile(ItemStack itemStack, GameProfile username); - /** - * @return {@link GameProfile} of the player encoded on this card, or a blank string. - */ - GameProfile getProfile( ItemStack is ); + /** + * @return {@link GameProfile} of the player encoded on this card, or a blank string. + */ + GameProfile getProfile(ItemStack is); - /** - * @param itemStack card - * @return the full list of permissions encoded on the card. - */ - EnumSet getPermissions( ItemStack itemStack ); + /** + * @param itemStack card + * @return the full list of permissions encoded on the card. + */ + EnumSet getPermissions(ItemStack itemStack); - /** - * Check if a permission is encoded on the card. - * - * @param permission card - * @return true if this permission is set on the card. - */ - boolean hasPermission( ItemStack is, SecurityPermissions permission ); + /** + * Check if a permission is encoded on the card. + * + * @param permission card + * @return true if this permission is set on the card. + */ + boolean hasPermission(ItemStack is, SecurityPermissions permission); - /** - * remove a permission from the item stack. - * - * @param itemStack card - * @param permission to be removed permission - */ - void removePermission( ItemStack itemStack, SecurityPermissions permission ); + /** + * remove a permission from the item stack. + * + * @param itemStack card + * @param permission to be removed permission + */ + void removePermission(ItemStack itemStack, SecurityPermissions permission); - /** - * add a permission to the item stack. - * - * @param itemStack card - * @param permission to be added permission - */ - void addPermission( ItemStack itemStack, SecurityPermissions permission ); + /** + * add a permission to the item stack. + * + * @param itemStack card + * @param permission to be added permission + */ + void addPermission(ItemStack itemStack, SecurityPermissions permission); - /** - * lets you handle submission of security values on the card for custom behavior. - * - * @param registry security registry - * @param pr player registry - * @param is card - */ - void registerPermissions( ISecurityRegistry registry, IPlayerRegistry pr, ItemStack is ); + /** + * lets you handle submission of security values on the card for custom behavior. + * + * @param registry security registry + * @param pr player registry + * @param is card + */ + void registerPermissions(ISecurityRegistry registry, IPlayerRegistry pr, ItemStack is); } diff --git a/src/main/java/appeng/api/implementations/items/IGrowableCrystal.java b/src/main/java/appeng/api/implementations/items/IGrowableCrystal.java index 489e2b89cb6..a76c2b0e7b2 100644 --- a/src/main/java/appeng/api/implementations/items/IGrowableCrystal.java +++ b/src/main/java/appeng/api/implementations/items/IGrowableCrystal.java @@ -23,16 +23,13 @@ package appeng.api.implementations.items; - import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.item.ItemStack; +public interface IGrowableCrystal { -public interface IGrowableCrystal -{ - - ItemStack triggerGrowth( ItemStack is ); + ItemStack triggerGrowth(ItemStack is); - float getMultiplier( Block blk, Material mat ); + float getMultiplier(Block blk, Material mat); } diff --git a/src/main/java/appeng/api/implementations/items/IItemGroup.java b/src/main/java/appeng/api/implementations/items/IItemGroup.java index 0b01aebad28..f061799f803 100644 --- a/src/main/java/appeng/api/implementations/items/IItemGroup.java +++ b/src/main/java/appeng/api/implementations/items/IItemGroup.java @@ -23,23 +23,19 @@ package appeng.api.implementations.items; - -import net.minecraft.item.ItemStack; - import java.util.Set; - +import net.minecraft.item.ItemStack; /** * Lets you specify the name of the group of items this falls under. */ -public interface IItemGroup -{ +public interface IItemGroup { - /** - * returning null, is the same as not implementing the interface at all. - * - * @param is item - * @return an unlocalized string to use for the items group name. - */ - String getUnlocalizedGroupName( Set otherItems, ItemStack is ); + /** + * returning null, is the same as not implementing the interface at all. + * + * @param is item + * @return an unlocalized string to use for the items group name. + */ + String getUnlocalizedGroupName(Set otherItems, ItemStack is); } diff --git a/src/main/java/appeng/api/implementations/items/IMemoryCard.java b/src/main/java/appeng/api/implementations/items/IMemoryCard.java index 380063f8477..0369fb160cb 100644 --- a/src/main/java/appeng/api/implementations/items/IMemoryCard.java +++ b/src/main/java/appeng/api/implementations/items/IMemoryCard.java @@ -23,54 +23,51 @@ package appeng.api.implementations.items; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; - /** * Memory Card API *

* AE's Memory Card Item Class implements this interface. */ -public interface IMemoryCard -{ +public interface IMemoryCard { - /** - * Configures the data stored on the memory card, the SettingsName, will be - * localized when displayed. - * - * @param is item - * @param SettingsName unlocalized string that represents the tile entity. - * @param data may contain a String called "tooltip" which is is a - * unlocalized string displayed after the settings name, optional - * but can be used to add details to the card for later. - */ - void setMemoryCardContents( ItemStack is, String SettingsName, NBTTagCompound data ); + /** + * Configures the data stored on the memory card, the SettingsName, will be + * localized when displayed. + * + * @param is item + * @param SettingsName unlocalized string that represents the tile entity. + * @param data may contain a String called "tooltip" which is is a + * unlocalized string displayed after the settings name, optional + * but can be used to add details to the card for later. + */ + void setMemoryCardContents(ItemStack is, String SettingsName, NBTTagCompound data); - /** - * returns the settings name provided by a previous call to - * setMemoryCardContents, or "AppEng.GuiITooltip.Blank" if there was no - * previous call to setMemoryCardContents. - * - * @param is item - * @return setting name - */ - String getSettingsName( ItemStack is ); + /** + * returns the settings name provided by a previous call to + * setMemoryCardContents, or "AppEng.GuiITooltip.Blank" if there was no + * previous call to setMemoryCardContents. + * + * @param is item + * @return setting name + */ + String getSettingsName(ItemStack is); - /** - * @param is item - * @return the NBT Data previously saved by setMemoryCardContents, or an - * empty NBTCompound - */ - NBTTagCompound getData( ItemStack is ); + /** + * @param is item + * @return the NBT Data previously saved by setMemoryCardContents, or an + * empty NBTCompound + */ + NBTTagCompound getData(ItemStack is); - /** - * notify the user of a outcome related to the memory card. - * - * @param player that used the card. - * @param msg which message to send. - */ - void notifyUser( EntityPlayer player, MemoryCardMessages msg ); + /** + * notify the user of a outcome related to the memory card. + * + * @param player that used the card. + * @param msg which message to send. + */ + void notifyUser(EntityPlayer player, MemoryCardMessages msg); } diff --git a/src/main/java/appeng/api/implementations/items/ISpatialStorageCell.java b/src/main/java/appeng/api/implementations/items/ISpatialStorageCell.java index c84fc67a795..7c942e68767 100644 --- a/src/main/java/appeng/api/implementations/items/ISpatialStorageCell.java +++ b/src/main/java/appeng/api/implementations/items/ISpatialStorageCell.java @@ -23,71 +23,68 @@ package appeng.api.implementations.items; - import appeng.api.implementations.TransitionResult; import appeng.api.util.WorldCoord; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; - /** * Implemented on a {@link Item} */ -public interface ISpatialStorageCell -{ +public interface ISpatialStorageCell { - /** - * @param is spatial storage cell - * @return true if this item is a spatial storage cell - */ - boolean isSpatialStorage( ItemStack is ); + /** + * @param is spatial storage cell + * @return true if this item is a spatial storage cell + */ + boolean isSpatialStorage(ItemStack is); - /** - * @param is spatial storage cell - * @return the maximum size of the spatial storage cell along any given axis - */ - int getMaxStoredDim( ItemStack is ); + /** + * @param is spatial storage cell + * @return the maximum size of the spatial storage cell along any given axis + */ + int getMaxStoredDim(ItemStack is); - /** - * @param is spatial storage cell - * @return the world for this cell - */ - World getWorld( ItemStack is ); + /** + * @param is spatial storage cell + * @return the world for this cell + */ + World getWorld(ItemStack is); - /** - * get the currently stored size. - * - * @param is spatial storage cell - * @return size of spatial - */ - WorldCoord getStoredSize( ItemStack is ); + /** + * get the currently stored size. + * + * @param is spatial storage cell + * @return size of spatial + */ + WorldCoord getStoredSize(ItemStack is); - /** - * Minimum coordinates in its world for the storage cell. - * - * @param is spatial storage cell - * @return minimum coordinate of dimension - */ - WorldCoord getMin( ItemStack is ); + /** + * Minimum coordinates in its world for the storage cell. + * + * @param is spatial storage cell + * @return minimum coordinate of dimension + */ + WorldCoord getMin(ItemStack is); - /** - * Maximum coordinates in its world for the storage cell. - * - * @param is spatial storage cell - * @return maximum coordinate of dimension - */ - WorldCoord getMax( ItemStack is ); + /** + * Maximum coordinates in its world for the storage cell. + * + * @param is spatial storage cell + * @return maximum coordinate of dimension + */ + WorldCoord getMax(ItemStack is); - /** - * Perform a spatial swap with the contents of the cell, and the world. - * - * @param is spatial storage cell - * @param w world of spatial - * @param min min coord - * @param max max coord - * @param doTransition transition - * @return result of transition - */ - TransitionResult doSpatialTransition( ItemStack is, World w, WorldCoord min, WorldCoord max, boolean doTransition ); -} \ No newline at end of file + /** + * Perform a spatial swap with the contents of the cell, and the world. + * + * @param is spatial storage cell + * @param w world of spatial + * @param min min coord + * @param max max coord + * @param doTransition transition + * @return result of transition + */ + TransitionResult doSpatialTransition(ItemStack is, World w, WorldCoord min, WorldCoord max, boolean doTransition); +} diff --git a/src/main/java/appeng/api/implementations/items/IStorageCell.java b/src/main/java/appeng/api/implementations/items/IStorageCell.java index c997ebf852f..372b735c47c 100644 --- a/src/main/java/appeng/api/implementations/items/IStorageCell.java +++ b/src/main/java/appeng/api/implementations/items/IStorageCell.java @@ -23,13 +23,10 @@ package appeng.api.implementations.items; - import appeng.api.storage.ICellWorkbenchItem; import appeng.api.storage.data.IAEItemStack; -import net.minecraft.item.ItemStack; - import javax.annotation.Nullable; - +import net.minecraft.item.ItemStack; /** * Any item which implements this can be treated as an IMEInventory via @@ -41,81 +38,80 @@ *

* The standard AE implementation only provides 1-63 Types */ -public interface IStorageCell extends ICellWorkbenchItem -{ +public interface IStorageCell extends ICellWorkbenchItem { - /** - * It wont work if the return is not a multiple of 8. - * The limit is ({@link Integer#MAX_VALUE} + 1) / 8. - * - * @param cellItem item - * @return number of bytes - */ - int getBytes( ItemStack cellItem ); + /** + * It wont work if the return is not a multiple of 8. + * The limit is ({@link Integer#MAX_VALUE} + 1) / 8. + * + * @param cellItem item + * @return number of bytes + */ + int getBytes(ItemStack cellItem); - /** - * Determines the number of bytes used for any type included on the cell. - * - * @param cellItem item - * @return number of bytes - * @deprecated use {@link IStorageCell#getBytesPerType(ItemStack)} - */ - @Deprecated - int BytePerType( ItemStack cellItem ); + /** + * Determines the number of bytes used for any type included on the cell. + * + * @param cellItem item + * @return number of bytes + * @deprecated use {@link IStorageCell#getBytesPerType(ItemStack)} + */ + @Deprecated + int BytePerType(ItemStack cellItem); - /** - * Determines the number of bytes used for any type included on the cell. - * - * @param cellItem item - * @return number of bytes - */ - int getBytesPerType( ItemStack cellItem ); + /** + * Determines the number of bytes used for any type included on the cell. + * + * @param cellItem item + * @return number of bytes + */ + int getBytesPerType(ItemStack cellItem); - /** - * Must be between 1 and 63, indicates how many types you want to store on - * the item. - * - * @param cellItem item - * @return number of types - */ - int getTotalTypes( ItemStack cellItem ); + /** + * Must be between 1 and 63, indicates how many types you want to store on + * the item. + * + * @param cellItem item + * @return number of types + */ + int getTotalTypes(ItemStack cellItem); - /** - * Allows you to fine tune which items are allowed on a given cell, if you - * don't care, just return false; As the handler for this type of cell is - * still the default cells, the normal AE black list is also applied. - * - * @param cellItem item - * @param requestedAddition requested addition - * @return true to preventAdditionOfItem - */ - boolean isBlackListed( ItemStack cellItem, IAEItemStack requestedAddition ); + /** + * Allows you to fine tune which items are allowed on a given cell, if you + * don't care, just return false; As the handler for this type of cell is + * still the default cells, the normal AE black list is also applied. + * + * @param cellItem item + * @param requestedAddition requested addition + * @return true to preventAdditionOfItem + */ + boolean isBlackListed(ItemStack cellItem, IAEItemStack requestedAddition); - /** - * Allows you to specify if this storage cell can be stored inside other - * storage cells, only set this for special items like the matter cannon - * that are not general purpose storage. - * - * @return true if the storage cell can be stored inside other storage - * cells, this is generally false, except for certain situations - * such as the matter cannon. - */ - boolean storableInStorageCell(); + /** + * Allows you to specify if this storage cell can be stored inside other + * storage cells, only set this for special items like the matter cannon + * that are not general purpose storage. + * + * @return true if the storage cell can be stored inside other storage + * cells, this is generally false, except for certain situations + * such as the matter cannon. + */ + boolean storableInStorageCell(); - /** - * Allows an item to selectively enable or disable its status as a storage - * cell. - * - * @param i item - * @return if the ItemStack should behavior as a storage cell. - */ - boolean isStorageCell( ItemStack i ); + /** + * Allows an item to selectively enable or disable its status as a storage + * cell. + * + * @param i item + * @return if the ItemStack should behavior as a storage cell. + */ + boolean isStorageCell(ItemStack i); - /** + /** * @param i item - * @return drain in ae/t this storage cell will use. - */ - default double getIdleDrain( @Nullable ItemStack i ) { + * @return drain in ae/t this storage cell will use. + */ + default double getIdleDrain(@Nullable ItemStack i) { // provided for API backwards compatibility return getIdleDrain(); } diff --git a/src/main/java/appeng/api/implementations/items/IStorageComponent.java b/src/main/java/appeng/api/implementations/items/IStorageComponent.java index 8a1f1f58e2a..cd0e643ca7c 100644 --- a/src/main/java/appeng/api/implementations/items/IStorageComponent.java +++ b/src/main/java/appeng/api/implementations/items/IStorageComponent.java @@ -23,32 +23,29 @@ package appeng.api.implementations.items; - import net.minecraft.item.Item; import net.minecraft.item.ItemStack; - /** * Implemented on a {@link Item} */ -public interface IStorageComponent -{ +public interface IStorageComponent { - /** - * This isn't necessarily the same as if you make a storage cell out of it, - * but all of AE's default cells do it that way, its currently only used for - * the condenser. - * - * @param is item - * @return number of bytes - */ - int getBytes( ItemStack is ); + /** + * This isn't necessarily the same as if you make a storage cell out of it, + * but all of AE's default cells do it that way, its currently only used for + * the condenser. + * + * @param is item + * @return number of bytes + */ + int getBytes(ItemStack is); - /** - * Just true or false for the item stack. - * - * @param is item - * @return true if item is a storage component - */ - boolean isStorageComponent( ItemStack is ); + /** + * Just true or false for the item stack. + * + * @param is item + * @return true if item is a storage component + */ + boolean isStorageComponent(ItemStack is); } diff --git a/src/main/java/appeng/api/implementations/items/IUpgradeModule.java b/src/main/java/appeng/api/implementations/items/IUpgradeModule.java index 1ee3c32b101..482b93c3743 100644 --- a/src/main/java/appeng/api/implementations/items/IUpgradeModule.java +++ b/src/main/java/appeng/api/implementations/items/IUpgradeModule.java @@ -23,17 +23,14 @@ package appeng.api.implementations.items; - import appeng.api.config.Upgrades; import net.minecraft.item.ItemStack; +public interface IUpgradeModule { -public interface IUpgradeModule -{ - - /** - * @param itemstack item with potential upgrades - * @return null, or a valid upgrade type. - */ - Upgrades getType( ItemStack itemstack ); + /** + * @param itemstack item with potential upgrades + * @return null, or a valid upgrade type. + */ + Upgrades getType(ItemStack itemstack); } diff --git a/src/main/java/appeng/api/implementations/items/MemoryCardMessages.java b/src/main/java/appeng/api/implementations/items/MemoryCardMessages.java index 0162131489e..cca2b33e01c 100644 --- a/src/main/java/appeng/api/implementations/items/MemoryCardMessages.java +++ b/src/main/java/appeng/api/implementations/items/MemoryCardMessages.java @@ -23,11 +23,12 @@ package appeng.api.implementations.items; - /** * Status Results for use with {@link IMemoryCard} */ -public enum MemoryCardMessages -{ - INVALID_MACHINE, SETTINGS_LOADED, SETTINGS_SAVED, SETTINGS_CLEARED +public enum MemoryCardMessages { + INVALID_MACHINE, + SETTINGS_LOADED, + SETTINGS_SAVED, + SETTINGS_CLEARED } diff --git a/src/main/java/appeng/api/implementations/parts/IPartCable.java b/src/main/java/appeng/api/implementations/parts/IPartCable.java index 0ffceb44e0a..a1dce229ce1 100644 --- a/src/main/java/appeng/api/implementations/parts/IPartCable.java +++ b/src/main/java/appeng/api/implementations/parts/IPartCable.java @@ -23,63 +23,59 @@ package appeng.api.implementations.parts; - import appeng.api.networking.IGridHost; import appeng.api.parts.BusSupport; import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import appeng.api.util.AECableType; import appeng.api.util.AEColor; +import java.util.EnumSet; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - /** * Implemented on the {@link IPart}s cable objects that can be placed at {@link ForgeDirection}.UNKNOWN in * {@link IPartHost}s */ -public interface IPartCable extends IPart, IGridHost -{ +public interface IPartCable extends IPart, IGridHost { - /** - * does this cable support buses? - */ - BusSupport supportsBuses(); + /** + * does this cable support buses? + */ + BusSupport supportsBuses(); - /** - * @return the current color of the cable. - */ - AEColor getCableColor(); + /** + * @return the current color of the cable. + */ + AEColor getCableColor(); - /** - * @return the Cable type. - */ - AECableType getCableConnectionType(); + /** + * @return the Cable type. + */ + AECableType getCableConnectionType(); - /** - * Change the color of the cable, this should cost a small amount of dye, or something. - * - * @param newColor new color - * @return if the color change was successful. - */ - boolean changeColor( AEColor newColor, EntityPlayer who ); + /** + * Change the color of the cable, this should cost a small amount of dye, or something. + * + * @param newColor new color + * @return if the color change was successful. + */ + boolean changeColor(AEColor newColor, EntityPlayer who); - /** - * Change sides on the cables node. - *

- * Called by AE, do not invoke. - * - * @param sides sides of cable - */ - void setValidSides( EnumSet sides ); + /** + * Change sides on the cables node. + *

+ * Called by AE, do not invoke. + * + * @param sides sides of cable + */ + void setValidSides(EnumSet sides); - /** - * used to tests if a cable connects to neighbors visually. - * - * @param side neighbor side - * @return true if this side is currently connects to an external block. - */ - boolean isConnected( ForgeDirection side ); + /** + * used to tests if a cable connects to neighbors visually. + * + * @param side neighbor side + * @return true if this side is currently connects to an external block. + */ + boolean isConnected(ForgeDirection side); } diff --git a/src/main/java/appeng/api/implementations/parts/IPartMonitor.java b/src/main/java/appeng/api/implementations/parts/IPartMonitor.java index 8b788e8447b..6d106624e62 100644 --- a/src/main/java/appeng/api/implementations/parts/IPartMonitor.java +++ b/src/main/java/appeng/api/implementations/parts/IPartMonitor.java @@ -23,20 +23,17 @@ package appeng.api.implementations.parts; - import appeng.api.networking.IGridHost; import appeng.api.parts.IPart; - /** * Implemented by all screen like parts provided by AE. */ -public interface IPartMonitor extends IPart, IGridHost -{ +public interface IPartMonitor extends IPart, IGridHost { - /** - * @return if the device is online you should check this before providing - * any other information. - */ - boolean isPowered(); + /** + * @return if the device is online you should check this before providing + * any other information. + */ + boolean isPowered(); } diff --git a/src/main/java/appeng/api/implementations/parts/IPartStorageMonitor.java b/src/main/java/appeng/api/implementations/parts/IPartStorageMonitor.java index 9bdfe650c14..ec1c60992dc 100644 --- a/src/main/java/appeng/api/implementations/parts/IPartStorageMonitor.java +++ b/src/main/java/appeng/api/implementations/parts/IPartStorageMonitor.java @@ -23,28 +23,25 @@ package appeng.api.implementations.parts; - import appeng.api.networking.IGridHost; import appeng.api.parts.IPart; import appeng.api.storage.data.IAEStack; import appeng.api.util.INetworkToolAgent; - /** * The Storage monitor is a {@link IPart} located on the sides of a IPartHost */ -public interface IPartStorageMonitor extends IPartMonitor, IPart, IGridHost, INetworkToolAgent -{ +public interface IPartStorageMonitor extends IPartMonitor, IPart, IGridHost, INetworkToolAgent { - /** - * @return the item being displayed on the storage monitor, in AEStack Form, can be either a IAEItemStack or an - * IAEFluidStack the quantity is important remember to use getStackSize() on the IAEStack, and not on the - * FluidStack/ItemStack acquired from it. - */ - IAEStack getDisplayed(); + /** + * @return the item being displayed on the storage monitor, in AEStack Form, can be either a IAEItemStack or an + * IAEFluidStack the quantity is important remember to use getStackSize() on the IAEStack, and not on the + * FluidStack/ItemStack acquired from it. + */ + IAEStack getDisplayed(); - /** - * @return the current locked state of the Storage Monitor - */ - boolean isLocked(); -} \ No newline at end of file + /** + * @return the current locked state of the Storage Monitor + */ + boolean isLocked(); +} diff --git a/src/main/java/appeng/api/implementations/tiles/IChestOrDrive.java b/src/main/java/appeng/api/implementations/tiles/IChestOrDrive.java index f1ae157364b..201f15c7e3c 100644 --- a/src/main/java/appeng/api/implementations/tiles/IChestOrDrive.java +++ b/src/main/java/appeng/api/implementations/tiles/IChestOrDrive.java @@ -23,42 +23,39 @@ package appeng.api.implementations.tiles; - import appeng.api.networking.IGridHost; import appeng.api.storage.ICellContainer; import appeng.api.util.IOrientable; - -public interface IChestOrDrive extends ICellContainer, IGridHost, IOrientable -{ - - /** - * @return how many slots are available. Chest has 1, Drive has 10. - */ - int getCellCount(); - - /** - * 0 - cell is missing. - *

- * 1 - green, - *

- * 2 - orange, - *

- * 3 - red - * - * @param slot slot index - * @return status of the slot, one of the above indices. - */ - int getCellStatus( int slot ); - - /** - * @return if the device is online you should check this before providing any other information. - */ - boolean isPowered(); - - /** - * @param slot slot index - * @return is the cell currently blinking to show activity. - */ - boolean isCellBlinking( int slot ); +public interface IChestOrDrive extends ICellContainer, IGridHost, IOrientable { + + /** + * @return how many slots are available. Chest has 1, Drive has 10. + */ + int getCellCount(); + + /** + * 0 - cell is missing. + *

+ * 1 - green, + *

+ * 2 - orange, + *

+ * 3 - red + * + * @param slot slot index + * @return status of the slot, one of the above indices. + */ + int getCellStatus(int slot); + + /** + * @return if the device is online you should check this before providing any other information. + */ + boolean isPowered(); + + /** + * @param slot slot index + * @return is the cell currently blinking to show activity. + */ + boolean isCellBlinking(int slot); } diff --git a/src/main/java/appeng/api/implementations/tiles/IColorableTile.java b/src/main/java/appeng/api/implementations/tiles/IColorableTile.java index 469c00d2ac9..a6d1860089b 100644 --- a/src/main/java/appeng/api/implementations/tiles/IColorableTile.java +++ b/src/main/java/appeng/api/implementations/tiles/IColorableTile.java @@ -23,16 +23,13 @@ package appeng.api.implementations.tiles; - import appeng.api.util.AEColor; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.common.util.ForgeDirection; +public interface IColorableTile { -public interface IColorableTile -{ - - AEColor getColor(); + AEColor getColor(); - boolean recolourBlock( ForgeDirection side, AEColor colour, EntityPlayer who ); + boolean recolourBlock(ForgeDirection side, AEColor colour, EntityPlayer who); } diff --git a/src/main/java/appeng/api/implementations/tiles/ICraftingMachine.java b/src/main/java/appeng/api/implementations/tiles/ICraftingMachine.java index 0a4c9b99ce6..bcd711b5635 100644 --- a/src/main/java/appeng/api/implementations/tiles/ICraftingMachine.java +++ b/src/main/java/appeng/api/implementations/tiles/ICraftingMachine.java @@ -23,30 +23,28 @@ package appeng.api.implementations.tiles; - import appeng.api.networking.crafting.ICraftingPatternDetails; import net.minecraft.inventory.InventoryCrafting; import net.minecraftforge.common.util.ForgeDirection; +public interface ICraftingMachine { -public interface ICraftingMachine -{ - - /** - * inserts a crafting plan, and the necessary items into the crafting machine. - * - * @param patternDetails details of pattern - * @param table crafting table - * @param ejectionDirection ejection direction - * @return if it was accepted, all or nothing. - */ - boolean pushPattern( ICraftingPatternDetails patternDetails, InventoryCrafting table, ForgeDirection ejectionDirection ); + /** + * inserts a crafting plan, and the necessary items into the crafting machine. + * + * @param patternDetails details of pattern + * @param table crafting table + * @param ejectionDirection ejection direction + * @return if it was accepted, all or nothing. + */ + boolean pushPattern( + ICraftingPatternDetails patternDetails, InventoryCrafting table, ForgeDirection ejectionDirection); - /** - * check if the crafting machine is accepting pushes via pushPattern, if this is false, all calls to push will fail, - * you can try inserting into the inventory instead. - * - * @return true, if pushPattern can complete, if its false push will always be false. - */ - boolean acceptsPlans(); + /** + * check if the crafting machine is accepting pushes via pushPattern, if this is false, all calls to push will fail, + * you can try inserting into the inventory instead. + * + * @return true, if pushPattern can complete, if its false push will always be false. + */ + boolean acceptsPlans(); } diff --git a/src/main/java/appeng/api/implementations/tiles/ICrankable.java b/src/main/java/appeng/api/implementations/tiles/ICrankable.java index 37bb2e952b7..5e5afcabcfd 100644 --- a/src/main/java/appeng/api/implementations/tiles/ICrankable.java +++ b/src/main/java/appeng/api/implementations/tiles/ICrankable.java @@ -23,10 +23,8 @@ package appeng.api.implementations.tiles; - import net.minecraftforge.common.util.ForgeDirection; - /** * Crank/Crankable API, *

@@ -37,23 +35,22 @@ *

* This interface must be implemented by a tile entity. */ -public interface ICrankable -{ - - /** - * Test if the crank can turn, return false if there is no work to be done. - * - * @return if crank should be allowed to turn. - */ - boolean canTurn(); - - /** - * The crank has completed one turn. - */ - void applyTurn(); - - /** - * @return true if the crank can attach on the given side. - */ - boolean canCrankAttach( ForgeDirection directionToCrank ); +public interface ICrankable { + + /** + * Test if the crank can turn, return false if there is no work to be done. + * + * @return if crank should be allowed to turn. + */ + boolean canTurn(); + + /** + * The crank has completed one turn. + */ + void applyTurn(); + + /** + * @return true if the crank can attach on the given side. + */ + boolean canCrankAttach(ForgeDirection directionToCrank); } diff --git a/src/main/java/appeng/api/implementations/tiles/ICrystalGrowthAccelerator.java b/src/main/java/appeng/api/implementations/tiles/ICrystalGrowthAccelerator.java index 9d8a9c29d56..e29196de02e 100644 --- a/src/main/java/appeng/api/implementations/tiles/ICrystalGrowthAccelerator.java +++ b/src/main/java/appeng/api/implementations/tiles/ICrystalGrowthAccelerator.java @@ -23,9 +23,7 @@ package appeng.api.implementations.tiles; +public interface ICrystalGrowthAccelerator { -public interface ICrystalGrowthAccelerator -{ - - boolean isPowered(); + boolean isPowered(); } diff --git a/src/main/java/appeng/api/implementations/tiles/IMEChest.java b/src/main/java/appeng/api/implementations/tiles/IMEChest.java index bbe957a991e..a5f74bf742e 100644 --- a/src/main/java/appeng/api/implementations/tiles/IMEChest.java +++ b/src/main/java/appeng/api/implementations/tiles/IMEChest.java @@ -23,11 +23,6 @@ package appeng.api.implementations.tiles; - import appeng.api.networking.energy.IEnergySource; - -public interface IMEChest extends IChestOrDrive, ITileStorageMonitorable, IEnergySource -{ - -} +public interface IMEChest extends IChestOrDrive, ITileStorageMonitorable, IEnergySource {} diff --git a/src/main/java/appeng/api/implementations/tiles/ISegmentedInventory.java b/src/main/java/appeng/api/implementations/tiles/ISegmentedInventory.java index 401516c2dbe..73314ce1203 100644 --- a/src/main/java/appeng/api/implementations/tiles/ISegmentedInventory.java +++ b/src/main/java/appeng/api/implementations/tiles/ISegmentedInventory.java @@ -23,19 +23,16 @@ package appeng.api.implementations.tiles; - import net.minecraft.inventory.IInventory; +public interface ISegmentedInventory { -public interface ISegmentedInventory -{ - - /** - * Access an internal inventory, note, not all inventories contain real items, some may be ghost items, and treating - * them a real inventories will result in duplication. - * - * @param name inventory name - * @return inventory with inventory name - */ - IInventory getInventoryByName( String name ); + /** + * Access an internal inventory, note, not all inventories contain real items, some may be ghost items, and treating + * them a real inventories will result in duplication. + * + * @param name inventory name + * @return inventory with inventory name + */ + IInventory getInventoryByName(String name); } diff --git a/src/main/java/appeng/api/implementations/tiles/ITileStorageMonitorable.java b/src/main/java/appeng/api/implementations/tiles/ITileStorageMonitorable.java index b84135a445a..cb816c1a184 100644 --- a/src/main/java/appeng/api/implementations/tiles/ITileStorageMonitorable.java +++ b/src/main/java/appeng/api/implementations/tiles/ITileStorageMonitorable.java @@ -23,17 +23,14 @@ package appeng.api.implementations.tiles; - import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IStorageMonitorable; import net.minecraftforge.common.util.ForgeDirection; - /** * Implemented on inventories that can share their inventories with other networks, best example, ME Interface. */ -public interface ITileStorageMonitorable -{ +public interface ITileStorageMonitorable { - IStorageMonitorable getMonitorable( ForgeDirection side, BaseActionSource src ); + IStorageMonitorable getMonitorable(ForgeDirection side, BaseActionSource src); } diff --git a/src/main/java/appeng/api/implementations/tiles/IViewCellStorage.java b/src/main/java/appeng/api/implementations/tiles/IViewCellStorage.java index 4a81ae12bff..5d74ba354f1 100644 --- a/src/main/java/appeng/api/implementations/tiles/IViewCellStorage.java +++ b/src/main/java/appeng/api/implementations/tiles/IViewCellStorage.java @@ -23,17 +23,14 @@ package appeng.api.implementations.tiles; - import net.minecraft.inventory.IInventory; +public interface IViewCellStorage { -public interface IViewCellStorage -{ - - /** - * should contains at least 5 slot, the first 5 - * - * @return inventory with at least 5 slot - */ - IInventory getViewCellStorage(); + /** + * should contains at least 5 slot, the first 5 + * + * @return inventory with at least 5 slot + */ + IInventory getViewCellStorage(); } diff --git a/src/main/java/appeng/api/implementations/tiles/IWirelessAccessPoint.java b/src/main/java/appeng/api/implementations/tiles/IWirelessAccessPoint.java index 038bc52db06..52a8e4eb090 100644 --- a/src/main/java/appeng/api/implementations/tiles/IWirelessAccessPoint.java +++ b/src/main/java/appeng/api/implementations/tiles/IWirelessAccessPoint.java @@ -23,32 +23,29 @@ package appeng.api.implementations.tiles; - import appeng.api.networking.IGrid; import appeng.api.networking.security.IActionHost; import appeng.api.util.DimensionalCoord; +public interface IWirelessAccessPoint extends IActionHost { -public interface IWirelessAccessPoint extends IActionHost -{ - - /** - * @return location of WAP - */ - DimensionalCoord getLocation(); + /** + * @return location of WAP + */ + DimensionalCoord getLocation(); - /** - * @return max range for this WAP - */ - double getRange(); + /** + * @return max range for this WAP + */ + double getRange(); - /** - * @return can you use this WAP? - */ - boolean isActive(); + /** + * @return can you use this WAP? + */ + boolean isActive(); - /** - * @return grid of linked WAP - */ - IGrid getGrid(); + /** + * @return grid of linked WAP + */ + IGrid getGrid(); } diff --git a/src/main/java/appeng/api/integration/IBeeComparison.java b/src/main/java/appeng/api/integration/IBeeComparison.java index 73bffa23624..a0c74959911 100644 --- a/src/main/java/appeng/api/integration/IBeeComparison.java +++ b/src/main/java/appeng/api/integration/IBeeComparison.java @@ -23,7 +23,6 @@ package appeng.api.integration; - /** * An interface to get access to the individual settings for AE's Internal Bee * Comparison handler. @@ -33,11 +32,10 @@ *

* If you don't have the forestry API, just delete this file when using the API. */ -public interface IBeeComparison -{ +public interface IBeeComparison { - /** - * @return the Forestry IIndividual for this comparison object - cast this to a IIndividual if you want to use it. - */ - Object getIndividual(); -} \ No newline at end of file + /** + * @return the Forestry IIndividual for this comparison object - cast this to a IIndividual if you want to use it. + */ + Object getIndividual(); +} diff --git a/src/main/java/appeng/api/movable/IMovableHandler.java b/src/main/java/appeng/api/movable/IMovableHandler.java index ae9bbd6b311..aa0fd2a1a3c 100644 --- a/src/main/java/appeng/api/movable/IMovableHandler.java +++ b/src/main/java/appeng/api/movable/IMovableHandler.java @@ -23,46 +23,43 @@ package appeng.api.movable; - import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; +public interface IMovableHandler { -public interface IMovableHandler -{ - - /** - * if you return true from this, your saying you can handle the class, not - * that single entity, you cannot opt out of single entities. - * - * @param myClass tile entity class - * @param tile tile entity - * @return true if it can handle moving - */ - boolean canHandle( Class myClass, TileEntity tile ); + /** + * if you return true from this, your saying you can handle the class, not + * that single entity, you cannot opt out of single entities. + * + * @param myClass tile entity class + * @param tile tile entity + * @return true if it can handle moving + */ + boolean canHandle(Class myClass, TileEntity tile); - /** - * request that the handler move the the tile from its current location to - * the new one. the tile has already been invalidated, and the blocks have - * already been fully moved. - *

- * Potential Example: - *

- *

-	 * {@code
-	 * Chunk c = world.getChunkFromBlockCoords( x, z ); c.setChunkBlockTileEntity( x
-	 * & 0xF, y + y, z & 0xF, tile );
-	 *
-	 * if ( c.isChunkLoaded ) { world.addTileEntity( tile ); world.markBlockForUpdate( x,
-	 * y, z ); }
-	 * }
-	 * 
- * - * @param tile to be moved tile - * @param world world of tile - * @param x x coord of tile - * @param y y coord of tile - * @param z z coord of tile - */ - void moveTile( TileEntity tile, World world, int x, int y, int z ); -} \ No newline at end of file + /** + * request that the handler move the the tile from its current location to + * the new one. the tile has already been invalidated, and the blocks have + * already been fully moved. + *

+ * Potential Example: + *

+ *

+     * {@code
+     * Chunk c = world.getChunkFromBlockCoords( x, z ); c.setChunkBlockTileEntity( x
+     * & 0xF, y + y, z & 0xF, tile );
+     *
+     * if ( c.isChunkLoaded ) { world.addTileEntity( tile ); world.markBlockForUpdate( x,
+     * y, z ); }
+     * }
+     * 
+ * + * @param tile to be moved tile + * @param world world of tile + * @param x x coord of tile + * @param y y coord of tile + * @param z z coord of tile + */ + void moveTile(TileEntity tile, World world, int x, int y, int z); +} diff --git a/src/main/java/appeng/api/movable/IMovableRegistry.java b/src/main/java/appeng/api/movable/IMovableRegistry.java index ffd0039451f..6b42a1a4fe7 100644 --- a/src/main/java/appeng/api/movable/IMovableRegistry.java +++ b/src/main/java/appeng/api/movable/IMovableRegistry.java @@ -23,11 +23,9 @@ package appeng.api.movable; - import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntity; - /** * Used to determine if a tile is marked as movable, a block will be considered movable, if... *

@@ -55,67 +53,66 @@ *

* If you need a build of deobf build of AE for testing, do not hesitate to ask. */ -public interface IMovableRegistry -{ +public interface IMovableRegistry { - /** - * Black list a block from movement, please only use this to prevent exploits. - *

- * You can also use the IMC, FMLInterModComms.sendMessage( "appliedenergistics2", "whitelist-spatial", - * "appeng.common.AppEngTile" ); - * - * @param blk block - */ - void blacklistBlock( Block blk ); + /** + * Black list a block from movement, please only use this to prevent exploits. + *

+ * You can also use the IMC, FMLInterModComms.sendMessage( "appliedenergistics2", "whitelist-spatial", + * "appeng.common.AppEngTile" ); + * + * @param blk block + */ + void blacklistBlock(Block blk); - /** - * White list your tile entity with the registry. - *

- * You can also use the IMC, FMLInterModComms.sendMessage( "appliedenergistics2", "blacklist-block-spatial", new - * ItemStack(...) ); - *

- * If you tile is handled with IMovableHandler or IMovableTile you do not need to white list it. - */ - void whiteListTileEntity( Class c ); + /** + * White list your tile entity with the registry. + *

+ * You can also use the IMC, FMLInterModComms.sendMessage( "appliedenergistics2", "blacklist-block-spatial", new + * ItemStack(...) ); + *

+ * If you tile is handled with IMovableHandler or IMovableTile you do not need to white list it. + */ + void whiteListTileEntity(Class c); - /** - * @param te to be moved tile entity - * @return true if the tile has accepted your request to move it - */ - boolean askToMove( TileEntity te ); + /** + * @param te to be moved tile entity + * @return true if the tile has accepted your request to move it + */ + boolean askToMove(TileEntity te); - /** - * tells the tile you are done moving it. - * - * @param te moved tile entity - */ - void doneMoving( TileEntity te ); + /** + * tells the tile you are done moving it. + * + * @param te moved tile entity + */ + void doneMoving(TileEntity te); - /** - * add a new handler movable handler. - * - * @param handler moving handler - */ - void addHandler( IMovableHandler handler ); + /** + * add a new handler movable handler. + * + * @param handler moving handler + */ + void addHandler(IMovableHandler handler); - /** - * handlers are used to perform movement, this allows you to override AE's internal version. - *

- * only valid after askToMove(...) = true - * - * @param te tile entity - * @return moving handler of tile entity - */ - IMovableHandler getHandler( TileEntity te ); + /** + * handlers are used to perform movement, this allows you to override AE's internal version. + *

+ * only valid after askToMove(...) = true + * + * @param te tile entity + * @return moving handler of tile entity + */ + IMovableHandler getHandler(TileEntity te); - /** - * @return a copy of the default handler - */ - IMovableHandler getDefaultHandler(); + /** + * @return a copy of the default handler + */ + IMovableHandler getDefaultHandler(); - /** - * @param blk block - * @return true if this block is blacklisted - */ - boolean isBlacklisted( Block blk ); -} \ No newline at end of file + /** + * @param blk block + * @return true if this block is blacklisted + */ + boolean isBlacklisted(Block blk); +} diff --git a/src/main/java/appeng/api/movable/IMovableTile.java b/src/main/java/appeng/api/movable/IMovableTile.java index feaaff2879e..4aa3a2c0bd0 100644 --- a/src/main/java/appeng/api/movable/IMovableTile.java +++ b/src/main/java/appeng/api/movable/IMovableTile.java @@ -23,24 +23,22 @@ package appeng.api.movable; - /** * You can implement this, or use the IMovableRegistry to white list your tile, * please see the registry for more information. */ -public interface IMovableTile -{ +public interface IMovableTile { - /** - * notification that your block will be moved, called instead of invalidate, - * return false to prevent movement. - * - * @return false to prevent movement - */ - boolean prepareToMove(); + /** + * notification that your block will be moved, called instead of invalidate, + * return false to prevent movement. + * + * @return false to prevent movement + */ + boolean prepareToMove(); - /** - * notification that your block was moved, called after validate. - */ - void doneMoving(); + /** + * notification that your block was moved, called after validate. + */ + void doneMoving(); } diff --git a/src/main/java/appeng/api/networking/GridFlags.java b/src/main/java/appeng/api/networking/GridFlags.java index 366663e867e..d4da9abc19c 100644 --- a/src/main/java/appeng/api/networking/GridFlags.java +++ b/src/main/java/appeng/api/networking/GridFlags.java @@ -23,52 +23,50 @@ package appeng.api.networking; - /** * Various flags to determine network node behavior. */ -public enum GridFlags -{ - /** - * import/export buses, terminals, and other devices that use network features, will use this setting. - */ - REQUIRE_CHANNEL, +public enum GridFlags { + /** + * import/export buses, terminals, and other devices that use network features, will use this setting. + */ + REQUIRE_CHANNEL, - /** - * P2P ME tunnels use this setting. - */ - COMPRESSED_CHANNEL, + /** + * P2P ME tunnels use this setting. + */ + COMPRESSED_CHANNEL, - /** - * cannot carry channels over this node. - */ - CANNOT_CARRY, + /** + * cannot carry channels over this node. + */ + CANNOT_CARRY, - /** - * Used by P2P Tunnels to prevent tunnels from tunneling recursively. - */ - CANNOT_CARRY_COMPRESSED, + /** + * Used by P2P Tunnels to prevent tunnels from tunneling recursively. + */ + CANNOT_CARRY_COMPRESSED, - /** - * This node can transmit 32 signals, this should only apply to Tier2 Cable, P2P Tunnels, and Quantum Network - * Bridges. - */ - DENSE_CAPACITY, + /** + * This node can transmit 32 signals, this should only apply to Tier2 Cable, P2P Tunnels, and Quantum Network + * Bridges. + */ + DENSE_CAPACITY, - /** - * This block is part of a multiblock, used in conjunction with REQUIRE_CHANNEL, and {@link IGridMultiblock} see this - * interface for details. - */ - MULTIBLOCK, + /** + * This block is part of a multiblock, used in conjunction with REQUIRE_CHANNEL, and {@link IGridMultiblock} see this + * interface for details. + */ + MULTIBLOCK, - /** - * Indicates which path might be preferred, this only matters if two routes of equal length exist, ad only changes - * the order they are processed in. - */ - PREFERRED, + /** + * Indicates which path might be preferred, this only matters if two routes of equal length exist, ad only changes + * the order they are processed in. + */ + PREFERRED, - /** - * This node can transmit 128 signals, this should only apply to Tier3 Cables only. - */ - ULTRA_DENSE_CAPACITY + /** + * This node can transmit 128 signals, this should only apply to Tier3 Cables only. + */ + ULTRA_DENSE_CAPACITY } diff --git a/src/main/java/appeng/api/networking/GridNotification.java b/src/main/java/appeng/api/networking/GridNotification.java index b53188d77a1..99f0d42cafc 100644 --- a/src/main/java/appeng/api/networking/GridNotification.java +++ b/src/main/java/appeng/api/networking/GridNotification.java @@ -23,11 +23,9 @@ package appeng.api.networking; - -public enum GridNotification -{ - /** - * the visible connections for this node have changed, useful for cable. - */ - ConnectionsChanged, +public enum GridNotification { + /** + * the visible connections for this node have changed, useful for cable. + */ + ConnectionsChanged, } diff --git a/src/main/java/appeng/api/networking/IGrid.java b/src/main/java/appeng/api/networking/IGrid.java index 8cd6ffaf222..06b25d94815 100644 --- a/src/main/java/appeng/api/networking/IGrid.java +++ b/src/main/java/appeng/api/networking/IGrid.java @@ -23,71 +23,68 @@ package appeng.api.networking; - import appeng.api.networking.events.MENetworkEvent; import appeng.api.util.IReadOnlyCollection; - /** * Gives you access to Grid based information. *

* Don't Implement. */ -public interface IGrid -{ +public interface IGrid { - /** - * Get Access to various grid modules - * - * @param iface face - * @return the IGridCache you requested. - */ - C getCache( Class iface ); + /** + * Get Access to various grid modules + * + * @param iface face + * @return the IGridCache you requested. + */ + C getCache(Class iface); - /** - * Post an event into the network event bus. - * - * @param ev - event to post - * @return returns ev back to original poster - */ - MENetworkEvent postEvent( MENetworkEvent ev ); + /** + * Post an event into the network event bus. + * + * @param ev - event to post + * @return returns ev back to original poster + */ + MENetworkEvent postEvent(MENetworkEvent ev); - /** - * Post an event into the network event bus, but direct it at a single node. - * - * @param ev event to post - * @return returns ev back to original poster - */ - MENetworkEvent postEventTo( IGridNode node, MENetworkEvent ev ); + /** + * Post an event into the network event bus, but direct it at a single node. + * + * @param ev event to post + * @return returns ev back to original poster + */ + MENetworkEvent postEventTo(IGridNode node, MENetworkEvent ev); - /** - * get a list of the diversity of classes, you can use this to better detect which machines your interested in, - * rather then iterating the entire grid to test them. - * - * @return IReadOnlyCollection of all available host types (Of Type IGridHost). - */ - IReadOnlyCollection> getMachinesClasses(); + /** + * get a list of the diversity of classes, you can use this to better detect which machines your interested in, + * rather then iterating the entire grid to test them. + * + * @return IReadOnlyCollection of all available host types (Of Type IGridHost). + */ + IReadOnlyCollection> getMachinesClasses(); - /** - * Get machines on the network. - * - * @param gridHostClass class of the grid host - * @return IMachineSet of all nodes belonging to hosts of specified class. - */ - IMachineSet getMachines( Class gridHostClass ); + /** + * Get machines on the network. + * + * @param gridHostClass class of the grid host + * @return IMachineSet of all nodes belonging to hosts of specified class. + */ + IMachineSet getMachines(Class gridHostClass); - /** - * @return IReadOnlyCollection for all nodes on the network, node visitors are preferred. - */ - IReadOnlyCollection getNodes(); + /** + * @return IReadOnlyCollection for all nodes on the network, node visitors are preferred. + */ + IReadOnlyCollection getNodes(); - /** - * @return true if the last node has been removed from the grid. - */ - boolean isEmpty(); + /** + * @return true if the last node has been removed from the grid. + */ + boolean isEmpty(); - /** - * @return the node considered the pivot point of the grid. - */ - IGridNode getPivot(); -} \ No newline at end of file + /** + * @return the node considered the pivot point of the grid. + */ + IGridNode getPivot(); +} diff --git a/src/main/java/appeng/api/networking/IGridBlock.java b/src/main/java/appeng/api/networking/IGridBlock.java index e311d14e694..43eb9f46258 100644 --- a/src/main/java/appeng/api/networking/IGridBlock.java +++ b/src/main/java/appeng/api/networking/IGridBlock.java @@ -23,92 +23,88 @@ package appeng.api.networking; - import appeng.api.parts.IPart; import appeng.api.util.AEColor; import appeng.api.util.DimensionalCoord; +import java.util.EnumSet; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - /** * An Implementation is required to create your node for IGridHost *

* Implement for use with IGridHost */ -public interface IGridBlock -{ - - /** - * how much power to drain per tick as part of idle network usage. - *

- * if the value of this changes, you must post a MENetworkPowerIdleChange - * - * @return ae/t to use. - */ - double getIdlePowerUsage(); - - /** - * Various flags that AE uses to modify basic behavior for various parts of the network. - * - * @return Set of flags for this IGridBlock - */ - EnumSet getFlags(); - - /** - * generally speaking you will return true for this, the one exception is buses, or worm holes where the node - * represents something that isn't a real connection in the world, but rather one represented internally to the - * block. - * - * @return if the world can connect to this node, and the node can connect to the world. - */ - boolean isWorldAccessible(); - - /** - * @return current location of this node - */ - DimensionalCoord getLocation(); - - /** - * @return Transparent, or a valid color, NULL IS NOT A VALID RETURN - */ - AEColor getGridColor(); - - /** - * Notifies your IGridBlock that changes were made to your connections - */ - void onGridNotification( GridNotification notification ); - - /** - * Update Blocks network/connection/booting status. grid, - * - * @param grid grid - * @param channelsInUse used channels - */ - void setNetworkStatus( IGrid grid, int channelsInUse ); - - /** - * Determine which sides of the block can be connected too, only used when isWorldAccessible returns true, not used - * for {@link IPart} implementations. - */ - EnumSet getConnectableSides(); - - /** - * @return the IGridHost for the node, this will be an IGridPart or a TileEntity generally speaking. - */ - IGridHost getMachine(); - - /** - * called when the grid for the node has changed, the general grid state should not be trusted at this point. - */ - void gridChanged(); - - /** - * Determines what item stack is used to render this node in the GUI. - * - * @return the render item stack to use to render this node, null is valid, and will not show this node. - */ - ItemStack getMachineRepresentation(); +public interface IGridBlock { + + /** + * how much power to drain per tick as part of idle network usage. + *

+ * if the value of this changes, you must post a MENetworkPowerIdleChange + * + * @return ae/t to use. + */ + double getIdlePowerUsage(); + + /** + * Various flags that AE uses to modify basic behavior for various parts of the network. + * + * @return Set of flags for this IGridBlock + */ + EnumSet getFlags(); + + /** + * generally speaking you will return true for this, the one exception is buses, or worm holes where the node + * represents something that isn't a real connection in the world, but rather one represented internally to the + * block. + * + * @return if the world can connect to this node, and the node can connect to the world. + */ + boolean isWorldAccessible(); + + /** + * @return current location of this node + */ + DimensionalCoord getLocation(); + + /** + * @return Transparent, or a valid color, NULL IS NOT A VALID RETURN + */ + AEColor getGridColor(); + + /** + * Notifies your IGridBlock that changes were made to your connections + */ + void onGridNotification(GridNotification notification); + + /** + * Update Blocks network/connection/booting status. grid, + * + * @param grid grid + * @param channelsInUse used channels + */ + void setNetworkStatus(IGrid grid, int channelsInUse); + + /** + * Determine which sides of the block can be connected too, only used when isWorldAccessible returns true, not used + * for {@link IPart} implementations. + */ + EnumSet getConnectableSides(); + + /** + * @return the IGridHost for the node, this will be an IGridPart or a TileEntity generally speaking. + */ + IGridHost getMachine(); + + /** + * called when the grid for the node has changed, the general grid state should not be trusted at this point. + */ + void gridChanged(); + + /** + * Determines what item stack is used to render this node in the GUI. + * + * @return the render item stack to use to render this node, null is valid, and will not show this node. + */ + ItemStack getMachineRepresentation(); } diff --git a/src/main/java/appeng/api/networking/IGridCache.java b/src/main/java/appeng/api/networking/IGridCache.java index 15ce7562c57..fd1fe2d6e9e 100644 --- a/src/main/java/appeng/api/networking/IGridCache.java +++ b/src/main/java/appeng/api/networking/IGridCache.java @@ -23,7 +23,6 @@ package appeng.api.networking; - /** * Allows you to create a network wise service, AE2 uses these for providing * item, spatial, and tunnel services. @@ -31,61 +30,60 @@ * Any Class that implements this, should have a public default constructor that * takes a single argument of type IGrid. */ -public interface IGridCache -{ +public interface IGridCache { - /** - * Called each tick for the network, allows you to have active network wide - * behaviors. - */ - void onUpdateTick(); + /** + * Called each tick for the network, allows you to have active network wide + * behaviors. + */ + void onUpdateTick(); - /** - * inform your cache, that a machine was removed from the grid. - *

- * Important: Do not trust the grids state in this method, interact only - * with the node you are passed, if you need to manage other grid - * information, do it on the next updateTick. - * - * @param gridNode removed from that grid - * @param machine to be removed machine - */ - void removeNode( IGridNode gridNode, IGridHost machine ); + /** + * inform your cache, that a machine was removed from the grid. + *

+ * Important: Do not trust the grids state in this method, interact only + * with the node you are passed, if you need to manage other grid + * information, do it on the next updateTick. + * + * @param gridNode removed from that grid + * @param machine to be removed machine + */ + void removeNode(IGridNode gridNode, IGridHost machine); - /** - * informs you cache that a machine was added to the grid. - *

- * Important: Do not trust the grids state in this method, interact only - * with the node you are passed, if you need to manage other grid - * information, do it on the next updateTick. - * - * @param gridNode added to grid node - * @param machine to be added machine - */ - void addNode( IGridNode gridNode, IGridHost machine ); + /** + * informs you cache that a machine was added to the grid. + *

+ * Important: Do not trust the grids state in this method, interact only + * with the node you are passed, if you need to manage other grid + * information, do it on the next updateTick. + * + * @param gridNode added to grid node + * @param machine to be added machine + */ + void addNode(IGridNode gridNode, IGridHost machine); - /** - * Called when a grid splits into two grids, AE will call a split as it - * Iteratively processes changes. The destination should receive half, and - * the current cache should receive half. - * - * @param destinationStorage storage which receives half of old grid - */ - void onSplit( IGridStorage destinationStorage ); + /** + * Called when a grid splits into two grids, AE will call a split as it + * Iteratively processes changes. The destination should receive half, and + * the current cache should receive half. + * + * @param destinationStorage storage which receives half of old grid + */ + void onSplit(IGridStorage destinationStorage); - /** - * Called when two grids merge into one, AE will call a join as it - * Iteratively processes changes. Use this method to incorporate all the - * data from the source into your cache. - * - * @param sourceStorage old storage - */ - void onJoin( IGridStorage sourceStorage ); + /** + * Called when two grids merge into one, AE will call a join as it + * Iteratively processes changes. Use this method to incorporate all the + * data from the source into your cache. + * + * @param sourceStorage old storage + */ + void onJoin(IGridStorage sourceStorage); - /** - * Called when saving changes, - * - * @param destinationStorage storage - */ - void populateGridStorage( IGridStorage destinationStorage ); + /** + * Called when saving changes, + * + * @param destinationStorage storage + */ + void populateGridStorage(IGridStorage destinationStorage); } diff --git a/src/main/java/appeng/api/networking/IGridCacheRegistry.java b/src/main/java/appeng/api/networking/IGridCacheRegistry.java index b554763268f..ef4b4ef5235 100644 --- a/src/main/java/appeng/api/networking/IGridCacheRegistry.java +++ b/src/main/java/appeng/api/networking/IGridCacheRegistry.java @@ -23,28 +23,25 @@ package appeng.api.networking; - import java.util.HashMap; - /** * A registry of grid caches to extend grid functionality. */ -public interface IGridCacheRegistry -{ +public interface IGridCacheRegistry { - /** - * Register a new grid cache for use during operation, must be called during the loading phase. - * - * @param iface grid cache class - */ - void registerGridCache( Class iface, Class implementation ); + /** + * Register a new grid cache for use during operation, must be called during the loading phase. + * + * @param iface grid cache class + */ + void registerGridCache(Class iface, Class implementation); - /** - * requests a new INSTANCE of a grid cache for use, used internally - * - * @param grid grid - * @return a new HashMap of IGridCaches from the registry, called from IGrid when constructing a new grid. - */ - HashMap, IGridCache> createCacheInstance( IGrid grid ); + /** + * requests a new INSTANCE of a grid cache for use, used internally + * + * @param grid grid + * @return a new HashMap of IGridCaches from the registry, called from IGrid when constructing a new grid. + */ + HashMap, IGridCache> createCacheInstance(IGrid grid); } diff --git a/src/main/java/appeng/api/networking/IGridConnection.java b/src/main/java/appeng/api/networking/IGridConnection.java index a4b048930cb..ec682a79318 100644 --- a/src/main/java/appeng/api/networking/IGridConnection.java +++ b/src/main/java/appeng/api/networking/IGridConnection.java @@ -23,10 +23,8 @@ package appeng.api.networking; - import net.minecraftforge.common.util.ForgeDirection; - /** * Access to AE's internal grid connections. *

@@ -35,48 +33,47 @@ *

* Don't Implement. */ -public interface IGridConnection -{ +public interface IGridConnection { - /** - * lets you get the opposing node of the connection by passing your own node. - * - * @param gridNode current grid node - * @return the IGridNode which represents the opposite side of the connection. - */ - IGridNode getOtherSide( IGridNode gridNode ); + /** + * lets you get the opposing node of the connection by passing your own node. + * + * @param gridNode current grid node + * @return the IGridNode which represents the opposite side of the connection. + */ + IGridNode getOtherSide(IGridNode gridNode); - /** - * determine the direction of the connection based on your node. - * - * @param gridNode current grid node - * @return the direction of the connection, only valid for in world connections. - */ - ForgeDirection getDirection( IGridNode gridNode ); + /** + * determine the direction of the connection based on your node. + * + * @param gridNode current grid node + * @return the direction of the connection, only valid for in world connections. + */ + ForgeDirection getDirection(IGridNode gridNode); - /** - * by destroying a connection you may create new grids, and trigger un-expected behavior, you should only destroy - * connections if you created them. - */ - void destroy(); + /** + * by destroying a connection you may create new grids, and trigger un-expected behavior, you should only destroy + * connections if you created them. + */ + void destroy(); - /** - * @return node A - */ - IGridNode a(); + /** + * @return node A + */ + IGridNode a(); - /** - * @return node B - */ - IGridNode b(); + /** + * @return node B + */ + IGridNode b(); - /** - * @return if the connection is invisible this returns false - */ - boolean hasDirection(); + /** + * @return if the connection is invisible this returns false + */ + boolean hasDirection(); - /** - * @return how many channels pass over this connections. - */ - int getUsedChannels(); -} \ No newline at end of file + /** + * @return how many channels pass over this connections. + */ + int getUsedChannels(); +} diff --git a/src/main/java/appeng/api/networking/IGridConnectionVisitor.java b/src/main/java/appeng/api/networking/IGridConnectionVisitor.java index 1842589e08a..3b6446709c2 100644 --- a/src/main/java/appeng/api/networking/IGridConnectionVisitor.java +++ b/src/main/java/appeng/api/networking/IGridConnectionVisitor.java @@ -23,14 +23,12 @@ package appeng.api.networking; +public interface IGridConnectionVisitor extends IGridVisitor { -public interface IGridConnectionVisitor extends IGridVisitor -{ - - /** - * Called for each connection on the network. - * - * @param n the connection. - */ - void visitConnection( IGridConnection n ); + /** + * Called for each connection on the network. + * + * @param n the connection. + */ + void visitConnection(IGridConnection n); } diff --git a/src/main/java/appeng/api/networking/IGridHost.java b/src/main/java/appeng/api/networking/IGridHost.java index dfe67a11d56..e32b7646ad2 100644 --- a/src/main/java/appeng/api/networking/IGridHost.java +++ b/src/main/java/appeng/api/networking/IGridHost.java @@ -23,42 +23,39 @@ package appeng.api.networking; - import appeng.api.parts.IPart; import appeng.api.util.AECableType; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; - /** * Implement to create a networked {@link TileEntity} or {@link IPart} must * be implemented for a part, or tile entity to become part of a grid. */ -public interface IGridHost -{ - - /** - * get the grid node for a particular side of a block, you can return null, - * by returning a valid node later and calling updateState, you can join the - * Grid when your block is ready. - * - * @param dir feel free to ignore this, most blocks will use the same node - * for every side. - * @return a new IGridNode, create these with - * AEApi.INSTANCE().createGridNode( MyIGridBlock ) - */ - IGridNode getGridNode( ForgeDirection dir ); - - /** - * Determines how cables render when they connect to this block. Priority is - * Smart > Covered > Glass - * - * @param dir direction - */ - AECableType getCableConnectionType( ForgeDirection dir ); - - /** - * break this host, its violating security rules, just break your block, or part. - */ - void securityBreak(); +public interface IGridHost { + + /** + * get the grid node for a particular side of a block, you can return null, + * by returning a valid node later and calling updateState, you can join the + * Grid when your block is ready. + * + * @param dir feel free to ignore this, most blocks will use the same node + * for every side. + * @return a new IGridNode, create these with + * AEApi.INSTANCE().createGridNode( MyIGridBlock ) + */ + IGridNode getGridNode(ForgeDirection dir); + + /** + * Determines how cables render when they connect to this block. Priority is + * Smart > Covered > Glass + * + * @param dir direction + */ + AECableType getCableConnectionType(ForgeDirection dir); + + /** + * break this host, its violating security rules, just break your block, or part. + */ + void securityBreak(); } diff --git a/src/main/java/appeng/api/networking/IGridMultiblock.java b/src/main/java/appeng/api/networking/IGridMultiblock.java index 7c3844bb7b9..8545f1b6bf4 100644 --- a/src/main/java/appeng/api/networking/IGridMultiblock.java +++ b/src/main/java/appeng/api/networking/IGridMultiblock.java @@ -23,22 +23,19 @@ package appeng.api.networking; - import java.util.Iterator; - /** * An extension of IGridBlock, only means something when your getFlags() contains REQUIRE_CHANNEL, when done properly it * will call the method to get a list of all related nodes and give each of them a channel simultaneously for the entire * set. This means your entire Multiblock can work with a single channel, instead of one channel per block. */ -public interface IGridMultiblock extends IGridBlock -{ +public interface IGridMultiblock extends IGridBlock { - /** - * Used to acquire a list of all nodes that are part of the multiblock. - * - * @return an iterator that will iterate all the nodes for the multiblock. ( read-only iterator expected. ) - */ - Iterator getMultiblockNodes(); + /** + * Used to acquire a list of all nodes that are part of the multiblock. + * + * @return an iterator that will iterate all the nodes for the multiblock. ( read-only iterator expected. ) + */ + Iterator getMultiblockNodes(); } diff --git a/src/main/java/appeng/api/networking/IGridNode.java b/src/main/java/appeng/api/networking/IGridNode.java index bb57f777b57..32950ccd59c 100644 --- a/src/main/java/appeng/api/networking/IGridNode.java +++ b/src/main/java/appeng/api/networking/IGridNode.java @@ -23,16 +23,13 @@ package appeng.api.networking; - import appeng.api.IAppEngApi; import appeng.api.util.IReadOnlyCollection; +import java.util.EnumSet; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - /** * Gives you a view into your Nodes connections and information. *

@@ -40,122 +37,121 @@ *

* Don't Implement; Acquire from {@link IAppEngApi}.createGridNode */ -public interface IGridNode -{ - - /** - * lets you walk the grid stating at the current node using a IGridVisitor, generally not needed, please use only if - * required. - * - * @param visitor visitor - */ - void beginVisit( IGridVisitor visitor ); - - /** - * inform the node that your IGridBlock has changed its internal state, and force the node to update. - *

- * ALWAYS make sure that your tile entity is in the world, and has its node properly saved to be returned from the - * host before updating state, - *

- * If your entity is not in the world, or if you IGridHost returns a different node for the same side you will - * likely crash the game. - */ - void updateState(); - - /** - * get the machine represented by the node. - * - * @return grid host - */ - IGridHost getMachine(); - - /** - * get the grid for the node, this can change at a moments notice. - * - * @return grid - */ - IGrid getGrid(); - - /** - * By destroying your node, you destroy any connections, and its existence in the grid, use in invalidate, or - * onChunkUnload - */ - void destroy(); - - /** - * @return the world the node is located in - */ - World getWorld(); - - /** - * @return a set of the connected sides, UNKNOWN represents an invisible connection - */ - EnumSet getConnectedSides(); - - /** - * lets you iterate a nodes connections - * - * @return grid connections - */ - IReadOnlyCollection getConnections(); - - /** - * @return the IGridBlock for this node - */ - IGridBlock getGridBlock(); - - /** - * Reflects the networks status, returns true only if the network is powered, and the network is not booting, this - * also takes into account channels. - * - * @return true if is Network node active, and participating. - */ - boolean isActive(); - - /** - * this should be called for each node you create, if you have a nodeData compound to load from, you can store all - * your nods on a single compound using name. - *

- * Important: You must call this before updateState. - * - * @param name nbt name - * @param nodeData to be loaded data - */ - void loadFromNBT( String name, NBTTagCompound nodeData ); - - /** - * this should be called for each node you maintain, you can save all your nodes to the same tag with different - * names, if you fail to complete the load / save procedure, network state may be lost between game load/saves. - * - * @param name nbt name - * @param nodeData to be saved data - */ - void saveToNBT( String name, NBTTagCompound nodeData ); - - /** - * @return if the node's channel requirements are currently met, use this for display purposes, use isActive for - * status. - */ - boolean meetsChannelRequirements(); - - /** - * see if this node has a certain flag - * - * @param flag flags - * @return true if has flag - */ - boolean hasFlag( GridFlags flag ); - - /** - * @return the ownerID this represents the person who placed the node. - */ - int getPlayerID(); - - /** - * tell the node who was responsible for placing it, failure to do this may result in in-compatibility with the - * security system. Called instead of loadFromNBT when initially placed, once set never required again, the value is saved with the Node NBT. - * - * @param playerID new player id - */ - void setPlayerID( int playerID ); -} \ No newline at end of file +public interface IGridNode { + + /** + * lets you walk the grid stating at the current node using a IGridVisitor, generally not needed, please use only if + * required. + * + * @param visitor visitor + */ + void beginVisit(IGridVisitor visitor); + + /** + * inform the node that your IGridBlock has changed its internal state, and force the node to update. + *

+ * ALWAYS make sure that your tile entity is in the world, and has its node properly saved to be returned from the + * host before updating state, + *

+ * If your entity is not in the world, or if you IGridHost returns a different node for the same side you will + * likely crash the game. + */ + void updateState(); + + /** + * get the machine represented by the node. + * + * @return grid host + */ + IGridHost getMachine(); + + /** + * get the grid for the node, this can change at a moments notice. + * + * @return grid + */ + IGrid getGrid(); + + /** + * By destroying your node, you destroy any connections, and its existence in the grid, use in invalidate, or + * onChunkUnload + */ + void destroy(); + + /** + * @return the world the node is located in + */ + World getWorld(); + + /** + * @return a set of the connected sides, UNKNOWN represents an invisible connection + */ + EnumSet getConnectedSides(); + + /** + * lets you iterate a nodes connections + * + * @return grid connections + */ + IReadOnlyCollection getConnections(); + + /** + * @return the IGridBlock for this node + */ + IGridBlock getGridBlock(); + + /** + * Reflects the networks status, returns true only if the network is powered, and the network is not booting, this + * also takes into account channels. + * + * @return true if is Network node active, and participating. + */ + boolean isActive(); + + /** + * this should be called for each node you create, if you have a nodeData compound to load from, you can store all + * your nods on a single compound using name. + *

+ * Important: You must call this before updateState. + * + * @param name nbt name + * @param nodeData to be loaded data + */ + void loadFromNBT(String name, NBTTagCompound nodeData); + + /** + * this should be called for each node you maintain, you can save all your nodes to the same tag with different + * names, if you fail to complete the load / save procedure, network state may be lost between game load/saves. + * + * @param name nbt name + * @param nodeData to be saved data + */ + void saveToNBT(String name, NBTTagCompound nodeData); + + /** + * @return if the node's channel requirements are currently met, use this for display purposes, use isActive for + * status. + */ + boolean meetsChannelRequirements(); + + /** + * see if this node has a certain flag + * + * @param flag flags + * @return true if has flag + */ + boolean hasFlag(GridFlags flag); + + /** + * @return the ownerID this represents the person who placed the node. + */ + int getPlayerID(); + + /** + * tell the node who was responsible for placing it, failure to do this may result in in-compatibility with the + * security system. Called instead of loadFromNBT when initially placed, once set never required again, the value is saved with the Node NBT. + * + * @param playerID new player id + */ + void setPlayerID(int playerID); +} diff --git a/src/main/java/appeng/api/networking/IGridStorage.java b/src/main/java/appeng/api/networking/IGridStorage.java index 0f9e9b7b553..c54115092e7 100644 --- a/src/main/java/appeng/api/networking/IGridStorage.java +++ b/src/main/java/appeng/api/networking/IGridStorage.java @@ -23,20 +23,17 @@ package appeng.api.networking; - import net.minecraft.nbt.NBTTagCompound; +public interface IGridStorage { -public interface IGridStorage -{ - - /** - * @return an NBTTagCompound that can be read, and written too. - */ - NBTTagCompound dataObject(); + /** + * @return an NBTTagCompound that can be read, and written too. + */ + NBTTagCompound dataObject(); - /** - * @return the id for this grid storage object, used internally - */ - long getID(); + /** + * @return the id for this grid storage object, used internally + */ + long getID(); } diff --git a/src/main/java/appeng/api/networking/IGridVisitor.java b/src/main/java/appeng/api/networking/IGridVisitor.java index ca6934961ab..9ad70c0128b 100644 --- a/src/main/java/appeng/api/networking/IGridVisitor.java +++ b/src/main/java/appeng/api/networking/IGridVisitor.java @@ -23,20 +23,18 @@ package appeng.api.networking; - /** * Simple Visitor pattern access to network nodes. */ -public interface IGridVisitor -{ +public interface IGridVisitor { - /** - * Called for each node on the network. - *

- * By returning false your informing the host to stop visiting nodes beyond the current node. - * - * @param n the current node. - * @return true to continue visiting nodes beyond this node. - */ - boolean visitNode( IGridNode n ); + /** + * Called for each node on the network. + *

+ * By returning false your informing the host to stop visiting nodes beyond the current node. + * + * @param n the current node. + * @return true to continue visiting nodes beyond this node. + */ + boolean visitNode(IGridNode n); } diff --git a/src/main/java/appeng/api/networking/IMachineSet.java b/src/main/java/appeng/api/networking/IMachineSet.java index 7d57b52cfee..c345ec8f8e2 100644 --- a/src/main/java/appeng/api/networking/IMachineSet.java +++ b/src/main/java/appeng/api/networking/IMachineSet.java @@ -23,15 +23,12 @@ package appeng.api.networking; - import appeng.api.util.IReadOnlyCollection; +public interface IMachineSet extends IReadOnlyCollection { -public interface IMachineSet extends IReadOnlyCollection -{ - - /** - * @return the machine class for this set. - */ - Class getMachineClass(); + /** + * @return the machine class for this set. + */ + Class getMachineClass(); } diff --git a/src/main/java/appeng/api/networking/crafting/CraftingItemList.java b/src/main/java/appeng/api/networking/crafting/CraftingItemList.java index c84c275d72c..7632196fc30 100644 --- a/src/main/java/appeng/api/networking/crafting/CraftingItemList.java +++ b/src/main/java/appeng/api/networking/crafting/CraftingItemList.java @@ -23,8 +23,9 @@ package appeng.api.networking.crafting; - -public enum CraftingItemList -{ - ALL, STORAGE, ACTIVE, PENDING +public enum CraftingItemList { + ALL, + STORAGE, + ACTIVE, + PENDING } diff --git a/src/main/java/appeng/api/networking/crafting/ICraftingCPU.java b/src/main/java/appeng/api/networking/crafting/ICraftingCPU.java index 750c2a32a83..c61921610df 100644 --- a/src/main/java/appeng/api/networking/crafting/ICraftingCPU.java +++ b/src/main/java/appeng/api/networking/crafting/ICraftingCPU.java @@ -23,65 +23,57 @@ package appeng.api.networking.crafting; - import appeng.api.networking.security.BaseActionSource; import appeng.api.networking.storage.IBaseMonitor; import appeng.api.storage.data.IAEItemStack; -import appeng.api.util.WorldCoord; - import javax.annotation.Nullable; - -public interface ICraftingCPU extends IBaseMonitor -{ +public interface ICraftingCPU extends IBaseMonitor { /** - * @return true if the CPU currently has a job. - */ - boolean isBusy(); + * @return true if the CPU currently has a job. + */ + boolean isBusy(); - /** - * @return the action source for the CPU. - */ - BaseActionSource getActionSource(); + /** + * @return the action source for the CPU. + */ + BaseActionSource getActionSource(); - /** - * @return the available storage in bytes - */ - long getAvailableStorage(); + /** + * @return the available storage in bytes + */ + long getAvailableStorage(); - /** - * @return the number of co-processors in the CPU. - */ - int getCoProcessors(); + /** + * @return the number of co-processors in the CPU. + */ + int getCoProcessors(); - /** - * @return an empty string or the name of the cpu. - */ - String getName(); + /** + * @return an empty string or the name of the cpu. + */ + String getName(); /** * @return final output of the current crafting operation, or null if not crafting */ @Nullable - default IAEItemStack getFinalOutput() - { + default IAEItemStack getFinalOutput() { return null; } /** * @return remaining count of items (or other units of processing) for the current crafting job */ - default long getRemainingItemCount() - { + default long getRemainingItemCount() { return 0; } /** * @return total count of items (or other units of processing) for the current crafting job */ - default long getStartItemCount() - { + default long getStartItemCount() { return 0; } } diff --git a/src/main/java/appeng/api/networking/crafting/ICraftingCallback.java b/src/main/java/appeng/api/networking/crafting/ICraftingCallback.java index 096b7226009..fd088fa9c79 100644 --- a/src/main/java/appeng/api/networking/crafting/ICraftingCallback.java +++ b/src/main/java/appeng/api/networking/crafting/ICraftingCallback.java @@ -23,14 +23,12 @@ package appeng.api.networking.crafting; +public interface ICraftingCallback { -public interface ICraftingCallback -{ - - /** - * this call back is synchronized with the world you passed. - * - * @param job - final job - */ - void calculationComplete( ICraftingJob job ); + /** + * this call back is synchronized with the world you passed. + * + * @param job - final job + */ + void calculationComplete(ICraftingJob job); } diff --git a/src/main/java/appeng/api/networking/crafting/ICraftingGrid.java b/src/main/java/appeng/api/networking/crafting/ICraftingGrid.java index 9fef233987b..174d78939ae 100644 --- a/src/main/java/appeng/api/networking/crafting/ICraftingGrid.java +++ b/src/main/java/appeng/api/networking/crafting/ICraftingGrid.java @@ -23,77 +23,80 @@ package appeng.api.networking.crafting; - import appeng.api.networking.IGrid; import appeng.api.networking.IGridCache; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.data.IAEItemStack; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableSet; -import net.minecraft.world.World; - import java.util.concurrent.Future; +import net.minecraft.world.World; +public interface ICraftingGrid extends IGridCache { -public interface ICraftingGrid extends IGridCache -{ - - /** - * @param whatToCraft requested craft - * @param world crafting world - * @param slot slot index - * @param details pattern details - * @return a collection of crafting patterns for the item in question. - */ - ImmutableCollection getCraftingFor( IAEItemStack whatToCraft, ICraftingPatternDetails details, int slot, World world ); + /** + * @param whatToCraft requested craft + * @param world crafting world + * @param slot slot index + * @param details pattern details + * @return a collection of crafting patterns for the item in question. + */ + ImmutableCollection getCraftingFor( + IAEItemStack whatToCraft, ICraftingPatternDetails details, int slot, World world); - /** - * Begin calculating a crafting job. - * - * @param world crafting world - * @param grid network - * @param actionSrc source - * @param craftWhat result - * @param callback callback - * -- optional - * @return a future which will at an undetermined point in the future get you the {@link ICraftingJob} do not wait - * on this, your be waiting forever. - */ - Future beginCraftingJob( World world, IGrid grid, BaseActionSource actionSrc, IAEItemStack craftWhat, ICraftingCallback callback ); + /** + * Begin calculating a crafting job. + * + * @param world crafting world + * @param grid network + * @param actionSrc source + * @param craftWhat result + * @param callback callback + * -- optional + * @return a future which will at an undetermined point in the future get you the {@link ICraftingJob} do not wait + * on this, your be waiting forever. + */ + Future beginCraftingJob( + World world, IGrid grid, BaseActionSource actionSrc, IAEItemStack craftWhat, ICraftingCallback callback); - /** - * Submit the job to the Crafting system for processing. - * - * @param job - the crafting job from beginCraftingJob - * @param requestingMachine - a machine if its being requested via automation, may be null. - * @param target - can be null - * @param prioritizePower - if cpu is null, this determine if the system should prioritize power, or if it should find the lower - * end cpus, automatic processes generally should pick lower end cpus. - * @param src - the action source to use when starting the job, this will be used for extracting items, should - * usually be the same as the one provided to beginCraftingJob. - * @return null ( if failed ) or an {@link ICraftingLink} other wise, if you send requestingMachine you need to - * properly keep track of this and handle the nbt saving and loading of the object as well as the - * {@link ICraftingRequester} methods. if you send null, this object should be discarded after verifying the - * return state. - */ - ICraftingLink submitJob( ICraftingJob job, ICraftingRequester requestingMachine, ICraftingCPU target, boolean prioritizePower, BaseActionSource src ); + /** + * Submit the job to the Crafting system for processing. + * + * @param job - the crafting job from beginCraftingJob + * @param requestingMachine - a machine if its being requested via automation, may be null. + * @param target - can be null + * @param prioritizePower - if cpu is null, this determine if the system should prioritize power, or if it should find the lower + * end cpus, automatic processes generally should pick lower end cpus. + * @param src - the action source to use when starting the job, this will be used for extracting items, should + * usually be the same as the one provided to beginCraftingJob. + * @return null ( if failed ) or an {@link ICraftingLink} other wise, if you send requestingMachine you need to + * properly keep track of this and handle the nbt saving and loading of the object as well as the + * {@link ICraftingRequester} methods. if you send null, this object should be discarded after verifying the + * return state. + */ + ICraftingLink submitJob( + ICraftingJob job, + ICraftingRequester requestingMachine, + ICraftingCPU target, + boolean prioritizePower, + BaseActionSource src); - /** - * @return list of all the crafting cpus on the grid - */ - ImmutableSet getCpus(); + /** + * @return list of all the crafting cpus on the grid + */ + ImmutableSet getCpus(); - /** - * @param what to be requested item - * @return true if the item can be requested via a crafting emitter. - */ - boolean canEmitFor( IAEItemStack what ); + /** + * @param what to be requested item + * @return true if the item can be requested via a crafting emitter. + */ + boolean canEmitFor(IAEItemStack what); - /** - * is this item being crafted? - * - * @param aeStackInSlot item being crafted - * @return true if it is being crafting - */ - boolean isRequesting( IAEItemStack aeStackInSlot ); + /** + * is this item being crafted? + * + * @param aeStackInSlot item being crafted + * @return true if it is being crafting + */ + boolean isRequesting(IAEItemStack aeStackInSlot); } diff --git a/src/main/java/appeng/api/networking/crafting/ICraftingJob.java b/src/main/java/appeng/api/networking/crafting/ICraftingJob.java index 55901230300..39ac75c2a43 100644 --- a/src/main/java/appeng/api/networking/crafting/ICraftingJob.java +++ b/src/main/java/appeng/api/networking/crafting/ICraftingJob.java @@ -23,35 +23,32 @@ package appeng.api.networking.crafting; - import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; - -public interface ICraftingJob -{ - - /** - * @return if this job is a simulation, simulations cannot be submitted and only represent 1 possible future - * crafting job with fake items. - */ - boolean isSimulation(); - - /** - * @return total number of bytes to process this job. - */ - long getByteTotal(); - - /** - * Populates the plan list with stack size, and requestable values that represent the stored, and crafting job - * contents respectively. - * - * @param plan plan - */ - void populatePlan( IItemList plan ); - - /** - * @return the final output of the job. - */ - IAEItemStack getOutput(); +public interface ICraftingJob { + + /** + * @return if this job is a simulation, simulations cannot be submitted and only represent 1 possible future + * crafting job with fake items. + */ + boolean isSimulation(); + + /** + * @return total number of bytes to process this job. + */ + long getByteTotal(); + + /** + * Populates the plan list with stack size, and requestable values that represent the stored, and crafting job + * contents respectively. + * + * @param plan plan + */ + void populatePlan(IItemList plan); + + /** + * @return the final output of the job. + */ + IAEItemStack getOutput(); } diff --git a/src/main/java/appeng/api/networking/crafting/ICraftingLink.java b/src/main/java/appeng/api/networking/crafting/ICraftingLink.java index b3976724402..2dc0e99c0d2 100644 --- a/src/main/java/appeng/api/networking/crafting/ICraftingLink.java +++ b/src/main/java/appeng/api/networking/crafting/ICraftingLink.java @@ -23,42 +23,39 @@ package appeng.api.networking.crafting; - import net.minecraft.nbt.NBTTagCompound; - -public interface ICraftingLink -{ - - /** - * @return true if the job was canceled. - */ - boolean isCanceled(); - - /** - * @return true if the job was completed. - */ - boolean isDone(); - - /** - * cancels the job. - */ - void cancel(); - - /** - * @return true if this link was generated without a requesting machine, such as a player generated request. - */ - boolean isStandalone(); - - /** - * write the link to an NBT Tag - * - * @param tag to be written data - */ - void writeToNBT( NBTTagCompound tag ); - - /** - * @return the crafting ID for this link. - */ - String getCraftingID(); +public interface ICraftingLink { + + /** + * @return true if the job was canceled. + */ + boolean isCanceled(); + + /** + * @return true if the job was completed. + */ + boolean isDone(); + + /** + * cancels the job. + */ + void cancel(); + + /** + * @return true if this link was generated without a requesting machine, such as a player generated request. + */ + boolean isStandalone(); + + /** + * write the link to an NBT Tag + * + * @param tag to be written data + */ + void writeToNBT(NBTTagCompound tag); + + /** + * @return the crafting ID for this link. + */ + String getCraftingID(); } diff --git a/src/main/java/appeng/api/networking/crafting/ICraftingMedium.java b/src/main/java/appeng/api/networking/crafting/ICraftingMedium.java index 78b4689442d..32023e55aca 100644 --- a/src/main/java/appeng/api/networking/crafting/ICraftingMedium.java +++ b/src/main/java/appeng/api/networking/crafting/ICraftingMedium.java @@ -23,28 +23,25 @@ package appeng.api.networking.crafting; - import net.minecraft.inventory.InventoryCrafting; - /** * A place to send Items for crafting purposes, this is considered part of AE's External crafting system. */ -public interface ICraftingMedium -{ +public interface ICraftingMedium { - /** - * instruct a medium to create the item represented by the pattern+details, the items on the table, and where if - * possible the output should be directed. - * - * @param patternDetails details - * @param table crafting table - * @return if the pattern was successfully pushed. - */ - boolean pushPattern( ICraftingPatternDetails patternDetails, InventoryCrafting table ); + /** + * instruct a medium to create the item represented by the pattern+details, the items on the table, and where if + * possible the output should be directed. + * + * @param patternDetails details + * @param table crafting table + * @return if the pattern was successfully pushed. + */ + boolean pushPattern(ICraftingPatternDetails patternDetails, InventoryCrafting table); - /** - * @return if this is false, the crafting engine will refuse to send new jobs to this medium. - */ - boolean isBusy(); + /** + * @return if this is false, the crafting engine will refuse to send new jobs to this medium. + */ + boolean isBusy(); } diff --git a/src/main/java/appeng/api/networking/crafting/ICraftingPatternDetails.java b/src/main/java/appeng/api/networking/crafting/ICraftingPatternDetails.java index c18305ff6b6..519d97ede23 100644 --- a/src/main/java/appeng/api/networking/crafting/ICraftingPatternDetails.java +++ b/src/main/java/appeng/api/networking/crafting/ICraftingPatternDetails.java @@ -23,85 +23,82 @@ package appeng.api.networking.crafting; - import appeng.api.implementations.ICraftingPatternItem; import appeng.api.storage.data.IAEItemStack; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.world.World; - /** * do not implement provided by {@link ICraftingPatternItem} *

* caching this INSTANCE will increase performance of validation and checks. */ -public interface ICraftingPatternDetails -{ - - /** - * @return source item. - */ - ItemStack getPattern(); - - /** - * @param slotIndex specific slot index - * @param itemStack item in slot - * @param world crafting world - * @return if an item can be used in the specific slot for this pattern. - */ - boolean isValidItemForSlot( int slotIndex, ItemStack itemStack, World world ); - - /** - * @return if this pattern is a crafting pattern ( work bench ) - */ - boolean isCraftable(); - - /** - * @return a list of the inputs, will include nulls. - */ - IAEItemStack[] getInputs(); - - /** - * @return a list of the inputs, will be clean - */ - IAEItemStack[] getCondensedInputs(); - - /** - * @return a list of the outputs, will be clean - */ - IAEItemStack[] getCondensedOutputs(); - - /** - * @return a list of the outputs, will include nulls. - */ - IAEItemStack[] getOutputs(); - - /** - * @return if this pattern is enabled to support substitutions. - */ - boolean canSubstitute(); - - /** - * Allow using this INSTANCE of the pattern details to preform the crafting action with performance enhancements. - * - * @param craftingInv inventory - * @param world crafting world - * @return the crafted ( work bench ) item. - */ - ItemStack getOutput( InventoryCrafting craftingInv, World world ); - - /** - * Get the priority of this pattern - * - * @return the priority of this pattern - */ - int getPriority(); - - /** - * Set the priority the of this pattern. - * - * @param priority priority of pattern - */ - void setPriority( int priority ); +public interface ICraftingPatternDetails { + + /** + * @return source item. + */ + ItemStack getPattern(); + + /** + * @param slotIndex specific slot index + * @param itemStack item in slot + * @param world crafting world + * @return if an item can be used in the specific slot for this pattern. + */ + boolean isValidItemForSlot(int slotIndex, ItemStack itemStack, World world); + + /** + * @return if this pattern is a crafting pattern ( work bench ) + */ + boolean isCraftable(); + + /** + * @return a list of the inputs, will include nulls. + */ + IAEItemStack[] getInputs(); + + /** + * @return a list of the inputs, will be clean + */ + IAEItemStack[] getCondensedInputs(); + + /** + * @return a list of the outputs, will be clean + */ + IAEItemStack[] getCondensedOutputs(); + + /** + * @return a list of the outputs, will include nulls. + */ + IAEItemStack[] getOutputs(); + + /** + * @return if this pattern is enabled to support substitutions. + */ + boolean canSubstitute(); + + /** + * Allow using this INSTANCE of the pattern details to preform the crafting action with performance enhancements. + * + * @param craftingInv inventory + * @param world crafting world + * @return the crafted ( work bench ) item. + */ + ItemStack getOutput(InventoryCrafting craftingInv, World world); + + /** + * Get the priority of this pattern + * + * @return the priority of this pattern + */ + int getPriority(); + + /** + * Set the priority the of this pattern. + * + * @param priority priority of pattern + */ + void setPriority(int priority); } diff --git a/src/main/java/appeng/api/networking/crafting/ICraftingProvider.java b/src/main/java/appeng/api/networking/crafting/ICraftingProvider.java index 79f89d448e7..a6a8af2c25c 100644 --- a/src/main/java/appeng/api/networking/crafting/ICraftingProvider.java +++ b/src/main/java/appeng/api/networking/crafting/ICraftingProvider.java @@ -23,21 +23,18 @@ package appeng.api.networking.crafting; - import appeng.api.networking.events.MENetworkCraftingPatternChange; - /** * Allows a IGridHost to provide crafting patterns to the network, post a {@link MENetworkCraftingPatternChange} to tell * AE2 to update. */ -public interface ICraftingProvider extends ICraftingMedium -{ +public interface ICraftingProvider extends ICraftingMedium { - /** - * called when the network is looking for possible crafting jobs. - * - * @param craftingTracker crafting helper - */ - void provideCrafting( ICraftingProviderHelper craftingTracker ); + /** + * called when the network is looking for possible crafting jobs. + * + * @param craftingTracker crafting helper + */ + void provideCrafting(ICraftingProviderHelper craftingTracker); } diff --git a/src/main/java/appeng/api/networking/crafting/ICraftingProviderHelper.java b/src/main/java/appeng/api/networking/crafting/ICraftingProviderHelper.java index ba666de9bbd..ef137bd05a0 100644 --- a/src/main/java/appeng/api/networking/crafting/ICraftingProviderHelper.java +++ b/src/main/java/appeng/api/networking/crafting/ICraftingProviderHelper.java @@ -23,23 +23,20 @@ package appeng.api.networking.crafting; - import appeng.api.storage.data.IAEItemStack; - /** * Passed to a ICraftingProvider as a interface to manipulate the available crafting jobs. */ -public interface ICraftingProviderHelper -{ +public interface ICraftingProviderHelper { - /** - * Add new Pattern to AE's crafting cache. - */ - void addCraftingOption( ICraftingMedium medium, ICraftingPatternDetails api ); + /** + * Add new Pattern to AE's crafting cache. + */ + void addCraftingOption(ICraftingMedium medium, ICraftingPatternDetails api); - /** - * Set an item can Emitable - */ - void setEmitable( IAEItemStack what ); + /** + * Set an item can Emitable + */ + void setEmitable(IAEItemStack what); } diff --git a/src/main/java/appeng/api/networking/crafting/ICraftingRequester.java b/src/main/java/appeng/api/networking/crafting/ICraftingRequester.java index 414d3eed7b5..701f9f50060 100644 --- a/src/main/java/appeng/api/networking/crafting/ICraftingRequester.java +++ b/src/main/java/appeng/api/networking/crafting/ICraftingRequester.java @@ -23,38 +23,35 @@ package appeng.api.networking.crafting; - import appeng.api.config.Actionable; import appeng.api.networking.security.IActionHost; import appeng.api.storage.data.IAEItemStack; import com.google.common.collect.ImmutableSet; - -public interface ICraftingRequester extends IActionHost -{ - - /** - * called when the host is added to the grid, and should return all crafting links it poses so they can be connected - * with the cpu that hosts the job. - * - * @return set of jobs, or an empty list. - */ - ImmutableSet getRequestedJobs(); - - /** - * items are injected into the requester as they are completed, any items that cannot be taken, or are unwanted can - * be returned. - * - * @param items item - * @param mode action mode - * @return unwanted item - */ - IAEItemStack injectCraftedItems( ICraftingLink link, IAEItemStack items, Actionable mode ); - - /** - * called when the job changes from in progress, to either complete, or canceled. - *

- * after this call the crafting link is "dead" and should be discarded. - */ - void jobStateChange( ICraftingLink link ); +public interface ICraftingRequester extends IActionHost { + + /** + * called when the host is added to the grid, and should return all crafting links it poses so they can be connected + * with the cpu that hosts the job. + * + * @return set of jobs, or an empty list. + */ + ImmutableSet getRequestedJobs(); + + /** + * items are injected into the requester as they are completed, any items that cannot be taken, or are unwanted can + * be returned. + * + * @param items item + * @param mode action mode + * @return unwanted item + */ + IAEItemStack injectCraftedItems(ICraftingLink link, IAEItemStack items, Actionable mode); + + /** + * called when the job changes from in progress, to either complete, or canceled. + *

+ * after this call the crafting link is "dead" and should be discarded. + */ + void jobStateChange(ICraftingLink link); } diff --git a/src/main/java/appeng/api/networking/crafting/ICraftingWatcher.java b/src/main/java/appeng/api/networking/crafting/ICraftingWatcher.java index 080d36d97dd..fd1fba30297 100644 --- a/src/main/java/appeng/api/networking/crafting/ICraftingWatcher.java +++ b/src/main/java/appeng/api/networking/crafting/ICraftingWatcher.java @@ -23,13 +23,7 @@ package appeng.api.networking.crafting; - import appeng.api.storage.data.IAEStack; - import java.util.Collection; - -public interface ICraftingWatcher extends Collection -{ - -} +public interface ICraftingWatcher extends Collection {} diff --git a/src/main/java/appeng/api/networking/crafting/ICraftingWatcherHost.java b/src/main/java/appeng/api/networking/crafting/ICraftingWatcherHost.java index ed6f6f9cc61..4fdc63e8236 100644 --- a/src/main/java/appeng/api/networking/crafting/ICraftingWatcherHost.java +++ b/src/main/java/appeng/api/networking/crafting/ICraftingWatcherHost.java @@ -23,26 +23,23 @@ package appeng.api.networking.crafting; - import appeng.api.storage.data.IAEItemStack; +public interface ICraftingWatcherHost { -public interface ICraftingWatcherHost -{ - - /** - * provides the ICraftingWatcher for this host, for the current network, is called when the hot changes networks. - * You do not need to clear your old watcher, its already been removed by the time this gets called. - * - * @param newWatcher crafting watcher for this host - */ - void updateWatcher( ICraftingWatcher newWatcher ); + /** + * provides the ICraftingWatcher for this host, for the current network, is called when the hot changes networks. + * You do not need to clear your old watcher, its already been removed by the time this gets called. + * + * @param newWatcher crafting watcher for this host + */ + void updateWatcher(ICraftingWatcher newWatcher); - /** - * Called when a crafting status changes. - * - * @param craftingGrid current crafting grid - * @param what change - */ - void onRequestChange( ICraftingGrid craftingGrid, IAEItemStack what ); + /** + * Called when a crafting status changes. + * + * @param craftingGrid current crafting grid + * @param what change + */ + void onRequestChange(ICraftingGrid craftingGrid, IAEItemStack what); } diff --git a/src/main/java/appeng/api/networking/energy/IAEPowerStorage.java b/src/main/java/appeng/api/networking/energy/IAEPowerStorage.java index 715a61f5305..1dac076f7dc 100644 --- a/src/main/java/appeng/api/networking/energy/IAEPowerStorage.java +++ b/src/main/java/appeng/api/networking/energy/IAEPowerStorage.java @@ -23,48 +23,45 @@ package appeng.api.networking.energy; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; - /** * Used to access information about AE's various power accepting blocks for monitoring purposes. */ -public interface IAEPowerStorage extends IEnergySource -{ +public interface IAEPowerStorage extends IEnergySource { - /** - * Inject amt, power into the device, it will store what it can, and return the amount unable to be stored. - * - * @param amt to be injected amount - * @param mode action mode - * @return amount of power which was unable to be stored - */ - double injectAEPower( double amt, Actionable mode ); + /** + * Inject amt, power into the device, it will store what it can, and return the amount unable to be stored. + * + * @param amt to be injected amount + * @param mode action mode + * @return amount of power which was unable to be stored + */ + double injectAEPower(double amt, Actionable mode); - /** - * @return the current maximum power ( this can change :P ) - */ - double getAEMaxPower(); + /** + * @return the current maximum power ( this can change :P ) + */ + double getAEMaxPower(); - /** - * @return the current AE Power Level, this may exceed getMEMaxPower() - */ - double getAECurrentPower(); + /** + * @return the current AE Power Level, this may exceed getMEMaxPower() + */ + double getAECurrentPower(); - /** - * Checked on network reset to see if your block can be used as a public power storage ( use getPowerFlow to control - * the behavior ) - * - * @return true if it can be used as a public power storage - */ - boolean isAEPublicPowerStorage(); + /** + * Checked on network reset to see if your block can be used as a public power storage ( use getPowerFlow to control + * the behavior ) + * + * @return true if it can be used as a public power storage + */ + boolean isAEPublicPowerStorage(); - /** - * Control the power flow by telling what the network can do, either add? or subtract? or both! - * - * @return access restriction what the network can do - */ - AccessRestriction getPowerFlow(); -} \ No newline at end of file + /** + * Control the power flow by telling what the network can do, either add? or subtract? or both! + * + * @return access restriction what the network can do + */ + AccessRestriction getPowerFlow(); +} diff --git a/src/main/java/appeng/api/networking/energy/IEnergyGrid.java b/src/main/java/appeng/api/networking/energy/IEnergyGrid.java index ba6105cf9a2..1b629c0f305 100644 --- a/src/main/java/appeng/api/networking/energy/IEnergyGrid.java +++ b/src/main/java/appeng/api/networking/energy/IEnergyGrid.java @@ -23,82 +23,79 @@ package appeng.api.networking.energy; - import appeng.api.config.Actionable; import appeng.api.networking.IGridCache; import appeng.api.networking.events.MENetworkPowerStatusChange; - /** * AE's Power system. */ -public interface IEnergyGrid extends IGridCache, IEnergySource, IEnergyGridProvider -{ +public interface IEnergyGrid extends IGridCache, IEnergySource, IEnergyGridProvider { - /** - * @return the current calculated idle energy drain each tick, is used internally to drain power for each tick. - */ - double getIdlePowerUsage(); + /** + * @return the current calculated idle energy drain each tick, is used internally to drain power for each tick. + */ + double getIdlePowerUsage(); - /** - * @return the average power drain over the past 10 ticks, includes idle usage during this time, and all use of - * extractPower. - */ - double getAvgPowerUsage(); + /** + * @return the average power drain over the past 10 ticks, includes idle usage during this time, and all use of + * extractPower. + */ + double getAvgPowerUsage(); - /** - * @return the average energy injected into the system per tick, for the last 10 ticks. - */ - double getAvgPowerInjection(); + /** + * @return the average energy injected into the system per tick, for the last 10 ticks. + */ + double getAvgPowerInjection(); - /** - * AE maintains an idle draw of power separate from active power draw, it condenses this into a single operation - * that determines the networks "powered state" if the network is considered off-line, your machines should not - * function. - *

- * {@link MENetworkPowerStatusChange} events are posted when this value changes if you need to be notified of the - * change, most machines can simply test the value when they operate. - * - * @return if the network is powered or not. - */ - boolean isNetworkPowered(); + /** + * AE maintains an idle draw of power separate from active power draw, it condenses this into a single operation + * that determines the networks "powered state" if the network is considered off-line, your machines should not + * function. + *

+ * {@link MENetworkPowerStatusChange} events are posted when this value changes if you need to be notified of the + * change, most machines can simply test the value when they operate. + * + * @return if the network is powered or not. + */ + boolean isNetworkPowered(); - /** - * AE will accept any power, and store it, to maintain sanity please don't send more then 10,000 at a time. - *

- * IMPORTANT: Network power knows no bounds, for less spamy power flow, networks can store more then their allotted - * storage, however, it should be kept to a minimum, to help with this, this method returns the networks current - * OVERFLOW, this is not energy you can store some where else, its already stored in the network, you can extract it - * if you want, however it it owned by the network, this is different then IAEEnergyStore - *

- * Another important note, is that if a network that had overflow is deleted, its power is gone, this is one of the - * reasons why keeping overflow to a minimum is important. - * - * @param amt power to inject into the network - * @param mode should the action be simulated or performed? - * @return the amount of power that the network has OVER the limit. - */ - double injectPower( double amt, Actionable mode ); + /** + * AE will accept any power, and store it, to maintain sanity please don't send more then 10,000 at a time. + *

+ * IMPORTANT: Network power knows no bounds, for less spamy power flow, networks can store more then their allotted + * storage, however, it should be kept to a minimum, to help with this, this method returns the networks current + * OVERFLOW, this is not energy you can store some where else, its already stored in the network, you can extract it + * if you want, however it it owned by the network, this is different then IAEEnergyStore + *

+ * Another important note, is that if a network that had overflow is deleted, its power is gone, this is one of the + * reasons why keeping overflow to a minimum is important. + * + * @param amt power to inject into the network + * @param mode should the action be simulated or performed? + * @return the amount of power that the network has OVER the limit. + */ + double injectPower(double amt, Actionable mode); - /** - * this is should be considered an estimate, and not relied upon for real calculations. - * - * @return estimated available power. - */ - double getStoredPower(); + /** + * this is should be considered an estimate, and not relied upon for real calculations. + * + * @return estimated available power. + */ + double getStoredPower(); - /** - * this is should be considered an estimate, and not relied upon for real calculations. - * - * @return estimated available power. - */ - double getMaxStoredPower(); + /** + * this is should be considered an estimate, and not relied upon for real calculations. + * + * @return estimated available power. + */ + double getMaxStoredPower(); - /** - * Calculation will be capped at maxRequired, this improves performance by limiting the number of nodes needed to - * calculate the demand. - * - * @return Amount of power required to charge the grid, in AE. - */ - double getEnergyDemand( double maxRequired ); + /** + * Calculation will be capped at maxRequired, this improves performance by limiting the number of nodes needed to + * calculate the demand. + * + * @return Amount of power required to charge the grid, in AE. + */ + double getEnergyDemand(double maxRequired); } diff --git a/src/main/java/appeng/api/networking/energy/IEnergyGridProvider.java b/src/main/java/appeng/api/networking/energy/IEnergyGridProvider.java index 1714fa81bcb..04c9da11e98 100644 --- a/src/main/java/appeng/api/networking/energy/IEnergyGridProvider.java +++ b/src/main/java/appeng/api/networking/energy/IEnergyGridProvider.java @@ -23,29 +23,25 @@ package appeng.api.networking.energy; - import appeng.api.config.Actionable; - import java.util.Set; - /** * internal use only. */ -public interface IEnergyGridProvider -{ - /** - * internal use only - */ - double extractAEPower( double amt, Actionable mode, Set seen ); - - /** - * internal use only - */ - double injectAEPower( double amt, Actionable mode, Set seen ); - - /** - * internal use only - */ - double getEnergyDemand( double d, Set seen ); +public interface IEnergyGridProvider { + /** + * internal use only + */ + double extractAEPower(double amt, Actionable mode, Set seen); + + /** + * internal use only + */ + double injectAEPower(double amt, Actionable mode, Set seen); + + /** + * internal use only + */ + double getEnergyDemand(double d, Set seen); } diff --git a/src/main/java/appeng/api/networking/energy/IEnergySource.java b/src/main/java/appeng/api/networking/energy/IEnergySource.java index bffc5833e26..d734e5ae426 100644 --- a/src/main/java/appeng/api/networking/energy/IEnergySource.java +++ b/src/main/java/appeng/api/networking/energy/IEnergySource.java @@ -23,20 +23,17 @@ package appeng.api.networking.energy; - import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; +public interface IEnergySource { -public interface IEnergySource -{ - - /** - * Extract power from the network. - * - * @param amt extracted power - * @param mode should the action be simulated or performed? - * @return returns extracted power. - */ - double extractAEPower( double amt, Actionable mode, PowerMultiplier usePowerMultiplier ); + /** + * Extract power from the network. + * + * @param amt extracted power + * @param mode should the action be simulated or performed? + * @return returns extracted power. + */ + double extractAEPower(double amt, Actionable mode, PowerMultiplier usePowerMultiplier); } diff --git a/src/main/java/appeng/api/networking/energy/IEnergyWatcher.java b/src/main/java/appeng/api/networking/energy/IEnergyWatcher.java index 5543df6da57..554fbf1c265 100644 --- a/src/main/java/appeng/api/networking/energy/IEnergyWatcher.java +++ b/src/main/java/appeng/api/networking/energy/IEnergyWatcher.java @@ -23,11 +23,6 @@ package appeng.api.networking.energy; - import java.util.Collection; - -public interface IEnergyWatcher extends Collection -{ - -} +public interface IEnergyWatcher extends Collection {} diff --git a/src/main/java/appeng/api/networking/energy/IEnergyWatcherHost.java b/src/main/java/appeng/api/networking/energy/IEnergyWatcherHost.java index 5f5237f0deb..501f84f87cc 100644 --- a/src/main/java/appeng/api/networking/energy/IEnergyWatcherHost.java +++ b/src/main/java/appeng/api/networking/energy/IEnergyWatcherHost.java @@ -23,22 +23,20 @@ package appeng.api.networking.energy; +public interface IEnergyWatcherHost { -public interface IEnergyWatcherHost -{ + /** + * provides the IEnergyWatcher for this host, for the current network, is called when the hot changes networks. You + * do not need to clear your old watcher, its already been removed by the time this gets called. + * + * @param newWatcher new watcher + */ + void updateWatcher(IEnergyWatcher newWatcher); - /** - * provides the IEnergyWatcher for this host, for the current network, is called when the hot changes networks. You - * do not need to clear your old watcher, its already been removed by the time this gets called. - * - * @param newWatcher new watcher - */ - void updateWatcher( IEnergyWatcher newWatcher ); - - /** - * Called when a threshold is crossed. - * - * @param energyGrid grid - */ - void onThresholdPass( IEnergyGrid energyGrid ); + /** + * Called when a threshold is crossed. + * + * @param energyGrid grid + */ + void onThresholdPass(IEnergyGrid energyGrid); } diff --git a/src/main/java/appeng/api/networking/events/MENetworkBootingStatusChange.java b/src/main/java/appeng/api/networking/events/MENetworkBootingStatusChange.java index b668a818b2d..58f6cac52d1 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkBootingStatusChange.java +++ b/src/main/java/appeng/api/networking/events/MENetworkBootingStatusChange.java @@ -23,17 +23,12 @@ package appeng.api.networking.events; - import appeng.api.networking.IGridNode; - /** * Posted by the network when the booting status of the network goes up * or down, the change is reflected via {@link IGridNode}.isActive() *

* Note: Most machines just need to check {@link IGridNode}.isActive() */ -public class MENetworkBootingStatusChange extends MENetworkEvent -{ - -} +public class MENetworkBootingStatusChange extends MENetworkEvent {} diff --git a/src/main/java/appeng/api/networking/events/MENetworkCellArrayUpdate.java b/src/main/java/appeng/api/networking/events/MENetworkCellArrayUpdate.java index 7fce5b45f97..8c4372a2015 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkCellArrayUpdate.java +++ b/src/main/java/appeng/api/networking/events/MENetworkCellArrayUpdate.java @@ -23,7 +23,6 @@ package appeng.api.networking.events; - /** * Posted by storage devices to inform AE to refresh its storage structure. *

@@ -33,7 +32,4 @@ * you do not need to send this event when your node is added / removed from the * grid. */ -public class MENetworkCellArrayUpdate extends MENetworkEvent -{ - -} +public class MENetworkCellArrayUpdate extends MENetworkEvent {} diff --git a/src/main/java/appeng/api/networking/events/MENetworkChannelChanged.java b/src/main/java/appeng/api/networking/events/MENetworkChannelChanged.java index b866311415e..92b4f493366 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkChannelChanged.java +++ b/src/main/java/appeng/api/networking/events/MENetworkChannelChanged.java @@ -23,21 +23,17 @@ package appeng.api.networking.events; - import appeng.api.networking.IGridNode; - /** * Posted by storage devices to inform AE the channel cache that the included node has changed its mind about its * channel requirements. */ -public class MENetworkChannelChanged extends MENetworkEvent -{ +public class MENetworkChannelChanged extends MENetworkEvent { - public final IGridNode node; + public final IGridNode node; - public MENetworkChannelChanged( final IGridNode n ) - { - this.node = n; - } + public MENetworkChannelChanged(final IGridNode n) { + this.node = n; + } } diff --git a/src/main/java/appeng/api/networking/events/MENetworkChannelsChanged.java b/src/main/java/appeng/api/networking/events/MENetworkChannelsChanged.java index 722b7902bf1..966433ff2b3 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkChannelsChanged.java +++ b/src/main/java/appeng/api/networking/events/MENetworkChannelsChanged.java @@ -23,16 +23,11 @@ package appeng.api.networking.events; - import appeng.api.networking.IGridHost; - /** * Posted to the {@link IGridHost} when the channels on the node connections are altered. *

* Never posted IGridCaches. */ -public class MENetworkChannelsChanged extends MENetworkEvent -{ - -} +public class MENetworkChannelsChanged extends MENetworkEvent {} diff --git a/src/main/java/appeng/api/networking/events/MENetworkControllerChange.java b/src/main/java/appeng/api/networking/events/MENetworkControllerChange.java index 040a3d4aa5a..b2ec9a12b8d 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkControllerChange.java +++ b/src/main/java/appeng/api/networking/events/MENetworkControllerChange.java @@ -23,13 +23,9 @@ package appeng.api.networking.events; - /** * Event posted when the networks controller state changes, this can be from no * controller to 1 controller, or any time the network changes from conflicted * to not conflicted. */ -public class MENetworkControllerChange extends MENetworkEvent -{ - -} +public class MENetworkControllerChange extends MENetworkEvent {} diff --git a/src/main/java/appeng/api/networking/events/MENetworkCraftingCpuChange.java b/src/main/java/appeng/api/networking/events/MENetworkCraftingCpuChange.java index 4a92e28cf95..d0ebcf47085 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkCraftingCpuChange.java +++ b/src/main/java/appeng/api/networking/events/MENetworkCraftingCpuChange.java @@ -23,17 +23,13 @@ package appeng.api.networking.events; - import appeng.api.networking.IGridNode; +public class MENetworkCraftingCpuChange extends MENetworkEvent { -public class MENetworkCraftingCpuChange extends MENetworkEvent -{ - - public final IGridNode node; + public final IGridNode node; - public MENetworkCraftingCpuChange( final IGridNode n ) - { - this.node = n; - } + public MENetworkCraftingCpuChange(final IGridNode n) { + this.node = n; + } } diff --git a/src/main/java/appeng/api/networking/events/MENetworkCraftingPatternChange.java b/src/main/java/appeng/api/networking/events/MENetworkCraftingPatternChange.java index 77b6a2e33a3..f8ecd6e7dbc 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkCraftingPatternChange.java +++ b/src/main/java/appeng/api/networking/events/MENetworkCraftingPatternChange.java @@ -23,20 +23,16 @@ package appeng.api.networking.events; - import appeng.api.networking.IGridNode; import appeng.api.networking.crafting.ICraftingProvider; +public class MENetworkCraftingPatternChange extends MENetworkEvent { -public class MENetworkCraftingPatternChange extends MENetworkEvent -{ - - public final ICraftingProvider provider; - public final IGridNode node; + public final ICraftingProvider provider; + public final IGridNode node; - public MENetworkCraftingPatternChange( final ICraftingProvider p, final IGridNode n ) - { - this.provider = p; - this.node = n; - } + public MENetworkCraftingPatternChange(final ICraftingProvider p, final IGridNode n) { + this.provider = p; + this.node = n; + } } diff --git a/src/main/java/appeng/api/networking/events/MENetworkEvent.java b/src/main/java/appeng/api/networking/events/MENetworkEvent.java index f40b183aee4..f37224e2428 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkEvent.java +++ b/src/main/java/appeng/api/networking/events/MENetworkEvent.java @@ -23,56 +23,49 @@ package appeng.api.networking.events; - import appeng.api.networking.IGrid; - /** * Part of AE's Event Bus. *

* Posted via {@link IGrid}.postEvent or {@link IGrid}.postEventTo */ -public class MENetworkEvent -{ +public class MENetworkEvent { - private int visited = 0; - private boolean canceled = false; + private int visited = 0; + private boolean canceled = false; - /** - * Call to prevent AE from posting the event to any further objects. - */ - public void cancel() - { - this.canceled = true; - } + /** + * Call to prevent AE from posting the event to any further objects. + */ + public void cancel() { + this.canceled = true; + } - /** - * called by AE after each object is called to cancel any future calls. - * - * @return true to cancel future calls - */ - public boolean isCanceled() - { - return this.canceled; - } + /** + * called by AE after each object is called to cancel any future calls. + * + * @return true to cancel future calls + */ + public boolean isCanceled() { + return this.canceled; + } - /** - * the number of objects that were visited by the event. - * - * @return number of visitors - */ - public int getVisitedObjects() - { - return this.visited; - } + /** + * the number of objects that were visited by the event. + * + * @return number of visitors + */ + public int getVisitedObjects() { + return this.visited; + } - /** - * Called by AE after iterating the event subscribers. - * - * @param v current number of visitors - */ - public void setVisitedObjects( final int v ) - { - this.visited = v; - } + /** + * Called by AE after iterating the event subscribers. + * + * @param v current number of visitors + */ + public void setVisitedObjects(final int v) { + this.visited = v; + } } diff --git a/src/main/java/appeng/api/networking/events/MENetworkEventSubscribe.java b/src/main/java/appeng/api/networking/events/MENetworkEventSubscribe.java index c66e69b6989..6e5d5e45949 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkEventSubscribe.java +++ b/src/main/java/appeng/api/networking/events/MENetworkEventSubscribe.java @@ -23,19 +23,13 @@ package appeng.api.networking.events; - import appeng.api.networking.IGridCache; import appeng.api.networking.IGridHost; - import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; - /** * Usable on any {@link IGridHost}, or {@link IGridCache} */ -@Retention( RetentionPolicy.RUNTIME ) -public @interface MENetworkEventSubscribe -{ - -} +@Retention(RetentionPolicy.RUNTIME) +public @interface MENetworkEventSubscribe {} diff --git a/src/main/java/appeng/api/networking/events/MENetworkPostCacheConstruction.java b/src/main/java/appeng/api/networking/events/MENetworkPostCacheConstruction.java index 1fddaa8aed2..7f5727ea41f 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkPostCacheConstruction.java +++ b/src/main/java/appeng/api/networking/events/MENetworkPostCacheConstruction.java @@ -23,12 +23,8 @@ package appeng.api.networking.events; - /** * Posted after all the caches are available, but before the grid is fully * constructed, can be used to perform cross cache construction processes. */ -public class MENetworkPostCacheConstruction extends MENetworkEvent -{ - -} +public class MENetworkPostCacheConstruction extends MENetworkEvent {} diff --git a/src/main/java/appeng/api/networking/events/MENetworkPowerIdleChange.java b/src/main/java/appeng/api/networking/events/MENetworkPowerIdleChange.java index 85915e84f0b..bfbd8b3202d 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkPowerIdleChange.java +++ b/src/main/java/appeng/api/networking/events/MENetworkPowerIdleChange.java @@ -23,10 +23,8 @@ package appeng.api.networking.events; - import appeng.api.networking.IGridNode; - /** * Implementers of a IGridBlock must post this event when your getIdlePowerUsage * starts returning a new value, if you do not post this event the network will @@ -34,13 +32,11 @@ *

* you do not need to send this event when your node is added / removed from the grid. */ -public class MENetworkPowerIdleChange extends MENetworkEvent -{ +public class MENetworkPowerIdleChange extends MENetworkEvent { - public final IGridNode node; + public final IGridNode node; - public MENetworkPowerIdleChange( final IGridNode nodeThatChanged ) - { - this.node = nodeThatChanged; - } + public MENetworkPowerIdleChange(final IGridNode nodeThatChanged) { + this.node = nodeThatChanged; + } } diff --git a/src/main/java/appeng/api/networking/events/MENetworkPowerStatusChange.java b/src/main/java/appeng/api/networking/events/MENetworkPowerStatusChange.java index a2d2d163f66..6d4e1e256cd 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkPowerStatusChange.java +++ b/src/main/java/appeng/api/networking/events/MENetworkPowerStatusChange.java @@ -23,11 +23,9 @@ package appeng.api.networking.events; - import appeng.api.networking.IGridNode; import appeng.api.networking.energy.IEnergyGrid; - /** * Posted by the network when the power status of the network goes up or down, * the change is reflected via the {@link IEnergyGrid}.isNetworkPowered() or via @@ -35,7 +33,4 @@ *

* Note: Most machines just need to check {@link IGridNode}.isActive() */ -public class MENetworkPowerStatusChange extends MENetworkEvent -{ - -} +public class MENetworkPowerStatusChange extends MENetworkEvent {} diff --git a/src/main/java/appeng/api/networking/events/MENetworkPowerStorage.java b/src/main/java/appeng/api/networking/events/MENetworkPowerStorage.java index c97c05f3de7..59b3baeebe8 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkPowerStorage.java +++ b/src/main/java/appeng/api/networking/events/MENetworkPowerStorage.java @@ -23,10 +23,8 @@ package appeng.api.networking.events; - import appeng.api.networking.energy.IAEPowerStorage; - /** * informs the network, that a {@link IAEPowerStorage} block that had either run, * out of power, or was full, is no longer in that state. @@ -36,28 +34,25 @@ *

* you do not need to send this event when your node is added / removed from the grid. */ -public class MENetworkPowerStorage extends MENetworkEvent -{ - - public final IAEPowerStorage storage; - public final PowerEventType type; - - public MENetworkPowerStorage( final IAEPowerStorage t, final PowerEventType y ) - { - this.storage = t; - this.type = y; - } - - public enum PowerEventType - { - /** - * informs the network this tile is ready to receive power again. - */ - REQUEST_POWER, - - /** - * informs the network this tile is ready to provide power again. - */ - PROVIDE_POWER - } +public class MENetworkPowerStorage extends MENetworkEvent { + + public final IAEPowerStorage storage; + public final PowerEventType type; + + public MENetworkPowerStorage(final IAEPowerStorage t, final PowerEventType y) { + this.storage = t; + this.type = y; + } + + public enum PowerEventType { + /** + * informs the network this tile is ready to receive power again. + */ + REQUEST_POWER, + + /** + * informs the network this tile is ready to provide power again. + */ + PROVIDE_POWER + } } diff --git a/src/main/java/appeng/api/networking/events/MENetworkSecurityChange.java b/src/main/java/appeng/api/networking/events/MENetworkSecurityChange.java index 968d84752fd..d2e7e0367de 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkSecurityChange.java +++ b/src/main/java/appeng/api/networking/events/MENetworkSecurityChange.java @@ -23,11 +23,7 @@ package appeng.api.networking.events; - /** * Posted by the security framework when permissions change */ -public class MENetworkSecurityChange extends MENetworkEvent -{ - -} +public class MENetworkSecurityChange extends MENetworkEvent {} diff --git a/src/main/java/appeng/api/networking/events/MENetworkSpatialEvent.java b/src/main/java/appeng/api/networking/events/MENetworkSpatialEvent.java index ea666a12d61..0f9ca24fb4c 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkSpatialEvent.java +++ b/src/main/java/appeng/api/networking/events/MENetworkSpatialEvent.java @@ -23,25 +23,21 @@ package appeng.api.networking.events; - import appeng.api.networking.IGridHost; - /** * An event that is posted whenever a spatial IO is active, called for IGridCache */ -public class MENetworkSpatialEvent extends MENetworkEvent -{ - public final IGridHost host; - public final double spatialEnergyUsage; +public class MENetworkSpatialEvent extends MENetworkEvent { + public final IGridHost host; + public final double spatialEnergyUsage; - /** - * @param SpatialIO ( INSTANCE of the SpatialIO block ) - * @param EnergyUsage ( the amount of energy that the SpatialIO uses) - */ - public MENetworkSpatialEvent( final IGridHost SpatialIO, final double EnergyUsage ) - { - this.host = SpatialIO; - this.spatialEnergyUsage = EnergyUsage; - } + /** + * @param SpatialIO ( INSTANCE of the SpatialIO block ) + * @param EnergyUsage ( the amount of energy that the SpatialIO uses) + */ + public MENetworkSpatialEvent(final IGridHost SpatialIO, final double EnergyUsage) { + this.host = SpatialIO; + this.spatialEnergyUsage = EnergyUsage; + } } diff --git a/src/main/java/appeng/api/networking/events/MENetworkStorageEvent.java b/src/main/java/appeng/api/networking/events/MENetworkStorageEvent.java index a919da07463..8c4142d1d4f 100644 --- a/src/main/java/appeng/api/networking/events/MENetworkStorageEvent.java +++ b/src/main/java/appeng/api/networking/events/MENetworkStorageEvent.java @@ -23,11 +23,9 @@ package appeng.api.networking.events; - import appeng.api.storage.IMEMonitor; import appeng.api.storage.StorageChannel; - /** * posted by the network when the networks Storage Changes, you can use the currentItems list to check levels, and * update status. @@ -36,15 +34,13 @@ *

* Do not modify the list or its contents in anyway. */ -public class MENetworkStorageEvent extends MENetworkEvent -{ +public class MENetworkStorageEvent extends MENetworkEvent { - public final IMEMonitor monitor; - public final StorageChannel channel; + public final IMEMonitor monitor; + public final StorageChannel channel; - public MENetworkStorageEvent( final IMEMonitor o, final StorageChannel chan ) - { - this.monitor = o; - this.channel = chan; - } + public MENetworkStorageEvent(final IMEMonitor o, final StorageChannel chan) { + this.monitor = o; + this.channel = chan; + } } diff --git a/src/main/java/appeng/api/networking/pathing/ControllerState.java b/src/main/java/appeng/api/networking/pathing/ControllerState.java index 0bb0e5e1a8e..f6f4d510cbf 100644 --- a/src/main/java/appeng/api/networking/pathing/ControllerState.java +++ b/src/main/java/appeng/api/networking/pathing/ControllerState.java @@ -23,21 +23,19 @@ package appeng.api.networking.pathing; +public enum ControllerState { + /** + * No controller blocks are present in the network. + */ + NO_CONTROLLER, -public enum ControllerState -{ - /** - * No controller blocks are present in the network. - */ - NO_CONTROLLER, + /** + * Controller rules followed, booting enabled. + */ + CONTROLLER_ONLINE, - /** - * Controller rules followed, booting enabled. - */ - CONTROLLER_ONLINE, - - /** - * Controller rules not followed, lock up while booting. - */ - CONTROLLER_CONFLICT + /** + * Controller rules not followed, lock up while booting. + */ + CONTROLLER_CONFLICT } diff --git a/src/main/java/appeng/api/networking/pathing/IPathingGrid.java b/src/main/java/appeng/api/networking/pathing/IPathingGrid.java index f9a592eee46..3720c92c105 100644 --- a/src/main/java/appeng/api/networking/pathing/IPathingGrid.java +++ b/src/main/java/appeng/api/networking/pathing/IPathingGrid.java @@ -23,26 +23,23 @@ package appeng.api.networking.pathing; - import appeng.api.networking.IGridCache; +public interface IPathingGrid extends IGridCache { -public interface IPathingGrid extends IGridCache -{ - - /** - * @return true if the network is in its booting stage - */ - boolean isNetworkBooting(); + /** + * @return true if the network is in its booting stage + */ + boolean isNetworkBooting(); - /** - * @return the controller state of the network, useful if you want to - * require a controller for a feature. - */ - ControllerState getControllerState(); + /** + * @return the controller state of the network, useful if you want to + * require a controller for a feature. + */ + ControllerState getControllerState(); - /** - * trigger a network reset, booting, path-finding and all. - */ - void repath(); -} \ No newline at end of file + /** + * trigger a network reset, booting, path-finding and all. + */ + void repath(); +} diff --git a/src/main/java/appeng/api/networking/security/BaseActionSource.java b/src/main/java/appeng/api/networking/security/BaseActionSource.java index bfaa66a2405..cec63cec536 100644 --- a/src/main/java/appeng/api/networking/security/BaseActionSource.java +++ b/src/main/java/appeng/api/networking/security/BaseActionSource.java @@ -23,17 +23,13 @@ package appeng.api.networking.security; +public class BaseActionSource { -public class BaseActionSource -{ + public boolean isPlayer() { + return false; + } - public boolean isPlayer() - { - return false; - } - - public boolean isMachine() - { - return false; - } + public boolean isMachine() { + return false; + } } diff --git a/src/main/java/appeng/api/networking/security/IActionHost.java b/src/main/java/appeng/api/networking/security/IActionHost.java index 90c056d8088..1a853908944 100644 --- a/src/main/java/appeng/api/networking/security/IActionHost.java +++ b/src/main/java/appeng/api/networking/security/IActionHost.java @@ -23,21 +23,18 @@ package appeng.api.networking.security; - import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; +public interface IActionHost extends IGridHost { -public interface IActionHost extends IGridHost -{ - - /** - * Used to for calculating security rules, you must supply a node from your - * IGridHost for the security test, this should be the primary node for the - * machine, unless the action is preformed by a non primary node. - * - * @return the the gridnode that actions from this IGridHost are preformed - * by. - */ - IGridNode getActionableNode(); + /** + * Used to for calculating security rules, you must supply a node from your + * IGridHost for the security test, this should be the primary node for the + * machine, unless the action is preformed by a non primary node. + * + * @return the the gridnode that actions from this IGridHost are preformed + * by. + */ + IGridNode getActionableNode(); } diff --git a/src/main/java/appeng/api/networking/security/ISecurityGrid.java b/src/main/java/appeng/api/networking/security/ISecurityGrid.java index ef1d73d49bd..93c49adbe50 100644 --- a/src/main/java/appeng/api/networking/security/ISecurityGrid.java +++ b/src/main/java/appeng/api/networking/security/ISecurityGrid.java @@ -23,40 +23,37 @@ package appeng.api.networking.security; - import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGridCache; import net.minecraft.entity.player.EntityPlayer; - -public interface ISecurityGrid extends IGridCache -{ - - /** - * @return true if a security provider is in the network ( and only 1 ) - */ - boolean isAvailable(); - - /** - * Check if a player has permissions. - * - * @param player to be checked player - * @param perm checked permissions - * @return true if the player has permissions. - */ - boolean hasPermission( EntityPlayer player, SecurityPermissions perm ); - - /** - * Check if a player has permissions. - * - * @param playerID id of player - * @param perm checked permissions - * @return true if the player has permissions. - */ - boolean hasPermission( int playerID, SecurityPermissions perm ); - - /** - * @return PlayerID of the admin, or owner, this is the person who placed the security block. - */ - int getOwner(); +public interface ISecurityGrid extends IGridCache { + + /** + * @return true if a security provider is in the network ( and only 1 ) + */ + boolean isAvailable(); + + /** + * Check if a player has permissions. + * + * @param player to be checked player + * @param perm checked permissions + * @return true if the player has permissions. + */ + boolean hasPermission(EntityPlayer player, SecurityPermissions perm); + + /** + * Check if a player has permissions. + * + * @param playerID id of player + * @param perm checked permissions + * @return true if the player has permissions. + */ + boolean hasPermission(int playerID, SecurityPermissions perm); + + /** + * @return PlayerID of the admin, or owner, this is the person who placed the security block. + */ + int getOwner(); } diff --git a/src/main/java/appeng/api/networking/security/ISecurityProvider.java b/src/main/java/appeng/api/networking/security/ISecurityProvider.java index 8ff1a5fd209..16c4a739019 100644 --- a/src/main/java/appeng/api/networking/security/ISecurityProvider.java +++ b/src/main/java/appeng/api/networking/security/ISecurityProvider.java @@ -23,40 +23,36 @@ package appeng.api.networking.security; - import appeng.api.config.SecurityPermissions; - import java.util.EnumSet; import java.util.HashMap; - /** * Implemented on Security Terminal to interface with security cache. */ -public interface ISecurityProvider -{ - - /** - * used to represent the security key for the network, should be based on a unique timestamp. - * - * @return unique key. - */ - long getSecurityKey(); - - /** - * Push permission data into security cache. - * - * @param playerPerms player permissions - */ - void readPermissions( HashMap> playerPerms ); - - /** - * @return is security on or off? - */ - boolean isSecurityEnabled(); - - /** - * @return player ID for who placed the security provider. - */ - int getOwner(); +public interface ISecurityProvider { + + /** + * used to represent the security key for the network, should be based on a unique timestamp. + * + * @return unique key. + */ + long getSecurityKey(); + + /** + * Push permission data into security cache. + * + * @param playerPerms player permissions + */ + void readPermissions(HashMap> playerPerms); + + /** + * @return is security on or off? + */ + boolean isSecurityEnabled(); + + /** + * @return player ID for who placed the security provider. + */ + int getOwner(); } diff --git a/src/main/java/appeng/api/networking/security/ISecurityRegistry.java b/src/main/java/appeng/api/networking/security/ISecurityRegistry.java index e20701862e4..6c5e8a21e0b 100644 --- a/src/main/java/appeng/api/networking/security/ISecurityRegistry.java +++ b/src/main/java/appeng/api/networking/security/ISecurityRegistry.java @@ -23,23 +23,19 @@ package appeng.api.networking.security; - import appeng.api.config.SecurityPermissions; - import java.util.EnumSet; - /** * Used by vanilla Security Terminal to post biometric data into the security cache. */ -public interface ISecurityRegistry -{ +public interface ISecurityRegistry { - /** - * Submit Permissions into the register. - * - * @param playerID player id - * @param permissions permissions of player - */ - void addPlayer( int playerID, EnumSet permissions ); + /** + * Submit Permissions into the register. + * + * @param playerID player id + * @param permissions permissions of player + */ + void addPlayer(int playerID, EnumSet permissions); } diff --git a/src/main/java/appeng/api/networking/security/MachineSource.java b/src/main/java/appeng/api/networking/security/MachineSource.java index 40a465360cb..714013c4d08 100644 --- a/src/main/java/appeng/api/networking/security/MachineSource.java +++ b/src/main/java/appeng/api/networking/security/MachineSource.java @@ -23,20 +23,16 @@ package appeng.api.networking.security; +public class MachineSource extends BaseActionSource { -public class MachineSource extends BaseActionSource -{ + public final IActionHost via; - public final IActionHost via; + public MachineSource(final IActionHost v) { + this.via = v; + } - public MachineSource( final IActionHost v ) - { - this.via = v; - } - - @Override - public boolean isMachine() - { - return true; - } + @Override + public boolean isMachine() { + return true; + } } diff --git a/src/main/java/appeng/api/networking/security/PlayerSource.java b/src/main/java/appeng/api/networking/security/PlayerSource.java index fc6cb37e734..0201629774a 100644 --- a/src/main/java/appeng/api/networking/security/PlayerSource.java +++ b/src/main/java/appeng/api/networking/security/PlayerSource.java @@ -23,25 +23,20 @@ package appeng.api.networking.security; - import net.minecraft.entity.player.EntityPlayer; +public class PlayerSource extends BaseActionSource { -public class PlayerSource extends BaseActionSource -{ - - public final EntityPlayer player; - public final IActionHost via; + public final EntityPlayer player; + public final IActionHost via; - public PlayerSource( final EntityPlayer p, final IActionHost v ) - { - this.player = p; - this.via = v; - } + public PlayerSource(final EntityPlayer p, final IActionHost v) { + this.player = p; + this.via = v; + } - @Override - public boolean isPlayer() - { - return true; - } + @Override + public boolean isPlayer() { + return true; + } } diff --git a/src/main/java/appeng/api/networking/spatial/ISpatialCache.java b/src/main/java/appeng/api/networking/spatial/ISpatialCache.java index d70b9bdaa74..543e5946f5b 100644 --- a/src/main/java/appeng/api/networking/spatial/ISpatialCache.java +++ b/src/main/java/appeng/api/networking/spatial/ISpatialCache.java @@ -23,41 +23,38 @@ package appeng.api.networking.spatial; - import appeng.api.networking.IGridCache; import appeng.api.util.DimensionalCoord; - -public interface ISpatialCache extends IGridCache -{ - - /** - * @return true if a region is defined at all, it doesn't have to be valid, but all points must be in the same world. - */ - boolean hasRegion(); - - /** - * @return true if the region defined is valid according to all rules. - */ - boolean isValidRegion(); - - /** - * @return the minimum anchor point for the spatial region. - */ - DimensionalCoord getMin(); - - /** - * @return the maximum anchor point for the spatial region. - */ - DimensionalCoord getMax(); - - /** - * @return how many AE units are required to preform the activation - */ - long requiredPower(); - - /** - * @return current 100% - 0% efficiency. - */ - float currentEfficiency(); +public interface ISpatialCache extends IGridCache { + + /** + * @return true if a region is defined at all, it doesn't have to be valid, but all points must be in the same world. + */ + boolean hasRegion(); + + /** + * @return true if the region defined is valid according to all rules. + */ + boolean isValidRegion(); + + /** + * @return the minimum anchor point for the spatial region. + */ + DimensionalCoord getMin(); + + /** + * @return the maximum anchor point for the spatial region. + */ + DimensionalCoord getMax(); + + /** + * @return how many AE units are required to preform the activation + */ + long requiredPower(); + + /** + * @return current 100% - 0% efficiency. + */ + float currentEfficiency(); } diff --git a/src/main/java/appeng/api/networking/storage/IBaseMonitor.java b/src/main/java/appeng/api/networking/storage/IBaseMonitor.java index 2d906ee3292..8c422f60617 100644 --- a/src/main/java/appeng/api/networking/storage/IBaseMonitor.java +++ b/src/main/java/appeng/api/networking/storage/IBaseMonitor.java @@ -23,21 +23,18 @@ package appeng.api.networking.storage; - import appeng.api.storage.IMEMonitorHandlerReceiver; import appeng.api.storage.data.IAEStack; +public interface IBaseMonitor { -public interface IBaseMonitor -{ - - /** - * add a new Listener to the monitor, be sure to properly remove yourself when your done. - */ - void addListener( IMEMonitorHandlerReceiver l, Object verificationToken ); + /** + * add a new Listener to the monitor, be sure to properly remove yourself when your done. + */ + void addListener(IMEMonitorHandlerReceiver l, Object verificationToken); - /** - * remove a Listener to the monitor. - */ - void removeListener( IMEMonitorHandlerReceiver l ); + /** + * remove a Listener to the monitor. + */ + void removeListener(IMEMonitorHandlerReceiver l); } diff --git a/src/main/java/appeng/api/networking/storage/IStackWatcher.java b/src/main/java/appeng/api/networking/storage/IStackWatcher.java index 6e829088dc6..4b0919a7b22 100644 --- a/src/main/java/appeng/api/networking/storage/IStackWatcher.java +++ b/src/main/java/appeng/api/networking/storage/IStackWatcher.java @@ -23,13 +23,7 @@ package appeng.api.networking.storage; - import appeng.api.storage.data.IAEStack; - import java.util.Collection; - -public interface IStackWatcher extends Collection -{ - -} +public interface IStackWatcher extends Collection {} diff --git a/src/main/java/appeng/api/networking/storage/IStackWatcherHost.java b/src/main/java/appeng/api/networking/storage/IStackWatcherHost.java index f2a9f3dcd12..0c48cc80bd9 100644 --- a/src/main/java/appeng/api/networking/storage/IStackWatcherHost.java +++ b/src/main/java/appeng/api/networking/storage/IStackWatcherHost.java @@ -23,32 +23,29 @@ package appeng.api.networking.storage; - import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; +public interface IStackWatcherHost { -public interface IStackWatcherHost -{ - - /** - * provides the IStackWatcher for this host, for the current network, is called when the hot changes networks. You - * do not need to clear your old watcher, its already been removed by the time this gets called. - * - * @param newWatcher stack watcher - */ - void updateWatcher( IStackWatcher newWatcher ); + /** + * provides the IStackWatcher for this host, for the current network, is called when the hot changes networks. You + * do not need to clear your old watcher, its already been removed by the time this gets called. + * + * @param newWatcher stack watcher + */ + void updateWatcher(IStackWatcher newWatcher); - /** - * Called when a watched item changes amounts. - * - * @param o changed item list - * @param fullStack old stack - * @param diffStack new stack - * @param src action source - * @param chan storage channel - */ - void onStackChange( IItemList o, IAEStack fullStack, IAEStack diffStack, BaseActionSource src, StorageChannel chan ); + /** + * Called when a watched item changes amounts. + * + * @param o changed item list + * @param fullStack old stack + * @param diffStack new stack + * @param src action source + * @param chan storage channel + */ + void onStackChange(IItemList o, IAEStack fullStack, IAEStack diffStack, BaseActionSource src, StorageChannel chan); } diff --git a/src/main/java/appeng/api/networking/storage/IStorageGrid.java b/src/main/java/appeng/api/networking/storage/IStorageGrid.java index 101ad2fe4b4..dd7a7b47d80 100644 --- a/src/main/java/appeng/api/networking/storage/IStorageGrid.java +++ b/src/main/java/appeng/api/networking/storage/IStorageGrid.java @@ -23,7 +23,6 @@ package appeng.api.networking.storage; - import appeng.api.networking.IGridCache; import appeng.api.networking.IGridHost; import appeng.api.networking.security.BaseActionSource; @@ -33,37 +32,35 @@ import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEStack; - /** * Common base class for item / fluid storage caches. */ -public interface IStorageGrid extends IGridCache, IStorageMonitorable -{ +public interface IStorageGrid extends IGridCache, IStorageMonitorable { - /** - * Used to inform the network of alterations to the storage system that fall outside of the standard Network - * operations, Examples, ME Chest inputs from the world, or a Storage Bus detecting modifications made to the chest - * by an outside force. - *

- * Expects the input to have either a negative or a positive stack size to correspond to the injection, or - * extraction operation. - * - * @param input injected items - */ - void postAlterationOfStoredItems( StorageChannel chan, Iterable input, BaseActionSource src ); + /** + * Used to inform the network of alterations to the storage system that fall outside of the standard Network + * operations, Examples, ME Chest inputs from the world, or a Storage Bus detecting modifications made to the chest + * by an outside force. + *

+ * Expects the input to have either a negative or a positive stack size to correspond to the injection, or + * extraction operation. + * + * @param input injected items + */ + void postAlterationOfStoredItems(StorageChannel chan, Iterable input, BaseActionSource src); - /** - * Used to add a cell provider to the storage system - *

- * THIS IT NOT FOR USE {@link IGridHost} THAT PROVIDE {@link ICellContainer} - those are automatically handled by - * the storage system. - * - * @param cc to be added cell provider - */ - void registerCellProvider( ICellProvider cc ); + /** + * Used to add a cell provider to the storage system + *

+ * THIS IT NOT FOR USE {@link IGridHost} THAT PROVIDE {@link ICellContainer} - those are automatically handled by + * the storage system. + * + * @param cc to be added cell provider + */ + void registerCellProvider(ICellProvider cc); - /** - * remove a provider added with addCellContainer - */ - void unregisterCellProvider( ICellProvider cc ); + /** + * remove a provider added with addCellContainer + */ + void unregisterCellProvider(ICellProvider cc); } diff --git a/src/main/java/appeng/api/networking/ticking/IGridTickable.java b/src/main/java/appeng/api/networking/ticking/IGridTickable.java index 10035323705..9a8087cf29b 100644 --- a/src/main/java/appeng/api/networking/ticking/IGridTickable.java +++ b/src/main/java/appeng/api/networking/ticking/IGridTickable.java @@ -23,54 +23,51 @@ package appeng.api.networking.ticking; - import appeng.api.networking.IGridNode; - /** * Implement on IGridHosts which want to use AE's Network Ticking Feature. */ -public interface IGridTickable -{ +public interface IGridTickable { - /** - * Important note regarding IGridTickables with more then one one node, - * - * If your IGridHost hosts multiple nodes, it may be on multiple grids, or - * its node may be present on the same grid multiple times, this is as - * designed, however if you choose to use the grid to tick these Hosts you - * must be aware that they they should probably pick a single node to tick - * for, and not tick for each node. - * - */ + /** + * Important note regarding IGridTickables with more then one one node, + * + * If your IGridHost hosts multiple nodes, it may be on multiple grids, or + * its node may be present on the same grid multiple times, this is as + * designed, however if you choose to use the grid to tick these Hosts you + * must be aware that they they should probably pick a single node to tick + * for, and not tick for each node. + * + */ - /** - * You can return null, if you wish to tick using MC's ticking mechanism, or - * you can return a valid TickingRequest to tell AE a guide for which type - * of responsiveness your device wants. - *

- * this will be called for your tile any time your tile changes grids, this - * can happen at any time, so if your using the sleep feature you may wish - * to preserve your sleep, in the result of this method. or you can simply - * reset it. - * - * @return null or a valid new TickingRequest - */ - TickingRequest getTickingRequest( IGridNode node ); + /** + * You can return null, if you wish to tick using MC's ticking mechanism, or + * you can return a valid TickingRequest to tell AE a guide for which type + * of responsiveness your device wants. + *

+ * this will be called for your tile any time your tile changes grids, this + * can happen at any time, so if your using the sleep feature you may wish + * to preserve your sleep, in the result of this method. or you can simply + * reset it. + * + * @return null or a valid new TickingRequest + */ + TickingRequest getTickingRequest(IGridNode node); - /** - * AE lets you adjust your tick rate based on the results of your tick, if - * your block as accomplished work you may wish to increase the ticking - * speed, if your block is idle you may wish to slow it down. - *

- * Its up to you. - *

- * Note: this is never called if you return null from getTickingRequest. - * - * @param TicksSinceLastCall the number of world ticks that were skipped since your last - * tick, you can use this to adjust speed of processing or adjust - * your tick rate. - * @return tick rate adjustment. - */ - TickRateModulation tickingRequest( IGridNode node, int TicksSinceLastCall ); + /** + * AE lets you adjust your tick rate based on the results of your tick, if + * your block as accomplished work you may wish to increase the ticking + * speed, if your block is idle you may wish to slow it down. + *

+ * Its up to you. + *

+ * Note: this is never called if you return null from getTickingRequest. + * + * @param TicksSinceLastCall the number of world ticks that were skipped since your last + * tick, you can use this to adjust speed of processing or adjust + * your tick rate. + * @return tick rate adjustment. + */ + TickRateModulation tickingRequest(IGridNode node, int TicksSinceLastCall); } diff --git a/src/main/java/appeng/api/networking/ticking/ITickManager.java b/src/main/java/appeng/api/networking/ticking/ITickManager.java index 4a70a7facf9..4a6a2327cc0 100644 --- a/src/main/java/appeng/api/networking/ticking/ITickManager.java +++ b/src/main/java/appeng/api/networking/ticking/ITickManager.java @@ -23,40 +23,37 @@ package appeng.api.networking.ticking; - import appeng.api.networking.IGridCache; import appeng.api.networking.IGridNode; - /** * The network tick manager. */ -public interface ITickManager extends IGridCache -{ - - /** - * immediately sets the node to tick, only valid if your node is marked as "Alertable" in its TickingRequest - *

- * Sleeping Devices Still Alertable, when your tile is alerted its new status is determined by the result of its - * tick. - * - * @param node gridnode - */ - boolean alertDevice( IGridNode node ); - - /** - * disables ticking for your device. - * - * @param node gridnode - * @return if the call was successful. - */ - boolean sleepDevice( IGridNode node ); - - /** - * enables ticking for your device, undoes a sleepDevice call. - * - * @param node gridnode - * @return if the call was successful. - */ - boolean wakeDevice( IGridNode node ); +public interface ITickManager extends IGridCache { + + /** + * immediately sets the node to tick, only valid if your node is marked as "Alertable" in its TickingRequest + *

+ * Sleeping Devices Still Alertable, when your tile is alerted its new status is determined by the result of its + * tick. + * + * @param node gridnode + */ + boolean alertDevice(IGridNode node); + + /** + * disables ticking for your device. + * + * @param node gridnode + * @return if the call was successful. + */ + boolean sleepDevice(IGridNode node); + + /** + * enables ticking for your device, undoes a sleepDevice call. + * + * @param node gridnode + * @return if the call was successful. + */ + boolean wakeDevice(IGridNode node); } diff --git a/src/main/java/appeng/api/networking/ticking/TickRateModulation.java b/src/main/java/appeng/api/networking/ticking/TickRateModulation.java index 35e83b921be..a83f2fbd1dd 100644 --- a/src/main/java/appeng/api/networking/ticking/TickRateModulation.java +++ b/src/main/java/appeng/api/networking/ticking/TickRateModulation.java @@ -23,36 +23,34 @@ package appeng.api.networking.ticking; - -public enum TickRateModulation -{ - /** - * same as idle, but also puts the node to sleep. - */ - SLEEP, - - /** - * set tick rate to maximum. - */ - IDLE, - - /** - * decrease the tick rate marginally. - */ - SLOWER, - - /** - * continue at current rate. - */ - SAME, - - /** - * increase the tick rate marginally. - */ - FASTER, - - /** - * changes the tick rate to the minimum tick rate. - */ - URGENT +public enum TickRateModulation { + /** + * same as idle, but also puts the node to sleep. + */ + SLEEP, + + /** + * set tick rate to maximum. + */ + IDLE, + + /** + * decrease the tick rate marginally. + */ + SLOWER, + + /** + * continue at current rate. + */ + SAME, + + /** + * increase the tick rate marginally. + */ + FASTER, + + /** + * changes the tick rate to the minimum tick rate. + */ + URGENT } diff --git a/src/main/java/appeng/api/networking/ticking/TickingRequest.java b/src/main/java/appeng/api/networking/ticking/TickingRequest.java index 6d46e23543e..7ebc6c8d995 100644 --- a/src/main/java/appeng/api/networking/ticking/TickingRequest.java +++ b/src/main/java/appeng/api/networking/ticking/TickingRequest.java @@ -23,48 +23,45 @@ package appeng.api.networking.ticking; - /** * Describes how your tiles ticking is executed. */ -public class TickingRequest -{ +public class TickingRequest { - /** - * the minimum number of ticks that must pass between ticks. - *

- * Valid Values are : 1+ - *

- * Suggested is 5-20 - */ - public final int minTickRate; + /** + * the minimum number of ticks that must pass between ticks. + *

+ * Valid Values are : 1+ + *

+ * Suggested is 5-20 + */ + public final int minTickRate; - /** - * the maximum number of ticks that can pass between ticks, if this value is - * exceeded the tile must tick. - *

- * Valid Values are 1+ - *

- * Suggested is 20-40 - */ - public final int maxTickRate; + /** + * the maximum number of ticks that can pass between ticks, if this value is + * exceeded the tile must tick. + *

+ * Valid Values are 1+ + *

+ * Suggested is 20-40 + */ + public final int maxTickRate; - /** - * Determines the current expected state of your node, if your node expects - * to be sleeping, then return true. - */ - public final boolean isSleeping; + /** + * Determines the current expected state of your node, if your node expects + * to be sleeping, then return true. + */ + public final boolean isSleeping; - /** - * True only if you call {@link ITickManager}.alertDevice( IGridNode ); - */ - public final boolean canBeAlerted; + /** + * True only if you call {@link ITickManager}.alertDevice( IGridNode ); + */ + public final boolean canBeAlerted; - public TickingRequest( final int min, final int max, final boolean sleep, final boolean alertable ) - { - this.minTickRate = min; - this.maxTickRate = max; - this.isSleeping = sleep; - this.canBeAlerted = alertable; - } + public TickingRequest(final int min, final int max, final boolean sleep, final boolean alertable) { + this.minTickRate = min; + this.maxTickRate = max; + this.isSleeping = sleep; + this.canBeAlerted = alertable; + } } diff --git a/src/main/java/appeng/api/package-info.java b/src/main/java/appeng/api/package-info.java index bd7d11bd4f1..7e5f4a57604 100644 --- a/src/main/java/appeng/api/package-info.java +++ b/src/main/java/appeng/api/package-info.java @@ -21,9 +21,7 @@ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -@API( apiVersion = "rv3", owner = "appliedenergistics2", provides = "appliedenergistics2|API" ) +@API(apiVersion = "rv3", owner = "appliedenergistics2", provides = "appliedenergistics2|API") package appeng.api; - import cpw.mods.fml.common.API; - diff --git a/src/main/java/appeng/api/parts/BusSupport.java b/src/main/java/appeng/api/parts/BusSupport.java index 03c54de413a..3255ed9de44 100644 --- a/src/main/java/appeng/api/parts/BusSupport.java +++ b/src/main/java/appeng/api/parts/BusSupport.java @@ -23,12 +23,10 @@ package appeng.api.parts; +public enum BusSupport { + CABLE, -public enum BusSupport -{ - CABLE, + DENSE_CABLE, - DENSE_CABLE, - - NO_PARTS + NO_PARTS } diff --git a/src/main/java/appeng/api/parts/CableRenderMode.java b/src/main/java/appeng/api/parts/CableRenderMode.java index d9e80bfc53b..db524c1a103 100644 --- a/src/main/java/appeng/api/parts/CableRenderMode.java +++ b/src/main/java/appeng/api/parts/CableRenderMode.java @@ -23,19 +23,16 @@ package appeng.api.parts; +public enum CableRenderMode { + Standard(false), -public enum CableRenderMode -{ - Standard( false ), + CableView(true); - CableView( true ); + public final boolean transparentFacades; + public final boolean opaqueFacades; - public final boolean transparentFacades; - public final boolean opaqueFacades; - - CableRenderMode( final boolean hideFacades ) - { - this.transparentFacades = hideFacades; - this.opaqueFacades = !hideFacades; - } + CableRenderMode(final boolean hideFacades) { + this.transparentFacades = hideFacades; + this.opaqueFacades = !hideFacades; + } } diff --git a/src/main/java/appeng/api/parts/IAlphaPassItem.java b/src/main/java/appeng/api/parts/IAlphaPassItem.java index db20111d32c..1f4d9ed9d9b 100644 --- a/src/main/java/appeng/api/parts/IAlphaPassItem.java +++ b/src/main/java/appeng/api/parts/IAlphaPassItem.java @@ -23,18 +23,15 @@ package appeng.api.parts; - import net.minecraft.item.ItemStack; +public interface IAlphaPassItem { -public interface IAlphaPassItem -{ - - /** - * Extend, and return true to enable a second pass for your parts in the bus rendering pipe line. - * - * @param is item - * @return true to enable a second pass for your parts in the bus rendering pipe line. - */ - boolean useAlphaPass( ItemStack is ); + /** + * Extend, and return true to enable a second pass for your parts in the bus rendering pipe line. + * + * @param is item + * @return true to enable a second pass for your parts in the bus rendering pipe line. + */ + boolean useAlphaPass(ItemStack is); } diff --git a/src/main/java/appeng/api/parts/IBoxProvider.java b/src/main/java/appeng/api/parts/IBoxProvider.java index a03230ef123..105842f1394 100644 --- a/src/main/java/appeng/api/parts/IBoxProvider.java +++ b/src/main/java/appeng/api/parts/IBoxProvider.java @@ -23,14 +23,12 @@ package appeng.api.parts; +public interface IBoxProvider { -public interface IBoxProvider -{ - - /** - * add your collision information to the the list. - * - * @param boxes collision boxes - */ - void getBoxes( IPartCollisionHelper boxes ); + /** + * add your collision information to the the list. + * + * @param boxes collision boxes + */ + void getBoxes(IPartCollisionHelper boxes); } diff --git a/src/main/java/appeng/api/parts/IFacadeContainer.java b/src/main/java/appeng/api/parts/IFacadeContainer.java index c34d6d13e34..1186f49e3b8 100644 --- a/src/main/java/appeng/api/parts/IFacadeContainer.java +++ b/src/main/java/appeng/api/parts/IFacadeContainer.java @@ -23,77 +23,73 @@ package appeng.api.parts; - import io.netty.buffer.ByteBuf; +import java.io.IOException; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; - - /** * Used Internally. *

* not intended for implementation. */ -public interface IFacadeContainer -{ +public interface IFacadeContainer { - /** - * Attempts to add the {@link IFacadePart} to the given side. - * - * @return true if the facade as successfully added. - */ - boolean addFacade( IFacadePart a ); + /** + * Attempts to add the {@link IFacadePart} to the given side. + * + * @return true if the facade as successfully added. + */ + boolean addFacade(IFacadePart a); - /** - * Removed the facade on the given side, or does nothing. - */ - void removeFacade( IPartHost host, ForgeDirection side ); + /** + * Removed the facade on the given side, or does nothing. + */ + void removeFacade(IPartHost host, ForgeDirection side); - /** - * @return the {@link IFacadePart} for a given side, or null. - */ - IFacadePart getFacade( ForgeDirection s ); + /** + * @return the {@link IFacadePart} for a given side, or null. + */ + IFacadePart getFacade(ForgeDirection s); - /** - * rotate the facades left. - */ - void rotateLeft(); + /** + * rotate the facades left. + */ + void rotateLeft(); - /** - * write nbt data - * - * @param data to be written data - */ - void writeToNBT( NBTTagCompound data ); + /** + * write nbt data + * + * @param data to be written data + */ + void writeToNBT(NBTTagCompound data); - /** - * read from stream - * - * @param data to be read data - * @return true if it was readable - * @throws IOException - */ - boolean readFromStream( ByteBuf data ) throws IOException; + /** + * read from stream + * + * @param data to be read data + * @return true if it was readable + * @throws IOException + */ + boolean readFromStream(ByteBuf data) throws IOException; - /** - * read from NBT - * - * @param data to be read data - */ - void readFromNBT( NBTTagCompound data ); + /** + * read from NBT + * + * @param data to be read data + */ + void readFromNBT(NBTTagCompound data); - /** - * write to stream - * - * @param data to be written data - * @throws IOException - */ - void writeToStream( ByteBuf data ) throws IOException; + /** + * write to stream + * + * @param data to be written data + * @throws IOException + */ + void writeToStream(ByteBuf data) throws IOException; - /** - * @return true if there are no facades. - */ - boolean isEmpty(); + /** + * @return true if there are no facades. + */ + boolean isEmpty(); } diff --git a/src/main/java/appeng/api/parts/IFacadePart.java b/src/main/java/appeng/api/parts/IFacadePart.java index 37893802b44..e110b636a4e 100644 --- a/src/main/java/appeng/api/parts/IFacadePart.java +++ b/src/main/java/appeng/api/parts/IFacadePart.java @@ -23,7 +23,6 @@ package appeng.api.parts; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.RenderBlocks; @@ -33,69 +32,75 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraftforge.common.util.ForgeDirection; - /** * Used Internally. *

* not intended for implementation. */ -public interface IFacadePart -{ - - /** - * used to save the part. - */ - ItemStack getItemStack(); - - /** - * used to collide, and pick the part - * - * @param ch collision helper - * @param e colliding entity - */ - void getBoxes( IPartCollisionHelper ch, Entity e ); - - /** - * render the part. - * - * @param x x pos of part - * @param y y pos of part - * @param z z pos of part - * @param instance render helper - * @param renderer renderer - * @param fc face container - * @param busBounds bounding box - * @param renderStilt if to render stilt - */ - @SideOnly( Side.CLIENT ) - void renderStatic( int x, int y, int z, IPartRenderHelper instance, RenderBlocks renderer, IFacadeContainer fc, AxisAlignedBB busBounds, boolean renderStilt ); - - /** - * render the part in inventory. - * - * @param instance render helper - * @param renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderInventory( IPartRenderHelper instance, RenderBlocks renderer ); - - /** - * @return side the facade is in - */ - ForgeDirection getSide(); - - /** - * @return the box for the face of the facade - */ - AxisAlignedBB getPrimaryBox(); - - Item getItem(); - - int getItemDamage(); - - boolean notAEFacade(); - - void setThinFacades( boolean useThinFacades ); - - boolean isTransparent(); -} \ No newline at end of file +public interface IFacadePart { + + /** + * used to save the part. + */ + ItemStack getItemStack(); + + /** + * used to collide, and pick the part + * + * @param ch collision helper + * @param e colliding entity + */ + void getBoxes(IPartCollisionHelper ch, Entity e); + + /** + * render the part. + * + * @param x x pos of part + * @param y y pos of part + * @param z z pos of part + * @param instance render helper + * @param renderer renderer + * @param fc face container + * @param busBounds bounding box + * @param renderStilt if to render stilt + */ + @SideOnly(Side.CLIENT) + void renderStatic( + int x, + int y, + int z, + IPartRenderHelper instance, + RenderBlocks renderer, + IFacadeContainer fc, + AxisAlignedBB busBounds, + boolean renderStilt); + + /** + * render the part in inventory. + * + * @param instance render helper + * @param renderer renderer + */ + @SideOnly(Side.CLIENT) + void renderInventory(IPartRenderHelper instance, RenderBlocks renderer); + + /** + * @return side the facade is in + */ + ForgeDirection getSide(); + + /** + * @return the box for the face of the facade + */ + AxisAlignedBB getPrimaryBox(); + + Item getItem(); + + int getItemDamage(); + + boolean notAEFacade(); + + void setThinFacades(boolean useThinFacades); + + boolean isTransparent(); +} diff --git a/src/main/java/appeng/api/parts/IPart.java b/src/main/java/appeng/api/parts/IPart.java index 02e5975331c..375c30d7ad0 100644 --- a/src/main/java/appeng/api/parts/IPart.java +++ b/src/main/java/appeng/api/parts/IPart.java @@ -23,11 +23,13 @@ package appeng.api.parts; - import appeng.api.networking.IGridNode; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.IOException; +import java.util.List; +import java.util.Random; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -40,250 +42,244 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; -import java.util.List; -import java.util.Random; - - -public interface IPart extends IBoxProvider -{ - - /** - * get an ItemStack that represents the bus, should contain the settings for whatever, can also be used in - * conjunction with removePart to take a part off and drop it or something. - *

- * This is used to drop the bus, and to save the bus, when saving the bus, wrenched is false, and writeToNBT will be - * called to save important details about the part, if the part is wrenched include in your NBT Data any settings - * you might want to keep around, you can restore those settings when constructing your part. - * - * @param type , what kind of ItemStack to return? - * @return item of part - */ - ItemStack getItemStack( PartItemStack type ); - - /** - * render item form for inventory, or entity. - *

- * GL Available - * - * @param rh helper - * @param renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ); - - /** - * render world renderer ( preferred ) - *

- * GL is NOT Available - * - * @param x x coord - * @param y y coord - * @param z z coord - * @param rh helper - * @param renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderStatic( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer ); - - /** - * render TESR. - *

- * GL Available - * - * @param x x coord - * @param y y coord - * @param z z coord - * @param rh helper - * @param renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderDynamic( double x, double y, double z, IPartRenderHelper rh, RenderBlocks renderer ); - - /** - * @return the Block sheet icon used when rendering the breaking particles, return null to use the ItemStack - * texture. - */ - @SideOnly( Side.CLIENT ) - IIcon getBreakingTexture(); - - /** - * return true only if your part require dynamic rendering, must be consistent. - * - * @return true to enable renderDynamic - */ - boolean requireDynamicRender(); - - /** - * @return if the bus has a solid side, and you can place random stuff on it like torches or levers - */ - boolean isSolid(); - - /** - * @return true if this part can connect to redstone ( also MFR Rednet ) - */ - boolean canConnectRedstone(); - - /** - * Write the part information for saving, the part will be saved with getItemStack(false) and this method will be - * called after to load settings, inventory or other values from the world. - * - * @param data to be written nbt data - */ - void writeToNBT( NBTTagCompound data ); - - /** - * Read the previously written NBT Data. this is the mirror for writeToNBT - * - * @param data to be read nbt data - */ - void readFromNBT( NBTTagCompound data ); - - /** - * @return get the amount of light produced by the bus - */ - int getLightLevel(); - - /** - * does this part act like a ladder? - * - * @param entity climbing entity - * @return true if entity can climb - */ - boolean isLadder( EntityLivingBase entity ); - - /** - * a block around the bus's host has been changed. - */ - void onNeighborChanged(); - - /** - * @return output redstone on facing side - */ - int isProvidingStrongPower(); - - /** - * @return output redstone on facing side - */ - int isProvidingWeakPower(); - - /** - * write data to bus packet. - * - * @param data to be written data - * @throws IOException - */ - void writeToStream( ByteBuf data ) throws IOException; - - /** - * read data from bus packet. - * - * @param data to be read data - * @return true will re-draw the part. - * @throws IOException - */ - boolean readFromStream( ByteBuf data ) throws IOException; - - /** - * get the Grid Node for the Bus, be sure your IGridBlock is NOT isWorldAccessible, if it is your going to cause - * crashes. - *

- * or null if you don't have a grid node. - * - * @return grid node - */ - IGridNode getGridNode(); - - /** - * called when an entity collides with the bus. - * - * @param entity colliding entity - */ - void onEntityCollision( Entity entity ); - - /** - * called when your part is being removed from the world. - */ - void removeFromWorld(); - - /** - * called when your part is being added to the world. - */ - void addToWorld(); - - /** - * used for tunnels. - * - * @return a grid node that represents the external facing side, these must be isWorldAccessible with the correct - * faces marked as external - */ - IGridNode getExternalFacingNode(); - - /** - * called by the Part host to keep your part informed. - * - * @param host part side - * @param tile tile entity of part - */ - void setPartHostInfo( ForgeDirection side, IPartHost host, TileEntity tile ); - - /** - * Called when you right click the part, very similar to Block.onActivateBlock - * - * @param player right clicking player - * @param pos position of block - * @return if your activate method performed something. - */ - boolean onActivate( EntityPlayer player, Vec3 pos ); - - /** - * Called when you right click the part, very similar to Block.onActivateBlock - * - * @param player shift right clicking player - * @param pos position of block - * @return if your activate method performed something, you should use false unless you really need it. - */ - boolean onShiftActivate( EntityPlayer player, Vec3 pos ); - - /** - * Add drops to the items being dropped into the world, if your item stores its contents when wrenched use the - * wrenched boolean to control what data is saved vs dropped when it is broken. - * - * @param drops item drops if wrenched - * @param wrenched control flag for wrenched vs broken - */ - void getDrops( List drops, boolean wrenched ); - - /** - * @return 0 - 8, reasonable default 3-4, this controls the cable connection to the node. - */ - int cableConnectionRenderTo(); - - /** - * same as Block.randomDisplayTick, for but parts. - * - * @param world world of block - * @param x x coord of block - * @param y y coord of block - * @param z z coord of block - * @param r random - */ - void randomDisplayTick( World world, int x, int y, int z, Random r ); - - /** - * Called when placed in the world by a player, this happens before addWorld. - * - * @param player placing player - * @param held held item - * @param side placing side - */ - void onPlacement( EntityPlayer player, ItemStack held, ForgeDirection side ); - - /** - * Used to determine which parts can be placed on what cables. - * - * @param what placed part - * @return true if the part can be placed on this support. - */ - boolean canBePlacedOn( BusSupport what ); -} \ No newline at end of file +public interface IPart extends IBoxProvider { + + /** + * get an ItemStack that represents the bus, should contain the settings for whatever, can also be used in + * conjunction with removePart to take a part off and drop it or something. + *

+ * This is used to drop the bus, and to save the bus, when saving the bus, wrenched is false, and writeToNBT will be + * called to save important details about the part, if the part is wrenched include in your NBT Data any settings + * you might want to keep around, you can restore those settings when constructing your part. + * + * @param type , what kind of ItemStack to return? + * @return item of part + */ + ItemStack getItemStack(PartItemStack type); + + /** + * render item form for inventory, or entity. + *

+ * GL Available + * + * @param rh helper + * @param renderer renderer + */ + @SideOnly(Side.CLIENT) + void renderInventory(IPartRenderHelper rh, RenderBlocks renderer); + + /** + * render world renderer ( preferred ) + *

+ * GL is NOT Available + * + * @param x x coord + * @param y y coord + * @param z z coord + * @param rh helper + * @param renderer renderer + */ + @SideOnly(Side.CLIENT) + void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer); + + /** + * render TESR. + *

+ * GL Available + * + * @param x x coord + * @param y y coord + * @param z z coord + * @param rh helper + * @param renderer renderer + */ + @SideOnly(Side.CLIENT) + void renderDynamic(double x, double y, double z, IPartRenderHelper rh, RenderBlocks renderer); + + /** + * @return the Block sheet icon used when rendering the breaking particles, return null to use the ItemStack + * texture. + */ + @SideOnly(Side.CLIENT) + IIcon getBreakingTexture(); + + /** + * return true only if your part require dynamic rendering, must be consistent. + * + * @return true to enable renderDynamic + */ + boolean requireDynamicRender(); + + /** + * @return if the bus has a solid side, and you can place random stuff on it like torches or levers + */ + boolean isSolid(); + + /** + * @return true if this part can connect to redstone ( also MFR Rednet ) + */ + boolean canConnectRedstone(); + + /** + * Write the part information for saving, the part will be saved with getItemStack(false) and this method will be + * called after to load settings, inventory or other values from the world. + * + * @param data to be written nbt data + */ + void writeToNBT(NBTTagCompound data); + + /** + * Read the previously written NBT Data. this is the mirror for writeToNBT + * + * @param data to be read nbt data + */ + void readFromNBT(NBTTagCompound data); + + /** + * @return get the amount of light produced by the bus + */ + int getLightLevel(); + + /** + * does this part act like a ladder? + * + * @param entity climbing entity + * @return true if entity can climb + */ + boolean isLadder(EntityLivingBase entity); + + /** + * a block around the bus's host has been changed. + */ + void onNeighborChanged(); + + /** + * @return output redstone on facing side + */ + int isProvidingStrongPower(); + + /** + * @return output redstone on facing side + */ + int isProvidingWeakPower(); + + /** + * write data to bus packet. + * + * @param data to be written data + * @throws IOException + */ + void writeToStream(ByteBuf data) throws IOException; + + /** + * read data from bus packet. + * + * @param data to be read data + * @return true will re-draw the part. + * @throws IOException + */ + boolean readFromStream(ByteBuf data) throws IOException; + + /** + * get the Grid Node for the Bus, be sure your IGridBlock is NOT isWorldAccessible, if it is your going to cause + * crashes. + *

+ * or null if you don't have a grid node. + * + * @return grid node + */ + IGridNode getGridNode(); + + /** + * called when an entity collides with the bus. + * + * @param entity colliding entity + */ + void onEntityCollision(Entity entity); + + /** + * called when your part is being removed from the world. + */ + void removeFromWorld(); + + /** + * called when your part is being added to the world. + */ + void addToWorld(); + + /** + * used for tunnels. + * + * @return a grid node that represents the external facing side, these must be isWorldAccessible with the correct + * faces marked as external + */ + IGridNode getExternalFacingNode(); + + /** + * called by the Part host to keep your part informed. + * + * @param host part side + * @param tile tile entity of part + */ + void setPartHostInfo(ForgeDirection side, IPartHost host, TileEntity tile); + + /** + * Called when you right click the part, very similar to Block.onActivateBlock + * + * @param player right clicking player + * @param pos position of block + * @return if your activate method performed something. + */ + boolean onActivate(EntityPlayer player, Vec3 pos); + + /** + * Called when you right click the part, very similar to Block.onActivateBlock + * + * @param player shift right clicking player + * @param pos position of block + * @return if your activate method performed something, you should use false unless you really need it. + */ + boolean onShiftActivate(EntityPlayer player, Vec3 pos); + + /** + * Add drops to the items being dropped into the world, if your item stores its contents when wrenched use the + * wrenched boolean to control what data is saved vs dropped when it is broken. + * + * @param drops item drops if wrenched + * @param wrenched control flag for wrenched vs broken + */ + void getDrops(List drops, boolean wrenched); + + /** + * @return 0 - 8, reasonable default 3-4, this controls the cable connection to the node. + */ + int cableConnectionRenderTo(); + + /** + * same as Block.randomDisplayTick, for but parts. + * + * @param world world of block + * @param x x coord of block + * @param y y coord of block + * @param z z coord of block + * @param r random + */ + void randomDisplayTick(World world, int x, int y, int z, Random r); + + /** + * Called when placed in the world by a player, this happens before addWorld. + * + * @param player placing player + * @param held held item + * @param side placing side + */ + void onPlacement(EntityPlayer player, ItemStack held, ForgeDirection side); + + /** + * Used to determine which parts can be placed on what cables. + * + * @param what placed part + * @return true if the part can be placed on this support. + */ + boolean canBePlacedOn(BusSupport what); +} diff --git a/src/main/java/appeng/api/parts/IPartCollisionHelper.java b/src/main/java/appeng/api/parts/IPartCollisionHelper.java index 84c35bf2c75..c7556aabf7b 100644 --- a/src/main/java/appeng/api/parts/IPartCollisionHelper.java +++ b/src/main/java/appeng/api/parts/IPartCollisionHelper.java @@ -23,44 +23,41 @@ package appeng.api.parts; - import net.minecraftforge.common.util.ForgeDirection; - -public interface IPartCollisionHelper -{ - - /** - * add a collision box, expects 0.0 - 16.0 block coords. - *

- * No complaints about the size, I like using pixels :P - * - * @param minX minimal x collision - * @param minY minimal y collision - * @param minZ minimal z collision - * @param maxX maximal x collision - * @param maxY maximal y collision - * @param maxZ maximal z collision - */ - void addBox( double minX, double minY, double minZ, double maxX, double maxY, double maxZ ); - - /** - * @return east in world space. - */ - ForgeDirection getWorldX(); - - /** - * @return up in world space. - */ - ForgeDirection getWorldY(); - - /** - * @return forward in world space. - */ - ForgeDirection getWorldZ(); - - /** - * @return true if this test is to get the BB Collision information. - */ - boolean isBBCollision(); +public interface IPartCollisionHelper { + + /** + * add a collision box, expects 0.0 - 16.0 block coords. + *

+ * No complaints about the size, I like using pixels :P + * + * @param minX minimal x collision + * @param minY minimal y collision + * @param minZ minimal z collision + * @param maxX maximal x collision + * @param maxY maximal y collision + * @param maxZ maximal z collision + */ + void addBox(double minX, double minY, double minZ, double maxX, double maxY, double maxZ); + + /** + * @return east in world space. + */ + ForgeDirection getWorldX(); + + /** + * @return up in world space. + */ + ForgeDirection getWorldY(); + + /** + * @return forward in world space. + */ + ForgeDirection getWorldZ(); + + /** + * @return true if this test is to get the BB Collision information. + */ + boolean isBBCollision(); } diff --git a/src/main/java/appeng/api/parts/IPartHelper.java b/src/main/java/appeng/api/parts/IPartHelper.java index d42d812ed0f..71a83b08a49 100644 --- a/src/main/java/appeng/api/parts/IPartHelper.java +++ b/src/main/java/appeng/api/parts/IPartHelper.java @@ -23,64 +23,61 @@ package appeng.api.parts; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; +public interface IPartHelper { -public interface IPartHelper -{ - - /** - * Register a new layer with the part layer system, this allows you to write - * an in between between tile entities and parts. - *

- * AE By Default includes, - *

- * 1. ISidedInventory ( and by extension IInventory. ) - *

- * 2. IFluidHandler Forge Fluids - *

- * 3. IPowerEmitter BC Power output. - *

- * 4. IPowerReceptor BC Power input. - *

- * 5. IEnergySink IC2 Power input. - *

- * 6. IEnergySource IC2 Power output. - *

- * 7. IPipeConnection BC Pipe Connections - *

- * As long as a valid layer is registered for a interface you can simply - * implement that interface on a part get implement it. - * - * @return true on success, false on failure, usually a error will be logged - * as well. - */ - boolean registerNewLayer( String string, String layerInterface ); + /** + * Register a new layer with the part layer system, this allows you to write + * an in between between tile entities and parts. + *

+ * AE By Default includes, + *

+ * 1. ISidedInventory ( and by extension IInventory. ) + *

+ * 2. IFluidHandler Forge Fluids + *

+ * 3. IPowerEmitter BC Power output. + *

+ * 4. IPowerReceptor BC Power input. + *

+ * 5. IEnergySink IC2 Power input. + *

+ * 6. IEnergySource IC2 Power output. + *

+ * 7. IPipeConnection BC Pipe Connections + *

+ * As long as a valid layer is registered for a interface you can simply + * implement that interface on a part get implement it. + * + * @return true on success, false on failure, usually a error will be logged + * as well. + */ + boolean registerNewLayer(String string, String layerInterface); - /** - * Register IBusItem with renderer - */ - void setItemBusRenderer( IPartItem i ); + /** + * Register IBusItem with renderer + */ + void setItemBusRenderer(IPartItem i); - /** - * use in use item, to try and place a IBusItem - * - * @param is ItemStack of an item which implements {@link IPartItem} - * @param x x pos of part - * @param y y pos of part - * @param z z pos of part - * @param side side which the part should be on - * @param player player placing part - * @param world part in world - * @return true if placing was successful - */ - boolean placeBus( ItemStack is, int x, int y, int z, int side, EntityPlayer player, World world ); + /** + * use in use item, to try and place a IBusItem + * + * @param is ItemStack of an item which implements {@link IPartItem} + * @param x x pos of part + * @param y y pos of part + * @param z z pos of part + * @param side side which the part should be on + * @param player player placing part + * @param world part in world + * @return true if placing was successful + */ + boolean placeBus(ItemStack is, int x, int y, int z, int side, EntityPlayer player, World world); - /** - * @return the render mode - */ - CableRenderMode getCableRenderMode(); + /** + * @return the render mode + */ + CableRenderMode getCableRenderMode(); } diff --git a/src/main/java/appeng/api/parts/IPartHost.java b/src/main/java/appeng/api/parts/IPartHost.java index c59afe1c954..551eee66cfb 100644 --- a/src/main/java/appeng/api/parts/IPartHost.java +++ b/src/main/java/appeng/api/parts/IPartHost.java @@ -23,154 +23,150 @@ package appeng.api.parts; - import appeng.api.util.AEColor; import appeng.api.util.DimensionalCoord; +import java.util.Set; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Set; - - /** * Implemented on AE's TileEntity or AE's FMP Part. *

* Do Not Implement */ -public interface IPartHost -{ - - /** - * @return the facade container - */ - IFacadeContainer getFacadeContainer(); - - /** - * Test if you can add a part to the specified side of the Part Host, {@link ForgeDirection}.UNKNOWN is used to - * represent the cable in the middle. - * - * @param part to be added part - * @param side part placed onto side - * @return returns false if the part cannot be added. - */ - boolean canAddPart( ItemStack part, ForgeDirection side ); - - /** - * try to add a new part to the specified side, returns false if it failed to be added. - * - * @param is new part - * @param side onto side - * @param owner with owning player - * @return null if the item failed to add, the side it was placed on other wise ( may different for cables, - * {@link ForgeDirection}.UNKNOWN ) - */ - ForgeDirection addPart( ItemStack is, ForgeDirection side, EntityPlayer owner ); - - /** - * Get part by side ( center is {@link ForgeDirection}.UNKNOWN ) - * - * @param side side of part - * @return the part located on the specified side, or null if there is no part. - */ - IPart getPart( ForgeDirection side ); - - /** - * removes the part on the side, this doesn't drop it or anything, if you don't do something with it, its just - * "gone" and its never coming back; think about it. - *

- * if you want to drop the part you must request it prior to removing it. - * - * @param side side of part - * @param suppressUpdate - used if you need to replace a part's INSTANCE, without really removing it first. - */ - void removePart( ForgeDirection side, boolean suppressUpdate ); - - /** - * something changed, might want to send a packet to clients to update state. - */ - void markForUpdate(); - - /** - * @return the physical location of the part host in the universe. - */ - DimensionalCoord getLocation(); - - /** - * @return the tile entity for the host, this can either be an FMP tile, or a AE tile - */ - TileEntity getTile(); - - /** - * @return the color of the host type ( this is determined by the middle cable. ) if no cable is present, it returns - * {@link AEColor} .Transparent other wise it returns the color of the cable in the center. - */ - AEColor getColor(); - - /** - * destroys the part container, for internal use. - */ - void clearContainer(); - - /** - * Used to test for FMP microblock blocking internally. - * - * @return returns if microblocks are blocking this cable path. - */ - boolean isBlocked( ForgeDirection side ); - - /** - * finds the part located at the position ( pos must be relative, not global ) - * - * @param pos part position - * @return a new SelectedPart, this is never null. - */ - SelectedPart selectPart( Vec3 pos ); - - /** - * can be used by parts to trigger the tile or part to save. - */ - void markForSave(); - - /** - * part of the {@link LayerBase} - */ - void partChanged(); - - /** - * get the redstone state of host on this side, this value is cached internally. - * - * @param side side of part - * @return true of the part host is receiving redstone from an external source. - */ - boolean hasRedstone( ForgeDirection side ); - - /** - * returns false if this block contains any parts or facades, true other wise. - */ - boolean isEmpty(); - - /** - * @return a mutable list of flags you can adjust to track state. - */ - Set getLayerFlags(); - - /** - * remove host from world... - */ - void cleanup(); - - /** - * notify neighbors uf updated status. - */ - void notifyNeighbors(); - - /** - * true if the tile is in the world, other wise false. - * - * @return true if tile is in world - */ - boolean isInWorld(); -} \ No newline at end of file +public interface IPartHost { + + /** + * @return the facade container + */ + IFacadeContainer getFacadeContainer(); + + /** + * Test if you can add a part to the specified side of the Part Host, {@link ForgeDirection}.UNKNOWN is used to + * represent the cable in the middle. + * + * @param part to be added part + * @param side part placed onto side + * @return returns false if the part cannot be added. + */ + boolean canAddPart(ItemStack part, ForgeDirection side); + + /** + * try to add a new part to the specified side, returns false if it failed to be added. + * + * @param is new part + * @param side onto side + * @param owner with owning player + * @return null if the item failed to add, the side it was placed on other wise ( may different for cables, + * {@link ForgeDirection}.UNKNOWN ) + */ + ForgeDirection addPart(ItemStack is, ForgeDirection side, EntityPlayer owner); + + /** + * Get part by side ( center is {@link ForgeDirection}.UNKNOWN ) + * + * @param side side of part + * @return the part located on the specified side, or null if there is no part. + */ + IPart getPart(ForgeDirection side); + + /** + * removes the part on the side, this doesn't drop it or anything, if you don't do something with it, its just + * "gone" and its never coming back; think about it. + *

+ * if you want to drop the part you must request it prior to removing it. + * + * @param side side of part + * @param suppressUpdate - used if you need to replace a part's INSTANCE, without really removing it first. + */ + void removePart(ForgeDirection side, boolean suppressUpdate); + + /** + * something changed, might want to send a packet to clients to update state. + */ + void markForUpdate(); + + /** + * @return the physical location of the part host in the universe. + */ + DimensionalCoord getLocation(); + + /** + * @return the tile entity for the host, this can either be an FMP tile, or a AE tile + */ + TileEntity getTile(); + + /** + * @return the color of the host type ( this is determined by the middle cable. ) if no cable is present, it returns + * {@link AEColor} .Transparent other wise it returns the color of the cable in the center. + */ + AEColor getColor(); + + /** + * destroys the part container, for internal use. + */ + void clearContainer(); + + /** + * Used to test for FMP microblock blocking internally. + * + * @return returns if microblocks are blocking this cable path. + */ + boolean isBlocked(ForgeDirection side); + + /** + * finds the part located at the position ( pos must be relative, not global ) + * + * @param pos part position + * @return a new SelectedPart, this is never null. + */ + SelectedPart selectPart(Vec3 pos); + + /** + * can be used by parts to trigger the tile or part to save. + */ + void markForSave(); + + /** + * part of the {@link LayerBase} + */ + void partChanged(); + + /** + * get the redstone state of host on this side, this value is cached internally. + * + * @param side side of part + * @return true of the part host is receiving redstone from an external source. + */ + boolean hasRedstone(ForgeDirection side); + + /** + * returns false if this block contains any parts or facades, true other wise. + */ + boolean isEmpty(); + + /** + * @return a mutable list of flags you can adjust to track state. + */ + Set getLayerFlags(); + + /** + * remove host from world... + */ + void cleanup(); + + /** + * notify neighbors uf updated status. + */ + void notifyNeighbors(); + + /** + * true if the tile is in the world, other wise false. + * + * @return true if tile is in world + */ + boolean isInWorld(); +} diff --git a/src/main/java/appeng/api/parts/IPartItem.java b/src/main/java/appeng/api/parts/IPartItem.java index 9458452f683..1273c19a41f 100644 --- a/src/main/java/appeng/api/parts/IPartItem.java +++ b/src/main/java/appeng/api/parts/IPartItem.java @@ -23,13 +23,10 @@ package appeng.api.parts; - -import net.minecraft.item.ItemStack; - import javax.annotation.Nullable; +import net.minecraft.item.ItemStack; -//@formatter:off - +// @formatter:off /** * This is a pretty basic requirement, once you implement the interface, and createPartFromItemStack @@ -55,15 +52,14 @@ * * */ -public interface IPartItem -{ +public interface IPartItem { - /** - * create a new part INSTANCE, from the item stack. - * - * @param is item - * @return part from item - */ - @Nullable - IPart createPartFromItemStack( ItemStack is ); + /** + * create a new part INSTANCE, from the item stack. + * + * @param is item + * @return part from item + */ + @Nullable + IPart createPartFromItemStack(ItemStack is); } diff --git a/src/main/java/appeng/api/parts/IPartRenderHelper.java b/src/main/java/appeng/api/parts/IPartRenderHelper.java index 339b5f49ba4..ca59bf6ff35 100644 --- a/src/main/java/appeng/api/parts/IPartRenderHelper.java +++ b/src/main/java/appeng/api/parts/IPartRenderHelper.java @@ -23,181 +23,178 @@ package appeng.api.parts; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public interface IPartRenderHelper -{ - - /** - * sets the Render Helpers Block Bounds. 0.0 - 16.0 block coords. - *

- * No complaints about the size, I like using pixels :P - * - * @param minX minimal x bound - * @param minY minimal y bound - * @param minZ minimal z bound - * @param maxX maximal x bound - * @param maxY maximal y bound - * @param maxZ maximal z bound - */ - void setBounds( float minX, float minY, float minZ, float maxX, float maxY, float maxZ ); - - /** - * static renderer - *

- * render a single face. - * - * @param x x coord of part - * @param y y coord of part - * @param z z coord of part - * @param ico icon of part - * @param face direction its facing - * @param renderer renderer of part - */ - @SideOnly( Side.CLIENT ) - void renderFace( int x, int y, int z, IIcon ico, ForgeDirection face, RenderBlocks renderer ); - - /** - * static renderer - *

- * render a box with a cut out box in the center. - * - * @param x x pos of part - * @param y y pos of part - * @param z z pos of part - * @param ico icon of part - * @param face face of part - * @param edgeThickness thickness of the edge - * @param renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderFaceCutout( int x, int y, int z, IIcon ico, ForgeDirection face, float edgeThickness, RenderBlocks renderer ); - - /** - * static renderer - *

- * render a block of specified bounds. - * - * @param x x pos of block - * @param y y pos of block - * @param z z pos of block - * @param renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderBlock( int x, int y, int z, RenderBlocks renderer ); - - /** - * render a single face in inventory renderer. - * - * @param IIcon icon of part - * @param direction face of part - * @param renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderInventoryFace( IIcon IIcon, ForgeDirection direction, RenderBlocks renderer ); - - /** - * render a box in inventory renderer. - * - * @param renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderInventoryBox( RenderBlocks renderer ); - - /** - * inventory, and static renderer. - *

- * set unique icons for each side of the block. - * - * @param down down face - * @param up up face - * @param north north face - * @param south south face - * @param west west face - * @param east east face - */ - void setTexture( IIcon down, IIcon up, IIcon north, IIcon south, IIcon west, IIcon east ); - - /** - * inventory, and static renderer. - *

- * set all sides to a single IIcon. - * - * @param ico to be set icon - */ - void setTexture( IIcon ico ); - - /** - * configure the color multiplier for the inventory renderer. - * - * @param whiteVariant color multiplier - */ - void setInvColor( int whiteVariant ); - - /** - * @return the block used for rendering, might need it for some reason... - */ - Block getBlock(); - - /** - * @return the east vector in world directions, rather then renderer - */ - ForgeDirection getWorldX(); - - /** - * @return the up vector in world directions, rather then renderer. - */ - ForgeDirection getWorldY(); - - /** - * @return the forward vector in world directions, rather then renderer. - */ - ForgeDirection getWorldZ(); - - /** - * Pre-Calculates default lighting for the part, call this before using the render helper to render anything else to - * get simplified, but faster lighting for more then one block. - *

- * Only worth it if you render more then 1 block. - */ - ISimplifiedBundle useSimplifiedRendering( int x, int y, int z, IBoxProvider p, ISimplifiedBundle sim ); - - /** - * disables, useSimplifiedRendering. - */ - void normalRendering(); - - /** - * render a block using the current renderer state. - * - * @param x x pos of part - * @param y y pos of part - * @param z z pos of part - * @param renderer renderer of part - */ - @SideOnly( Side.CLIENT ) - void renderBlockCurrentBounds( int x, int y, int z, RenderBlocks renderer ); - - /** - * allow you to enable your part to render during the alpha pass or the standard pass. - * - * @param pass render pass - */ - void renderForPass( int pass ); - - /** - * Set which faces to render, remember to set back to ALL when you are done. - * - * @param complementOf sides to render - */ - void setFacesToRender( EnumSet complementOf ); -} \ No newline at end of file +public interface IPartRenderHelper { + + /** + * sets the Render Helpers Block Bounds. 0.0 - 16.0 block coords. + *

+ * No complaints about the size, I like using pixels :P + * + * @param minX minimal x bound + * @param minY minimal y bound + * @param minZ minimal z bound + * @param maxX maximal x bound + * @param maxY maximal y bound + * @param maxZ maximal z bound + */ + void setBounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ); + + /** + * static renderer + *

+ * render a single face. + * + * @param x x coord of part + * @param y y coord of part + * @param z z coord of part + * @param ico icon of part + * @param face direction its facing + * @param renderer renderer of part + */ + @SideOnly(Side.CLIENT) + void renderFace(int x, int y, int z, IIcon ico, ForgeDirection face, RenderBlocks renderer); + + /** + * static renderer + *

+ * render a box with a cut out box in the center. + * + * @param x x pos of part + * @param y y pos of part + * @param z z pos of part + * @param ico icon of part + * @param face face of part + * @param edgeThickness thickness of the edge + * @param renderer renderer + */ + @SideOnly(Side.CLIENT) + void renderFaceCutout( + int x, int y, int z, IIcon ico, ForgeDirection face, float edgeThickness, RenderBlocks renderer); + + /** + * static renderer + *

+ * render a block of specified bounds. + * + * @param x x pos of block + * @param y y pos of block + * @param z z pos of block + * @param renderer renderer + */ + @SideOnly(Side.CLIENT) + void renderBlock(int x, int y, int z, RenderBlocks renderer); + + /** + * render a single face in inventory renderer. + * + * @param IIcon icon of part + * @param direction face of part + * @param renderer renderer + */ + @SideOnly(Side.CLIENT) + void renderInventoryFace(IIcon IIcon, ForgeDirection direction, RenderBlocks renderer); + + /** + * render a box in inventory renderer. + * + * @param renderer renderer + */ + @SideOnly(Side.CLIENT) + void renderInventoryBox(RenderBlocks renderer); + + /** + * inventory, and static renderer. + *

+ * set unique icons for each side of the block. + * + * @param down down face + * @param up up face + * @param north north face + * @param south south face + * @param west west face + * @param east east face + */ + void setTexture(IIcon down, IIcon up, IIcon north, IIcon south, IIcon west, IIcon east); + + /** + * inventory, and static renderer. + *

+ * set all sides to a single IIcon. + * + * @param ico to be set icon + */ + void setTexture(IIcon ico); + + /** + * configure the color multiplier for the inventory renderer. + * + * @param whiteVariant color multiplier + */ + void setInvColor(int whiteVariant); + + /** + * @return the block used for rendering, might need it for some reason... + */ + Block getBlock(); + + /** + * @return the east vector in world directions, rather then renderer + */ + ForgeDirection getWorldX(); + + /** + * @return the up vector in world directions, rather then renderer. + */ + ForgeDirection getWorldY(); + + /** + * @return the forward vector in world directions, rather then renderer. + */ + ForgeDirection getWorldZ(); + + /** + * Pre-Calculates default lighting for the part, call this before using the render helper to render anything else to + * get simplified, but faster lighting for more then one block. + *

+ * Only worth it if you render more then 1 block. + */ + ISimplifiedBundle useSimplifiedRendering(int x, int y, int z, IBoxProvider p, ISimplifiedBundle sim); + + /** + * disables, useSimplifiedRendering. + */ + void normalRendering(); + + /** + * render a block using the current renderer state. + * + * @param x x pos of part + * @param y y pos of part + * @param z z pos of part + * @param renderer renderer of part + */ + @SideOnly(Side.CLIENT) + void renderBlockCurrentBounds(int x, int y, int z, RenderBlocks renderer); + + /** + * allow you to enable your part to render during the alpha pass or the standard pass. + * + * @param pass render pass + */ + void renderForPass(int pass); + + /** + * Set which faces to render, remember to set back to ALL when you are done. + * + * @param complementOf sides to render + */ + void setFacesToRender(EnumSet complementOf); +} diff --git a/src/main/java/appeng/api/parts/ISimplifiedBundle.java b/src/main/java/appeng/api/parts/ISimplifiedBundle.java index ad16791f942..baad8781ef4 100644 --- a/src/main/java/appeng/api/parts/ISimplifiedBundle.java +++ b/src/main/java/appeng/api/parts/ISimplifiedBundle.java @@ -23,8 +23,4 @@ package appeng.api.parts; - -public interface ISimplifiedBundle -{ - -} +public interface ISimplifiedBundle {} diff --git a/src/main/java/appeng/api/parts/LayerBase.java b/src/main/java/appeng/api/parts/LayerBase.java index 9a7bed93197..01358ada1c4 100644 --- a/src/main/java/appeng/api/parts/LayerBase.java +++ b/src/main/java/appeng/api/parts/LayerBase.java @@ -23,13 +23,10 @@ package appeng.api.parts; - +import java.util.Set; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Set; - - /** * All Layers must extends this, this get part implementation is provided to interface with the parts, however a real * implementation will be used at runtime. @@ -37,43 +34,36 @@ public abstract class LayerBase extends TileEntity // implements IPartHost { - /** - * Grants access for the layer to the parts of the host. - *

- * This Method looks silly, that is because its not used at runtime, a real implementation will be used instead. - * - * @param side side of part - * @return the part for the requested side. - */ - public IPart getPart( final ForgeDirection side ) - { - return null; // place holder. - } + /** + * Grants access for the layer to the parts of the host. + *

+ * This Method looks silly, that is because its not used at runtime, a real implementation will be used instead. + * + * @param side side of part + * @return the part for the requested side. + */ + public IPart getPart(final ForgeDirection side) { + return null; // place holder. + } - /** - * called when the parts change in the container, YOU MUST CALL super.PartChanged(); - */ - public void notifyNeighbors() - { - } + /** + * called when the parts change in the container, YOU MUST CALL super.PartChanged(); + */ + public void notifyNeighbors() {} - /** - * called when the parts change in the container, YOU MUST CALL super.PartChanged(); - */ - public void partChanged() - { - } + /** + * called when the parts change in the container, YOU MUST CALL super.PartChanged(); + */ + public void partChanged() {} - /** - * @return a mutable list of flags you can adjust to track state. - */ - public Set getLayerFlags() - { - return null; // place holder. - } + /** + * @return a mutable list of flags you can adjust to track state. + */ + public Set getLayerFlags() { + return null; // place holder. + } - public void markForSave() - { - // something! - } + public void markForSave() { + // something! + } } diff --git a/src/main/java/appeng/api/parts/LayerFlags.java b/src/main/java/appeng/api/parts/LayerFlags.java index af04459bdac..98b237d3ede 100644 --- a/src/main/java/appeng/api/parts/LayerFlags.java +++ b/src/main/java/appeng/api/parts/LayerFlags.java @@ -23,10 +23,6 @@ package appeng.api.parts; - -public enum LayerFlags -{ - - IC2_ENET - +public enum LayerFlags { + IC2_ENET } diff --git a/src/main/java/appeng/api/parts/PartItemStack.java b/src/main/java/appeng/api/parts/PartItemStack.java index 795dd49175f..07be0d13197 100644 --- a/src/main/java/appeng/api/parts/PartItemStack.java +++ b/src/main/java/appeng/api/parts/PartItemStack.java @@ -23,16 +23,14 @@ package appeng.api.parts; +public enum PartItemStack { + Pick, -public enum PartItemStack -{ - Pick, + Break, - Break, + Wrench, - Wrench, + Network, - Network, - - World + World } diff --git a/src/main/java/appeng/api/parts/SelectedPart.java b/src/main/java/appeng/api/parts/SelectedPart.java index bc308db33f3..7c5e588937e 100644 --- a/src/main/java/appeng/api/parts/SelectedPart.java +++ b/src/main/java/appeng/api/parts/SelectedPart.java @@ -23,49 +23,43 @@ package appeng.api.parts; - import net.minecraftforge.common.util.ForgeDirection; - /** * Reports a selected part from th IPartHost */ -public class SelectedPart -{ +public class SelectedPart { - /** - * selected part. - */ - public final IPart part; + /** + * selected part. + */ + public final IPart part; - /** - * facade part. - */ - public final IFacadePart facade; + /** + * facade part. + */ + public final IFacadePart facade; - /** - * side the part is mounted too, or {@link ForgeDirection}.UNKNOWN for cables. - */ - public final ForgeDirection side; + /** + * side the part is mounted too, or {@link ForgeDirection}.UNKNOWN for cables. + */ + public final ForgeDirection side; - public SelectedPart() - { - this.part = null; - this.facade = null; - this.side = ForgeDirection.UNKNOWN; - } + public SelectedPart() { + this.part = null; + this.facade = null; + this.side = ForgeDirection.UNKNOWN; + } - public SelectedPart( final IPart part, final ForgeDirection side ) - { - this.part = part; - this.facade = null; - this.side = side; - } + public SelectedPart(final IPart part, final ForgeDirection side) { + this.part = part; + this.facade = null; + this.side = side; + } - public SelectedPart( final IFacadePart facade, final ForgeDirection side ) - { - this.part = null; - this.facade = facade; - this.side = side; - } + public SelectedPart(final IFacadePart facade, final ForgeDirection side) { + this.part = null; + this.facade = facade; + this.side = side; + } } diff --git a/src/main/java/appeng/api/recipes/ICraftHandler.java b/src/main/java/appeng/api/recipes/ICraftHandler.java index 19ca1ff99c3..839c53bfe6f 100644 --- a/src/main/java/appeng/api/recipes/ICraftHandler.java +++ b/src/main/java/appeng/api/recipes/ICraftHandler.java @@ -23,31 +23,27 @@ package appeng.api.recipes; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; - import java.util.List; - -public interface ICraftHandler -{ - - /** - * Called when your recipe handler receives a newly parsed list of inputs/outputs. - * - * @param input parsed inputs - * @param output parsed outputs - * @throws RecipeError - */ - void setup( List> input, List> output ) throws RecipeError; - - /** - * called when all recipes are parsed, and your required to register your recipe. - * - * @throws RegistrationError - * @throws MissingIngredientError - */ - void register() throws RegistrationError, MissingIngredientError; +public interface ICraftHandler { + + /** + * Called when your recipe handler receives a newly parsed list of inputs/outputs. + * + * @param input parsed inputs + * @param output parsed outputs + * @throws RecipeError + */ + void setup(List> input, List> output) throws RecipeError; + + /** + * called when all recipes are parsed, and your required to register your recipe. + * + * @throws RegistrationError + * @throws MissingIngredientError + */ + void register() throws RegistrationError, MissingIngredientError; } diff --git a/src/main/java/appeng/api/recipes/IIngredient.java b/src/main/java/appeng/api/recipes/IIngredient.java index 7117a221bd6..b9fb060f34c 100644 --- a/src/main/java/appeng/api/recipes/IIngredient.java +++ b/src/main/java/appeng/api/recipes/IIngredient.java @@ -23,67 +23,64 @@ package appeng.api.recipes; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; import net.minecraft.item.ItemStack; +public interface IIngredient { -public interface IIngredient -{ - - /** - * Acquire a single input stack for the current recipe, if more then one ItemStack is possible a - * RegistrationError exception will be thrown, ignore these and let the system handle the error. - * - * @return a single ItemStack for the recipe handler. - * @throws RegistrationError - * @throws MissingIngredientError - */ - ItemStack getItemStack() throws RegistrationError, MissingIngredientError; + /** + * Acquire a single input stack for the current recipe, if more then one ItemStack is possible a + * RegistrationError exception will be thrown, ignore these and let the system handle the error. + * + * @return a single ItemStack for the recipe handler. + * @throws RegistrationError + * @throws MissingIngredientError + */ + ItemStack getItemStack() throws RegistrationError, MissingIngredientError; - /** - * Acquire a list of all the input stacks for the current recipe, this is for handlers that support - * multiple inputs per slot. - * - * @return an array of ItemStacks for the recipe handler. - * @throws RegistrationError - * @throws MissingIngredientError - */ - ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError; + /** + * Acquire a list of all the input stacks for the current recipe, this is for handlers that support + * multiple inputs per slot. + * + * @return an array of ItemStacks for the recipe handler. + * @throws RegistrationError + * @throws MissingIngredientError + */ + ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError; - /** - * If you wish to support air, you must test before getting the ItemStack, or ItemStackSet - * - * @return true if this slot contains no ItemStack, this is passed as "_" - */ - boolean isAir(); + /** + * If you wish to support air, you must test before getting the ItemStack, or ItemStackSet + * + * @return true if this slot contains no ItemStack, this is passed as "_" + */ + boolean isAir(); - /** - * @return The Name Space of the item. Prefer getItemStack or getItemStackSet - */ - String getNameSpace(); + /** + * @return The Name Space of the item. Prefer getItemStack or getItemStackSet + */ + String getNameSpace(); - /** - * @return The Name of the item. Prefer getItemStack or getItemStackSet - */ - String getItemName(); + /** + * @return The Name of the item. Prefer getItemStack or getItemStackSet + */ + String getItemName(); - /** - * @return The Damage Value of the item. Prefer getItemStack or getItemStackSet - */ - int getDamageValue(); + /** + * @return The Damage Value of the item. Prefer getItemStack or getItemStackSet + */ + int getDamageValue(); - /** - * @return The Damage Value of the item. Prefer getItemStack or getItemStackSet - */ - int getQty(); + /** + * @return The Damage Value of the item. Prefer getItemStack or getItemStackSet + */ + int getQty(); - /** - * Bakes the lists in for faster runtime look-ups. - * - * @throws MissingIngredientError - * @throws RegistrationError - */ - void bake() throws RegistrationError, MissingIngredientError; + /** + * Bakes the lists in for faster runtime look-ups. + * + * @throws MissingIngredientError + * @throws RegistrationError + */ + void bake() throws RegistrationError, MissingIngredientError; } diff --git a/src/main/java/appeng/api/recipes/IRecipeHandler.java b/src/main/java/appeng/api/recipes/IRecipeHandler.java index 5c7b32e06e1..1cb7fd40a6d 100644 --- a/src/main/java/appeng/api/recipes/IRecipeHandler.java +++ b/src/main/java/appeng/api/recipes/IRecipeHandler.java @@ -23,23 +23,21 @@ package appeng.api.recipes; - /** * Represents the AE2 Recipe Loading/Reading Class */ -public interface IRecipeHandler -{ +public interface IRecipeHandler { - /** - * Call when you want to read recipes in from a file based on a loader - * - * @param loader recipe loader - * @param path path of file - */ - void parseRecipes( IRecipeLoader loader, String path ); + /** + * Call when you want to read recipes in from a file based on a loader + * + * @param loader recipe loader + * @param path path of file + */ + void parseRecipes(IRecipeLoader loader, String path); - /** - * this loads the read recipes into minecraft, should be called in Init. - */ - void injectRecipes(); + /** + * this loads the read recipes into minecraft, should be called in Init. + */ + void injectRecipes(); } diff --git a/src/main/java/appeng/api/recipes/IRecipeLoader.java b/src/main/java/appeng/api/recipes/IRecipeLoader.java index fe1e485c993..bb69f245667 100644 --- a/src/main/java/appeng/api/recipes/IRecipeLoader.java +++ b/src/main/java/appeng/api/recipes/IRecipeLoader.java @@ -23,17 +23,14 @@ package appeng.api.recipes; - -import javax.annotation.Nonnull; import java.io.BufferedReader; +import javax.annotation.Nonnull; - -public interface IRecipeLoader -{ - /** - * @param filePath the path to the to be loaded file - * @return reader handler of the file - * @throws Exception if reading goes wrong - */ - BufferedReader getFile( @Nonnull String filePath ) throws Exception; +public interface IRecipeLoader { + /** + * @param filePath the path to the to be loaded file + * @return reader handler of the file + * @throws Exception if reading goes wrong + */ + BufferedReader getFile(@Nonnull String filePath) throws Exception; } diff --git a/src/main/java/appeng/api/recipes/ISubItemResolver.java b/src/main/java/appeng/api/recipes/ISubItemResolver.java index 3ef2bd09d4d..3c311b0a407 100644 --- a/src/main/java/appeng/api/recipes/ISubItemResolver.java +++ b/src/main/java/appeng/api/recipes/ISubItemResolver.java @@ -23,13 +23,11 @@ package appeng.api.recipes; - -public interface ISubItemResolver -{ - /** - * @param namespace namespace of sub item - * @param fullName name of sub item - * @return either a ResolveResult, or a ResolverResultSet - */ - Object resolveItemByName( String namespace, String fullName ); +public interface ISubItemResolver { + /** + * @param namespace namespace of sub item + * @param fullName name of sub item + * @return either a ResolveResult, or a ResolverResultSet + */ + Object resolveItemByName(String namespace, String fullName); } diff --git a/src/main/java/appeng/api/recipes/ResolverResult.java b/src/main/java/appeng/api/recipes/ResolverResult.java index 51405576946..eb293a53f78 100644 --- a/src/main/java/appeng/api/recipes/ResolverResult.java +++ b/src/main/java/appeng/api/recipes/ResolverResult.java @@ -23,28 +23,23 @@ package appeng.api.recipes; - import net.minecraft.nbt.NBTTagCompound; +public class ResolverResult { -public class ResolverResult -{ - - public final String itemName; - public final int damageValue; - public final NBTTagCompound compound; + public final String itemName; + public final int damageValue; + public final NBTTagCompound compound; - public ResolverResult( final String name, final int damage ) - { - this.itemName = name; - this.damageValue = damage; - this.compound = null; - } + public ResolverResult(final String name, final int damage) { + this.itemName = name; + this.damageValue = damage; + this.compound = null; + } - public ResolverResult( final String name, final int damage, final NBTTagCompound data ) - { - this.itemName = name; - this.damageValue = damage; - this.compound = data; - } + public ResolverResult(final String name, final int damage, final NBTTagCompound data) { + this.itemName = name; + this.damageValue = damage; + this.compound = data; + } } diff --git a/src/main/java/appeng/api/recipes/ResolverResultSet.java b/src/main/java/appeng/api/recipes/ResolverResultSet.java index 0531ba6141d..ee81f2e16c0 100644 --- a/src/main/java/appeng/api/recipes/ResolverResultSet.java +++ b/src/main/java/appeng/api/recipes/ResolverResultSet.java @@ -23,22 +23,17 @@ package appeng.api.recipes; - -import net.minecraft.item.ItemStack; - import java.util.Arrays; import java.util.List; +import net.minecraft.item.ItemStack; +public class ResolverResultSet { -public class ResolverResultSet -{ - - public final String name; - public final List results; + public final String name; + public final List results; - public ResolverResultSet( final String myName, final ItemStack... set ) - { - this.results = Arrays.asList( set ); - this.name = myName; - } + public ResolverResultSet(final String myName, final ItemStack... set) { + this.results = Arrays.asList(set); + this.name = myName; + } } diff --git a/src/main/java/appeng/api/storage/ICellContainer.java b/src/main/java/appeng/api/storage/ICellContainer.java index 4445dd3e464..1916a317281 100644 --- a/src/main/java/appeng/api/storage/ICellContainer.java +++ b/src/main/java/appeng/api/storage/ICellContainer.java @@ -23,20 +23,17 @@ package appeng.api.storage; - import appeng.api.networking.security.IActionHost; - /** * Represents an {@link appeng.api.networking.IGridHost} that contributes to storage, such as a ME Chest, or ME Drive. */ -public interface ICellContainer extends IActionHost, ICellProvider, ISaveProvider -{ +public interface ICellContainer extends IActionHost, ICellProvider, ISaveProvider { - /** - * tell the Cell container that this slot should blink, the slot number is relative to the - * - * @param slot slot index - */ - void blinkCell( int slot ); + /** + * tell the Cell container that this slot should blink, the slot number is relative to the + * + * @param slot slot index + */ + void blinkCell(int slot); } diff --git a/src/main/java/appeng/api/storage/ICellHandler.java b/src/main/java/appeng/api/storage/ICellHandler.java index 005659ed517..a7762c25e7a 100644 --- a/src/main/java/appeng/api/storage/ICellHandler.java +++ b/src/main/java/appeng/api/storage/ICellHandler.java @@ -23,7 +23,6 @@ package appeng.api.storage; - import appeng.api.implementations.tiles.IChestOrDrive; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -31,88 +30,92 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; - /** * Registration record for {@link ICellRegistry} */ -public interface ICellHandler -{ +public interface ICellHandler { - /** - * return true if the provided item is handled by your cell handler. ( AE May choose to skip this method, and just - * request a handler ) - * - * @param is to be checked item - * @return return true, if getCellHandler will not return null. - */ - boolean isCell( ItemStack is ); + /** + * return true if the provided item is handled by your cell handler. ( AE May choose to skip this method, and just + * request a handler ) + * + * @param is to be checked item + * @return return true, if getCellHandler will not return null. + */ + boolean isCell(ItemStack is); - /** - * If you cannot handle the provided item, return null - * - * @param is a storage cell item. - * @param host anytime the contents of your storage cell changes it should use this to request a save, please - * note, this value can be null. - * @param channel the storage channel requested. - * @return a new IMEHandler for the provided item - */ - IMEInventoryHandler getCellInventory( ItemStack is, ISaveProvider host, StorageChannel channel ); + /** + * If you cannot handle the provided item, return null + * + * @param is a storage cell item. + * @param host anytime the contents of your storage cell changes it should use this to request a save, please + * note, this value can be null. + * @param channel the storage channel requested. + * @return a new IMEHandler for the provided item + */ + IMEInventoryHandler getCellInventory(ItemStack is, ISaveProvider host, StorageChannel channel); - /** - * @return the ME Chest texture for light pixels this storage cell type, should be 10x10 with 3px of transparent - * padding on a 16x16 texture, null is valid if your cell cannot be used in the ME Chest. refer to the - * assets for examples. - */ - @SideOnly( Side.CLIENT ) - IIcon getTopTexture_Light(); + /** + * @return the ME Chest texture for light pixels this storage cell type, should be 10x10 with 3px of transparent + * padding on a 16x16 texture, null is valid if your cell cannot be used in the ME Chest. refer to the + * assets for examples. + */ + @SideOnly(Side.CLIENT) + IIcon getTopTexture_Light(); - /** - * @return the ME Chest texture for medium pixels this storage cell type, should be 10x10 with 3px of transparent - * padding on a 16x16 texture, null is valid if your cell cannot be used in the ME Chest. refer to the - * assets for examples. - */ - @SideOnly( Side.CLIENT ) - IIcon getTopTexture_Medium(); + /** + * @return the ME Chest texture for medium pixels this storage cell type, should be 10x10 with 3px of transparent + * padding on a 16x16 texture, null is valid if your cell cannot be used in the ME Chest. refer to the + * assets for examples. + */ + @SideOnly(Side.CLIENT) + IIcon getTopTexture_Medium(); - /** - * @return the ME Chest texture for dark pixels this storage cell type, should be 10x10 with 3px of transparent - * padding on a 16x16 texture, null is valid if your cell cannot be used in the ME Chest. refer to the - * assets for examples. - */ - @SideOnly( Side.CLIENT ) - IIcon getTopTexture_Dark(); + /** + * @return the ME Chest texture for dark pixels this storage cell type, should be 10x10 with 3px of transparent + * padding on a 16x16 texture, null is valid if your cell cannot be used in the ME Chest. refer to the + * assets for examples. + */ + @SideOnly(Side.CLIENT) + IIcon getTopTexture_Dark(); - /** - * Called when the storage cell is planed in an ME Chest and the user tries to open the terminal side, if your item - * is not available via ME Chests simply tell the user they can't use it, or something, other wise you should open - * your gui and display the cell to the user. - * - * @param player player opening chest gui - * @param chest to be opened chest - * @param cellHandler cell handler - * @param inv inventory handler - * @param is item - * @param chan storage channel - */ - void openChestGui( EntityPlayer player, IChestOrDrive chest, ICellHandler cellHandler, IMEInventoryHandler inv, ItemStack is, StorageChannel chan ); + /** + * Called when the storage cell is planed in an ME Chest and the user tries to open the terminal side, if your item + * is not available via ME Chests simply tell the user they can't use it, or something, other wise you should open + * your gui and display the cell to the user. + * + * @param player player opening chest gui + * @param chest to be opened chest + * @param cellHandler cell handler + * @param inv inventory handler + * @param is item + * @param chan storage channel + */ + void openChestGui( + EntityPlayer player, + IChestOrDrive chest, + ICellHandler cellHandler, + IMEInventoryHandler inv, + ItemStack is, + StorageChannel chan); - /** - * 0 - cell is missing. - *

- * 1 - green, ( usually means available room for types or items. ) - *

- * 2 - orange, ( usually means available room for items, but not types. ) - *

- * 3 - red, ( usually means the cell is 100% full ) - * - * @param is the cell item. ( use the handler for any details you can ) - * @param handler the handler for the cell is provides for reference, you can cast this to your handler. - * @return get the status of the cell based on its contents. - */ - int getStatusForCell( ItemStack is, IMEInventory handler ); + /** + * 0 - cell is missing. + *

+ * 1 - green, ( usually means available room for types or items. ) + *

+ * 2 - orange, ( usually means available room for items, but not types. ) + *

+ * 3 - red, ( usually means the cell is 100% full ) + * + * @param is the cell item. ( use the handler for any details you can ) + * @param handler the handler for the cell is provides for reference, you can cast this to your handler. + * @return get the status of the cell based on its contents. + */ + int getStatusForCell(ItemStack is, IMEInventory handler); - /** - * @return the ae/t to drain for this storage cell inside a chest/drive. - */ - double cellIdleDrain( ItemStack is, IMEInventory handler ); -} \ No newline at end of file + /** + * @return the ae/t to drain for this storage cell inside a chest/drive. + */ + double cellIdleDrain(ItemStack is, IMEInventory handler); +} diff --git a/src/main/java/appeng/api/storage/ICellInventory.java b/src/main/java/appeng/api/storage/ICellInventory.java index def584de8e1..ccf8add9bc8 100644 --- a/src/main/java/appeng/api/storage/ICellInventory.java +++ b/src/main/java/appeng/api/storage/ICellInventory.java @@ -23,100 +23,97 @@ package appeng.api.storage; - import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEItemStack; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - -public interface ICellInventory extends IMEInventory -{ - - /** - * @return the item stack of this storage cell. - */ - ItemStack getItemStack(); - - /** - * @return idle cost for this Storage Cell - */ - double getIdleDrain(); - - /** - * @return fuzzy setting - */ - FuzzyMode getFuzzyMode(); - - /** - * @return access configured list - */ - IInventory getConfigInventory(); - - /** - * @return access installed upgrades. - */ - IInventory getUpgradesInventory(); - - /** - * @return How many bytes are used for each type? - */ - int getBytesPerType(); - - /** - * @return true if a new item type can be added. - */ - boolean canHoldNewItem(); - - /** - * @return total byte storage. - */ - long getTotalBytes(); - - /** - * @return how many bytes are free. - */ - long getFreeBytes(); - - /** - * @return how many bytes are in use. - */ - long getUsedBytes(); - - /** - * @return max number of types. - */ - long getTotalItemTypes(); - - /** - * @return how many items are stored. - */ - long getStoredItemCount(); - - /** - * @return how many items types are currently stored. - */ - long getStoredItemTypes(); - - /** - * @return how many item types remain. - */ - long getRemainingItemTypes(); - - /** - * @return how many more items can be stored. - */ - long getRemainingItemCount(); - - /** - * @return how many items can be added without consuming another byte. - */ - int getUnusedItemCount(); - - /** - * @return the status number for this drive. - */ - int getStatusForCell(); - - String getOreFilter(); +public interface ICellInventory extends IMEInventory { + + /** + * @return the item stack of this storage cell. + */ + ItemStack getItemStack(); + + /** + * @return idle cost for this Storage Cell + */ + double getIdleDrain(); + + /** + * @return fuzzy setting + */ + FuzzyMode getFuzzyMode(); + + /** + * @return access configured list + */ + IInventory getConfigInventory(); + + /** + * @return access installed upgrades. + */ + IInventory getUpgradesInventory(); + + /** + * @return How many bytes are used for each type? + */ + int getBytesPerType(); + + /** + * @return true if a new item type can be added. + */ + boolean canHoldNewItem(); + + /** + * @return total byte storage. + */ + long getTotalBytes(); + + /** + * @return how many bytes are free. + */ + long getFreeBytes(); + + /** + * @return how many bytes are in use. + */ + long getUsedBytes(); + + /** + * @return max number of types. + */ + long getTotalItemTypes(); + + /** + * @return how many items are stored. + */ + long getStoredItemCount(); + + /** + * @return how many items types are currently stored. + */ + long getStoredItemTypes(); + + /** + * @return how many item types remain. + */ + long getRemainingItemTypes(); + + /** + * @return how many more items can be stored. + */ + long getRemainingItemCount(); + + /** + * @return how many items can be added without consuming another byte. + */ + int getUnusedItemCount(); + + /** + * @return the status number for this drive. + */ + int getStatusForCell(); + + String getOreFilter(); } diff --git a/src/main/java/appeng/api/storage/ICellInventoryHandler.java b/src/main/java/appeng/api/storage/ICellInventoryHandler.java index 3f1e77ad904..016a745eac7 100644 --- a/src/main/java/appeng/api/storage/ICellInventoryHandler.java +++ b/src/main/java/appeng/api/storage/ICellInventoryHandler.java @@ -23,22 +23,19 @@ package appeng.api.storage; - import appeng.api.config.IncludeExclude; import appeng.api.storage.data.IAEItemStack; +public interface ICellInventoryHandler extends IMEInventoryHandler { -public interface ICellInventoryHandler extends IMEInventoryHandler -{ - - /** - * @return get access to the Cell Inventory. - */ - ICellInventory getCellInv(); + /** + * @return get access to the Cell Inventory. + */ + ICellInventory getCellInv(); - boolean isPreformatted(); + boolean isPreformatted(); - boolean isFuzzy(); + boolean isFuzzy(); - IncludeExclude getIncludeExcludeMode(); + IncludeExclude getIncludeExcludeMode(); } diff --git a/src/main/java/appeng/api/storage/ICellProvider.java b/src/main/java/appeng/api/storage/ICellProvider.java index 589ca335c31..3e7807b7381 100644 --- a/src/main/java/appeng/api/storage/ICellProvider.java +++ b/src/main/java/appeng/api/storage/ICellProvider.java @@ -23,31 +23,28 @@ package appeng.api.storage; - import java.util.List; - /** * Allows you to provide cells via non IGridHosts directly to the storage system, drives, and similar features should go * though {@link ICellContainer} and be automatically handled by the storage system. */ -public interface ICellProvider -{ +public interface ICellProvider { - /** - * Inventory of the tile for use with ME, should always return an valid list, never NULL. - *

- * You must return the correct Handler for the correct channel, if your handler returns a IAEItemStack handler, for - * a Fluid Channel stuffs going to explode, same with the reverse. - * - * @return a valid list of handlers, NEVER NULL - */ - List getCellArray( StorageChannel channel ); + /** + * Inventory of the tile for use with ME, should always return an valid list, never NULL. + *

+ * You must return the correct Handler for the correct channel, if your handler returns a IAEItemStack handler, for + * a Fluid Channel stuffs going to explode, same with the reverse. + * + * @return a valid list of handlers, NEVER NULL + */ + List getCellArray(StorageChannel channel); - /** - * the storage's priority. - *

- * Positive and negative are supported - */ - int getPriority(); + /** + * the storage's priority. + *

+ * Positive and negative are supported + */ + int getPriority(); } diff --git a/src/main/java/appeng/api/storage/ICellRegistry.java b/src/main/java/appeng/api/storage/ICellRegistry.java index c2000bd024f..928c6fb8288 100644 --- a/src/main/java/appeng/api/storage/ICellRegistry.java +++ b/src/main/java/appeng/api/storage/ICellRegistry.java @@ -23,51 +23,48 @@ package appeng.api.storage; - import appeng.api.IAppEngApi; import net.minecraft.item.ItemStack; - /** * Storage Cell Registry, used for specially implemented cells, if you just want to make a item act like a cell, or new * cell with different bytes, then you should probably consider IStorageCell instead its considerably simpler. *

* Do not Implement, obtained via {@link IAppEngApi}.getCellRegistry() */ -public interface ICellRegistry -{ +public interface ICellRegistry { - /** - * Register a new handler. - * - * @param handler cell handler - */ - void addCellHandler( ICellHandler handler ); + /** + * Register a new handler. + * + * @param handler cell handler + */ + void addCellHandler(ICellHandler handler); - /** - * return true, if you can get a InventoryHandler for the item passed. - * - * @param is to be checked item - * @return true if the provided item, can be handled by a handler in AE, ( AE May choose to skip this and just get - * the handler instead. ) - */ - boolean isCellHandled( ItemStack is ); + /** + * return true, if you can get a InventoryHandler for the item passed. + * + * @param is to be checked item + * @return true if the provided item, can be handled by a handler in AE, ( AE May choose to skip this and just get + * the handler instead. ) + */ + boolean isCellHandled(ItemStack is); - /** - * get the handler, for the requested type. - * - * @param is to be checked item - * @return the handler registered for this item type. - */ - ICellHandler getHandler( ItemStack is ); + /** + * get the handler, for the requested type. + * + * @param is to be checked item + * @return the handler registered for this item type. + */ + ICellHandler getHandler(ItemStack is); - /** - * returns an IMEInventoryHandler for the provided item. - * - * @param is item with inventory handler - * @param host can be null, or the hosting tile / part. - * @param chan the storage channel to request the handler for. - * @return new IMEInventoryHandler, or null if there isn't one. - */ - IMEInventoryHandler getCellInventory( ItemStack is, ISaveProvider host, StorageChannel chan ); -} \ No newline at end of file + /** + * returns an IMEInventoryHandler for the provided item. + * + * @param is item with inventory handler + * @param host can be null, or the hosting tile / part. + * @param chan the storage channel to request the handler for. + * @return new IMEInventoryHandler, or null if there isn't one. + */ + IMEInventoryHandler getCellInventory(ItemStack is, ISaveProvider host, StorageChannel chan); +} diff --git a/src/main/java/appeng/api/storage/ICellWorkbenchItem.java b/src/main/java/appeng/api/storage/ICellWorkbenchItem.java index 925ca2118e2..f65b3504f51 100644 --- a/src/main/java/appeng/api/storage/ICellWorkbenchItem.java +++ b/src/main/java/appeng/api/storage/ICellWorkbenchItem.java @@ -23,59 +23,58 @@ package appeng.api.storage; - import appeng.api.config.FuzzyMode; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public interface ICellWorkbenchItem { -public interface ICellWorkbenchItem -{ - - /** - * if this return false, the item will not be treated as a cell, and cannot be inserted into the work bench. - * - * @param is item - * @return true if the item should be editable in the cell workbench. - */ - boolean isEditable( ItemStack is ); + /** + * if this return false, the item will not be treated as a cell, and cannot be inserted into the work bench. + * + * @param is item + * @return true if the item should be editable in the cell workbench. + */ + boolean isEditable(ItemStack is); - /** - * used to edit the upgrade slots on your cell, should have a capacity of 0-24, you are also responsible for - * implementing the valid checks, and any storage/usage of them. - *

- * onInventoryChange will be called when saving is needed. - */ - IInventory getUpgradesInventory( ItemStack is ); + /** + * used to edit the upgrade slots on your cell, should have a capacity of 0-24, you are also responsible for + * implementing the valid checks, and any storage/usage of them. + *

+ * onInventoryChange will be called when saving is needed. + */ + IInventory getUpgradesInventory(ItemStack is); - /** - * Used to extract, or mirror the contents of the work bench onto the cell. - *

- * - This should have exactly 63 slots, any more, or less might cause issues. - *

- * onInventoryChange will be called when saving is needed. - */ - IInventory getConfigInventory( ItemStack is ); + /** + * Used to extract, or mirror the contents of the work bench onto the cell. + *

+ * - This should have exactly 63 slots, any more, or less might cause issues. + *

+ * onInventoryChange will be called when saving is needed. + */ + IInventory getConfigInventory(ItemStack is); - /** - * @return the current fuzzy status. - */ - FuzzyMode getFuzzyMode( ItemStack is ); + /** + * @return the current fuzzy status. + */ + FuzzyMode getFuzzyMode(ItemStack is); - /** - * sets the setting on the cell. - */ - void setFuzzyMode( ItemStack is, FuzzyMode fzMode ); + /** + * sets the setting on the cell. + */ + void setFuzzyMode(ItemStack is, FuzzyMode fzMode); - /** - * @param is cell item - * @return current ore dictionary filter - */ - default String getOreFilter(ItemStack is){ return ""; } + /** + * @param is cell item + * @return current ore dictionary filter + */ + default String getOreFilter(ItemStack is) { + return ""; + } - /** - * @param is cell item - * @param filter new ore dictionary filter - */ - default void setOreFilter(ItemStack is, String filter) {} + /** + * @param is cell item + * @param filter new ore dictionary filter + */ + default void setOreFilter(ItemStack is, String filter) {} } diff --git a/src/main/java/appeng/api/storage/IExternalStorageHandler.java b/src/main/java/appeng/api/storage/IExternalStorageHandler.java index e3c421c0902..b4d3a408c0b 100644 --- a/src/main/java/appeng/api/storage/IExternalStorageHandler.java +++ b/src/main/java/appeng/api/storage/IExternalStorageHandler.java @@ -23,39 +23,36 @@ package appeng.api.storage; - import appeng.api.networking.security.BaseActionSource; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; - /** * A Registration Record for {@link IExternalStorageRegistry} */ -public interface IExternalStorageHandler -{ +public interface IExternalStorageHandler { - /** - * if this can handle the provided inventory, return true. ( Generally skipped by AE, and it just calls getInventory - * ) - * - * @param te to be handled tile entity - * @param mySrc source - * @return true, if it can get a handler via getInventory - */ - boolean canHandle( TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource mySrc ); + /** + * if this can handle the provided inventory, return true. ( Generally skipped by AE, and it just calls getInventory + * ) + * + * @param te to be handled tile entity + * @param mySrc source + * @return true, if it can get a handler via getInventory + */ + boolean canHandle(TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource mySrc); - /** - * if this can handle the given inventory, return the a IMEInventory implementing class for it, if not return null - *

- * please note that if your inventory changes and requires polling, you must use an {@link IMEMonitor} instead of an - * {@link IMEInventory} failure to do so will result in invalid item counts and reporting of the inventory. - * - * @param te to be handled tile entity - * @param d direction - * @param channel channel - * @param src source - * @return The Handler for the inventory - */ - IMEInventory getInventory( TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource src ); -} \ No newline at end of file + /** + * if this can handle the given inventory, return the a IMEInventory implementing class for it, if not return null + *

+ * please note that if your inventory changes and requires polling, you must use an {@link IMEMonitor} instead of an + * {@link IMEInventory} failure to do so will result in invalid item counts and reporting of the inventory. + * + * @param te to be handled tile entity + * @param d direction + * @param channel channel + * @param src source + * @return The Handler for the inventory + */ + IMEInventory getInventory(TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource src); +} diff --git a/src/main/java/appeng/api/storage/IExternalStorageRegistry.java b/src/main/java/appeng/api/storage/IExternalStorageRegistry.java index 0be24a559a7..2598feb90e9 100644 --- a/src/main/java/appeng/api/storage/IExternalStorageRegistry.java +++ b/src/main/java/appeng/api/storage/IExternalStorageRegistry.java @@ -23,34 +23,32 @@ package appeng.api.storage; - import appeng.api.IAppEngApi; import appeng.api.networking.security.BaseActionSource; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; - /** * A Registry of External Storage handlers. *

* Do not implement obtain via {@link IAppEngApi}.registries().getExternalStorageRegistry() */ -public interface IExternalStorageRegistry -{ +public interface IExternalStorageRegistry { - /** - * A registry for StorageBus interactions - * - * @param esh storage handler - */ - void addExternalStorageInterface( IExternalStorageHandler esh ); + /** + * A registry for StorageBus interactions + * + * @param esh storage handler + */ + void addExternalStorageInterface(IExternalStorageHandler esh); - /** - * @param te tile entity - * @param opposite direction - * @param channel channel - * @param mySrc source - * @return the handler for a given tile / forge direction - */ - IExternalStorageHandler getHandler( TileEntity te, ForgeDirection opposite, StorageChannel channel, BaseActionSource mySrc ); -} \ No newline at end of file + /** + * @param te tile entity + * @param opposite direction + * @param channel channel + * @param mySrc source + * @return the handler for a given tile / forge direction + */ + IExternalStorageHandler getHandler( + TileEntity te, ForgeDirection opposite, StorageChannel channel, BaseActionSource mySrc); +} diff --git a/src/main/java/appeng/api/storage/IMEInventory.java b/src/main/java/appeng/api/storage/IMEInventory.java index 51f4a790881..3641375a470 100644 --- a/src/main/java/appeng/api/storage/IMEInventory.java +++ b/src/main/java/appeng/api/storage/IMEInventory.java @@ -23,13 +23,11 @@ package appeng.api.storage; - import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; - /** * AE's Equivalent to IInventory, used to reading contents, and manipulating contents of ME Inventories. *

@@ -40,38 +38,37 @@ * If you want to request a stack of an item, you should should determine that prior to requesting the stack from the * inventory. */ -public interface IMEInventory -{ +public interface IMEInventory { - /** - * Store new items, or simulate the addition of new items into the ME Inventory. - * - * @param input item to add. - * @param type action type - * @param src action source - * @return returns the number of items not added. - */ - StackType injectItems( StackType input, Actionable type, BaseActionSource src ); + /** + * Store new items, or simulate the addition of new items into the ME Inventory. + * + * @param input item to add. + * @param type action type + * @param src action source + * @return returns the number of items not added. + */ + StackType injectItems(StackType input, Actionable type, BaseActionSource src); - /** - * Extract the specified item from the ME Inventory - * - * @param request item to request ( with stack size. ) - * @param mode simulate, or perform action? - * @return returns the number of items extracted, null - */ - StackType extractItems( StackType request, Actionable mode, BaseActionSource src ); + /** + * Extract the specified item from the ME Inventory + * + * @param request item to request ( with stack size. ) + * @param mode simulate, or perform action? + * @return returns the number of items extracted, null + */ + StackType extractItems(StackType request, Actionable mode, BaseActionSource src); - /** - * request a full report of all available items, storage. - * - * @param out the IItemList the results will be written too - * @return returns same list that was passed in, is passed out - */ - IItemList getAvailableItems( IItemList out ); + /** + * request a full report of all available items, storage. + * + * @param out the IItemList the results will be written too + * @return returns same list that was passed in, is passed out + */ + IItemList getAvailableItems(IItemList out); - /** - * @return the type of channel your handler should be part of - */ - StorageChannel getChannel(); + /** + * @return the type of channel your handler should be part of + */ + StorageChannel getChannel(); } diff --git a/src/main/java/appeng/api/storage/IMEInventoryHandler.java b/src/main/java/appeng/api/storage/IMEInventoryHandler.java index 52806c5269e..e6552b035df 100644 --- a/src/main/java/appeng/api/storage/IMEInventoryHandler.java +++ b/src/main/java/appeng/api/storage/IMEInventoryHandler.java @@ -23,67 +23,64 @@ package appeng.api.storage; - import appeng.api.config.AccessRestriction; import appeng.api.storage.data.IAEStack; - /** * Thin logic layer that can be swapped with different IMEInventory implementations, used to handle features related to * storage, that are Separate from the storage medium itself. * * @param */ -public interface IMEInventoryHandler extends IMEInventory -{ +public interface IMEInventoryHandler extends IMEInventory { - /** - * determine if items can be injected/extracted. - * - * @return the access - */ - AccessRestriction getAccess(); + /** + * determine if items can be injected/extracted. + * + * @return the access + */ + AccessRestriction getAccess(); - /** - * determine if a particular item is prioritized for this inventory handler, if it is, then it will be added to this - * inventory prior to any non-prioritized inventories. - * - * @param input - item that might be added - * @return if its prioritized - */ - boolean isPrioritized( StackType input ); + /** + * determine if a particular item is prioritized for this inventory handler, if it is, then it will be added to this + * inventory prior to any non-prioritized inventories. + * + * @param input - item that might be added + * @return if its prioritized + */ + boolean isPrioritized(StackType input); - /** - * determine if an item can be accepted and stored. - * - * @param input - item that might be added - * @return if the item can be added - */ - boolean canAccept( StackType input ); + /** + * determine if an item can be accepted and stored. + * + * @param input - item that might be added + * @return if the item can be added + */ + boolean canAccept(StackType input); - /** - * determine what the priority of the inventory is. - * - * @return the priority, zero is default, positive and negative are supported. - */ - int getPriority(); + /** + * determine what the priority of the inventory is. + * + * @return the priority, zero is default, positive and negative are supported. + */ + int getPriority(); - /** - * pass back value for blinkCell. - * - * @return the slot index for the cell that this represents in the storage unit, the method on the - * {@link ICellContainer} will be called with this value, only trust the return value of this method if you - * are the implementer of this. - */ - int getSlot(); + /** + * pass back value for blinkCell. + * + * @return the slot index for the cell that this represents in the storage unit, the method on the + * {@link ICellContainer} will be called with this value, only trust the return value of this method if you + * are the implementer of this. + */ + int getSlot(); - /** - * AE Uses a two pass placement system, the first pass checks contents and tries to find a place where the item - * belongs, however in some cases you can save processor time, or require that the second, or first pass is simply - * ignored, this allows you to do that. - * - * @param i - pass number ( 1 or 2 ) - * @return true, if this inventory is valid for this pass. - */ - boolean validForPass( int i ); + /** + * AE Uses a two pass placement system, the first pass checks contents and tries to find a place where the item + * belongs, however in some cases you can save processor time, or require that the second, or first pass is simply + * ignored, this allows you to do that. + * + * @param i - pass number ( 1 or 2 ) + * @return true, if this inventory is valid for this pass. + */ + boolean validForPass(int i); } diff --git a/src/main/java/appeng/api/storage/IMEMonitor.java b/src/main/java/appeng/api/storage/IMEMonitor.java index 752691e2f17..29434970c21 100644 --- a/src/main/java/appeng/api/storage/IMEMonitor.java +++ b/src/main/java/appeng/api/storage/IMEMonitor.java @@ -23,26 +23,23 @@ package appeng.api.storage; - import appeng.api.networking.storage.IBaseMonitor; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; +public interface IMEMonitor extends IMEInventoryHandler, IBaseMonitor { -public interface IMEMonitor extends IMEInventoryHandler, IBaseMonitor -{ - - /** - * This method is discouraged when accessing data via a IMEMonitor - */ - @Override - @Deprecated - IItemList getAvailableItems( IItemList out ); + /** + * This method is discouraged when accessing data via a IMEMonitor + */ + @Override + @Deprecated + IItemList getAvailableItems(IItemList out); - /** - * Get access to the full item list of the network, preferred over {@link IMEInventory} .getAvailableItems(...) - * - * @return full storage list. - */ - IItemList getStorageList(); + /** + * Get access to the full item list of the network, preferred over {@link IMEInventory} .getAvailableItems(...) + * + * @return full storage list. + */ + IItemList getStorageList(); } diff --git a/src/main/java/appeng/api/storage/IMEMonitorHandlerReceiver.java b/src/main/java/appeng/api/storage/IMEMonitorHandlerReceiver.java index 9b8a9f5f894..a9475f7dbe3 100644 --- a/src/main/java/appeng/api/storage/IMEMonitorHandlerReceiver.java +++ b/src/main/java/appeng/api/storage/IMEMonitorHandlerReceiver.java @@ -23,32 +23,29 @@ package appeng.api.storage; - import appeng.api.networking.security.BaseActionSource; import appeng.api.networking.storage.IBaseMonitor; import appeng.api.storage.data.IAEStack; - -public interface IMEMonitorHandlerReceiver -{ - - /** - * return true if this object should remain as a listener. - * - * @param verificationToken to be checked object - * @return true if object should remain as a listener - */ - boolean isValid( Object verificationToken ); - - /** - * called when changes are made to the Monitor, but only if listener is still valid. - * - * @param change done change - */ - void postChange( IBaseMonitor monitor, Iterable change, BaseActionSource actionSource ); - - /** - * called when the list updates its contents, this is mostly for handling power events. - */ - void onListUpdate(); +public interface IMEMonitorHandlerReceiver { + + /** + * return true if this object should remain as a listener. + * + * @param verificationToken to be checked object + * @return true if object should remain as a listener + */ + boolean isValid(Object verificationToken); + + /** + * called when changes are made to the Monitor, but only if listener is still valid. + * + * @param change done change + */ + void postChange(IBaseMonitor monitor, Iterable change, BaseActionSource actionSource); + + /** + * called when the list updates its contents, this is mostly for handling power events. + */ + void onListUpdate(); } diff --git a/src/main/java/appeng/api/storage/ISaveProvider.java b/src/main/java/appeng/api/storage/ISaveProvider.java index 7c046826c30..06fbc9c016e 100644 --- a/src/main/java/appeng/api/storage/ISaveProvider.java +++ b/src/main/java/appeng/api/storage/ISaveProvider.java @@ -23,9 +23,7 @@ package appeng.api.storage; +public interface ISaveProvider { -public interface ISaveProvider -{ - - void saveChanges( IMEInventory cellInventory ); + void saveChanges(IMEInventory cellInventory); } diff --git a/src/main/java/appeng/api/storage/IStorageHelper.java b/src/main/java/appeng/api/storage/IStorageHelper.java index 5a36f74c26b..10d0982b959 100644 --- a/src/main/java/appeng/api/storage/IStorageHelper.java +++ b/src/main/java/appeng/api/storage/IStorageHelper.java @@ -23,7 +23,6 @@ package appeng.api.storage; - import appeng.api.networking.crafting.ICraftingLink; import appeng.api.networking.crafting.ICraftingRequester; import appeng.api.networking.energy.IEnergySource; @@ -32,89 +31,88 @@ import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; import io.netty.buffer.ByteBuf; +import java.io.IOException; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidStack; -import java.io.IOException; - - -public interface IStorageHelper -{ - - /** - * load a crafting link from nbt data. - * - * @param data to be loaded data - * @return crafting link - */ - ICraftingLink loadCraftingLink( NBTTagCompound data, ICraftingRequester req ); - - /** - * @param is An ItemStack - * @return a new INSTANCE of {@link IAEItemStack} from a MC {@link ItemStack} - */ - IAEItemStack createItemStack( ItemStack is ); - - /** - * @param is A FluidStack - * @return a new INSTANCE of {@link IAEFluidStack} from a Forge {@link FluidStack} - */ - IAEFluidStack createFluidStack( FluidStack is ); - - /** - * @return a new INSTANCE of {@link IItemList} for items - */ - IItemList createItemList(); - - /** - * @return a new INSTANCE of {@link IItemList} for items that does not support sorted output, fuzzy lookup - * (findFuzzy would raise UnsupportedOperationException!) nor concurrent access, but does work much faster - */ - IItemList createPrimitiveItemList(); - - /** - * @return a new INSTANCE of {@link IItemList} for fluids - */ - IItemList createFluidList(); - - /** - * Read a AE Item Stack from a byte stream, returns a AE item stack or null. - * - * @param input to be loaded data - * @return item based of data - * @throws IOException if file could not be read - */ - IAEItemStack readItemFromPacket( ByteBuf input ) throws IOException; - - /** - * Read a AE Fluid Stack from a byte stream, returns a AE fluid stack or null. - * - * @param input to be loaded data - * @return fluid based on data - * @throws IOException if file could not be written - */ - IAEFluidStack readFluidFromPacket( ByteBuf input ) throws IOException; - - /** - * use energy from energy, to remove request items from cell, at the request of src. - * - * @param energy to be drained energy source - * @param cell cell of requested items - * @param request requested items - * @param src action source - * @return items that successfully extracted. - */ - IAEItemStack poweredExtraction( IEnergySource energy, IMEInventory cell, IAEItemStack request, BaseActionSource src ); - - /** - * use energy from energy, to inject input items into cell, at the request of src - * - * @param energy to be added energy source - * @param cell injected cell - * @param input to be injected items - * @param src action source - * @return items that failed to insert. - */ - IAEItemStack poweredInsert( IEnergySource energy, IMEInventory cell, IAEItemStack input, BaseActionSource src ); +public interface IStorageHelper { + + /** + * load a crafting link from nbt data. + * + * @param data to be loaded data + * @return crafting link + */ + ICraftingLink loadCraftingLink(NBTTagCompound data, ICraftingRequester req); + + /** + * @param is An ItemStack + * @return a new INSTANCE of {@link IAEItemStack} from a MC {@link ItemStack} + */ + IAEItemStack createItemStack(ItemStack is); + + /** + * @param is A FluidStack + * @return a new INSTANCE of {@link IAEFluidStack} from a Forge {@link FluidStack} + */ + IAEFluidStack createFluidStack(FluidStack is); + + /** + * @return a new INSTANCE of {@link IItemList} for items + */ + IItemList createItemList(); + + /** + * @return a new INSTANCE of {@link IItemList} for items that does not support sorted output, fuzzy lookup + * (findFuzzy would raise UnsupportedOperationException!) nor concurrent access, but does work much faster + */ + IItemList createPrimitiveItemList(); + + /** + * @return a new INSTANCE of {@link IItemList} for fluids + */ + IItemList createFluidList(); + + /** + * Read a AE Item Stack from a byte stream, returns a AE item stack or null. + * + * @param input to be loaded data + * @return item based of data + * @throws IOException if file could not be read + */ + IAEItemStack readItemFromPacket(ByteBuf input) throws IOException; + + /** + * Read a AE Fluid Stack from a byte stream, returns a AE fluid stack or null. + * + * @param input to be loaded data + * @return fluid based on data + * @throws IOException if file could not be written + */ + IAEFluidStack readFluidFromPacket(ByteBuf input) throws IOException; + + /** + * use energy from energy, to remove request items from cell, at the request of src. + * + * @param energy to be drained energy source + * @param cell cell of requested items + * @param request requested items + * @param src action source + * @return items that successfully extracted. + */ + IAEItemStack poweredExtraction( + IEnergySource energy, IMEInventory cell, IAEItemStack request, BaseActionSource src); + + /** + * use energy from energy, to inject input items into cell, at the request of src + * + * @param energy to be added energy source + * @param cell injected cell + * @param input to be injected items + * @param src action source + * @return items that failed to insert. + */ + IAEItemStack poweredInsert( + IEnergySource energy, IMEInventory cell, IAEItemStack input, BaseActionSource src); } diff --git a/src/main/java/appeng/api/storage/IStorageMonitorable.java b/src/main/java/appeng/api/storage/IStorageMonitorable.java index 251b7ebe173..4a2b45f79b7 100644 --- a/src/main/java/appeng/api/storage/IStorageMonitorable.java +++ b/src/main/java/appeng/api/storage/IStorageMonitorable.java @@ -23,27 +23,24 @@ package appeng.api.storage; - import appeng.api.implementations.tiles.ITileStorageMonitorable; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEItemStack; - /** * represents the internal behavior of a {@link ITileStorageMonitorable} use it to get this value for a tile, or part. *

* never check a tile for this, always go though ITileStorageMonitorable if you wish to use this interface. */ -public interface IStorageMonitorable -{ +public interface IStorageMonitorable { - /** - * Access the item inventory for the monitorable storage. - */ - IMEMonitor getItemInventory(); + /** + * Access the item inventory for the monitorable storage. + */ + IMEMonitor getItemInventory(); - /** - * Access the fluid inventory for the monitorable storage. - */ - IMEMonitor getFluidInventory(); + /** + * Access the fluid inventory for the monitorable storage. + */ + IMEMonitor getFluidInventory(); } diff --git a/src/main/java/appeng/api/storage/ITerminalHost.java b/src/main/java/appeng/api/storage/ITerminalHost.java index f802b6d654e..742ced27f70 100644 --- a/src/main/java/appeng/api/storage/ITerminalHost.java +++ b/src/main/java/appeng/api/storage/ITerminalHost.java @@ -23,11 +23,6 @@ package appeng.api.storage; - import appeng.api.util.IConfigurableObject; - -public interface ITerminalHost extends IStorageMonitorable, IConfigurableObject -{ - -} +public interface ITerminalHost extends IStorageMonitorable, IConfigurableObject {} diff --git a/src/main/java/appeng/api/storage/MEMonitorHandler.java b/src/main/java/appeng/api/storage/MEMonitorHandler.java index 414501515d5..0edf192be04 100644 --- a/src/main/java/appeng/api/storage/MEMonitorHandler.java +++ b/src/main/java/appeng/api/storage/MEMonitorHandler.java @@ -23,192 +23,158 @@ package appeng.api.storage; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; import com.google.common.collect.ImmutableList; - import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; - /** * Common implementation of a simple class that monitors injection/extraction of a inventory to send events to a list of * listeners. * * @param */ -public class MEMonitorHandler implements IMEMonitor -{ - - private final IMEInventoryHandler internalHandler; - private final IItemList cachedList; - private final HashMap, Object> listeners = new HashMap, Object>(); - - protected boolean hasChanged = true; - - public MEMonitorHandler( final IMEInventoryHandler t ) - { - this.internalHandler = t; - this.cachedList = (IItemList) t.getChannel().createList(); - } - - public MEMonitorHandler( final IMEInventoryHandler t, final StorageChannel chan ) - { - this.internalHandler = t; - this.cachedList = (IItemList) chan.createList(); - } - - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } - - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } - - @Override - public StackType injectItems( final StackType input, final Actionable mode, final BaseActionSource src ) - { - if( mode == Actionable.SIMULATE ) - { - return this.getHandler().injectItems( input, mode, src ); - } - return this.monitorDifference( input.copy(), this.getHandler().injectItems( input, mode, src ), false, src ); - } - - protected IMEInventoryHandler getHandler() - { - return this.internalHandler; - } - - private StackType monitorDifference( final IAEStack original, final StackType leftOvers, final boolean extraction, final BaseActionSource src ) - { - final StackType diff = (StackType) original.copy(); - - if( extraction ) - { - diff.setStackSize( leftOvers == null ? 0 : -leftOvers.getStackSize() ); - } - else if( leftOvers != null ) - { - diff.decStackSize( leftOvers.getStackSize() ); - } - - if( diff.getStackSize() != 0 ) - { - this.postChangesToListeners( ImmutableList.of( diff ), src ); - } - - return leftOvers; - } - - protected void postChangesToListeners( final Iterable changes, final BaseActionSource src ) - { - this.notifyListenersOfChange( changes, src ); - } - - protected void notifyListenersOfChange( final Iterable diff, final BaseActionSource src ) - { - this.hasChanged = true;// need to update the cache. - final Iterator, Object>> i = this.getListeners(); - while( i.hasNext() ) - { - final Entry, Object> o = i.next(); - final IMEMonitorHandlerReceiver receiver = o.getKey(); - if( receiver.isValid( o.getValue() ) ) - { - receiver.postChange( this, diff, src ); - } - else - { - i.remove(); - } - } - } - - protected Iterator, Object>> getListeners() - { - return this.listeners.entrySet().iterator(); - } - - @Override - public StackType extractItems( final StackType request, final Actionable mode, final BaseActionSource src ) - { - if( mode == Actionable.SIMULATE ) - { - return this.getHandler().extractItems( request, mode, src ); - } - return this.monitorDifference( request.copy(), this.getHandler().extractItems( request, mode, src ), true, src ); - } - - @Override - public StorageChannel getChannel() - { - return this.getHandler().getChannel(); - } - - @Override - public AccessRestriction getAccess() - { - return this.getHandler().getAccess(); - } - - @Override - public IItemList getStorageList() - { - if( this.hasChanged ) - { - this.hasChanged = false; - this.cachedList.resetStatus(); - return this.getAvailableItems( this.cachedList ); - } - - return this.cachedList; - } - - @Override - public boolean isPrioritized( final StackType input ) - { - return this.getHandler().isPrioritized( input ); - } - - @Override - public boolean canAccept( final StackType input ) - { - return this.getHandler().canAccept( input ); - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return this.getHandler().getAvailableItems( out ); - } - - @Override - public int getPriority() - { - return this.getHandler().getPriority(); - } - - @Override - public int getSlot() - { - return this.getHandler().getSlot(); - } - - @Override - public boolean validForPass( final int i ) - { - return this.getHandler().validForPass( i ); - } - +public class MEMonitorHandler implements IMEMonitor { + + private final IMEInventoryHandler internalHandler; + private final IItemList cachedList; + private final HashMap, Object> listeners = + new HashMap, Object>(); + + protected boolean hasChanged = true; + + public MEMonitorHandler(final IMEInventoryHandler t) { + this.internalHandler = t; + this.cachedList = (IItemList) t.getChannel().createList(); + } + + public MEMonitorHandler(final IMEInventoryHandler t, final StorageChannel chan) { + this.internalHandler = t; + this.cachedList = (IItemList) chan.createList(); + } + + @Override + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + this.listeners.put(l, verificationToken); + } + + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } + + @Override + public StackType injectItems(final StackType input, final Actionable mode, final BaseActionSource src) { + if (mode == Actionable.SIMULATE) { + return this.getHandler().injectItems(input, mode, src); + } + return this.monitorDifference(input.copy(), this.getHandler().injectItems(input, mode, src), false, src); + } + + protected IMEInventoryHandler getHandler() { + return this.internalHandler; + } + + private StackType monitorDifference( + final IAEStack original, final StackType leftOvers, final boolean extraction, final BaseActionSource src) { + final StackType diff = (StackType) original.copy(); + + if (extraction) { + diff.setStackSize(leftOvers == null ? 0 : -leftOvers.getStackSize()); + } else if (leftOvers != null) { + diff.decStackSize(leftOvers.getStackSize()); + } + + if (diff.getStackSize() != 0) { + this.postChangesToListeners(ImmutableList.of(diff), src); + } + + return leftOvers; + } + + protected void postChangesToListeners(final Iterable changes, final BaseActionSource src) { + this.notifyListenersOfChange(changes, src); + } + + protected void notifyListenersOfChange(final Iterable diff, final BaseActionSource src) { + this.hasChanged = true; // need to update the cache. + final Iterator, Object>> i = this.getListeners(); + while (i.hasNext()) { + final Entry, Object> o = i.next(); + final IMEMonitorHandlerReceiver receiver = o.getKey(); + if (receiver.isValid(o.getValue())) { + receiver.postChange(this, diff, src); + } else { + i.remove(); + } + } + } + + protected Iterator, Object>> getListeners() { + return this.listeners.entrySet().iterator(); + } + + @Override + public StackType extractItems(final StackType request, final Actionable mode, final BaseActionSource src) { + if (mode == Actionable.SIMULATE) { + return this.getHandler().extractItems(request, mode, src); + } + return this.monitorDifference(request.copy(), this.getHandler().extractItems(request, mode, src), true, src); + } + + @Override + public StorageChannel getChannel() { + return this.getHandler().getChannel(); + } + + @Override + public AccessRestriction getAccess() { + return this.getHandler().getAccess(); + } + + @Override + public IItemList getStorageList() { + if (this.hasChanged) { + this.hasChanged = false; + this.cachedList.resetStatus(); + return this.getAvailableItems(this.cachedList); + } + + return this.cachedList; + } + + @Override + public boolean isPrioritized(final StackType input) { + return this.getHandler().isPrioritized(input); + } + + @Override + public boolean canAccept(final StackType input) { + return this.getHandler().canAccept(input); + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + return this.getHandler().getAvailableItems(out); + } + + @Override + public int getPriority() { + return this.getHandler().getPriority(); + } + + @Override + public int getSlot() { + return this.getHandler().getSlot(); + } + + @Override + public boolean validForPass(final int i) { + return this.getHandler().validForPass(i); + } } diff --git a/src/main/java/appeng/api/storage/StorageChannel.java b/src/main/java/appeng/api/storage/StorageChannel.java index 2e57310f34c..018c2b11754 100644 --- a/src/main/java/appeng/api/storage/StorageChannel.java +++ b/src/main/java/appeng/api/storage/StorageChannel.java @@ -23,42 +23,34 @@ package appeng.api.storage; - import appeng.api.AEApi; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; - -public enum StorageChannel -{ - /** - * AE2's Default Storage. - */ - ITEMS( IAEItemStack.class ), - - /** - * AE2's Fluid Based Storage ( mainly added to better support ExtraCells ) - */ - FLUIDS( IAEFluidStack.class ); - - public final Class type; - - StorageChannel( final Class t ) - { - this.type = t; - } - - public IItemList createList() - { - if( this == ITEMS ) - { - return AEApi.instance().storage().createItemList(); - } - else - { - return AEApi.instance().storage().createFluidList(); - } - } +public enum StorageChannel { + /** + * AE2's Default Storage. + */ + ITEMS(IAEItemStack.class), + + /** + * AE2's Fluid Based Storage ( mainly added to better support ExtraCells ) + */ + FLUIDS(IAEFluidStack.class); + + public final Class type; + + StorageChannel(final Class t) { + this.type = t; + } + + public IItemList createList() { + if (this == ITEMS) { + return AEApi.instance().storage().createItemList(); + } else { + return AEApi.instance().storage().createFluidList(); + } + } } diff --git a/src/main/java/appeng/api/storage/data/IAEFluidStack.java b/src/main/java/appeng/api/storage/data/IAEFluidStack.java index 3ffb5a4fd41..b62630d620b 100644 --- a/src/main/java/appeng/api/storage/data/IAEFluidStack.java +++ b/src/main/java/appeng/api/storage/data/IAEFluidStack.java @@ -23,11 +23,9 @@ package appeng.api.storage.data; - import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; - /** * An alternate version of FluidStack for AE to keep tabs on things easier, and * to support larger storage. stackSizes of getFluidStack will be capped. @@ -39,36 +37,35 @@ *

* Construct with Util.createFluidStack( FluidStack ) */ -public interface IAEFluidStack extends IAEStack -{ +public interface IAEFluidStack extends IAEStack { - /** - * creates a standard Forge FluidStack for the fluid. - * - * @return new FluidStack - */ - FluidStack getFluidStack(); + /** + * creates a standard Forge FluidStack for the fluid. + * + * @return new FluidStack + */ + FluidStack getFluidStack(); - /** - * Combines two IAEItemStacks via addition. - * - * @param option , to add to the current one. - */ - @Override - void add( IAEFluidStack option ); + /** + * Combines two IAEItemStacks via addition. + * + * @param option , to add to the current one. + */ + @Override + void add(IAEFluidStack option); - /** - * create a AE Fluid clone. - * - * @return the copy. - */ - @Override - IAEFluidStack copy(); + /** + * create a AE Fluid clone. + * + * @return the copy. + */ + @Override + IAEFluidStack copy(); - /** - * quick way to get access to the Forge Fluid Definition. - * - * @return fluid definition - */ - Fluid getFluid(); + /** + * quick way to get access to the Forge Fluid Definition. + * + * @return fluid definition + */ + Fluid getFluid(); } diff --git a/src/main/java/appeng/api/storage/data/IAEItemStack.java b/src/main/java/appeng/api/storage/data/IAEItemStack.java index 883479d6a76..583b18019b8 100644 --- a/src/main/java/appeng/api/storage/data/IAEItemStack.java +++ b/src/main/java/appeng/api/storage/data/IAEItemStack.java @@ -23,11 +23,9 @@ package appeng.api.storage.data; - import net.minecraft.item.Item; import net.minecraft.item.ItemStack; - /** * An alternate version of ItemStack for AE to keep tabs on things easier, and to support larger storage. stackSizes of * getItemStack will be capped. @@ -38,69 +36,68 @@ *

* Construct with Util.createItemStack( ItemStack ) */ -public interface IAEItemStack extends IAEStack -{ +public interface IAEItemStack extends IAEStack { - /** - * creates a standard MC ItemStack for the item. - * - * @return new ItemStack - */ - ItemStack getItemStack(); + /** + * creates a standard MC ItemStack for the item. + * + * @return new ItemStack + */ + ItemStack getItemStack(); - /** - * is there NBT Data for this item? - * - * @return if there is - */ - boolean hasTagCompound(); + /** + * is there NBT Data for this item? + * + * @return if there is + */ + boolean hasTagCompound(); - /** - * Combines two IAEItemStacks via addition. - * - * @param option to add to the current one. - */ - @Override - void add( IAEItemStack option ); + /** + * Combines two IAEItemStacks via addition. + * + * @param option to add to the current one. + */ + @Override + void add(IAEItemStack option); - /** - * create a AE Item clone - * - * @return the copy - */ - @Override - IAEItemStack copy(); + /** + * create a AE Item clone + * + * @return the copy + */ + @Override + IAEItemStack copy(); - /** - * quick way to get access to the MC Item Definition. - * - * @return item definition - */ - Item getItem(); + /** + * quick way to get access to the MC Item Definition. + * + * @return item definition + */ + Item getItem(); - /** - * @return the items damage value - */ - int getItemDamage(); + /** + * @return the items damage value + */ + int getItemDamage(); - /** - * Compare the Ore Dictionary ID for this to another item. - */ - boolean sameOre( IAEItemStack is ); + /** + * Compare the Ore Dictionary ID for this to another item. + */ + boolean sameOre(IAEItemStack is); - /** - * compare the item/damage/nbt of the stack. - * - * @param otherStack to be compared item - * @return true if it is the same type (same item, damage, nbt) - */ - boolean isSameType( IAEItemStack otherStack ); + /** + * compare the item/damage/nbt of the stack. + * + * @param otherStack to be compared item + * @return true if it is the same type (same item, damage, nbt) + */ + boolean isSameType(IAEItemStack otherStack); - /** - * compare the item/damage/nbt of the stack. - * - * @param stored to be compared item - * @return true if it is the same type (same item, damage, nbt) - */ - boolean isSameType( ItemStack stored ); -} \ No newline at end of file + /** + * compare the item/damage/nbt of the stack. + * + * @param stored to be compared item + * @return true if it is the same type (same item, damage, nbt) + */ + boolean isSameType(ItemStack stored); +} diff --git a/src/main/java/appeng/api/storage/data/IAEStack.java b/src/main/java/appeng/api/storage/data/IAEStack.java index 4548fe4918a..075e028a65c 100644 --- a/src/main/java/appeng/api/storage/data/IAEStack.java +++ b/src/main/java/appeng/api/storage/data/IAEStack.java @@ -23,179 +23,175 @@ package appeng.api.storage.data; - import appeng.api.config.FuzzyMode; import appeng.api.storage.StorageChannel; import io.netty.buffer.ByteBuf; -import net.minecraft.nbt.NBTTagCompound; - import java.io.IOException; +import net.minecraft.nbt.NBTTagCompound; - -public interface IAEStack -{ - - /** - * add two stacks together - * - * @param is added item - */ - void add( StackType is ); - - /** - * number of items in the stack. - * - * @return basically ItemStack.stackSize - */ - long getStackSize(); - - /** - * changes the number of items in the stack. - * - * @param stackSize , ItemStack.stackSize = N - */ - StackType setStackSize( long stackSize ); - - /** - * Same as getStackSize, but for requestable items. ( LP ) - * - * @return basically itemStack.stackSize but for requestable items. - */ - long getCountRequestable(); - - /** - * Same as setStackSize, but for requestable items. ( LP ) - * - * @return basically itemStack.stackSize = N but for setStackSize items. - */ - StackType setCountRequestable( long countRequestable ); - - /** - * true, if the item can be crafted. - * - * @return true, if it can be crafted. - */ - boolean isCraftable(); - - /** - * change weather the item can be crafted. - * - * @param isCraftable can item be crafted - */ - StackType setCraftable( boolean isCraftable ); - - /** - * clears, requestable, craftable, and stack sizes. - */ - StackType reset(); - - /** - * returns true, if the item can be crafted, requested, or extracted. - * - * @return isThisRecordMeaningful - */ - boolean isMeaningful(); - - /** - * Adds more to the stack size... - * - * @param i additional stack size - */ - void incStackSize( long i ); - - /** - * removes some from the stack size. - */ - void decStackSize( long i ); - - /** - * adds items to the requestable - * - * @param i increased amount of requested items - */ - void incCountRequestable( long i ); - - /** - * removes items from the requestable - * - * @param i decreased amount of requested items - */ - void decCountRequestable( long i ); - - /** - * write to a NBTTagCompound. - * - * @param i to be written data - */ - void writeToNBT( NBTTagCompound i ); - - /** - * Compare stacks using precise logic. - *

- * a IAEItemStack to another AEItemStack or a ItemStack. - *

- * or - *

- * IAEFluidStack, FluidStack - * - * @param obj compared object - * @return true if they are the same. - */ - @Override - boolean equals( Object obj ); - - /** - * compare stacks using fuzzy logic - *

- * a IAEItemStack to another AEItemStack or a ItemStack. - * - * @param st stacks - * @param mode used fuzzy mode - * @return true if two stacks are equal based on AE Fuzzy Comparison. - */ - boolean fuzzyComparison( Object st, FuzzyMode mode ); - - /** - * Slower for disk saving, but smaller/more efficient for packets. - * - * @param data to be written data - * @throws IOException - */ - void writeToPacket( ByteBuf data ) throws IOException; - - /** - * Clone the Item / Fluid Stack - * - * @return a new Stack, which is copied from the original. - */ - StackType copy(); - - /** - * create an empty stack. - * - * @return a new stack, which represents an empty copy of the original. - */ - StackType empty(); - - /** - * obtain the NBT Data for the item. - * - * @return nbt data - */ - IAETagCompound getTagCompound(); - - /** - * @return true if the stack is a {@link IAEItemStack} - */ - boolean isItem(); - - /** - * @return true if the stack is a {@link IAEFluidStack} - */ - boolean isFluid(); - - /** - * @return ITEM or FLUID - */ - StorageChannel getChannel(); +public interface IAEStack { + + /** + * add two stacks together + * + * @param is added item + */ + void add(StackType is); + + /** + * number of items in the stack. + * + * @return basically ItemStack.stackSize + */ + long getStackSize(); + + /** + * changes the number of items in the stack. + * + * @param stackSize , ItemStack.stackSize = N + */ + StackType setStackSize(long stackSize); + + /** + * Same as getStackSize, but for requestable items. ( LP ) + * + * @return basically itemStack.stackSize but for requestable items. + */ + long getCountRequestable(); + + /** + * Same as setStackSize, but for requestable items. ( LP ) + * + * @return basically itemStack.stackSize = N but for setStackSize items. + */ + StackType setCountRequestable(long countRequestable); + + /** + * true, if the item can be crafted. + * + * @return true, if it can be crafted. + */ + boolean isCraftable(); + + /** + * change weather the item can be crafted. + * + * @param isCraftable can item be crafted + */ + StackType setCraftable(boolean isCraftable); + + /** + * clears, requestable, craftable, and stack sizes. + */ + StackType reset(); + + /** + * returns true, if the item can be crafted, requested, or extracted. + * + * @return isThisRecordMeaningful + */ + boolean isMeaningful(); + + /** + * Adds more to the stack size... + * + * @param i additional stack size + */ + void incStackSize(long i); + + /** + * removes some from the stack size. + */ + void decStackSize(long i); + + /** + * adds items to the requestable + * + * @param i increased amount of requested items + */ + void incCountRequestable(long i); + + /** + * removes items from the requestable + * + * @param i decreased amount of requested items + */ + void decCountRequestable(long i); + + /** + * write to a NBTTagCompound. + * + * @param i to be written data + */ + void writeToNBT(NBTTagCompound i); + + /** + * Compare stacks using precise logic. + *

+ * a IAEItemStack to another AEItemStack or a ItemStack. + *

+ * or + *

+ * IAEFluidStack, FluidStack + * + * @param obj compared object + * @return true if they are the same. + */ + @Override + boolean equals(Object obj); + + /** + * compare stacks using fuzzy logic + *

+ * a IAEItemStack to another AEItemStack or a ItemStack. + * + * @param st stacks + * @param mode used fuzzy mode + * @return true if two stacks are equal based on AE Fuzzy Comparison. + */ + boolean fuzzyComparison(Object st, FuzzyMode mode); + + /** + * Slower for disk saving, but smaller/more efficient for packets. + * + * @param data to be written data + * @throws IOException + */ + void writeToPacket(ByteBuf data) throws IOException; + + /** + * Clone the Item / Fluid Stack + * + * @return a new Stack, which is copied from the original. + */ + StackType copy(); + + /** + * create an empty stack. + * + * @return a new stack, which represents an empty copy of the original. + */ + StackType empty(); + + /** + * obtain the NBT Data for the item. + * + * @return nbt data + */ + IAETagCompound getTagCompound(); + + /** + * @return true if the stack is a {@link IAEItemStack} + */ + boolean isItem(); + + /** + * @return true if the stack is a {@link IAEFluidStack} + */ + boolean isFluid(); + + /** + * @return ITEM or FLUID + */ + StorageChannel getChannel(); } diff --git a/src/main/java/appeng/api/storage/data/IAETagCompound.java b/src/main/java/appeng/api/storage/data/IAETagCompound.java index 64973739afa..6a0a483fec8 100644 --- a/src/main/java/appeng/api/storage/data/IAETagCompound.java +++ b/src/main/java/appeng/api/storage/data/IAETagCompound.java @@ -23,35 +23,32 @@ package appeng.api.storage.data; - import appeng.api.features.IItemComparison; import net.minecraft.nbt.NBTTagCompound; - /** * Don't cast this... either compare with it, or copy it. *

* Don't Implement. */ -public interface IAETagCompound -{ - - /** - * @return a copy ( the copy will not be a IAETagCompound, it will be a NBTTagCompound ) - */ - NBTTagCompound getNBTTagCompoundCopy(); - - /** - * compare to other NBTTagCompounds or IAETagCompounds - * - * @param a compared object - * @return true, if they are the same. - */ - @Override - boolean equals( Object a ); - - /** - * @return the special comparison for this tag - */ - IItemComparison getSpecialComparison(); -} \ No newline at end of file +public interface IAETagCompound { + + /** + * @return a copy ( the copy will not be a IAETagCompound, it will be a NBTTagCompound ) + */ + NBTTagCompound getNBTTagCompoundCopy(); + + /** + * compare to other NBTTagCompounds or IAETagCompounds + * + * @param a compared object + * @return true, if they are the same. + */ + @Override + boolean equals(Object a); + + /** + * @return the special comparison for this tag + */ + IItemComparison getSpecialComparison(); +} diff --git a/src/main/java/appeng/api/storage/data/IItemContainer.java b/src/main/java/appeng/api/storage/data/IItemContainer.java index b47c3a376ea..603396b875e 100644 --- a/src/main/java/appeng/api/storage/data/IItemContainer.java +++ b/src/main/java/appeng/api/storage/data/IItemContainer.java @@ -23,12 +23,9 @@ package appeng.api.storage.data; - import appeng.api.config.FuzzyMode; - import java.util.Collection; - /** * Represents a list of items in AE. *

@@ -36,31 +33,30 @@ *

* Construct with Util.createItemList() */ -public interface IItemContainer -{ - - /** - * add a stack to the list, this will merge the stack with an item already in the list if found. - * - * @param option added stack - */ - void add( StackType option ); // adds stack as is - - /** - * @param i compared item - * @return a stack equivalent to the stack passed in, but with the correct stack size information, or null if its - * not present - */ - StackType findPrecise( StackType i ); - - /** - * @param input compared item - * @return a list of relevant fuzzy matched stacks - */ - Collection findFuzzy( StackType input, FuzzyMode fuzzy ); - - /** - * @return true if there are no items in the list - */ - boolean isEmpty(); -} \ No newline at end of file +public interface IItemContainer { + + /** + * add a stack to the list, this will merge the stack with an item already in the list if found. + * + * @param option added stack + */ + void add(StackType option); // adds stack as is + + /** + * @param i compared item + * @return a stack equivalent to the stack passed in, but with the correct stack size information, or null if its + * not present + */ + StackType findPrecise(StackType i); + + /** + * @param input compared item + * @return a list of relevant fuzzy matched stacks + */ + Collection findFuzzy(StackType input, FuzzyMode fuzzy); + + /** + * @return true if there are no items in the list + */ + boolean isEmpty(); +} diff --git a/src/main/java/appeng/api/storage/data/IItemList.java b/src/main/java/appeng/api/storage/data/IItemList.java index 2a07c11cbae..5cbd6bcffd2 100644 --- a/src/main/java/appeng/api/storage/data/IItemList.java +++ b/src/main/java/appeng/api/storage/data/IItemList.java @@ -23,10 +23,8 @@ package appeng.api.storage.data; - import java.util.Iterator; - /** * Represents a list of items in AE. *

@@ -34,50 +32,49 @@ *

* Construct with Util.createItemList() */ -public interface IItemList extends IItemContainer, Iterable -{ +public interface IItemList extends IItemContainer, Iterable { - /** - * add a stack to the list stackSize is used to add to stackSize, this will merge the stack with an item already in - * the list if found. - * - * @param option stacktype option - */ - void addStorage( StackType option ); // adds a stack as stored + /** + * add a stack to the list stackSize is used to add to stackSize, this will merge the stack with an item already in + * the list if found. + * + * @param option stacktype option + */ + void addStorage(StackType option); // adds a stack as stored - /** - * add a stack to the list as craftable, this will merge the stack with an item already in the list if found. - * - * @param option stacktype option - */ - void addCrafting( StackType option ); + /** + * add a stack to the list as craftable, this will merge the stack with an item already in the list if found. + * + * @param option stacktype option + */ + void addCrafting(StackType option); - /** - * add a stack to the list, stack size is used to add to requestable, this will merge the stack with an item already - * in the list if found. - * - * @param option stacktype option - */ - void addRequestable( StackType option ); // adds a stack as requestable + /** + * add a stack to the list, stack size is used to add to requestable, this will merge the stack with an item already + * in the list if found. + * + * @param option stacktype option + */ + void addRequestable(StackType option); // adds a stack as requestable - /** - * @return the first item in the list - */ - StackType getFirstItem(); + /** + * @return the first item in the list + */ + StackType getFirstItem(); - /** - * @return the number of items in the list - */ - int size(); + /** + * @return the number of items in the list + */ + int size(); - /** - * allows you to iterate the list. - */ - @Override - Iterator iterator(); + /** + * allows you to iterate the list. + */ + @Override + Iterator iterator(); - /** - * resets stack sizes to 0. - */ - void resetStatus(); -} \ No newline at end of file + /** + * resets stack sizes to 0. + */ + void resetStatus(); +} diff --git a/src/main/java/appeng/api/util/AECableType.java b/src/main/java/appeng/api/util/AECableType.java index 65c84d2db10..2ae6d27d01a 100644 --- a/src/main/java/appeng/api/util/AECableType.java +++ b/src/main/java/appeng/api/util/AECableType.java @@ -23,46 +23,44 @@ package appeng.api.util; +public enum AECableType { + /** + * No Cable present. + */ + NONE, -public enum AECableType -{ - /** - * No Cable present. - */ - NONE, + /** + * Connections to this block should render as glass. + */ + GLASS, - /** - * Connections to this block should render as glass. - */ - GLASS, + /** + * Connections to this block should render as covered. + */ + COVERED, - /** - * Connections to this block should render as covered. - */ - COVERED, + /** + * Connections to this block should render as smart. + */ + SMART, - /** - * Connections to this block should render as smart. - */ - SMART, + /** + * Dense Cable, represents a tier 2 block that can carry 32 channels. + */ + DENSE, - /** - * Dense Cable, represents a tier 2 block that can carry 32 channels. - */ - DENSE, + /** + * Dense Covered Cable, represents a tier 2 block that can carry 32 channels that should render as covered. + */ + DENSE_COVERED, - /** - * Dense Covered Cable, represents a tier 2 block that can carry 32 channels that should render as covered. - */ - DENSE_COVERED, + /** + * Ultra Dense Cable, represents a tier 3 block that can carry 128 channels. + */ + ULTRA_DENSE, - /** - * Ultra Dense Cable, represents a tier 3 block that can carry 128 channels. - */ - ULTRA_DENSE, - - /** - * Ultra Dense Cable, represents a tier 3 block that can carry 128 channels and renders as smart (4 channels per line). - */ - ULTRA_DENSE_SMART + /** + * Ultra Dense Cable, represents a tier 3 block that can carry 128 channels and renders as smart (4 channels per line). + */ + ULTRA_DENSE_SMART } diff --git a/src/main/java/appeng/api/util/AEColor.java b/src/main/java/appeng/api/util/AEColor.java index 0b0fc276ea9..abc10c1fd61 100644 --- a/src/main/java/appeng/api/util/AEColor.java +++ b/src/main/java/appeng/api/util/AEColor.java @@ -23,97 +23,90 @@ package appeng.api.util; - -import net.minecraft.util.StatCollector; - import java.util.Arrays; import java.util.List; - +import net.minecraft.util.StatCollector; /** * List of all colors supported by AE, their names, and various colors for display. *

* Should be the same order as Dyes, excluding Transparent. */ -public enum AEColor -{ - - White( "gui.appliedenergistics2.White", 0xBEBEBE, 0xDBDBDB, 0xFAFAFA ), - - Orange( "gui.appliedenergistics2.Orange", 0xF99739, 0xFAAE44, 0xF4DEC3 ), +public enum AEColor { + White("gui.appliedenergistics2.White", 0xBEBEBE, 0xDBDBDB, 0xFAFAFA), - Magenta( "gui.appliedenergistics2.Magenta", 0x821E82, 0xB82AB8, 0xC598C8 ), + Orange("gui.appliedenergistics2.Orange", 0xF99739, 0xFAAE44, 0xF4DEC3), - LightBlue( "gui.appliedenergistics2.LightBlue", 0x628DCB, 0x82ACE7, 0xD8F6FF ), + Magenta("gui.appliedenergistics2.Magenta", 0x821E82, 0xB82AB8, 0xC598C8), - Yellow( "gui.appliedenergistics2.Yellow", 0xFFF7AA, 0xF8FF4A, 0xFFFFE8 ), + LightBlue("gui.appliedenergistics2.LightBlue", 0x628DCB, 0x82ACE7, 0xD8F6FF), - Lime( "gui.appliedenergistics2.Lime", 0x7CFF4A, 0xBBFF51, 0xE7F7D7 ), + Yellow("gui.appliedenergistics2.Yellow", 0xFFF7AA, 0xF8FF4A, 0xFFFFE8), - Pink( "gui.appliedenergistics2.Pink", 0xDC8DB5, 0xF8B5D7, 0xF7DEEB ), + Lime("gui.appliedenergistics2.Lime", 0x7CFF4A, 0xBBFF51, 0xE7F7D7), - Gray( "gui.appliedenergistics2.Gray", 0x7C7C7C, 0xA0A0A0, 0xC9C9C9 ), + Pink("gui.appliedenergistics2.Pink", 0xDC8DB5, 0xF8B5D7, 0xF7DEEB), - LightGray( "gui.appliedenergistics2.LightGray", 0x9D9D9D, 0xCDCDCD, 0xEFEFEF ), + Gray("gui.appliedenergistics2.Gray", 0x7C7C7C, 0xA0A0A0, 0xC9C9C9), - Cyan( "gui.appliedenergistics2.Cyan", 0x2F9BA5, 0x51AAC6, 0xAEDDF4 ), + LightGray("gui.appliedenergistics2.LightGray", 0x9D9D9D, 0xCDCDCD, 0xEFEFEF), - Purple( "gui.appliedenergistics2.Purple", 0x8230B2, 0xA453CE, 0xC7A3CC ), + Cyan("gui.appliedenergistics2.Cyan", 0x2F9BA5, 0x51AAC6, 0xAEDDF4), - Blue( "gui.appliedenergistics2.Blue", 0x2D29A0, 0x514AFF, 0xDDE6FF ), + Purple("gui.appliedenergistics2.Purple", 0x8230B2, 0xA453CE, 0xC7A3CC), - Brown( "gui.appliedenergistics2.Brown", 0x724E35, 0xB7967F, 0xE0D2C8 ), + Blue("gui.appliedenergistics2.Blue", 0x2D29A0, 0x514AFF, 0xDDE6FF), - Green( "gui.appliedenergistics2.Green", 0x45A021, 0x60E32E, 0xE3F2E3 ), + Brown("gui.appliedenergistics2.Brown", 0x724E35, 0xB7967F, 0xE0D2C8), - Red( "gui.appliedenergistics2.Red", 0xA50029, 0xFF003C, 0xFFE6ED ), + Green("gui.appliedenergistics2.Green", 0x45A021, 0x60E32E, 0xE3F2E3), - Black( "gui.appliedenergistics2.Black", 0x2B2B2B, 0x565656, 0x848484 ), + Red("gui.appliedenergistics2.Red", 0xA50029, 0xFF003C, 0xFFE6ED), - Transparent( "gui.appliedenergistics2.Fluix", 0x1B2344, 0x895CA8, 0xD7BBEC ); + Black("gui.appliedenergistics2.Black", 0x2B2B2B, 0x565656, 0x848484), - public static final List VALID_COLORS = Arrays.asList( White, Orange, Magenta, LightBlue, Yellow, Lime, Pink, Gray, LightGray, Cyan, Purple, Blue, Brown, Green, Red, Black ); + Transparent("gui.appliedenergistics2.Fluix", 0x1B2344, 0x895CA8, 0xD7BBEC); - /** - * Unlocalized name for color. - */ - public final String unlocalizedName; + public static final List VALID_COLORS = Arrays.asList( + White, Orange, Magenta, LightBlue, Yellow, Lime, Pink, Gray, LightGray, Cyan, Purple, Blue, Brown, Green, + Red, Black); - /** - * Darkest Variant of the color, nearly black; as a RGB HEX Integer - */ - public final int blackVariant; + /** + * Unlocalized name for color. + */ + public final String unlocalizedName; - /** - * The Variant of the color that is used to represent the color normally; as a RGB HEX Integer - */ - public final int mediumVariant; + /** + * Darkest Variant of the color, nearly black; as a RGB HEX Integer + */ + public final int blackVariant; - /** - * Lightest Variant of the color, nearly white; as a RGB HEX Integer - */ - public final int whiteVariant; + /** + * The Variant of the color that is used to represent the color normally; as a RGB HEX Integer + */ + public final int mediumVariant; - AEColor( final String unlocalizedName, final int blackHex, final int medHex, final int whiteHex ) - { - this.unlocalizedName = unlocalizedName; - this.blackVariant = blackHex; - this.mediumVariant = medHex; - this.whiteVariant = whiteHex; - } + /** + * Lightest Variant of the color, nearly white; as a RGB HEX Integer + */ + public final int whiteVariant; - /** - * Logic to see which colors match each other.. special handle for Transparent - */ - public boolean matches( final AEColor color ) - { - return this == Transparent || color == Transparent || this == color; - } + AEColor(final String unlocalizedName, final int blackHex, final int medHex, final int whiteHex) { + this.unlocalizedName = unlocalizedName; + this.blackVariant = blackHex; + this.mediumVariant = medHex; + this.whiteVariant = whiteHex; + } - @Override - public String toString() - { - return StatCollector.translateToLocal( this.unlocalizedName ); - } + /** + * Logic to see which colors match each other.. special handle for Transparent + */ + public boolean matches(final AEColor color) { + return this == Transparent || color == Transparent || this == color; + } + @Override + public String toString() { + return StatCollector.translateToLocal(this.unlocalizedName); + } } diff --git a/src/main/java/appeng/api/util/AEColoredItemDefinition.java b/src/main/java/appeng/api/util/AEColoredItemDefinition.java index 331adca18d7..4c516c28102 100644 --- a/src/main/java/appeng/api/util/AEColoredItemDefinition.java +++ b/src/main/java/appeng/api/util/AEColoredItemDefinition.java @@ -23,48 +23,45 @@ package appeng.api.util; - import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +public interface AEColoredItemDefinition { -public interface AEColoredItemDefinition -{ - - /** - * @return the {@link Block} Implementation if applicable - */ - Block block( AEColor color ); + /** + * @return the {@link Block} Implementation if applicable + */ + Block block(AEColor color); - /** - * @return the {@link Item} Implementation if applicable - */ - Item item( AEColor color ); + /** + * @return the {@link Item} Implementation if applicable + */ + Item item(AEColor color); - /** - * @return the {@link TileEntity} Class if applicable. - */ - Class entity( AEColor color ); + /** + * @return the {@link TileEntity} Class if applicable. + */ + Class entity(AEColor color); - /** - * @return an {@link ItemStack} with specified quantity of this item. - */ - ItemStack stack( AEColor color, int stackSize ); + /** + * @return an {@link ItemStack} with specified quantity of this item. + */ + ItemStack stack(AEColor color, int stackSize); - /** - * @param stackSize - stack size of the result. - * @return an array of all colors. - */ - ItemStack[] allStacks( int stackSize ); + /** + * @param stackSize - stack size of the result. + * @return an array of all colors. + */ + ItemStack[] allStacks(int stackSize); - /** - * Compare {@link ItemStack} with this - * - * @param color compared color of item - * @param comparableItem compared item - * @return true if the item stack is a matching item. - */ - boolean sameAs( AEColor color, ItemStack comparableItem ); + /** + * Compare {@link ItemStack} with this + * + * @param color compared color of item + * @param comparableItem compared item + * @return true if the item stack is a matching item. + */ + boolean sameAs(AEColor color, ItemStack comparableItem); } diff --git a/src/main/java/appeng/api/util/AEItemDefinition.java b/src/main/java/appeng/api/util/AEItemDefinition.java index 1db0adf346e..047180905d3 100644 --- a/src/main/java/appeng/api/util/AEItemDefinition.java +++ b/src/main/java/appeng/api/util/AEItemDefinition.java @@ -23,80 +23,76 @@ package appeng.api.util; - import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IComparableDefinition; import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.ITileDefinition; +import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; -import javax.annotation.Nullable; - - /** * Gives easy access to different part of the various, items/blocks/materials in AE. * * @deprecated use {@link ITileDefinition} and its sub-classes */ @Deprecated -public interface AEItemDefinition -{ - /** - * @return the {@link Block} Implementation if applicable - * @deprecated use {@link IBlockDefinition#maybeBlock()} - */ - @Deprecated - @Nullable - Block block(); +public interface AEItemDefinition { + /** + * @return the {@link Block} Implementation if applicable + * @deprecated use {@link IBlockDefinition#maybeBlock()} + */ + @Deprecated + @Nullable + Block block(); - /** - * @return the {@link Item} Implementation if applicable - * @deprecated use {@link IItemDefinition#maybeItem()} - */ - @Deprecated - @Nullable - Item item(); + /** + * @return the {@link Item} Implementation if applicable + * @deprecated use {@link IItemDefinition#maybeItem()} + */ + @Deprecated + @Nullable + Item item(); - /** - * @return the {@link TileEntity} Class if applicable. - * @deprecated use {@link ITileDefinition#maybeEntity()} - */ - @Deprecated - @Nullable - Class entity(); + /** + * @return the {@link TileEntity} Class if applicable. + * @deprecated use {@link ITileDefinition#maybeEntity()} + */ + @Deprecated + @Nullable + Class entity(); - /** - * @return an {@link ItemStack} with specified quantity of this item. - * @deprecated use {@link IItemDefinition#maybeStack(int)} - */ - @Deprecated - @Nullable - ItemStack stack( int stackSize ); + /** + * @return an {@link ItemStack} with specified quantity of this item. + * @deprecated use {@link IItemDefinition#maybeStack(int)} + */ + @Deprecated + @Nullable + ItemStack stack(int stackSize); - /** - * Compare {@link ItemStack} with this - * - * @param comparableItem compared item - * @return true if the item stack is a matching item. - * @deprecated use {@link IComparableDefinition#isSameAs(ItemStack)} - */ - @Deprecated - boolean sameAsStack( ItemStack comparableItem ); + /** + * Compare {@link ItemStack} with this + * + * @param comparableItem compared item + * @return true if the item stack is a matching item. + * @deprecated use {@link IComparableDefinition#isSameAs(ItemStack)} + */ + @Deprecated + boolean sameAsStack(ItemStack comparableItem); - /** - * Compare Block with world. - * - * @param world world of block - * @param x x pos of block - * @param y y pos of block - * @param z z pos of block - * @return if the block is placed in the world at the specific location. - * @deprecated use {@link IComparableDefinition#isSameAs(IBlockAccess, int, int, int)} } - */ - @Deprecated - boolean sameAsBlock( IBlockAccess world, int x, int y, int z ); + /** + * Compare Block with world. + * + * @param world world of block + * @param x x pos of block + * @param y y pos of block + * @param z z pos of block + * @return if the block is placed in the world at the specific location. + * @deprecated use {@link IComparableDefinition#isSameAs(IBlockAccess, int, int, int)} } + */ + @Deprecated + boolean sameAsBlock(IBlockAccess world, int x, int y, int z); } diff --git a/src/main/java/appeng/api/util/DimensionalCoord.java b/src/main/java/appeng/api/util/DimensionalCoord.java index 426fd67b2c6..f0a20e7b394 100644 --- a/src/main/java/appeng/api/util/DimensionalCoord.java +++ b/src/main/java/appeng/api/util/DimensionalCoord.java @@ -23,86 +23,74 @@ package appeng.api.util; - import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; - /** * Represents a location in the Minecraft Universe */ -public class DimensionalCoord extends WorldCoord -{ - - private final World w; - private final int dimId; - - public DimensionalCoord( final DimensionalCoord s ) - { - super( s.x, s.y, s.z ); - this.w = s.w; - this.dimId = s.dimId; - } - - public DimensionalCoord( final TileEntity s ) - { - super( s ); - this.w = s.getWorldObj(); - this.dimId = this.w.provider.dimensionId; - } - - public DimensionalCoord( final World _w, final int _x, final int _y, final int _z ) - { - super( _x, _y, _z ); - this.w = _w; - this.dimId = _w.provider.dimensionId; - } - - public DimensionalCoord( final int _x, final int _y, final int _z, final int _dim ) - { - super( _x, _y, _z ); - this.w = null; - this.dimId = _dim; - } - - @Override - public DimensionalCoord copy() - { - return new DimensionalCoord( this ); - } - - @Override - public int hashCode() - { - return super.hashCode() ^ this.dimId; - } - - @Override - public boolean equals( final Object obj ) - { - return obj instanceof DimensionalCoord && this.isEqual( (DimensionalCoord) obj ); - } - - public boolean isEqual( final DimensionalCoord c ) - { - return this.x == c.x && this.y == c.y && this.z == c.z && c.w == this.w; - } - - @Override - public String toString() - { - return "dimension=" + this.dimId + ", " + super.toString(); - } - - public boolean isInWorld( final World world ) - { - return this.w == world; - } - - public World getWorld() - { - return this.w; - } - - public int getDimension() { return dimId; } +public class DimensionalCoord extends WorldCoord { + + private final World w; + private final int dimId; + + public DimensionalCoord(final DimensionalCoord s) { + super(s.x, s.y, s.z); + this.w = s.w; + this.dimId = s.dimId; + } + + public DimensionalCoord(final TileEntity s) { + super(s); + this.w = s.getWorldObj(); + this.dimId = this.w.provider.dimensionId; + } + + public DimensionalCoord(final World _w, final int _x, final int _y, final int _z) { + super(_x, _y, _z); + this.w = _w; + this.dimId = _w.provider.dimensionId; + } + + public DimensionalCoord(final int _x, final int _y, final int _z, final int _dim) { + super(_x, _y, _z); + this.w = null; + this.dimId = _dim; + } + + @Override + public DimensionalCoord copy() { + return new DimensionalCoord(this); + } + + @Override + public int hashCode() { + return super.hashCode() ^ this.dimId; + } + + @Override + public boolean equals(final Object obj) { + return obj instanceof DimensionalCoord && this.isEqual((DimensionalCoord) obj); + } + + public boolean isEqual(final DimensionalCoord c) { + return this.x == c.x && this.y == c.y && this.z == c.z && c.w == this.w; + } + + @Override + public String toString() { + return "dimension=" + this.dimId + ", " + super.toString(); + } + + public boolean isInWorld(final World world) { + return this.w == world; + } + + public World getWorld() { + return this.w; + } + + public int getDimension() { + return dimId; + } } diff --git a/src/main/java/appeng/api/util/ICommonTile.java b/src/main/java/appeng/api/util/ICommonTile.java index 6465e57da61..0b156ad0e12 100644 --- a/src/main/java/appeng/api/util/ICommonTile.java +++ b/src/main/java/appeng/api/util/ICommonTile.java @@ -23,25 +23,21 @@ package appeng.api.util; - +import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import java.util.List; - - -public interface ICommonTile -{ +public interface ICommonTile { - /** - * implemented on AE's Tile Entities, Gets a list of drops that the entity will normally drop, this doesn't include - * the block itself. - * - * @param world world of tile entity - * @param x x pos of tile entity - * @param y y pos of tile entity - * @param z z pos of tile entity - * @param drops drops of tile entity - */ - void getDrops( World world, int x, int y, int z, List drops ); -} \ No newline at end of file + /** + * implemented on AE's Tile Entities, Gets a list of drops that the entity will normally drop, this doesn't include + * the block itself. + * + * @param world world of tile entity + * @param x x pos of tile entity + * @param y y pos of tile entity + * @param z z pos of tile entity + * @param drops drops of tile entity + */ + void getDrops(World world, int x, int y, int z, List drops); +} diff --git a/src/main/java/appeng/api/util/IConfigManager.java b/src/main/java/appeng/api/util/IConfigManager.java index 553b1982b66..0abd7f57acf 100644 --- a/src/main/java/appeng/api/util/IConfigManager.java +++ b/src/main/java/appeng/api/util/IConfigManager.java @@ -23,64 +23,60 @@ package appeng.api.util; - import appeng.api.config.Settings; -import net.minecraft.nbt.NBTTagCompound; - import java.util.Set; - +import net.minecraft.nbt.NBTTagCompound; /** * Used to adjust settings on an object, *

* Obtained via {@link IConfigurableObject} */ -public interface IConfigManager -{ +public interface IConfigManager { - /** - * get a list of different settings - * - * @return enum set of settings - */ - Set getSettings(); + /** + * get a list of different settings + * + * @return enum set of settings + */ + Set getSettings(); - /** - * used to initialize the configuration manager, should be called for all settings. - * - * @param settingName name of setting - * @param defaultValue default value of setting - */ - void registerSetting( Settings settingName, Enum defaultValue ); + /** + * used to initialize the configuration manager, should be called for all settings. + * + * @param settingName name of setting + * @param defaultValue default value of setting + */ + void registerSetting(Settings settingName, Enum defaultValue); - /** - * Get Value of a particular setting - * - * @param settingName name of setting - * @return value of setting - */ - Enum getSetting( Settings settingName ); + /** + * Get Value of a particular setting + * + * @param settingName name of setting + * @return value of setting + */ + Enum getSetting(Settings settingName); - /** - * Change setting - * - * @param settingName to be changed setting - * @param newValue new value for setting - * @return changed setting - */ - Enum putSetting( Settings settingName, Enum newValue ); + /** + * Change setting + * + * @param settingName to be changed setting + * @param newValue new value for setting + * @return changed setting + */ + Enum putSetting(Settings settingName, Enum newValue); - /** - * write all settings to the NBT Tag so they can be read later. - * - * @param destination to be written nbt tag - */ - void writeToNBT( NBTTagCompound destination ); + /** + * write all settings to the NBT Tag so they can be read later. + * + * @param destination to be written nbt tag + */ + void writeToNBT(NBTTagCompound destination); - /** - * Only works after settings have been registered - * - * @param src to be read nbt tag - */ - void readFromNBT( NBTTagCompound src ); + /** + * Only works after settings have been registered + * + * @param src to be read nbt tag + */ + void readFromNBT(NBTTagCompound src); } diff --git a/src/main/java/appeng/api/util/IConfigurableObject.java b/src/main/java/appeng/api/util/IConfigurableObject.java index e25e74035fe..8c7a210f616 100644 --- a/src/main/java/appeng/api/util/IConfigurableObject.java +++ b/src/main/java/appeng/api/util/IConfigurableObject.java @@ -23,15 +23,13 @@ package appeng.api.util; - /** * Implemented by various Tiles or Parts in AE */ -public interface IConfigurableObject -{ +public interface IConfigurableObject { - /** - * get the config manager for the object. - */ - IConfigManager getConfigManager(); + /** + * get the config manager for the object. + */ + IConfigManager getConfigManager(); } diff --git a/src/main/java/appeng/api/util/INetworkToolAgent.java b/src/main/java/appeng/api/util/INetworkToolAgent.java index 915df02c553..70e135253d4 100644 --- a/src/main/java/appeng/api/util/INetworkToolAgent.java +++ b/src/main/java/appeng/api/util/INetworkToolAgent.java @@ -23,15 +23,12 @@ package appeng.api.util; - import net.minecraft.util.MovingObjectPosition; - /** * Implement on Tile or part to customize if the info gui opens, or an action is preformed. */ -public interface INetworkToolAgent -{ +public interface INetworkToolAgent { - boolean showNetworkInfo( MovingObjectPosition where ); + boolean showNetworkInfo(MovingObjectPosition where); } diff --git a/src/main/java/appeng/api/util/IOrientable.java b/src/main/java/appeng/api/util/IOrientable.java index fa53913c738..6f10711f41b 100644 --- a/src/main/java/appeng/api/util/IOrientable.java +++ b/src/main/java/appeng/api/util/IOrientable.java @@ -23,10 +23,8 @@ package appeng.api.util; - import net.minecraftforge.common.util.ForgeDirection; - /** * Nearly all of AE's Tile Entities implement IOrientable. *

@@ -34,29 +32,28 @@ *

* AE also responds to Block.rotateBlock */ -public interface IOrientable -{ - - /** - * @return true or false, if the tile rotation is meaningful, or even changeable - */ - boolean canBeRotated(); - - /** - * @return the direction the tile is facing - */ - ForgeDirection getForward(); - - /** - * @return the direction top of the tile - */ - ForgeDirection getUp(); - - /** - * Update the orientation - * - * @param Forward new forward direction - * @param Up new upwards direction - */ - void setOrientation( ForgeDirection Forward, ForgeDirection Up ); -} \ No newline at end of file +public interface IOrientable { + + /** + * @return true or false, if the tile rotation is meaningful, or even changeable + */ + boolean canBeRotated(); + + /** + * @return the direction the tile is facing + */ + ForgeDirection getForward(); + + /** + * @return the direction top of the tile + */ + ForgeDirection getUp(); + + /** + * Update the orientation + * + * @param Forward new forward direction + * @param Up new upwards direction + */ + void setOrientation(ForgeDirection Forward, ForgeDirection Up); +} diff --git a/src/main/java/appeng/api/util/IOrientableBlock.java b/src/main/java/appeng/api/util/IOrientableBlock.java index dea99d14d5d..3aa9be861da 100644 --- a/src/main/java/appeng/api/util/IOrientableBlock.java +++ b/src/main/java/appeng/api/util/IOrientableBlock.java @@ -23,27 +23,24 @@ package appeng.api.util; - import net.minecraft.world.IBlockAccess; - /** * Implemented on many of AE's non Tile Entity Blocks as a way to get a IOrientable. */ -public interface IOrientableBlock -{ +public interface IOrientableBlock { - /** - * @return if this block uses metadata to store its rotation. - */ - boolean usesMetadata(); + /** + * @return if this block uses metadata to store its rotation. + */ + boolean usesMetadata(); - /** - * @param world world of block - * @param x x pos of block - * @param y y pos of block - * @param z z pos of block - * @return a IOrientable if applicable - */ - IOrientable getOrientable( IBlockAccess world, int x, int y, int z ); -} \ No newline at end of file + /** + * @param world world of block + * @param x x pos of block + * @param y y pos of block + * @param z z pos of block + * @return a IOrientable if applicable + */ + IOrientable getOrientable(IBlockAccess world, int x, int y, int z); +} diff --git a/src/main/java/appeng/api/util/IReadOnlyCollection.java b/src/main/java/appeng/api/util/IReadOnlyCollection.java index 84e042ae7b6..86b57ab3154 100644 --- a/src/main/java/appeng/api/util/IReadOnlyCollection.java +++ b/src/main/java/appeng/api/util/IReadOnlyCollection.java @@ -23,22 +23,20 @@ package appeng.api.util; +public interface IReadOnlyCollection extends Iterable { -public interface IReadOnlyCollection extends Iterable -{ + /** + * @return the objects in in the set. + */ + int size(); - /** - * @return the objects in in the set. - */ - int size(); + /** + * @return true if there are objects in the set + */ + boolean isEmpty(); - /** - * @return true if there are objects in the set - */ - boolean isEmpty(); - - /** - * @return return true if the object is part of the set. - */ - boolean contains( Object node ); + /** + * @return return true if the object is part of the set. + */ + boolean contains(Object node); } diff --git a/src/main/java/appeng/api/util/WorldCoord.java b/src/main/java/appeng/api/util/WorldCoord.java index 1a4b16fbe40..e6e8dd44059 100644 --- a/src/main/java/appeng/api/util/WorldCoord.java +++ b/src/main/java/appeng/api/util/WorldCoord.java @@ -23,169 +23,144 @@ package appeng.api.util; - import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; - /** * Represents a relative coordinate, either relative to another object, or * relative to the origin of a dimension. */ -public class WorldCoord -{ - - public int x; - public int y; - public int z; - - public WorldCoord( final TileEntity s ) - { - this( s.xCoord, s.yCoord, s.zCoord ); - } - - public WorldCoord( final int _x, final int _y, final int _z ) - { - this.x = _x; - this.y = _y; - this.z = _z; - } - - public WorldCoord subtract( final ForgeDirection direction, final int length ) - { - this.x -= direction.offsetX * length; - this.y -= direction.offsetY * length; - this.z -= direction.offsetZ * length; - return this; - } - - public WorldCoord add( final int _x, final int _y, final int _z ) - { - this.x += _x; - this.y += _y; - this.z += _z; - return this; - } - - public WorldCoord subtract( final int _x, final int _y, final int _z ) - { - this.x -= _x; - this.y -= _y; - this.z -= _z; - return this; - } - - public WorldCoord multiple( final int _x, final int _y, final int _z ) - { - this.x *= _x; - this.y *= _y; - this.z *= _z; - return this; - } - - public WorldCoord divide( final int _x, final int _y, final int _z ) - { - this.x /= _x; - this.y /= _y; - this.z /= _z; - return this; - } - - /** - * Will Return NULL if it's at some diagonal! - */ - public ForgeDirection directionTo( final WorldCoord loc ) - { - final int ox = this.x - loc.x; - final int oy = this.y - loc.y; - final int oz = this.z - loc.z; - - final int xlen = Math.abs( ox ); - final int ylen = Math.abs( oy ); - final int zlen = Math.abs( oz ); - - if( loc.isEqual( this.copy().add( ForgeDirection.EAST, xlen ) ) ) - { - return ForgeDirection.EAST; - } - - if( loc.isEqual( this.copy().add( ForgeDirection.WEST, xlen ) ) ) - { - return ForgeDirection.WEST; - } - - if( loc.isEqual( this.copy().add( ForgeDirection.NORTH, zlen ) ) ) - { - return ForgeDirection.NORTH; - } - - if( loc.isEqual( this.copy().add( ForgeDirection.SOUTH, zlen ) ) ) - { - return ForgeDirection.SOUTH; - } - - if( loc.isEqual( this.copy().add( ForgeDirection.UP, ylen ) ) ) - { - return ForgeDirection.UP; - } - - if( loc.isEqual( this.copy().add( ForgeDirection.DOWN, ylen ) ) ) - { - return ForgeDirection.DOWN; - } - - return null; - } - - public double distanceTo( final WorldCoord c ) - { - double dx = c.x - x; - double dy = c.y - y; - double dz = c.z - z; - return Math.sqrt(dx*dx + dy*dy + dz*dz); - } - - public static long getTaxicabDistance( WorldCoord blockPos, WorldCoord blockPos2 ) - { - long dx = Math.abs(blockPos.x - blockPos2.x); - long dy = Math.abs(blockPos.y - blockPos2.y); - long dz = Math.abs(blockPos.z - blockPos2.z); - return dx + dy + dz; - } - - public boolean isEqual( final WorldCoord c ) - { - return this.x == c.x && this.y == c.y && this.z == c.z; - } - - public WorldCoord add( final ForgeDirection direction, final int length ) - { - this.x += direction.offsetX * length; - this.y += direction.offsetY * length; - this.z += direction.offsetZ * length; - return this; - } - - public WorldCoord copy() - { - return new WorldCoord( this.x, this.y, this.z ); - } - - @Override - public int hashCode() - { - return ( this.y << 24 ) ^ this.x ^ this.z; - } - - @Override - public boolean equals( final Object obj ) - { - return obj instanceof WorldCoord && this.isEqual( (WorldCoord) obj ); - } - - @Override - public String toString() - { - return "x=" + this.x + ", y=" + this.y + ", z=" + this.z; - } +public class WorldCoord { + + public int x; + public int y; + public int z; + + public WorldCoord(final TileEntity s) { + this(s.xCoord, s.yCoord, s.zCoord); + } + + public WorldCoord(final int _x, final int _y, final int _z) { + this.x = _x; + this.y = _y; + this.z = _z; + } + + public WorldCoord subtract(final ForgeDirection direction, final int length) { + this.x -= direction.offsetX * length; + this.y -= direction.offsetY * length; + this.z -= direction.offsetZ * length; + return this; + } + + public WorldCoord add(final int _x, final int _y, final int _z) { + this.x += _x; + this.y += _y; + this.z += _z; + return this; + } + + public WorldCoord subtract(final int _x, final int _y, final int _z) { + this.x -= _x; + this.y -= _y; + this.z -= _z; + return this; + } + + public WorldCoord multiple(final int _x, final int _y, final int _z) { + this.x *= _x; + this.y *= _y; + this.z *= _z; + return this; + } + + public WorldCoord divide(final int _x, final int _y, final int _z) { + this.x /= _x; + this.y /= _y; + this.z /= _z; + return this; + } + + /** + * Will Return NULL if it's at some diagonal! + */ + public ForgeDirection directionTo(final WorldCoord loc) { + final int ox = this.x - loc.x; + final int oy = this.y - loc.y; + final int oz = this.z - loc.z; + + final int xlen = Math.abs(ox); + final int ylen = Math.abs(oy); + final int zlen = Math.abs(oz); + + if (loc.isEqual(this.copy().add(ForgeDirection.EAST, xlen))) { + return ForgeDirection.EAST; + } + + if (loc.isEqual(this.copy().add(ForgeDirection.WEST, xlen))) { + return ForgeDirection.WEST; + } + + if (loc.isEqual(this.copy().add(ForgeDirection.NORTH, zlen))) { + return ForgeDirection.NORTH; + } + + if (loc.isEqual(this.copy().add(ForgeDirection.SOUTH, zlen))) { + return ForgeDirection.SOUTH; + } + + if (loc.isEqual(this.copy().add(ForgeDirection.UP, ylen))) { + return ForgeDirection.UP; + } + + if (loc.isEqual(this.copy().add(ForgeDirection.DOWN, ylen))) { + return ForgeDirection.DOWN; + } + + return null; + } + + public double distanceTo(final WorldCoord c) { + double dx = c.x - x; + double dy = c.y - y; + double dz = c.z - z; + return Math.sqrt(dx * dx + dy * dy + dz * dz); + } + + public static long getTaxicabDistance(WorldCoord blockPos, WorldCoord blockPos2) { + long dx = Math.abs(blockPos.x - blockPos2.x); + long dy = Math.abs(blockPos.y - blockPos2.y); + long dz = Math.abs(blockPos.z - blockPos2.z); + return dx + dy + dz; + } + + public boolean isEqual(final WorldCoord c) { + return this.x == c.x && this.y == c.y && this.z == c.z; + } + + public WorldCoord add(final ForgeDirection direction, final int length) { + this.x += direction.offsetX * length; + this.y += direction.offsetY * length; + this.z += direction.offsetZ * length; + return this; + } + + public WorldCoord copy() { + return new WorldCoord(this.x, this.y, this.z); + } + + @Override + public int hashCode() { + return (this.y << 24) ^ this.x ^ this.z; + } + + @Override + public boolean equals(final Object obj) { + return obj instanceof WorldCoord && this.isEqual((WorldCoord) obj); + } + + @Override + public String toString() { + return "x=" + this.x + ", y=" + this.y + ", z=" + this.z; + } } diff --git a/src/main/java/appeng/block/AEBaseBlock.java b/src/main/java/appeng/block/AEBaseBlock.java index 3b0e55fb7fe..98f5de0eb55 100644 --- a/src/main/java/appeng/block/AEBaseBlock.java +++ b/src/main/java/appeng/block/AEBaseBlock.java @@ -18,7 +18,6 @@ package appeng.block; - import appeng.api.util.IOrientable; import appeng.api.util.IOrientableBlock; import appeng.client.render.BaseBlockRender; @@ -35,6 +34,9 @@ import com.google.common.base.Optional; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; @@ -50,564 +52,497 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; - - -public abstract class AEBaseBlock extends Block implements IAEFeature -{ - private final String featureFullName; - protected final Optional featureSubName; - protected boolean isOpaque = true; - protected boolean isFullSize = true; - protected boolean hasSubtypes = false; - protected boolean isInventory = false; - private IFeatureHandler handler; - @SideOnly( Side.CLIENT ) - private BlockRenderInfo renderInfo; - - protected AEBaseBlock( final Material mat ) - { - this( mat, Optional.absent() ); - this.setLightOpacity( 255 ); - this.setLightLevel( 0 ); - this.setHardness( 2.2F ); - this.setHarvestLevel( "pickaxe", 0 ); - } - - protected AEBaseBlock( final Material mat, final Optional subName ) - { - super( mat ); - - if( mat == AEGlassMaterial.INSTANCE || mat == Material.glass ) - { - this.setStepSound( Block.soundTypeGlass ); - } - else if( mat == Material.rock ) - { - this.setStepSound( Block.soundTypeStone ); - } - else if( mat == Material.wood ) - { - this.setStepSound( Block.soundTypeWood ); - } - else - { - this.setStepSound( Block.soundTypeMetal ); - } - - this.featureFullName = new FeatureNameExtractor( this.getClass(), subName ).get(); - this.featureSubName = subName; - } - - @Override - public String toString() - { - return this.featureFullName; - } - - public void registerNoIcons() - { - final BlockRenderInfo info = this.getRendererInstance(); - final FlippableIcon i = new FlippableIcon( new MissingIcon( this ) ); - info.updateIcons( i, i, i, i, i, i ); - } - - @SideOnly( Side.CLIENT ) - public BlockRenderInfo getRendererInstance() - { - if( this.renderInfo != null ) - { - return this.renderInfo; - } - - final BaseBlockRender renderer = this.getRenderer(); - this.renderInfo = new BlockRenderInfo( renderer ); - - return this.renderInfo; - } - - /** - * Factory method to create a new render instance. - * - * @return the newly created instance. - */ - @SideOnly( Side.CLIENT ) - protected BaseBlockRender getRenderer() - { - return new BaseBlockRender(); - } - - IIcon unmappedGetIcon( final IBlockAccess w, final int x, final int y, final int z, final int s ) - { - return super.getIcon( w, x, y, z, s ); - } - - protected void setFeature( final EnumSet f ) - { - final AEBlockFeatureHandler featureHandler = new AEBlockFeatureHandler( f, this, this.featureSubName ); - this.setHandler( featureHandler ); - } - - @Override - public final IFeatureHandler handler() - { - return this.handler; - } - - protected final void setHandler( final IFeatureHandler handler ) - { - this.handler = handler; - } - - @Override - public void postInit() - { - // override! - } - - public boolean isOpaque() - { - return this.isOpaque; - } - - @Override - public boolean renderAsNormalBlock() - { - return this.isFullSize && this.isOpaque; - } - - @Override - @SideOnly( Side.CLIENT ) - public int getRenderType() - { - return WorldRender.INSTANCE.getRenderId(); - } - - @Override - public IIcon getIcon( final IBlockAccess w, final int x, final int y, final int z, final int s ) - { - return this.getIcon( this.mapRotation( w, x, y, z, s ), w.getBlockMetadata( x, y, z ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getIcon( final int direction, final int metadata ) - { - return this.getRendererInstance().getTexture( ForgeDirection.getOrientation( direction ) ); - } - - protected ICustomCollision getCustomCollision( final World w, final int x, final int y, final int z ) - { - if( this instanceof ICustomCollision ) - { - return (ICustomCollision) this; - } - return null; - } - - @Override - @SuppressWarnings( "unchecked" ) - // NOTE: WAS FINAL, changed for Immibis - public void addCollisionBoxesToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - final ICustomCollision collisionHandler = this.getCustomCollision( w, x, y, z ); - - if( collisionHandler != null && bb != null ) - { - final List tmp = new ArrayList(); - collisionHandler.addCollidingBlockToList( w, x, y, z, bb, tmp, e ); - for( final AxisAlignedBB b : tmp ) - { - b.minX += x; - b.minY += y; - b.minZ += z; - b.maxX += x; - b.maxY += y; - b.maxZ += z; - if( bb.intersectsWith( b ) ) - { - out.add( b ); - } - } - } - else - { - super.addCollisionBoxesToList( w, x, y, z, bb, out, e ); - } - } - - @Override - @SideOnly( Side.CLIENT ) - public final AxisAlignedBB getSelectedBoundingBoxFromPool( final World w, final int x, final int y, final int z ) - { - final ICustomCollision collisionHandler = this.getCustomCollision( w, x, y, z ); - - if( collisionHandler != null ) - { - if( Platform.isClient() ) - { - final EntityPlayer player = Minecraft.getMinecraft().thePlayer; - final LookDirection ld = Platform.getPlayerRay( player, Platform.getEyeOffset( player ) ); - - final Iterable bbs = collisionHandler.getSelectedBoundingBoxesFromPool( w, x, y, z, Minecraft.getMinecraft().thePlayer, true ); - AxisAlignedBB br = null; - - double lastDist = 0; - - for( final AxisAlignedBB bb : bbs ) - { - this.setBlockBounds( (float) bb.minX, (float) bb.minY, (float) bb.minZ, (float) bb.maxX, (float) bb.maxY, (float) bb.maxZ ); - - final MovingObjectPosition r = super.collisionRayTrace( w, x, y, z, ld.getA(), ld.getB() ); - - this.setBlockBounds( 0, 0, 0, 1, 1, 1 ); - - if( r != null ) - { - final double xLen = ( ld.getA().xCoord - r.hitVec.xCoord ); - final double yLen = ( ld.getA().yCoord - r.hitVec.yCoord ); - final double zLen = ( ld.getA().zCoord - r.hitVec.zCoord ); - - final double thisDist = xLen * xLen + yLen * yLen + zLen * zLen; - - if( br == null || lastDist > thisDist ) - { - lastDist = thisDist; - br = bb; - } - } - } - - if( br != null ) - { - br.setBounds( br.minX + x, br.minY + y, br.minZ + z, br.maxX + x, br.maxY + y, br.maxZ + z ); - return br; - } - } - - final AxisAlignedBB b = AxisAlignedBB.getBoundingBox( 16d, 16d, 16d, 0d, 0d, 0d ); - - for( final AxisAlignedBB bx : collisionHandler.getSelectedBoundingBoxesFromPool( w, x, y, z, null, false ) ) - { - final double minX = Math.min( b.minX, bx.minX ); - final double minY = Math.min( b.minY, bx.minY ); - final double minZ = Math.min( b.minZ, bx.minZ ); - final double maxX = Math.max( b.maxX, bx.maxX ); - final double maxY = Math.max( b.maxY, bx.maxY ); - final double maxZ = Math.max( b.maxZ, bx.maxZ ); - - b.setBounds( minX, minY, minZ, maxX, maxY, maxZ ); - } - - b.setBounds( b.minX + x, b.minY + y, b.minZ + z, b.maxX + x, b.maxY + y, b.maxZ + z ); - - return b; - } - - return super.getSelectedBoundingBoxFromPool( w, x, y, z ); - } - - @Override - public final boolean isOpaqueCube() - { - return this.isOpaque; - } - - @Override - public MovingObjectPosition collisionRayTrace( final World w, final int x, final int y, final int z, final Vec3 a, final Vec3 b ) - { - final ICustomCollision collisionHandler = this.getCustomCollision( w, x, y, z ); - - if( collisionHandler != null ) - { - final Iterable bbs = collisionHandler.getSelectedBoundingBoxesFromPool( w, x, y, z, null, true ); - MovingObjectPosition br = null; - - double lastDist = 0; - - for( final AxisAlignedBB bb : bbs ) - { - this.setBlockBounds( (float) bb.minX, (float) bb.minY, (float) bb.minZ, (float) bb.maxX, (float) bb.maxY, (float) bb.maxZ ); - - final MovingObjectPosition r = super.collisionRayTrace( w, x, y, z, a, b ); - - this.setBlockBounds( 0, 0, 0, 1, 1, 1 ); - - if( r != null ) - { - final double xLen = ( a.xCoord - r.hitVec.xCoord ); - final double yLen = ( a.yCoord - r.hitVec.yCoord ); - final double zLen = ( a.zCoord - r.hitVec.zCoord ); - - final double thisDist = xLen * xLen + yLen * yLen + zLen * zLen; - if( br == null || lastDist > thisDist ) - { - lastDist = thisDist; - br = r; - } - } - } - - if( br != null ) - { - return br; - } - - return null; - } - - this.setBlockBounds( 0, 0, 0, 1, 1, 1 ); - return super.collisionRayTrace( w, x, y, z, a, b ); - } - - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - return false; - } - - @Override - @SideOnly( Side.CLIENT ) - @SuppressWarnings( "unchecked" ) - public final void getSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - this.getCheckedSubBlocks( item, tabs, itemStacks ); - } - - @Override - public boolean hasComparatorInputOverride() - { - return this.isInventory; - } - - @Override - public int getComparatorInputOverride( final World w, final int x, final int y, final int z, final int s ) - { - return 0; - } - - @Override - @SideOnly( Side.CLIENT ) - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - final BlockRenderInfo info = this.getRendererInstance(); - final FlippableIcon topIcon = this.optionalIcon( iconRegistry, this.getTextureName(), null ); - final FlippableIcon bottomIcon = this.optionalIcon( iconRegistry, this.getTextureName() + "Bottom", topIcon ); - final FlippableIcon sideIcon = this.optionalIcon( iconRegistry, this.getTextureName() + "Side", topIcon ); - final FlippableIcon eastIcon = this.optionalIcon( iconRegistry, this.getTextureName() + "East", sideIcon ); - final FlippableIcon westIcon = this.optionalIcon( iconRegistry, this.getTextureName() + "West", sideIcon ); - final FlippableIcon southIcon = this.optionalIcon( iconRegistry, this.getTextureName() + "Front", sideIcon ); - final FlippableIcon northIcon = this.optionalIcon( iconRegistry, this.getTextureName() + "Back", sideIcon ); - - this.blockIcon = topIcon; - - info.updateIcons( bottomIcon, topIcon, northIcon, southIcon, eastIcon, westIcon ); - } - - @Override - public final boolean isNormalCube( final IBlockAccess world, final int x, final int y, final int z ) - { - return this.isFullSize; - } - - public IOrientable getOrientable( final IBlockAccess w, final int x, final int y, final int z ) - { - if( this instanceof IOrientableBlock ) - { - return this.getOrientable( w, x, y, z ); - } - return null; - } - - @Override - public final boolean rotateBlock( final World w, final int x, final int y, final int z, final ForgeDirection axis ) - { - final IOrientable rotatable = this.getOrientable( w, x, y, z ); - - if( rotatable != null && rotatable.canBeRotated() ) - { - if( this.hasCustomRotation() ) - { - this.customRotateBlock( rotatable, axis ); - return true; - } - else - { - ForgeDirection forward = rotatable.getForward(); - ForgeDirection up = rotatable.getUp(); - - for( int rs = 0; rs < 4; rs++ ) - { - forward = Platform.rotateAround( forward, axis ); - up = Platform.rotateAround( up, axis ); - - if( this.isValidOrientation( w, x, y, z, forward, up ) ) - { - rotatable.setOrientation( forward, up ); - return true; - } - } - } - } - - return super.rotateBlock( w, x, y, z, axis ); - } - - protected boolean hasCustomRotation() - { - return false; - } - - protected void customRotateBlock( final IOrientable rotatable, final ForgeDirection axis ) - { - - } - - public boolean isValidOrientation( final World w, final int x, final int y, final int z, final ForgeDirection forward, final ForgeDirection up ) - { - return true; - } - - @Override - public ForgeDirection[] getValidRotations( final World w, final int x, final int y, final int z ) - { - return new ForgeDirection[0]; - } - - @SideOnly( Side.CLIENT ) - private FlippableIcon optionalIcon( final IIconRegister ir, final String name, IIcon substitute ) - { - // if the input is an flippable IIcon find the original. - while( substitute instanceof FlippableIcon ) - { - substitute = ( (FlippableIcon) substitute ).getOriginal(); - } - - if( substitute != null ) - { - try - { - ResourceLocation resLoc = new ResourceLocation( name ); - resLoc = new ResourceLocation( resLoc.getResourceDomain(), String.format( "%s/%s%s", "textures/blocks", resLoc.getResourcePath(), ".png" ) ); - - final IResource res = Minecraft.getMinecraft().getResourceManager().getResource( resLoc ); - if( res != null ) - { - return new FlippableIcon( ir.registerIcon( name ) ); - } - } - catch( final Throwable e ) - { - return new FlippableIcon( substitute ); - } - } - - return new FlippableIcon( ir.registerIcon( name ) ); - } - - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - super.getSubBlocks( item, tabs, itemStacks ); - } - - private int mapRotation( final IBlockAccess w, final int x, final int y, final int z, final int s ) - { - final IOrientable ori = this.getOrientable( w, x, y, z ); - - if( ori != null && ori.canBeRotated() ) - { - return this.mapRotation( ori, ForgeDirection.getOrientation( s ) ).ordinal(); - } - - return s; - } - - public ForgeDirection mapRotation( final IOrientable ori, final ForgeDirection dir ) - { - // case DOWN: return bottomIcon; - // case UP: return blockIcon; - // case NORTH: return northIcon; - // case SOUTH: return southIcon; - // case WEST: return sideIcon; - // case EAST: return sideIcon; - - final ForgeDirection forward = ori.getForward(); - final ForgeDirection up = ori.getUp(); - - if( forward == null || up == null ) - { - return dir; - } - - final int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; - final int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; - final int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; - - ForgeDirection west = ForgeDirection.UNKNOWN; - for( final ForgeDirection dx : ForgeDirection.VALID_DIRECTIONS ) - { - if( dx.offsetX == west_x && dx.offsetY == west_y && dx.offsetZ == west_z ) - { - west = dx; - } - } - - if( dir == forward ) - { - return ForgeDirection.SOUTH; - } - if( dir == forward.getOpposite() ) - { - return ForgeDirection.NORTH; - } - - if( dir == up ) - { - return ForgeDirection.UP; - } - if( dir == up.getOpposite() ) - { - return ForgeDirection.DOWN; - } - - if( dir == west ) - { - return ForgeDirection.WEST; - } - if( dir == west.getOpposite() ) - { - return ForgeDirection.EAST; - } - - return ForgeDirection.UNKNOWN; - } - - @SideOnly( Side.CLIENT ) - public void setRenderStateByMeta( final int itemDamage ) - { - - } - - public String getUnlocalizedName( final ItemStack is ) - { - return this.getUnlocalizedName(); - } - - void addInformation( final ItemStack is, final EntityPlayer player, final List lines, final boolean advancedItemTooltips ) - { - - } - - public Class getItemBlockClass() - { - return AEBaseItemBlock.class; - } - - public boolean hasSubtypes() - { - return this.hasSubtypes; - } - +public abstract class AEBaseBlock extends Block implements IAEFeature { + private final String featureFullName; + protected final Optional featureSubName; + protected boolean isOpaque = true; + protected boolean isFullSize = true; + protected boolean hasSubtypes = false; + protected boolean isInventory = false; + private IFeatureHandler handler; + + @SideOnly(Side.CLIENT) + private BlockRenderInfo renderInfo; + + protected AEBaseBlock(final Material mat) { + this(mat, Optional.absent()); + this.setLightOpacity(255); + this.setLightLevel(0); + this.setHardness(2.2F); + this.setHarvestLevel("pickaxe", 0); + } + + protected AEBaseBlock(final Material mat, final Optional subName) { + super(mat); + + if (mat == AEGlassMaterial.INSTANCE || mat == Material.glass) { + this.setStepSound(Block.soundTypeGlass); + } else if (mat == Material.rock) { + this.setStepSound(Block.soundTypeStone); + } else if (mat == Material.wood) { + this.setStepSound(Block.soundTypeWood); + } else { + this.setStepSound(Block.soundTypeMetal); + } + + this.featureFullName = new FeatureNameExtractor(this.getClass(), subName).get(); + this.featureSubName = subName; + } + + @Override + public String toString() { + return this.featureFullName; + } + + public void registerNoIcons() { + final BlockRenderInfo info = this.getRendererInstance(); + final FlippableIcon i = new FlippableIcon(new MissingIcon(this)); + info.updateIcons(i, i, i, i, i, i); + } + + @SideOnly(Side.CLIENT) + public BlockRenderInfo getRendererInstance() { + if (this.renderInfo != null) { + return this.renderInfo; + } + + final BaseBlockRender renderer = this.getRenderer(); + this.renderInfo = new BlockRenderInfo(renderer); + + return this.renderInfo; + } + + /** + * Factory method to create a new render instance. + * + * @return the newly created instance. + */ + @SideOnly(Side.CLIENT) + protected BaseBlockRender getRenderer() { + return new BaseBlockRender(); + } + + IIcon unmappedGetIcon(final IBlockAccess w, final int x, final int y, final int z, final int s) { + return super.getIcon(w, x, y, z, s); + } + + protected void setFeature(final EnumSet f) { + final AEBlockFeatureHandler featureHandler = new AEBlockFeatureHandler(f, this, this.featureSubName); + this.setHandler(featureHandler); + } + + @Override + public final IFeatureHandler handler() { + return this.handler; + } + + protected final void setHandler(final IFeatureHandler handler) { + this.handler = handler; + } + + @Override + public void postInit() { + // override! + } + + public boolean isOpaque() { + return this.isOpaque; + } + + @Override + public boolean renderAsNormalBlock() { + return this.isFullSize && this.isOpaque; + } + + @Override + @SideOnly(Side.CLIENT) + public int getRenderType() { + return WorldRender.INSTANCE.getRenderId(); + } + + @Override + public IIcon getIcon(final IBlockAccess w, final int x, final int y, final int z, final int s) { + return this.getIcon(this.mapRotation(w, x, y, z, s), w.getBlockMetadata(x, y, z)); + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(final int direction, final int metadata) { + return this.getRendererInstance().getTexture(ForgeDirection.getOrientation(direction)); + } + + protected ICustomCollision getCustomCollision(final World w, final int x, final int y, final int z) { + if (this instanceof ICustomCollision) { + return (ICustomCollision) this; + } + return null; + } + + @Override + @SuppressWarnings("unchecked") + // NOTE: WAS FINAL, changed for Immibis + public void addCollisionBoxesToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e) { + final ICustomCollision collisionHandler = this.getCustomCollision(w, x, y, z); + + if (collisionHandler != null && bb != null) { + final List tmp = new ArrayList(); + collisionHandler.addCollidingBlockToList(w, x, y, z, bb, tmp, e); + for (final AxisAlignedBB b : tmp) { + b.minX += x; + b.minY += y; + b.minZ += z; + b.maxX += x; + b.maxY += y; + b.maxZ += z; + if (bb.intersectsWith(b)) { + out.add(b); + } + } + } else { + super.addCollisionBoxesToList(w, x, y, z, bb, out, e); + } + } + + @Override + @SideOnly(Side.CLIENT) + public final AxisAlignedBB getSelectedBoundingBoxFromPool(final World w, final int x, final int y, final int z) { + final ICustomCollision collisionHandler = this.getCustomCollision(w, x, y, z); + + if (collisionHandler != null) { + if (Platform.isClient()) { + final EntityPlayer player = Minecraft.getMinecraft().thePlayer; + final LookDirection ld = Platform.getPlayerRay(player, Platform.getEyeOffset(player)); + + final Iterable bbs = collisionHandler.getSelectedBoundingBoxesFromPool( + w, x, y, z, Minecraft.getMinecraft().thePlayer, true); + AxisAlignedBB br = null; + + double lastDist = 0; + + for (final AxisAlignedBB bb : bbs) { + this.setBlockBounds( + (float) bb.minX, (float) bb.minY, (float) bb.minZ, (float) bb.maxX, (float) bb.maxY, (float) + bb.maxZ); + + final MovingObjectPosition r = super.collisionRayTrace(w, x, y, z, ld.getA(), ld.getB()); + + this.setBlockBounds(0, 0, 0, 1, 1, 1); + + if (r != null) { + final double xLen = (ld.getA().xCoord - r.hitVec.xCoord); + final double yLen = (ld.getA().yCoord - r.hitVec.yCoord); + final double zLen = (ld.getA().zCoord - r.hitVec.zCoord); + + final double thisDist = xLen * xLen + yLen * yLen + zLen * zLen; + + if (br == null || lastDist > thisDist) { + lastDist = thisDist; + br = bb; + } + } + } + + if (br != null) { + br.setBounds(br.minX + x, br.minY + y, br.minZ + z, br.maxX + x, br.maxY + y, br.maxZ + z); + return br; + } + } + + final AxisAlignedBB b = AxisAlignedBB.getBoundingBox(16d, 16d, 16d, 0d, 0d, 0d); + + for (final AxisAlignedBB bx : collisionHandler.getSelectedBoundingBoxesFromPool(w, x, y, z, null, false)) { + final double minX = Math.min(b.minX, bx.minX); + final double minY = Math.min(b.minY, bx.minY); + final double minZ = Math.min(b.minZ, bx.minZ); + final double maxX = Math.max(b.maxX, bx.maxX); + final double maxY = Math.max(b.maxY, bx.maxY); + final double maxZ = Math.max(b.maxZ, bx.maxZ); + + b.setBounds(minX, minY, minZ, maxX, maxY, maxZ); + } + + b.setBounds(b.minX + x, b.minY + y, b.minZ + z, b.maxX + x, b.maxY + y, b.maxZ + z); + + return b; + } + + return super.getSelectedBoundingBoxFromPool(w, x, y, z); + } + + @Override + public final boolean isOpaqueCube() { + return this.isOpaque; + } + + @Override + public MovingObjectPosition collisionRayTrace( + final World w, final int x, final int y, final int z, final Vec3 a, final Vec3 b) { + final ICustomCollision collisionHandler = this.getCustomCollision(w, x, y, z); + + if (collisionHandler != null) { + final Iterable bbs = + collisionHandler.getSelectedBoundingBoxesFromPool(w, x, y, z, null, true); + MovingObjectPosition br = null; + + double lastDist = 0; + + for (final AxisAlignedBB bb : bbs) { + this.setBlockBounds( + (float) bb.minX, (float) bb.minY, (float) bb.minZ, (float) bb.maxX, (float) bb.maxY, (float) + bb.maxZ); + + final MovingObjectPosition r = super.collisionRayTrace(w, x, y, z, a, b); + + this.setBlockBounds(0, 0, 0, 1, 1, 1); + + if (r != null) { + final double xLen = (a.xCoord - r.hitVec.xCoord); + final double yLen = (a.yCoord - r.hitVec.yCoord); + final double zLen = (a.zCoord - r.hitVec.zCoord); + + final double thisDist = xLen * xLen + yLen * yLen + zLen * zLen; + if (br == null || lastDist > thisDist) { + lastDist = thisDist; + br = r; + } + } + } + + if (br != null) { + return br; + } + + return null; + } + + this.setBlockBounds(0, 0, 0, 1, 1, 1); + return super.collisionRayTrace(w, x, y, z, a, b); + } + + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + return false; + } + + @Override + @SideOnly(Side.CLIENT) + @SuppressWarnings("unchecked") + public final void getSubBlocks(final Item item, final CreativeTabs tabs, final List itemStacks) { + this.getCheckedSubBlocks(item, tabs, itemStacks); + } + + @Override + public boolean hasComparatorInputOverride() { + return this.isInventory; + } + + @Override + public int getComparatorInputOverride(final World w, final int x, final int y, final int z, final int s) { + return 0; + } + + @Override + @SideOnly(Side.CLIENT) + public void registerBlockIcons(final IIconRegister iconRegistry) { + final BlockRenderInfo info = this.getRendererInstance(); + final FlippableIcon topIcon = this.optionalIcon(iconRegistry, this.getTextureName(), null); + final FlippableIcon bottomIcon = this.optionalIcon(iconRegistry, this.getTextureName() + "Bottom", topIcon); + final FlippableIcon sideIcon = this.optionalIcon(iconRegistry, this.getTextureName() + "Side", topIcon); + final FlippableIcon eastIcon = this.optionalIcon(iconRegistry, this.getTextureName() + "East", sideIcon); + final FlippableIcon westIcon = this.optionalIcon(iconRegistry, this.getTextureName() + "West", sideIcon); + final FlippableIcon southIcon = this.optionalIcon(iconRegistry, this.getTextureName() + "Front", sideIcon); + final FlippableIcon northIcon = this.optionalIcon(iconRegistry, this.getTextureName() + "Back", sideIcon); + + this.blockIcon = topIcon; + + info.updateIcons(bottomIcon, topIcon, northIcon, southIcon, eastIcon, westIcon); + } + + @Override + public final boolean isNormalCube(final IBlockAccess world, final int x, final int y, final int z) { + return this.isFullSize; + } + + public IOrientable getOrientable(final IBlockAccess w, final int x, final int y, final int z) { + if (this instanceof IOrientableBlock) { + return this.getOrientable(w, x, y, z); + } + return null; + } + + @Override + public final boolean rotateBlock(final World w, final int x, final int y, final int z, final ForgeDirection axis) { + final IOrientable rotatable = this.getOrientable(w, x, y, z); + + if (rotatable != null && rotatable.canBeRotated()) { + if (this.hasCustomRotation()) { + this.customRotateBlock(rotatable, axis); + return true; + } else { + ForgeDirection forward = rotatable.getForward(); + ForgeDirection up = rotatable.getUp(); + + for (int rs = 0; rs < 4; rs++) { + forward = Platform.rotateAround(forward, axis); + up = Platform.rotateAround(up, axis); + + if (this.isValidOrientation(w, x, y, z, forward, up)) { + rotatable.setOrientation(forward, up); + return true; + } + } + } + } + + return super.rotateBlock(w, x, y, z, axis); + } + + protected boolean hasCustomRotation() { + return false; + } + + protected void customRotateBlock(final IOrientable rotatable, final ForgeDirection axis) {} + + public boolean isValidOrientation( + final World w, + final int x, + final int y, + final int z, + final ForgeDirection forward, + final ForgeDirection up) { + return true; + } + + @Override + public ForgeDirection[] getValidRotations(final World w, final int x, final int y, final int z) { + return new ForgeDirection[0]; + } + + @SideOnly(Side.CLIENT) + private FlippableIcon optionalIcon(final IIconRegister ir, final String name, IIcon substitute) { + // if the input is an flippable IIcon find the original. + while (substitute instanceof FlippableIcon) { + substitute = ((FlippableIcon) substitute).getOriginal(); + } + + if (substitute != null) { + try { + ResourceLocation resLoc = new ResourceLocation(name); + resLoc = new ResourceLocation( + resLoc.getResourceDomain(), + String.format("%s/%s%s", "textures/blocks", resLoc.getResourcePath(), ".png")); + + final IResource res = + Minecraft.getMinecraft().getResourceManager().getResource(resLoc); + if (res != null) { + return new FlippableIcon(ir.registerIcon(name)); + } + } catch (final Throwable e) { + return new FlippableIcon(substitute); + } + } + + return new FlippableIcon(ir.registerIcon(name)); + } + + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks(final Item item, final CreativeTabs tabs, final List itemStacks) { + super.getSubBlocks(item, tabs, itemStacks); + } + + private int mapRotation(final IBlockAccess w, final int x, final int y, final int z, final int s) { + final IOrientable ori = this.getOrientable(w, x, y, z); + + if (ori != null && ori.canBeRotated()) { + return this.mapRotation(ori, ForgeDirection.getOrientation(s)).ordinal(); + } + + return s; + } + + public ForgeDirection mapRotation(final IOrientable ori, final ForgeDirection dir) { + // case DOWN: return bottomIcon; + // case UP: return blockIcon; + // case NORTH: return northIcon; + // case SOUTH: return southIcon; + // case WEST: return sideIcon; + // case EAST: return sideIcon; + + final ForgeDirection forward = ori.getForward(); + final ForgeDirection up = ori.getUp(); + + if (forward == null || up == null) { + return dir; + } + + final int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; + final int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; + final int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; + + ForgeDirection west = ForgeDirection.UNKNOWN; + for (final ForgeDirection dx : ForgeDirection.VALID_DIRECTIONS) { + if (dx.offsetX == west_x && dx.offsetY == west_y && dx.offsetZ == west_z) { + west = dx; + } + } + + if (dir == forward) { + return ForgeDirection.SOUTH; + } + if (dir == forward.getOpposite()) { + return ForgeDirection.NORTH; + } + + if (dir == up) { + return ForgeDirection.UP; + } + if (dir == up.getOpposite()) { + return ForgeDirection.DOWN; + } + + if (dir == west) { + return ForgeDirection.WEST; + } + if (dir == west.getOpposite()) { + return ForgeDirection.EAST; + } + + return ForgeDirection.UNKNOWN; + } + + @SideOnly(Side.CLIENT) + public void setRenderStateByMeta(final int itemDamage) {} + + public String getUnlocalizedName(final ItemStack is) { + return this.getUnlocalizedName(); + } + + void addInformation( + final ItemStack is, + final EntityPlayer player, + final List lines, + final boolean advancedItemTooltips) {} + + public Class getItemBlockClass() { + return AEBaseItemBlock.class; + } + + public boolean hasSubtypes() { + return this.hasSubtypes; + } } diff --git a/src/main/java/appeng/block/AEBaseItemBlock.java b/src/main/java/appeng/block/AEBaseItemBlock.java index f792b4181d1..0bd5ebac6f1 100644 --- a/src/main/java/appeng/block/AEBaseItemBlock.java +++ b/src/main/java/appeng/block/AEBaseItemBlock.java @@ -18,7 +18,6 @@ package appeng.block; - import appeng.api.util.IOrientable; import appeng.api.util.IOrientableBlock; import appeng.block.misc.BlockLightDetector; @@ -30,6 +29,7 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; @@ -39,182 +39,161 @@ import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.common.util.ForgeDirection; -import java.util.List; - - -public class AEBaseItemBlock extends ItemBlock -{ - - private final AEBaseBlock blockType; - - public AEBaseItemBlock( final Block id ) - { - super( id ); - this.blockType = (AEBaseBlock) id; - this.hasSubtypes = this.blockType.hasSubtypes; - - if( Platform.isClient() ) - { - MinecraftForgeClient.registerItemRenderer( this, ItemRenderer.INSTANCE ); - } - } - - @Override - public int getMetadata( final int dmg ) - { - if( this.hasSubtypes ) - { - return dmg; - } - return 0; - } - - @Override - @SideOnly( Side.CLIENT ) - @SuppressWarnings( "unchecked" ) - public final void addInformation( final ItemStack itemStack, final EntityPlayer player, final List toolTip, final boolean advancedTooltips ) - { - this.addCheckedInformation( itemStack, player, toolTip, advancedTooltips ); - } - - @SideOnly( Side.CLIENT ) - public void addCheckedInformation( final ItemStack itemStack, final EntityPlayer player, final List toolTip, final boolean advancedToolTips ) - { - this.blockType.addInformation( itemStack, player, toolTip, advancedToolTips ); - } - - @Override - public boolean isBookEnchantable( final ItemStack itemstack1, final ItemStack itemstack2 ) - { - return false; - } - - @Override - public String getUnlocalizedName( final ItemStack is ) - { - return this.blockType.getUnlocalizedName( is ); - } - - @Override - public boolean placeBlockAt( final ItemStack stack, final EntityPlayer player, final World w, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ, final int metadata ) - { - ForgeDirection up = ForgeDirection.UNKNOWN; - ForgeDirection forward = ForgeDirection.UNKNOWN; - - if( this.blockType instanceof AEBaseTileBlock ) - { - if( this.blockType instanceof BlockLightDetector ) - { - up = ForgeDirection.getOrientation( side ); - if( up == ForgeDirection.UP || up == ForgeDirection.DOWN ) - { - forward = ForgeDirection.SOUTH; - } - else - { - forward = ForgeDirection.UP; - } - } - else if( this.blockType instanceof BlockWireless || this.blockType instanceof BlockSkyCompass ) - { - forward = ForgeDirection.getOrientation( side ); - if( forward == ForgeDirection.UP || forward == ForgeDirection.DOWN ) - { - up = ForgeDirection.SOUTH; - } - else - { - up = ForgeDirection.UP; - } - } - else - { - up = ForgeDirection.UP; - - final byte rotation = (byte) ( MathHelper.floor_double( ( player.rotationYaw * 4F ) / 360F + 2.5D ) & 3 ); - - switch( rotation ) - { - default: - case 0: - forward = ForgeDirection.SOUTH; - break; - case 1: - forward = ForgeDirection.WEST; - break; - case 2: - forward = ForgeDirection.NORTH; - break; - case 3: - forward = ForgeDirection.EAST; - break; - } - - if( player.rotationPitch > 65 ) - { - up = forward.getOpposite(); - forward = ForgeDirection.UP; - } - else if( player.rotationPitch < -65 ) - { - up = forward.getOpposite(); - forward = ForgeDirection.DOWN; - } - } - } - - IOrientable ori = null; - if( this.blockType instanceof IOrientableBlock ) - { - ori = this.blockType.getOrientable( w, x, y, z ); - up = ForgeDirection.getOrientation( side ); - forward = ForgeDirection.SOUTH; - if( up.offsetY == 0 ) - { - forward = ForgeDirection.UP; - } - } - - if( !this.blockType.isValidOrientation( w, x, y, z, forward, up ) ) - { - return false; - } - - if( super.placeBlockAt( stack, player, w, x, y, z, side, hitX, hitY, hitZ, metadata ) ) - { - if( this.blockType instanceof AEBaseTileBlock && !( this.blockType instanceof BlockLightDetector ) ) - { - final AEBaseTile tile = ( (AEBaseTileBlock) this.blockType ).getTileEntity( w, x, y, z ); - ori = tile; - - if( tile == null ) - { - return true; - } - - if( ori.canBeRotated() && !this.blockType.hasCustomRotation() ) - { - if( ori.getForward() == null || ori.getUp() == null || // null - tile.getForward() == ForgeDirection.UNKNOWN || ori.getUp() == ForgeDirection.UNKNOWN ) - { - ori.setOrientation( forward, up ); - } - } - - if( tile instanceof IGridProxyable ) - { - ( (IGridProxyable) tile ).getProxy().setOwner( player ); - } - - tile.onPlacement( stack, player, side ); - } - else if( this.blockType instanceof IOrientableBlock ) - { - ori.setOrientation( forward, up ); - } - - return true; - } - return false; - } +public class AEBaseItemBlock extends ItemBlock { + + private final AEBaseBlock blockType; + + public AEBaseItemBlock(final Block id) { + super(id); + this.blockType = (AEBaseBlock) id; + this.hasSubtypes = this.blockType.hasSubtypes; + + if (Platform.isClient()) { + MinecraftForgeClient.registerItemRenderer(this, ItemRenderer.INSTANCE); + } + } + + @Override + public int getMetadata(final int dmg) { + if (this.hasSubtypes) { + return dmg; + } + return 0; + } + + @Override + @SideOnly(Side.CLIENT) + @SuppressWarnings("unchecked") + public final void addInformation( + final ItemStack itemStack, final EntityPlayer player, final List toolTip, final boolean advancedTooltips) { + this.addCheckedInformation(itemStack, player, toolTip, advancedTooltips); + } + + @SideOnly(Side.CLIENT) + public void addCheckedInformation( + final ItemStack itemStack, + final EntityPlayer player, + final List toolTip, + final boolean advancedToolTips) { + this.blockType.addInformation(itemStack, player, toolTip, advancedToolTips); + } + + @Override + public boolean isBookEnchantable(final ItemStack itemstack1, final ItemStack itemstack2) { + return false; + } + + @Override + public String getUnlocalizedName(final ItemStack is) { + return this.blockType.getUnlocalizedName(is); + } + + @Override + public boolean placeBlockAt( + final ItemStack stack, + final EntityPlayer player, + final World w, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ, + final int metadata) { + ForgeDirection up = ForgeDirection.UNKNOWN; + ForgeDirection forward = ForgeDirection.UNKNOWN; + + if (this.blockType instanceof AEBaseTileBlock) { + if (this.blockType instanceof BlockLightDetector) { + up = ForgeDirection.getOrientation(side); + if (up == ForgeDirection.UP || up == ForgeDirection.DOWN) { + forward = ForgeDirection.SOUTH; + } else { + forward = ForgeDirection.UP; + } + } else if (this.blockType instanceof BlockWireless || this.blockType instanceof BlockSkyCompass) { + forward = ForgeDirection.getOrientation(side); + if (forward == ForgeDirection.UP || forward == ForgeDirection.DOWN) { + up = ForgeDirection.SOUTH; + } else { + up = ForgeDirection.UP; + } + } else { + up = ForgeDirection.UP; + + final byte rotation = (byte) (MathHelper.floor_double((player.rotationYaw * 4F) / 360F + 2.5D) & 3); + + switch (rotation) { + default: + case 0: + forward = ForgeDirection.SOUTH; + break; + case 1: + forward = ForgeDirection.WEST; + break; + case 2: + forward = ForgeDirection.NORTH; + break; + case 3: + forward = ForgeDirection.EAST; + break; + } + + if (player.rotationPitch > 65) { + up = forward.getOpposite(); + forward = ForgeDirection.UP; + } else if (player.rotationPitch < -65) { + up = forward.getOpposite(); + forward = ForgeDirection.DOWN; + } + } + } + + IOrientable ori = null; + if (this.blockType instanceof IOrientableBlock) { + ori = this.blockType.getOrientable(w, x, y, z); + up = ForgeDirection.getOrientation(side); + forward = ForgeDirection.SOUTH; + if (up.offsetY == 0) { + forward = ForgeDirection.UP; + } + } + + if (!this.blockType.isValidOrientation(w, x, y, z, forward, up)) { + return false; + } + + if (super.placeBlockAt(stack, player, w, x, y, z, side, hitX, hitY, hitZ, metadata)) { + if (this.blockType instanceof AEBaseTileBlock && !(this.blockType instanceof BlockLightDetector)) { + final AEBaseTile tile = ((AEBaseTileBlock) this.blockType).getTileEntity(w, x, y, z); + ori = tile; + + if (tile == null) { + return true; + } + + if (ori.canBeRotated() && !this.blockType.hasCustomRotation()) { + if (ori.getForward() == null + || ori.getUp() == null + || // null + tile.getForward() == ForgeDirection.UNKNOWN + || ori.getUp() == ForgeDirection.UNKNOWN) { + ori.setOrientation(forward, up); + } + } + + if (tile instanceof IGridProxyable) { + ((IGridProxyable) tile).getProxy().setOwner(player); + } + + tile.onPlacement(stack, player, side); + } else if (this.blockType instanceof IOrientableBlock) { + ori.setOrientation(forward, up); + } + + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/AEBaseItemBlockChargeable.java b/src/main/java/appeng/block/AEBaseItemBlockChargeable.java index e6c6a473728..dbe1f4120cc 100644 --- a/src/main/java/appeng/block/AEBaseItemBlockChargeable.java +++ b/src/main/java/appeng/block/AEBaseItemBlockChargeable.java @@ -18,7 +18,6 @@ package appeng.block; - import appeng.api.config.AccessRestriction; import appeng.api.config.PowerUnits; import appeng.api.definitions.IBlockDefinition; @@ -28,121 +27,107 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.text.MessageFormat; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.text.MessageFormat; -import java.util.List; - - -public class AEBaseItemBlockChargeable extends AEBaseItemBlock implements IAEItemPowerStorage -{ - - public AEBaseItemBlockChargeable( final Block id ) - { - super( id ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void addCheckedInformation( final ItemStack itemStack, final EntityPlayer player, final List toolTip, final boolean advancedTooltips ) - { - final NBTTagCompound tag = itemStack.getTagCompound(); - double internalCurrentPower = 0; - final double internalMaxPower = this.getMaxEnergyCapacity(); - - if( tag != null ) - { - internalCurrentPower = tag.getDouble( "internalCurrentPower" ); - } - - final double percent = internalCurrentPower / internalMaxPower; - - toolTip.add( GuiText.StoredEnergy.getLocal() + ':' + MessageFormat.format( " {0,number,#} ", internalCurrentPower ) + Platform.gui_localize( PowerUnits.AE.unlocalizedName ) + " - " + MessageFormat.format( " {0,number,#.##%} ", percent ) ); - } - - private double getMaxEnergyCapacity() - { - final Block blockID = Block.getBlockFromItem( this ); - final IBlockDefinition energyCell = Api.INSTANCE.definitions().blocks().energyCell(); - for( final Block block : energyCell.maybeBlock().asSet() ) - { - if( blockID == block ) - { - return 200000; - } - else - { - return 8 * 200000; - } - } - - return 0; - } - - @Override - public double injectAEPower( final ItemStack is, double amt ) - { - double internalCurrentPower = this.getInternal( is ); - final double internalMaxPower = this.getMaxEnergyCapacity(); - internalCurrentPower += amt; - if( internalCurrentPower > internalMaxPower ) - { - amt = internalCurrentPower - internalMaxPower; - internalCurrentPower = internalMaxPower; - this.setInternal( is, internalCurrentPower ); - return amt; - } - - this.setInternal( is, internalCurrentPower ); - return 0; - } - - private double getInternal( final ItemStack is ) - { - final NBTTagCompound nbt = Platform.openNbtData( is ); - return nbt.getDouble( "internalCurrentPower" ); - } - - private void setInternal( final ItemStack is, final double amt ) - { - final NBTTagCompound nbt = Platform.openNbtData( is ); - nbt.setDouble( "internalCurrentPower", amt ); - } - - @Override - public double extractAEPower( final ItemStack is, double amt ) - { - double internalCurrentPower = this.getInternal( is ); - if( internalCurrentPower > amt ) - { - internalCurrentPower -= amt; - this.setInternal( is, internalCurrentPower ); - return amt; - } - - amt = internalCurrentPower; - this.setInternal( is, 0 ); - return amt; - } - - @Override - public double getAEMaxPower( final ItemStack is ) - { - return this.getMaxEnergyCapacity(); - } - - @Override - public double getAECurrentPower( final ItemStack is ) - { - return this.getInternal( is ); - } - - @Override - public AccessRestriction getPowerFlow( final ItemStack is ) - { - return AccessRestriction.WRITE; - } +public class AEBaseItemBlockChargeable extends AEBaseItemBlock implements IAEItemPowerStorage { + + public AEBaseItemBlockChargeable(final Block id) { + super(id); + } + + @Override + @SideOnly(Side.CLIENT) + public void addCheckedInformation( + final ItemStack itemStack, + final EntityPlayer player, + final List toolTip, + final boolean advancedTooltips) { + final NBTTagCompound tag = itemStack.getTagCompound(); + double internalCurrentPower = 0; + final double internalMaxPower = this.getMaxEnergyCapacity(); + + if (tag != null) { + internalCurrentPower = tag.getDouble("internalCurrentPower"); + } + + final double percent = internalCurrentPower / internalMaxPower; + + toolTip.add(GuiText.StoredEnergy.getLocal() + ':' + MessageFormat.format(" {0,number,#} ", internalCurrentPower) + + Platform.gui_localize(PowerUnits.AE.unlocalizedName) + " - " + + MessageFormat.format(" {0,number,#.##%} ", percent)); + } + + private double getMaxEnergyCapacity() { + final Block blockID = Block.getBlockFromItem(this); + final IBlockDefinition energyCell = Api.INSTANCE.definitions().blocks().energyCell(); + for (final Block block : energyCell.maybeBlock().asSet()) { + if (blockID == block) { + return 200000; + } else { + return 8 * 200000; + } + } + + return 0; + } + + @Override + public double injectAEPower(final ItemStack is, double amt) { + double internalCurrentPower = this.getInternal(is); + final double internalMaxPower = this.getMaxEnergyCapacity(); + internalCurrentPower += amt; + if (internalCurrentPower > internalMaxPower) { + amt = internalCurrentPower - internalMaxPower; + internalCurrentPower = internalMaxPower; + this.setInternal(is, internalCurrentPower); + return amt; + } + + this.setInternal(is, internalCurrentPower); + return 0; + } + + private double getInternal(final ItemStack is) { + final NBTTagCompound nbt = Platform.openNbtData(is); + return nbt.getDouble("internalCurrentPower"); + } + + private void setInternal(final ItemStack is, final double amt) { + final NBTTagCompound nbt = Platform.openNbtData(is); + nbt.setDouble("internalCurrentPower", amt); + } + + @Override + public double extractAEPower(final ItemStack is, double amt) { + double internalCurrentPower = this.getInternal(is); + if (internalCurrentPower > amt) { + internalCurrentPower -= amt; + this.setInternal(is, internalCurrentPower); + return amt; + } + + amt = internalCurrentPower; + this.setInternal(is, 0); + return amt; + } + + @Override + public double getAEMaxPower(final ItemStack is) { + return this.getMaxEnergyCapacity(); + } + + @Override + public double getAECurrentPower(final ItemStack is) { + return this.getInternal(is); + } + + @Override + public AccessRestriction getPowerFlow(final ItemStack is) { + return AccessRestriction.WRITE; + } } diff --git a/src/main/java/appeng/block/AEBaseItemBlockSlab.java b/src/main/java/appeng/block/AEBaseItemBlockSlab.java index 40d05544f40..94f94fd04bc 100644 --- a/src/main/java/appeng/block/AEBaseItemBlockSlab.java +++ b/src/main/java/appeng/block/AEBaseItemBlockSlab.java @@ -1,15 +1,15 @@ package appeng.block; - import net.minecraft.block.Block; import net.minecraft.item.ItemSlab; +public class AEBaseItemBlockSlab extends ItemSlab { -public class AEBaseItemBlockSlab extends ItemSlab -{ - - public AEBaseItemBlockSlab( final Block block, final AEBaseSlabBlock singleSlab, final AEBaseSlabBlock doubleSlab, final Boolean isDoubleSlab ) - { - super( block, singleSlab, doubleSlab, isDoubleSlab ); - } + public AEBaseItemBlockSlab( + final Block block, + final AEBaseSlabBlock singleSlab, + final AEBaseSlabBlock doubleSlab, + final Boolean isDoubleSlab) { + super(block, singleSlab, doubleSlab, isDoubleSlab); + } } diff --git a/src/main/java/appeng/block/AEBaseSlabBlock.java b/src/main/java/appeng/block/AEBaseSlabBlock.java index 3a47f45bde1..c040098e7af 100644 --- a/src/main/java/appeng/block/AEBaseSlabBlock.java +++ b/src/main/java/appeng/block/AEBaseSlabBlock.java @@ -18,11 +18,12 @@ package appeng.block; - import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; import appeng.core.features.IFeatureHandler; import appeng.core.features.SlabBlockFeatureHandler; +import java.util.EnumSet; +import java.util.Random; import net.minecraft.block.BlockSlab; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.Item; @@ -31,108 +32,93 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -import java.util.EnumSet; -import java.util.Random; - - -public class AEBaseSlabBlock extends BlockSlab implements IAEFeature -{ - private final IFeatureHandler features; - private final AEBaseBlock block; - private final int meta; - private AEBaseSlabBlock slabs; - private AEBaseSlabBlock doubleSlabs; - private final String name; - - public AEBaseSlabBlock( final AEBaseBlock block, final int meta, final EnumSet features, final boolean isDoubleSlab, final String name ) - { - super( isDoubleSlab, block.getMaterial() ); - this.block = block; - this.meta = meta; - this.name = name; - this.setBlockName( "appliedenergistics2." + name ); - this.setHardness( block.getBlockHardness( null, 0, 0, 0 ) ); - this.setResistance( block.getExplosionResistance( null ) * 5.0F / 3.0F ); - this.setStepSound( block.stepSound ); - this.useNeighborBrightness = true; - if( !this.field_150004_a ) - { - this.doubleSlabs = new AEBaseSlabBlock( block, meta, features, true, name + ".double" ).setSlabs( this ); - } - this.features = !this.field_150004_a ? new SlabBlockFeatureHandler( features, this ) : null; - } - - private AEBaseSlabBlock setSlabs( final AEBaseSlabBlock slabs ) - { - this.slabs = slabs; - return this; - } - - public AEBaseSlabBlock slabs() - { - return this.slabs; - } - - public AEBaseSlabBlock doubleSlabs() - { - return this.doubleSlabs; - } - - @Override - public IFeatureHandler handler() - { - return this.features; - } - - @Override - public void postInit() - { - // Override to do stuff - } - - @Override - public IIcon getIcon( final int dir, final int meta ) - { - return this.block.getIcon( dir, this.meta ); - } - - @Override - public String func_150002_b( final int p_150002_1_ ) - { - return this.getUnlocalizedName(); - } - - @Override - public void registerBlockIcons( final IIconRegister reg ) - { - } - - @Override - public Item getItemDropped( final int meta, final Random rand, final int fortune ) - { - return this.field_150004_a ? Item.getItemFromBlock( this.slabs ) : Item.getItemFromBlock( this ); - } - - @Override - public ItemStack getPickBlock( final MovingObjectPosition target, final World world, final int x, final int y, final int z ) - { - AEBaseSlabBlock block = (AEBaseSlabBlock) world.getBlock( x, y, z ); - - if( block == null ) - { - return null; - } - if( block.field_150004_a ) - { - block = this.slabs; - } - - final int meta = world.getBlockMetadata( x, y, z ) & 7; - return new ItemStack( block, 1, meta ); - } - - public String name() - { - return this.name; - } +public class AEBaseSlabBlock extends BlockSlab implements IAEFeature { + private final IFeatureHandler features; + private final AEBaseBlock block; + private final int meta; + private AEBaseSlabBlock slabs; + private AEBaseSlabBlock doubleSlabs; + private final String name; + + public AEBaseSlabBlock( + final AEBaseBlock block, + final int meta, + final EnumSet features, + final boolean isDoubleSlab, + final String name) { + super(isDoubleSlab, block.getMaterial()); + this.block = block; + this.meta = meta; + this.name = name; + this.setBlockName("appliedenergistics2." + name); + this.setHardness(block.getBlockHardness(null, 0, 0, 0)); + this.setResistance(block.getExplosionResistance(null) * 5.0F / 3.0F); + this.setStepSound(block.stepSound); + this.useNeighborBrightness = true; + if (!this.field_150004_a) { + this.doubleSlabs = new AEBaseSlabBlock(block, meta, features, true, name + ".double").setSlabs(this); + } + this.features = !this.field_150004_a ? new SlabBlockFeatureHandler(features, this) : null; + } + + private AEBaseSlabBlock setSlabs(final AEBaseSlabBlock slabs) { + this.slabs = slabs; + return this; + } + + public AEBaseSlabBlock slabs() { + return this.slabs; + } + + public AEBaseSlabBlock doubleSlabs() { + return this.doubleSlabs; + } + + @Override + public IFeatureHandler handler() { + return this.features; + } + + @Override + public void postInit() { + // Override to do stuff + } + + @Override + public IIcon getIcon(final int dir, final int meta) { + return this.block.getIcon(dir, this.meta); + } + + @Override + public String func_150002_b(final int p_150002_1_) { + return this.getUnlocalizedName(); + } + + @Override + public void registerBlockIcons(final IIconRegister reg) {} + + @Override + public Item getItemDropped(final int meta, final Random rand, final int fortune) { + return this.field_150004_a ? Item.getItemFromBlock(this.slabs) : Item.getItemFromBlock(this); + } + + @Override + public ItemStack getPickBlock( + final MovingObjectPosition target, final World world, final int x, final int y, final int z) { + AEBaseSlabBlock block = (AEBaseSlabBlock) world.getBlock(x, y, z); + + if (block == null) { + return null; + } + if (block.field_150004_a) { + block = this.slabs; + } + + final int meta = world.getBlockMetadata(x, y, z) & 7; + return new ItemStack(block, 1, meta); + } + + public String name() { + return this.name; + } } diff --git a/src/main/java/appeng/block/AEBaseStairBlock.java b/src/main/java/appeng/block/AEBaseStairBlock.java index a78810809de..9a184155376 100644 --- a/src/main/java/appeng/block/AEBaseStairBlock.java +++ b/src/main/java/appeng/block/AEBaseStairBlock.java @@ -18,41 +18,34 @@ package appeng.block; - import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; import appeng.core.features.IFeatureHandler; import appeng.core.features.StairBlockFeatureHandler; import com.google.common.base.Optional; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.block.BlockStairs; -import java.util.EnumSet; - - -public abstract class AEBaseStairBlock extends BlockStairs implements IAEFeature -{ - private final IFeatureHandler features; +public abstract class AEBaseStairBlock extends BlockStairs implements IAEFeature { + private final IFeatureHandler features; - protected AEBaseStairBlock( final Block block, final int meta, final EnumSet features ) - { - super( block, meta ); + protected AEBaseStairBlock(final Block block, final int meta, final EnumSet features) { + super(block, meta); - this.features = new StairBlockFeatureHandler( features, this, Optional.absent() ); - this.setBlockName( block.getUnlocalizedName() ); + this.features = new StairBlockFeatureHandler(features, this, Optional.absent()); + this.setBlockName(block.getUnlocalizedName()); - this.setLightOpacity( 0 ); - } + this.setLightOpacity(0); + } - @Override - public IFeatureHandler handler() - { - return this.features; - } + @Override + public IFeatureHandler handler() { + return this.features; + } - @Override - public void postInit() - { - // Override to do stuff - } + @Override + public void postInit() { + // Override to do stuff + } } diff --git a/src/main/java/appeng/block/AEBaseTileBlock.java b/src/main/java/appeng/block/AEBaseTileBlock.java index 4b150444326..705f255be87 100644 --- a/src/main/java/appeng/block/AEBaseTileBlock.java +++ b/src/main/java/appeng/block/AEBaseTileBlock.java @@ -18,7 +18,6 @@ package appeng.block; - import appeng.api.implementations.items.IMemoryCard; import appeng.api.implementations.items.MemoryCardMessages; import appeng.api.implementations.tiles.IColorableTile; @@ -39,6 +38,11 @@ import com.google.common.base.Optional; import com.google.common.collect.Lists; import cpw.mods.fml.relauncher.ReflectionHelper; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.material.Material; @@ -56,311 +60,262 @@ import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.world.BlockEvent; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; - - -public abstract class AEBaseTileBlock extends AEBaseBlock implements IAEFeature, ITileEntityProvider -{ - - @Nonnull - private Class tileEntityType; - - public AEBaseTileBlock( final Material mat ) - { - super( mat ); - } - - protected AEBaseTileBlock( final Material mat, final Optional subName ) - { - super( mat, subName ); - } - - @Override - protected void setFeature( final EnumSet f ) - { - final AETileBlockFeatureHandler featureHandler = new AETileBlockFeatureHandler( f, this, this.featureSubName ); - this.setHandler( featureHandler ); - } - - protected void setTileEntity( final Class c ) - { - this.tileEntityType = c; - this.isInventory = IInventory.class.isAssignableFrom( c ); - this.setTileProvider( this.hasBlockTileEntity() ); - } - - // update Block value. - private void setTileProvider( final boolean b ) - { - ReflectionHelper.setPrivateValue( Block.class, this, b, "isTileProvider" ); - } - - private boolean hasBlockTileEntity() - { - return this.tileEntityType != null; - } - - public Class getTileEntityClass() - { - return this.tileEntityType; - } - - @Nullable - public T getTileEntity( final IBlockAccess w, final int x, final int y, final int z ) - { - if( !this.hasBlockTileEntity() ) - { - return null; - } - - final TileEntity te = w.getTileEntity( x, y, z ); - if( this.tileEntityType.isInstance( te ) ) - { - return (T) te; - } - - return null; - } - - @Override - public final TileEntity createNewTileEntity( final World var1, final int var2 ) - { - if( this.hasBlockTileEntity() ) - { - try - { - return this.tileEntityType.newInstance(); - } - catch( final InstantiationException e ) - { - throw new IllegalStateException( "Failed to create a new instance of an illegal class " + this.tileEntityType, e ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( "Failed to create a new instance of " + this.tileEntityType + ", because lack of permissions", e ); - } - } - - return null; - } - - @Override - public void breakBlock( final World w, final int x, final int y, final int z, final Block a, final int b ) - { - final AEBaseTile te = this.getTileEntity( w, x, y, z ); - if( te != null ) - { - final ArrayList drops = new ArrayList(); - if( te.dropItems() ) - { - te.getDrops( w, x, y, z, drops ); - } - else - { - te.getNoDrops( w, x, y, z, drops ); - } - - // Cry ;_; ... - Platform.spawnDrops( w, x, y, z, drops ); - } - - // super will remove the TE, as it is not an instance of BlockContainer - super.breakBlock( w, x, y, z, a, b ); - } - - @Override - public final ForgeDirection[] getValidRotations( final World w, final int x, final int y, final int z ) - { - final AEBaseTile obj = this.getTileEntity( w, x, y, z ); - if( obj != null && obj.canBeRotated() ) - { - return ForgeDirection.VALID_DIRECTIONS; - } - - return super.getValidRotations( w, x, y, z ); - } - - @Override - public boolean recolourBlock( final World world, final int x, final int y, final int z, final ForgeDirection side, final int colour ) - { - final TileEntity te = this.getTileEntity( world, x, y, z ); - - if( te instanceof IColorableTile ) - { - final IColorableTile ct = (IColorableTile) te; - final AEColor c = ct.getColor(); - final AEColor newColor = AEColor.values()[colour]; - - if( c != newColor ) - { - ct.recolourBlock( side, newColor, null ); - return true; - } - return false; - } - - return super.recolourBlock( world, x, y, z, side, colour ); - } - - @Override - public int getComparatorInputOverride( final World w, final int x, final int y, final int z, final int s ) - { - final TileEntity te = this.getTileEntity( w, x, y, z ); - if( te instanceof IInventory ) - { - return Container.calcRedstoneFromInventory( (IInventory) te ); - } - return 0; - } - - @Override - public boolean onBlockEventReceived( final World p_149696_1_, final int p_149696_2_, final int p_149696_3_, final int p_149696_4_, final int p_149696_5_, final int p_149696_6_ ) - { - super.onBlockEventReceived( p_149696_1_, p_149696_2_, p_149696_3_, p_149696_4_, p_149696_5_, p_149696_6_ ); - final TileEntity tileentity = p_149696_1_.getTileEntity( p_149696_2_, p_149696_3_, p_149696_4_ ); - return tileentity != null && tileentity.receiveClientEvent( p_149696_5_, p_149696_6_ ); - } - - @Override - public void onBlockPlacedBy( final World w, final int x, final int y, final int z, final EntityLivingBase player, final ItemStack is ) - { - if( is.hasDisplayName() ) - { - final TileEntity te = this.getTileEntity( w, x, y, z ); - if( te instanceof AEBaseTile ) - { - ( (AEBaseTile) w.getTileEntity( x, y, z ) ).setName( is.getDisplayName() ); - } - } - } - - @Override - public boolean onBlockActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( player != null ) - { - final ItemStack is = player.inventory.getCurrentItem(); - if( is != null ) - { - if( Platform.isWrench( player, is, x, y, z ) && player.isSneaking() ) - { - final Block id = w.getBlock( x, y, z ); - if( id != null ) - { - final AEBaseTile tile = this.getTileEntity( w, x, y, z ); - final ItemStack[] drops = Platform.getBlockDrops( w, x, y, z ); - - if( tile == null ) - { - return false; - } - - if( tile instanceof TileCableBus || tile instanceof TileSkyChest ) - { - return false; - } - - BlockEvent.BreakEvent event = new BlockEvent.BreakEvent( x, y, z, w, this, 0, player ); - MinecraftForge.EVENT_BUS.post( event ); - if( event.isCanceled() ) - { - return false; - } - - final ItemStack op = new ItemStack( this ); - for( final ItemStack ol : drops ) - { - if( Platform.isSameItemType( ol, op ) ) - { - final NBTTagCompound tag = tile.downloadSettings( SettingsFrom.DISMANTLE_ITEM ); - if( tag != null ) - { - ol.setTagCompound( tag ); - } - } - } - - if( id.removedByPlayer( w, player, x, y, z, false ) ) - { - final List l = Lists.newArrayList( drops ); - Platform.spawnDrops( w, x, y, z, l ); - w.setBlockToAir( x, y, z ); - } - } - return false; - } - - if( is.getItem() instanceof IMemoryCard && !( this instanceof BlockCableBus ) ) - { - final IMemoryCard memoryCard = (IMemoryCard) is.getItem(); - if( player.isSneaking() ) - { - final AEBaseTile t = this.getTileEntity( w, x, y, z ); - if( t != null ) - { - final String name = this.getUnlocalizedName(); - final NBTTagCompound data = t.downloadSettings( SettingsFrom.MEMORY_CARD ); - if( data != null ) - { - memoryCard.setMemoryCardContents( is, name, data ); - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_SAVED ); - return true; - } - } - } - else - { - final String name = memoryCard.getSettingsName( is ); - final NBTTagCompound data = memoryCard.getData( is ); - if( this.getUnlocalizedName().equals( name ) ) - { - final AEBaseTile t = this.getTileEntity( w, x, y, z ); - t.uploadSettings( SettingsFrom.MEMORY_CARD, data ); - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_LOADED ); - } - else - { - memoryCard.notifyUser( player, MemoryCardMessages.INVALID_MACHINE ); - } - return false; - } - } - if( is.getItem() instanceof ToolQuartzCuttingKnife && !( this instanceof BlockCableBus ) ) - { - if( ForgeEventFactory.onItemUseStart( player, is, 1 ) <= 0 ) - return false; - final AEBaseTile tile = this.getTileEntity( w, x, y, z ); - if( tile == null ) - return false; - Platform.openGUI( player, tile, ForgeDirection.getOrientation( side ), GuiBridge.GUI_RENAMER ); - return true; - } - } - } - - return this.onActivated( w, x, y, z, player, side, hitX, hitY, hitZ ); - } - - @Override - public IOrientable getOrientable( final IBlockAccess w, final int x, final int y, final int z ) - { - return this.getTileEntity( w, x, y, z ); - } - - @Override - public ICustomCollision getCustomCollision( final World w, final int x, final int y, final int z ) - { - final AEBaseTile te = this.getTileEntity( w, x, y, z ); - if( te instanceof ICustomCollision ) - { - return (ICustomCollision) te; - } - - return super.getCustomCollision( w, x, y, z ); - } - +public abstract class AEBaseTileBlock extends AEBaseBlock implements IAEFeature, ITileEntityProvider { + + @Nonnull + private Class tileEntityType; + + public AEBaseTileBlock(final Material mat) { + super(mat); + } + + protected AEBaseTileBlock(final Material mat, final Optional subName) { + super(mat, subName); + } + + @Override + protected void setFeature(final EnumSet f) { + final AETileBlockFeatureHandler featureHandler = new AETileBlockFeatureHandler(f, this, this.featureSubName); + this.setHandler(featureHandler); + } + + protected void setTileEntity(final Class c) { + this.tileEntityType = c; + this.isInventory = IInventory.class.isAssignableFrom(c); + this.setTileProvider(this.hasBlockTileEntity()); + } + + // update Block value. + private void setTileProvider(final boolean b) { + ReflectionHelper.setPrivateValue(Block.class, this, b, "isTileProvider"); + } + + private boolean hasBlockTileEntity() { + return this.tileEntityType != null; + } + + public Class getTileEntityClass() { + return this.tileEntityType; + } + + @Nullable + public T getTileEntity(final IBlockAccess w, final int x, final int y, final int z) { + if (!this.hasBlockTileEntity()) { + return null; + } + + final TileEntity te = w.getTileEntity(x, y, z); + if (this.tileEntityType.isInstance(te)) { + return (T) te; + } + + return null; + } + + @Override + public final TileEntity createNewTileEntity(final World var1, final int var2) { + if (this.hasBlockTileEntity()) { + try { + return this.tileEntityType.newInstance(); + } catch (final InstantiationException e) { + throw new IllegalStateException( + "Failed to create a new instance of an illegal class " + this.tileEntityType, e); + } catch (final IllegalAccessException e) { + throw new IllegalStateException( + "Failed to create a new instance of " + this.tileEntityType + ", because lack of permissions", + e); + } + } + + return null; + } + + @Override + public void breakBlock(final World w, final int x, final int y, final int z, final Block a, final int b) { + final AEBaseTile te = this.getTileEntity(w, x, y, z); + if (te != null) { + final ArrayList drops = new ArrayList(); + if (te.dropItems()) { + te.getDrops(w, x, y, z, drops); + } else { + te.getNoDrops(w, x, y, z, drops); + } + + // Cry ;_; ... + Platform.spawnDrops(w, x, y, z, drops); + } + + // super will remove the TE, as it is not an instance of BlockContainer + super.breakBlock(w, x, y, z, a, b); + } + + @Override + public final ForgeDirection[] getValidRotations(final World w, final int x, final int y, final int z) { + final AEBaseTile obj = this.getTileEntity(w, x, y, z); + if (obj != null && obj.canBeRotated()) { + return ForgeDirection.VALID_DIRECTIONS; + } + + return super.getValidRotations(w, x, y, z); + } + + @Override + public boolean recolourBlock( + final World world, final int x, final int y, final int z, final ForgeDirection side, final int colour) { + final TileEntity te = this.getTileEntity(world, x, y, z); + + if (te instanceof IColorableTile) { + final IColorableTile ct = (IColorableTile) te; + final AEColor c = ct.getColor(); + final AEColor newColor = AEColor.values()[colour]; + + if (c != newColor) { + ct.recolourBlock(side, newColor, null); + return true; + } + return false; + } + + return super.recolourBlock(world, x, y, z, side, colour); + } + + @Override + public int getComparatorInputOverride(final World w, final int x, final int y, final int z, final int s) { + final TileEntity te = this.getTileEntity(w, x, y, z); + if (te instanceof IInventory) { + return Container.calcRedstoneFromInventory((IInventory) te); + } + return 0; + } + + @Override + public boolean onBlockEventReceived( + final World p_149696_1_, + final int p_149696_2_, + final int p_149696_3_, + final int p_149696_4_, + final int p_149696_5_, + final int p_149696_6_) { + super.onBlockEventReceived(p_149696_1_, p_149696_2_, p_149696_3_, p_149696_4_, p_149696_5_, p_149696_6_); + final TileEntity tileentity = p_149696_1_.getTileEntity(p_149696_2_, p_149696_3_, p_149696_4_); + return tileentity != null && tileentity.receiveClientEvent(p_149696_5_, p_149696_6_); + } + + @Override + public void onBlockPlacedBy( + final World w, final int x, final int y, final int z, final EntityLivingBase player, final ItemStack is) { + if (is.hasDisplayName()) { + final TileEntity te = this.getTileEntity(w, x, y, z); + if (te instanceof AEBaseTile) { + ((AEBaseTile) w.getTileEntity(x, y, z)).setName(is.getDisplayName()); + } + } + } + + @Override + public boolean onBlockActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (player != null) { + final ItemStack is = player.inventory.getCurrentItem(); + if (is != null) { + if (Platform.isWrench(player, is, x, y, z) && player.isSneaking()) { + final Block id = w.getBlock(x, y, z); + if (id != null) { + final AEBaseTile tile = this.getTileEntity(w, x, y, z); + final ItemStack[] drops = Platform.getBlockDrops(w, x, y, z); + + if (tile == null) { + return false; + } + + if (tile instanceof TileCableBus || tile instanceof TileSkyChest) { + return false; + } + + BlockEvent.BreakEvent event = new BlockEvent.BreakEvent(x, y, z, w, this, 0, player); + MinecraftForge.EVENT_BUS.post(event); + if (event.isCanceled()) { + return false; + } + + final ItemStack op = new ItemStack(this); + for (final ItemStack ol : drops) { + if (Platform.isSameItemType(ol, op)) { + final NBTTagCompound tag = tile.downloadSettings(SettingsFrom.DISMANTLE_ITEM); + if (tag != null) { + ol.setTagCompound(tag); + } + } + } + + if (id.removedByPlayer(w, player, x, y, z, false)) { + final List l = Lists.newArrayList(drops); + Platform.spawnDrops(w, x, y, z, l); + w.setBlockToAir(x, y, z); + } + } + return false; + } + + if (is.getItem() instanceof IMemoryCard && !(this instanceof BlockCableBus)) { + final IMemoryCard memoryCard = (IMemoryCard) is.getItem(); + if (player.isSneaking()) { + final AEBaseTile t = this.getTileEntity(w, x, y, z); + if (t != null) { + final String name = this.getUnlocalizedName(); + final NBTTagCompound data = t.downloadSettings(SettingsFrom.MEMORY_CARD); + if (data != null) { + memoryCard.setMemoryCardContents(is, name, data); + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_SAVED); + return true; + } + } + } else { + final String name = memoryCard.getSettingsName(is); + final NBTTagCompound data = memoryCard.getData(is); + if (this.getUnlocalizedName().equals(name)) { + final AEBaseTile t = this.getTileEntity(w, x, y, z); + t.uploadSettings(SettingsFrom.MEMORY_CARD, data); + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_LOADED); + } else { + memoryCard.notifyUser(player, MemoryCardMessages.INVALID_MACHINE); + } + return false; + } + } + if (is.getItem() instanceof ToolQuartzCuttingKnife && !(this instanceof BlockCableBus)) { + if (ForgeEventFactory.onItemUseStart(player, is, 1) <= 0) return false; + final AEBaseTile tile = this.getTileEntity(w, x, y, z); + if (tile == null) return false; + Platform.openGUI(player, tile, ForgeDirection.getOrientation(side), GuiBridge.GUI_RENAMER); + return true; + } + } + } + + return this.onActivated(w, x, y, z, player, side, hitX, hitY, hitZ); + } + + @Override + public IOrientable getOrientable(final IBlockAccess w, final int x, final int y, final int z) { + return this.getTileEntity(w, x, y, z); + } + + @Override + public ICustomCollision getCustomCollision(final World w, final int x, final int y, final int z) { + final AEBaseTile te = this.getTileEntity(w, x, y, z); + if (te instanceof ICustomCollision) { + return (ICustomCollision) te; + } + + return super.getCustomCollision(w, x, y, z); + } } diff --git a/src/main/java/appeng/block/AEDecorativeBlock.java b/src/main/java/appeng/block/AEDecorativeBlock.java index 08d68287475..1d31a4c29fb 100644 --- a/src/main/java/appeng/block/AEDecorativeBlock.java +++ b/src/main/java/appeng/block/AEDecorativeBlock.java @@ -18,28 +18,22 @@ package appeng.block; - import net.minecraft.block.material.Material; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; +public class AEDecorativeBlock extends AEBaseBlock { + public AEDecorativeBlock(final Material mat) { + super(mat); + } -public class AEDecorativeBlock extends AEBaseBlock -{ - public AEDecorativeBlock( final Material mat ) - { - super( mat ); - } - - @Override - public int getRenderType() - { - return 0; - } + @Override + public int getRenderType() { + return 0; + } - @Override - public IIcon getIcon( final IBlockAccess w, final int x, final int y, final int z, final int s ) - { - return super.unmappedGetIcon( w, x, y, z, s ); - } + @Override + public IIcon getIcon(final IBlockAccess w, final int x, final int y, final int z, final int s) { + return super.unmappedGetIcon(w, x, y, z, s); + } } diff --git a/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java b/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java index c119001ac78..8165449fd0e 100644 --- a/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java +++ b/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java @@ -18,13 +18,13 @@ package appeng.block.crafting; - import appeng.api.AEApi; import appeng.client.render.blocks.RenderBlockCraftingCPUMonitor; import appeng.client.texture.ExtraBlockTextures; import appeng.tile.crafting.TileCraftingMonitorTile; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; @@ -32,48 +32,42 @@ import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import java.util.List; - - -public class BlockCraftingMonitor extends BlockCraftingUnit -{ - public BlockCraftingMonitor() - { - this.setTileEntity( TileCraftingMonitorTile.class ); - } +public class BlockCraftingMonitor extends BlockCraftingUnit { + public BlockCraftingMonitor() { + this.setTileEntity(TileCraftingMonitorTile.class); + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockCraftingCPUMonitor getRenderer() - { - return new RenderBlockCraftingCPUMonitor(); - } + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockCraftingCPUMonitor getRenderer() { + return new RenderBlockCraftingCPUMonitor(); + } - @Override - public IIcon getIcon( final int direction, final int metadata ) - { - if( direction != ForgeDirection.SOUTH.ordinal() ) - { - for( final Block craftingUnitBlock : AEApi.instance().definitions().blocks().craftingUnit().maybeBlock().asSet() ) - { - return craftingUnitBlock.getIcon( direction, metadata ); - } - } + @Override + public IIcon getIcon(final int direction, final int metadata) { + if (direction != ForgeDirection.SOUTH.ordinal()) { + for (final Block craftingUnitBlock : AEApi.instance() + .definitions() + .blocks() + .craftingUnit() + .maybeBlock() + .asSet()) { + return craftingUnitBlock.getIcon(direction, metadata); + } + } - switch( metadata ) - { - default: - case 0: - return super.getIcon( 0, 0 ); - case FLAG_FORMED: - return ExtraBlockTextures.BlockCraftingMonitorFit_Light.getIcon(); - } - } + switch (metadata) { + default: + case 0: + return super.getIcon(0, 0); + case FLAG_FORMED: + return ExtraBlockTextures.BlockCraftingMonitorFit_Light.getIcon(); + } + } - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - itemStacks.add( new ItemStack( this, 1, 0 ) ); - } + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks(final Item item, final CreativeTabs tabs, final List itemStacks) { + itemStacks.add(new ItemStack(this, 1, 0)); + } } diff --git a/src/main/java/appeng/block/crafting/BlockCraftingStorage.java b/src/main/java/appeng/block/crafting/BlockCraftingStorage.java index c71b92d0b53..49745b24c4a 100644 --- a/src/main/java/appeng/block/crafting/BlockCraftingStorage.java +++ b/src/main/java/appeng/block/crafting/BlockCraftingStorage.java @@ -18,87 +18,74 @@ package appeng.block.crafting; - import appeng.client.texture.ExtraBlockTextures; import appeng.tile.crafting.TileCraftingStorageTile; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; -import java.util.List; - - -public class BlockCraftingStorage extends BlockCraftingUnit -{ - public BlockCraftingStorage() - { - this.setTileEntity( TileCraftingStorageTile.class ); - } +public class BlockCraftingStorage extends BlockCraftingUnit { + public BlockCraftingStorage() { + this.setTileEntity(TileCraftingStorageTile.class); + } - @Override - public Class getItemBlockClass() - { - return ItemCraftingStorage.class; - } + @Override + public Class getItemBlockClass() { + return ItemCraftingStorage.class; + } - @Override - public IIcon getIcon( final int direction, final int metadata ) - { - switch( metadata & ( ~4 ) ) - { - default: + @Override + public IIcon getIcon(final int direction, final int metadata) { + switch (metadata & (~4)) { + default: - case 0: - return super.getIcon( 0, 0 ); - case 1: - return ExtraBlockTextures.BlockCraftingStorage4k.getIcon(); - case 2: - return ExtraBlockTextures.BlockCraftingStorage16k.getIcon(); - case 3: - return ExtraBlockTextures.BlockCraftingStorage64k.getIcon(); + case 0: + return super.getIcon(0, 0); + case 1: + return ExtraBlockTextures.BlockCraftingStorage4k.getIcon(); + case 2: + return ExtraBlockTextures.BlockCraftingStorage16k.getIcon(); + case 3: + return ExtraBlockTextures.BlockCraftingStorage64k.getIcon(); - case FLAG_FORMED: - return ExtraBlockTextures.BlockCraftingStorage1kFit.getIcon(); - case 1 | FLAG_FORMED: - return ExtraBlockTextures.BlockCraftingStorage4kFit.getIcon(); - case 2 | FLAG_FORMED: - return ExtraBlockTextures.BlockCraftingStorage16kFit.getIcon(); - case 3 | FLAG_FORMED: - return ExtraBlockTextures.BlockCraftingStorage64kFit.getIcon(); - } - } + case FLAG_FORMED: + return ExtraBlockTextures.BlockCraftingStorage1kFit.getIcon(); + case 1 | FLAG_FORMED: + return ExtraBlockTextures.BlockCraftingStorage4kFit.getIcon(); + case 2 | FLAG_FORMED: + return ExtraBlockTextures.BlockCraftingStorage16kFit.getIcon(); + case 3 | FLAG_FORMED: + return ExtraBlockTextures.BlockCraftingStorage64kFit.getIcon(); + } + } - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - itemStacks.add( new ItemStack( this, 1, 0 ) ); - itemStacks.add( new ItemStack( this, 1, 1 ) ); - itemStacks.add( new ItemStack( this, 1, 2 ) ); - itemStacks.add( new ItemStack( this, 1, 3 ) ); - } + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks(final Item item, final CreativeTabs tabs, final List itemStacks) { + itemStacks.add(new ItemStack(this, 1, 0)); + itemStacks.add(new ItemStack(this, 1, 1)); + itemStacks.add(new ItemStack(this, 1, 2)); + itemStacks.add(new ItemStack(this, 1, 3)); + } - @Override - public String getUnlocalizedName( final ItemStack is ) - { - if( is.getItemDamage() == 1 ) - { - return "tile.appliedenergistics2.BlockCraftingStorage4k"; - } + @Override + public String getUnlocalizedName(final ItemStack is) { + if (is.getItemDamage() == 1) { + return "tile.appliedenergistics2.BlockCraftingStorage4k"; + } - if( is.getItemDamage() == 2 ) - { - return "tile.appliedenergistics2.BlockCraftingStorage16k"; - } + if (is.getItemDamage() == 2) { + return "tile.appliedenergistics2.BlockCraftingStorage16k"; + } - if( is.getItemDamage() == 3 ) - { - return "tile.appliedenergistics2.BlockCraftingStorage64k"; - } + if (is.getItemDamage() == 3) { + return "tile.appliedenergistics2.BlockCraftingStorage64k"; + } - return this.getItemUnlocalizedName( is ); - } + return this.getItemUnlocalizedName(is); + } } diff --git a/src/main/java/appeng/block/crafting/BlockCraftingUnit.java b/src/main/java/appeng/block/crafting/BlockCraftingUnit.java index ce22c0bd6f3..c979d7532b9 100644 --- a/src/main/java/appeng/block/crafting/BlockCraftingUnit.java +++ b/src/main/java/appeng/block/crafting/BlockCraftingUnit.java @@ -18,7 +18,6 @@ package appeng.block.crafting; - import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockCraftingCPU; import appeng.client.texture.ExtraBlockTextures; @@ -28,6 +27,8 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; @@ -38,38 +39,29 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.List; - - -public class BlockCraftingUnit extends AEBaseTileBlock -{ - static final int FLAG_FORMED = 8; - - public BlockCraftingUnit() - { - super( Material.iron ); - - this.hasSubtypes = true; - this.setTileEntity( TileCraftingTile.class ); - this.setFeature( EnumSet.of( AEFeature.CraftingCPU ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockCraftingCPU getRenderer() - { - return new RenderBlockCraftingCPU(); - } - - @Override - public IIcon getIcon( final int direction, final int metadata ) - { - switch( metadata ) - { - default: - case 0: - return super.getIcon( 0, 0 ); +public class BlockCraftingUnit extends AEBaseTileBlock { + static final int FLAG_FORMED = 8; + + public BlockCraftingUnit() { + super(Material.iron); + + this.hasSubtypes = true; + this.setTileEntity(TileCraftingTile.class); + this.setFeature(EnumSet.of(AEFeature.CraftingCPU)); + } + + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockCraftingCPU getRenderer() { + return new RenderBlockCraftingCPU(); + } + + @Override + public IIcon getIcon(final int direction, final int metadata) { + switch (metadata) { + default: + case 0: + return super.getIcon(0, 0); case 1: return ExtraBlockTextures.BlockCraftingAccelerator.getIcon(); case FLAG_FORMED: @@ -84,99 +76,92 @@ public IIcon getIcon( final int direction, final int metadata ) return ExtraBlockTextures.BlockCraftingAccelerator16x.getIcon(); case 3 | FLAG_FORMED: return ExtraBlockTextures.BlockCraftingAccelerator16xFit.getIcon(); - } - } - - @Override - public boolean onBlockActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - final TileCraftingTile tg = this.getTileEntity( w, x, y, z ); - if( tg != null && !p.isSneaking() && tg.isFormed() && tg.isActive() ) - { - if( Platform.isClient() ) - { - return true; - } - - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_CRAFTING_CPU ); - return true; - } - - return super.onBlockActivated( w, x, y, z, p, side, hitX, hitY, hitZ ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - itemStacks.add( new ItemStack( this, 1, 0 ) ); - itemStacks.add( new ItemStack( this, 1, 1 ) ); - itemStacks.add( new ItemStack( this, 1, 2 ) ); - itemStacks.add( new ItemStack( this, 1, 3 ) ); - } - - @Override - public void setRenderStateByMeta( final int itemDamage ) - { - final IIcon front = this.getIcon( ForgeDirection.SOUTH.ordinal(), itemDamage ); - final IIcon other = this.getIcon( ForgeDirection.NORTH.ordinal(), itemDamage ); - this.getRendererInstance().setTemporaryRenderIcons( other, other, front, other, other, other ); - } - - @Override - public void breakBlock( final World w, final int x, final int y, final int z, final Block a, final int b ) - { - final TileCraftingTile cp = this.getTileEntity( w, x, y, z ); - if( cp != null ) - { - cp.breakCluster(); - } - - super.breakBlock( w, x, y, z, a, b ); - } - - @Override - public String getUnlocalizedName( final ItemStack is ) - { - if( is.getItemDamage() == 1 ) - { + } + } + + @Override + public boolean onBlockActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + final TileCraftingTile tg = this.getTileEntity(w, x, y, z); + if (tg != null && !p.isSneaking() && tg.isFormed() && tg.isActive()) { + if (Platform.isClient()) { + return true; + } + + Platform.openGUI(p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_CRAFTING_CPU); + return true; + } + + return super.onBlockActivated(w, x, y, z, p, side, hitX, hitY, hitZ); + } + + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks(final Item item, final CreativeTabs tabs, final List itemStacks) { + itemStacks.add(new ItemStack(this, 1, 0)); + itemStacks.add(new ItemStack(this, 1, 1)); + itemStacks.add(new ItemStack(this, 1, 2)); + itemStacks.add(new ItemStack(this, 1, 3)); + } + + @Override + public void setRenderStateByMeta(final int itemDamage) { + final IIcon front = this.getIcon(ForgeDirection.SOUTH.ordinal(), itemDamage); + final IIcon other = this.getIcon(ForgeDirection.NORTH.ordinal(), itemDamage); + this.getRendererInstance().setTemporaryRenderIcons(other, other, front, other, other, other); + } + + @Override + public void breakBlock(final World w, final int x, final int y, final int z, final Block a, final int b) { + final TileCraftingTile cp = this.getTileEntity(w, x, y, z); + if (cp != null) { + cp.breakCluster(); + } + + super.breakBlock(w, x, y, z, a, b); + } + + @Override + public String getUnlocalizedName(final ItemStack is) { + if (is.getItemDamage() == 1) { return "tile.appliedenergistics2.BlockCraftingAccelerator"; - } else if( is.getItemDamage() == 2 ) - { + } else if (is.getItemDamage() == 2) { return "tile.appliedenergistics2.BlockCraftingAccelerator4x"; - } else if( is.getItemDamage() == 3 ) - { + } else if (is.getItemDamage() == 3) { return "tile.appliedenergistics2.BlockCraftingAccelerator16x"; } - return this.getItemUnlocalizedName( is ); - } - - protected String getItemUnlocalizedName( final ItemStack is ) - { - return super.getUnlocalizedName( is ); - } - - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block junk ) - { - final TileCraftingTile cp = this.getTileEntity( w, x, y, z ); - if( cp != null ) - { - cp.updateMultiBlock(); - } - } - - @Override - public int damageDropped( final int meta ) - { - return meta & 3; - } - - @Override - public int getDamageValue( final World w, final int x, final int y, final int z ) - { - final int meta = w.getBlockMetadata( x, y, z ); - return this.damageDropped( meta ); - } + return this.getItemUnlocalizedName(is); + } + + protected String getItemUnlocalizedName(final ItemStack is) { + return super.getUnlocalizedName(is); + } + + @Override + public void onNeighborBlockChange(final World w, final int x, final int y, final int z, final Block junk) { + final TileCraftingTile cp = this.getTileEntity(w, x, y, z); + if (cp != null) { + cp.updateMultiBlock(); + } + } + + @Override + public int damageDropped(final int meta) { + return meta & 3; + } + + @Override + public int getDamageValue(final World w, final int x, final int y, final int z) { + final int meta = w.getBlockMetadata(x, y, z); + return this.damageDropped(meta); + } } diff --git a/src/main/java/appeng/block/crafting/BlockMolecularAssembler.java b/src/main/java/appeng/block/crafting/BlockMolecularAssembler.java index 0dd83e915fd..50563b0091f 100644 --- a/src/main/java/appeng/block/crafting/BlockMolecularAssembler.java +++ b/src/main/java/appeng/block/crafting/BlockMolecularAssembler.java @@ -18,7 +18,6 @@ package appeng.block.crafting; - import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockAssembler; import appeng.core.features.AEFeature; @@ -27,68 +26,66 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class BlockMolecularAssembler extends AEBaseTileBlock -{ +public class BlockMolecularAssembler extends AEBaseTileBlock { - private static boolean booleanAlphaPass = false; + private static boolean booleanAlphaPass = false; - public BlockMolecularAssembler() - { - super( Material.iron ); + public BlockMolecularAssembler() { + super(Material.iron); - this.setTileEntity( TileMolecularAssembler.class ); - this.isOpaque = false; - this.lightOpacity = 1; - this.setFeature( EnumSet.of( AEFeature.MolecularAssembler ) ); - } + this.setTileEntity(TileMolecularAssembler.class); + this.isOpaque = false; + this.lightOpacity = 1; + this.setFeature(EnumSet.of(AEFeature.MolecularAssembler)); + } - @Override - public int getRenderBlockPass() - { - return 1; - } + @Override + public int getRenderBlockPass() { + return 1; + } - @Override - public boolean canRenderInPass( final int pass ) - { - setBooleanAlphaPass( pass == 1 ); - return pass == 0 || pass == 1; - } + @Override + public boolean canRenderInPass(final int pass) { + setBooleanAlphaPass(pass == 1); + return pass == 0 || pass == 1; + } - @Override - @SideOnly( Side.CLIENT ) - public RenderBlockAssembler getRenderer() - { - return new RenderBlockAssembler(); - } + @Override + @SideOnly(Side.CLIENT) + public RenderBlockAssembler getRenderer() { + return new RenderBlockAssembler(); + } - @Override - public boolean onBlockActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - final TileMolecularAssembler tg = this.getTileEntity( w, x, y, z ); - if( tg != null && !p.isSneaking() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_MAC ); - return true; - } - return super.onBlockActivated( w, x, y, z, p, side, hitX, hitY, hitZ ); - } + @Override + public boolean onBlockActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + final TileMolecularAssembler tg = this.getTileEntity(w, x, y, z); + if (tg != null && !p.isSneaking()) { + Platform.openGUI(p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_MAC); + return true; + } + return super.onBlockActivated(w, x, y, z, p, side, hitX, hitY, hitZ); + } - public static boolean isBooleanAlphaPass() - { - return booleanAlphaPass; - } + public static boolean isBooleanAlphaPass() { + return booleanAlphaPass; + } - private static void setBooleanAlphaPass( final boolean booleanAlphaPass ) - { - BlockMolecularAssembler.booleanAlphaPass = booleanAlphaPass; - } + private static void setBooleanAlphaPass(final boolean booleanAlphaPass) { + BlockMolecularAssembler.booleanAlphaPass = booleanAlphaPass; + } } diff --git a/src/main/java/appeng/block/crafting/ItemCraftingStorage.java b/src/main/java/appeng/block/crafting/ItemCraftingStorage.java index 885dbce7cd4..73e5b70fadd 100644 --- a/src/main/java/appeng/block/crafting/ItemCraftingStorage.java +++ b/src/main/java/appeng/block/crafting/ItemCraftingStorage.java @@ -18,7 +18,6 @@ package appeng.block.crafting; - import appeng.api.AEApi; import appeng.block.AEBaseItemBlock; import appeng.core.AEConfig; @@ -26,29 +25,28 @@ import net.minecraft.block.Block; import net.minecraft.item.ItemStack; - -public class ItemCraftingStorage extends AEBaseItemBlock -{ - - public ItemCraftingStorage( final Block id ) - { - super( id ); - } - - @Override - public ItemStack getContainerItem( final ItemStack itemStack ) - { - for( final ItemStack stack : AEApi.instance().definitions().blocks().craftingUnit().maybeStack( 1 ).asSet() ) - { - return stack; - } - - return null; - } - - @Override - public boolean hasContainerItem( final ItemStack stack ) - { - return AEConfig.instance.isFeatureEnabled( AEFeature.EnableDisassemblyCrafting ); - } +public class ItemCraftingStorage extends AEBaseItemBlock { + + public ItemCraftingStorage(final Block id) { + super(id); + } + + @Override + public ItemStack getContainerItem(final ItemStack itemStack) { + for (final ItemStack stack : AEApi.instance() + .definitions() + .blocks() + .craftingUnit() + .maybeStack(1) + .asSet()) { + return stack; + } + + return null; + } + + @Override + public boolean hasContainerItem(final ItemStack stack) { + return AEConfig.instance.isFeatureEnabled(AEFeature.EnableDisassemblyCrafting); + } } diff --git a/src/main/java/appeng/block/grindstone/BlockCrank.java b/src/main/java/appeng/block/grindstone/BlockCrank.java index 56bbad6eaea..ded1c13ff63 100644 --- a/src/main/java/appeng/block/grindstone/BlockCrank.java +++ b/src/main/java/appeng/block/grindstone/BlockCrank.java @@ -18,7 +18,6 @@ package appeng.block.grindstone; - import appeng.api.implementations.tiles.ICrankable; import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockCrank; @@ -28,6 +27,7 @@ import appeng.tile.grindstone.TileCrank; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.EntityLivingBase; @@ -38,123 +38,117 @@ import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class BlockCrank extends AEBaseTileBlock -{ - - public BlockCrank() - { - super( Material.wood ); - - this.setTileEntity( TileCrank.class ); - this.setLightOpacity( 0 ); - this.setHarvestLevel( "axe", 0 ); - this.isFullSize = this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.GrindStone ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - public RenderBlockCrank getRenderer() - { - return new RenderBlockCrank(); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( player instanceof FakePlayer || player == null ) - { - this.dropCrank( w, x, y, z ); - return true; - } - - final AEBaseTile tile = this.getTileEntity( w, x, y, z ); - if( tile instanceof TileCrank ) - { - if( ( (TileCrank) tile ).power() ) - { - Stats.TurnedCranks.addToPlayer( player, 1 ); - } - } - - return true; - } - - private void dropCrank( final World world, final int x, final int y, final int z ) - { - world.func_147480_a( x, y, z, true ); // w.destroyBlock( x, y, z, true ); - world.markBlockForUpdate( x, y, z ); - } - - @Override - public void onBlockPlacedBy( final World world, final int x, final int y, final int z, final EntityLivingBase placer, final ItemStack itemStack ) - { - final AEBaseTile tile = this.getTileEntity( world, x, y, z ); - if( tile != null ) - { - final ForgeDirection mnt = this.findCrankable( world, x, y, z ); - ForgeDirection forward = ForgeDirection.UP; - if( mnt == ForgeDirection.UP || mnt == ForgeDirection.DOWN ) - { - forward = ForgeDirection.SOUTH; - } - tile.setOrientation( forward, mnt.getOpposite() ); - } - else - { - this.dropCrank( world, x, y, z ); - } - } - - @Override - public boolean isValidOrientation( final World world, final int x, final int y, final int z, final ForgeDirection forward, final ForgeDirection up ) - { - final TileEntity te = world.getTileEntity( x, y, z ); - return !( te instanceof TileCrank ) || this.isCrankable( world, x, y, z, up.getOpposite() ); - } - - private ForgeDirection findCrankable( final World world, final int x, final int y, final int z ) - { - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.isCrankable( world, x, y, z, dir ) ) - { - return dir; - } - } - return ForgeDirection.UNKNOWN; - } - - private boolean isCrankable( final World world, final int x, final int y, final int z, final ForgeDirection offset ) - { - final TileEntity te = world.getTileEntity( x + offset.offsetX, y + offset.offsetY, z + offset.offsetZ ); - - return te instanceof ICrankable && ( (ICrankable) te ).canCrankAttach( offset.getOpposite() ); - } - - @Override - public void onNeighborBlockChange( final World world, final int x, final int y, final int z, final Block block ) - { - final AEBaseTile tile = this.getTileEntity( world, x, y, z ); - if( tile != null ) - { - if( !this.isCrankable( world, x, y, z, tile.getUp().getOpposite() ) ) - { - this.dropCrank( world, x, y, z ); - } - } - else - { - this.dropCrank( world, x, y, z ); - } - } - - @Override - public boolean canPlaceBlockAt( final World world, final int x, final int y, final int z ) - { - return this.findCrankable( world, x, y, z ) != ForgeDirection.UNKNOWN; - } +public class BlockCrank extends AEBaseTileBlock { + + public BlockCrank() { + super(Material.wood); + + this.setTileEntity(TileCrank.class); + this.setLightOpacity(0); + this.setHarvestLevel("axe", 0); + this.isFullSize = this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.GrindStone)); + } + + @Override + @SideOnly(Side.CLIENT) + public RenderBlockCrank getRenderer() { + return new RenderBlockCrank(); + } + + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (player instanceof FakePlayer || player == null) { + this.dropCrank(w, x, y, z); + return true; + } + + final AEBaseTile tile = this.getTileEntity(w, x, y, z); + if (tile instanceof TileCrank) { + if (((TileCrank) tile).power()) { + Stats.TurnedCranks.addToPlayer(player, 1); + } + } + + return true; + } + + private void dropCrank(final World world, final int x, final int y, final int z) { + world.func_147480_a(x, y, z, true); // w.destroyBlock( x, y, z, true ); + world.markBlockForUpdate(x, y, z); + } + + @Override + public void onBlockPlacedBy( + final World world, + final int x, + final int y, + final int z, + final EntityLivingBase placer, + final ItemStack itemStack) { + final AEBaseTile tile = this.getTileEntity(world, x, y, z); + if (tile != null) { + final ForgeDirection mnt = this.findCrankable(world, x, y, z); + ForgeDirection forward = ForgeDirection.UP; + if (mnt == ForgeDirection.UP || mnt == ForgeDirection.DOWN) { + forward = ForgeDirection.SOUTH; + } + tile.setOrientation(forward, mnt.getOpposite()); + } else { + this.dropCrank(world, x, y, z); + } + } + + @Override + public boolean isValidOrientation( + final World world, + final int x, + final int y, + final int z, + final ForgeDirection forward, + final ForgeDirection up) { + final TileEntity te = world.getTileEntity(x, y, z); + return !(te instanceof TileCrank) || this.isCrankable(world, x, y, z, up.getOpposite()); + } + + private ForgeDirection findCrankable(final World world, final int x, final int y, final int z) { + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + if (this.isCrankable(world, x, y, z, dir)) { + return dir; + } + } + return ForgeDirection.UNKNOWN; + } + + private boolean isCrankable(final World world, final int x, final int y, final int z, final ForgeDirection offset) { + final TileEntity te = world.getTileEntity(x + offset.offsetX, y + offset.offsetY, z + offset.offsetZ); + + return te instanceof ICrankable && ((ICrankable) te).canCrankAttach(offset.getOpposite()); + } + + @Override + public void onNeighborBlockChange(final World world, final int x, final int y, final int z, final Block block) { + final AEBaseTile tile = this.getTileEntity(world, x, y, z); + if (tile != null) { + if (!this.isCrankable(world, x, y, z, tile.getUp().getOpposite())) { + this.dropCrank(world, x, y, z); + } + } else { + this.dropCrank(world, x, y, z); + } + } + + @Override + public boolean canPlaceBlockAt(final World world, final int x, final int y, final int z) { + return this.findCrankable(world, x, y, z) != ForgeDirection.UNKNOWN; + } } diff --git a/src/main/java/appeng/block/grindstone/BlockGrinder.java b/src/main/java/appeng/block/grindstone/BlockGrinder.java index f93b03e4c0b..55ee8ad7db7 100644 --- a/src/main/java/appeng/block/grindstone/BlockGrinder.java +++ b/src/main/java/appeng/block/grindstone/BlockGrinder.java @@ -18,41 +18,43 @@ package appeng.block.grindstone; - import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; import appeng.core.sync.GuiBridge; import appeng.tile.grindstone.TileGrinder; import appeng.util.Platform; +import java.util.EnumSet; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class BlockGrinder extends AEBaseTileBlock -{ - - public BlockGrinder() - { - super( Material.rock ); - - this.setTileEntity( TileGrinder.class ); - this.setHardness( 3.2F ); - this.setFeature( EnumSet.of( AEFeature.GrindStone ) ); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - final TileGrinder tg = this.getTileEntity( w, x, y, z ); - if( tg != null && !p.isSneaking() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_GRINDER ); - return true; - } - return false; - } +public class BlockGrinder extends AEBaseTileBlock { + + public BlockGrinder() { + super(Material.rock); + + this.setTileEntity(TileGrinder.class); + this.setHardness(3.2F); + this.setFeature(EnumSet.of(AEFeature.GrindStone)); + } + + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + final TileGrinder tg = this.getTileEntity(w, x, y, z); + if (tg != null && !p.isSneaking()) { + Platform.openGUI(p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_GRINDER); + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/misc/BlockCellWorkbench.java b/src/main/java/appeng/block/misc/BlockCellWorkbench.java index 410d0886579..1997ba6254c 100644 --- a/src/main/java/appeng/block/misc/BlockCellWorkbench.java +++ b/src/main/java/appeng/block/misc/BlockCellWorkbench.java @@ -18,48 +18,48 @@ package appeng.block.misc; - import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; import appeng.core.sync.GuiBridge; import appeng.tile.misc.TileCellWorkbench; import appeng.util.Platform; +import java.util.EnumSet; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class BlockCellWorkbench extends AEBaseTileBlock -{ +public class BlockCellWorkbench extends AEBaseTileBlock { - public BlockCellWorkbench() - { - super( Material.iron ); + public BlockCellWorkbench() { + super(Material.iron); - this.setTileEntity( TileCellWorkbench.class ); - this.setFeature( EnumSet.of( AEFeature.StorageCells ) ); - } + this.setTileEntity(TileCellWorkbench.class); + this.setFeature(EnumSet.of(AEFeature.StorageCells)); + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileCellWorkbench tg = this.getTileEntity( w, x, y, z ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_CELL_WORKBENCH ); - } - return true; - } - return false; - } + final TileCellWorkbench tg = this.getTileEntity(w, x, y, z); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_CELL_WORKBENCH); + } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/misc/BlockCharger.java b/src/main/java/appeng/block/misc/BlockCharger.java index 6d764e29495..6236f5d8c59 100644 --- a/src/main/java/appeng/block/misc/BlockCharger.java +++ b/src/main/java/appeng/block/misc/BlockCharger.java @@ -18,7 +18,6 @@ package appeng.block.misc; - import appeng.api.AEApi; import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockCharger; @@ -32,6 +31,10 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; @@ -40,148 +43,144 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; - - -public class BlockCharger extends AEBaseTileBlock implements ICustomCollision -{ - - public BlockCharger() - { - super( Material.iron ); - - this.setTileEntity( TileCharger.class ); - this.setLightOpacity( 2 ); - this.isFullSize = this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockCharger getRenderer() - { - return new RenderBlockCharger(); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( player.isSneaking() ) - { - return false; - } - - if( Platform.isServer() ) - { - final TileCharger tc = this.getTileEntity( w, x, y, z ); - if( tc != null ) - { - tc.activate( player ); - } - } - - return true; - } - - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World w, final int x, final int y, final int z, final Random r ) - { - if( !AEConfig.instance.enableEffects ) - { - return; - } - - if( r.nextFloat() < 0.98 ) - { - return; - } - - final AEBaseTile tile = this.getTileEntity( w, x, y, z ); - if( tile instanceof TileCharger ) - { - final TileCharger tc = (TileCharger) tile; - - if( AEApi.instance().definitions().materials().certusQuartzCrystalCharged().isSameAs( tc.getStackInSlot( 0 ) ) ) - { - final double xOff = 0.0; - final double yOff = 0.0; - final double zOff = 0.0; - - for( int bolts = 0; bolts < 3; bolts++ ) - { - if( CommonHelper.proxy.shouldAddParticles( r ) ) - { - final LightningFX fx = new LightningFX( w, xOff + 0.5 + x, yOff + 0.5 + y, zOff + 0.5 + z, 0.0D, 0.0D, 0.0D ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - } - } - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - final TileCharger tile = this.getTileEntity( w, x, y, z ); - if( tile != null ) - { - final double twoPixels = 2.0 / 16.0; - final ForgeDirection up = tile.getUp(); - final ForgeDirection forward = tile.getForward(); - final AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( twoPixels, twoPixels, twoPixels, 1.0 - twoPixels, 1.0 - twoPixels, 1.0 - twoPixels ); - - if( up.offsetX != 0 ) - { - bb.minX = 0; - bb.maxX = 1; - } - if( up.offsetY != 0 ) - { - bb.minY = 0; - bb.maxY = 1; - } - if( up.offsetZ != 0 ) - { - bb.minZ = 0; - bb.maxZ = 1; - } - - switch( forward ) - { - case DOWN: - bb.maxY = 1; - break; - case UP: - bb.minY = 0; - break; - case NORTH: - bb.maxZ = 1; - break; - case SOUTH: - bb.minZ = 0; - break; - case EAST: - bb.minX = 0; - break; - case WEST: - bb.maxX = 1; - break; - default: - break; - } - - return Collections.singletonList( bb ); - } - return Collections.singletonList( AxisAlignedBB.getBoundingBox( 0.0, 0, 0.0, 1.0, 1.0, 1.0 ) ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - out.add( AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, 1.0, 1.0, 1.0 ) ); - } +public class BlockCharger extends AEBaseTileBlock implements ICustomCollision { + + public BlockCharger() { + super(Material.iron); + + this.setTileEntity(TileCharger.class); + this.setLightOpacity(2); + this.isFullSize = this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.Core)); + } + + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockCharger getRenderer() { + return new RenderBlockCharger(); + } + + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (player.isSneaking()) { + return false; + } + + if (Platform.isServer()) { + final TileCharger tc = this.getTileEntity(w, x, y, z); + if (tc != null) { + tc.activate(player); + } + } + + return true; + } + + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(final World w, final int x, final int y, final int z, final Random r) { + if (!AEConfig.instance.enableEffects) { + return; + } + + if (r.nextFloat() < 0.98) { + return; + } + + final AEBaseTile tile = this.getTileEntity(w, x, y, z); + if (tile instanceof TileCharger) { + final TileCharger tc = (TileCharger) tile; + + if (AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystalCharged() + .isSameAs(tc.getStackInSlot(0))) { + final double xOff = 0.0; + final double yOff = 0.0; + final double zOff = 0.0; + + for (int bolts = 0; bolts < 3; bolts++) { + if (CommonHelper.proxy.shouldAddParticles(r)) { + final LightningFX fx = + new LightningFX(w, xOff + 0.5 + x, yOff + 0.5 + y, zOff + 0.5 + z, 0.0D, 0.0D, 0.0D); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } + } + } + } + + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual) { + final TileCharger tile = this.getTileEntity(w, x, y, z); + if (tile != null) { + final double twoPixels = 2.0 / 16.0; + final ForgeDirection up = tile.getUp(); + final ForgeDirection forward = tile.getForward(); + final AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( + twoPixels, twoPixels, twoPixels, 1.0 - twoPixels, 1.0 - twoPixels, 1.0 - twoPixels); + + if (up.offsetX != 0) { + bb.minX = 0; + bb.maxX = 1; + } + if (up.offsetY != 0) { + bb.minY = 0; + bb.maxY = 1; + } + if (up.offsetZ != 0) { + bb.minZ = 0; + bb.maxZ = 1; + } + + switch (forward) { + case DOWN: + bb.maxY = 1; + break; + case UP: + bb.minY = 0; + break; + case NORTH: + bb.maxZ = 1; + break; + case SOUTH: + bb.minZ = 0; + break; + case EAST: + bb.minX = 0; + break; + case WEST: + bb.maxX = 1; + break; + default: + break; + } + + return Collections.singletonList(bb); + } + return Collections.singletonList(AxisAlignedBB.getBoundingBox(0.0, 0, 0.0, 1.0, 1.0, 1.0)); + } + + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e) { + out.add(AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.0, 1.0, 1.0, 1.0)); + } } diff --git a/src/main/java/appeng/block/misc/BlockCondenser.java b/src/main/java/appeng/block/misc/BlockCondenser.java index c8f1785a57a..a10fc831a66 100644 --- a/src/main/java/appeng/block/misc/BlockCondenser.java +++ b/src/main/java/appeng/block/misc/BlockCondenser.java @@ -18,49 +18,49 @@ package appeng.block.misc; - import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; import appeng.core.sync.GuiBridge; import appeng.tile.misc.TileCondenser; import appeng.util.Platform; +import java.util.EnumSet; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class BlockCondenser extends AEBaseTileBlock -{ +public class BlockCondenser extends AEBaseTileBlock { - public BlockCondenser() - { - super( Material.iron ); + public BlockCondenser() { + super(Material.iron); - this.setTileEntity( TileCondenser.class ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } + this.setTileEntity(TileCondenser.class); + this.setFeature(EnumSet.of(AEFeature.Core)); + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( player.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (player.isSneaking()) { + return false; + } - if( Platform.isServer() ) - { - final TileCondenser tc = this.getTileEntity( w, x, y, z ); - if( tc != null && !player.isSneaking() ) - { - Platform.openGUI( player, tc, ForgeDirection.getOrientation( side ), GuiBridge.GUI_CONDENSER ); - return true; - } - } + if (Platform.isServer()) { + final TileCondenser tc = this.getTileEntity(w, x, y, z); + if (tc != null && !player.isSneaking()) { + Platform.openGUI(player, tc, ForgeDirection.getOrientation(side), GuiBridge.GUI_CONDENSER); + return true; + } + } - return true; - } + return true; + } } diff --git a/src/main/java/appeng/block/misc/BlockInscriber.java b/src/main/java/appeng/block/misc/BlockInscriber.java index 84afe2dc1a7..c86d7b3381f 100644 --- a/src/main/java/appeng/block/misc/BlockInscriber.java +++ b/src/main/java/appeng/block/misc/BlockInscriber.java @@ -18,7 +18,6 @@ package appeng.block.misc; - import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockInscriber; import appeng.core.features.AEFeature; @@ -27,51 +26,51 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class BlockInscriber extends AEBaseTileBlock -{ +public class BlockInscriber extends AEBaseTileBlock { - public BlockInscriber() - { - super( Material.iron ); + public BlockInscriber() { + super(Material.iron); - this.setTileEntity( TileInscriber.class ); - this.setLightOpacity( 2 ); - this.isFullSize = this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.Inscriber ) ); - } + this.setTileEntity(TileInscriber.class); + this.setLightOpacity(2); + this.isFullSize = this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.Inscriber)); + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockInscriber getRenderer() - { - return new RenderBlockInscriber(); - } + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockInscriber getRenderer() { + return new RenderBlockInscriber(); + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileInscriber tg = this.getTileEntity( w, x, y, z ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_INSCRIBER ); - } - return true; - } - return false; - } + final TileInscriber tg = this.getTileEntity(w, x, y, z); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_INSCRIBER); + } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/misc/BlockInterface.java b/src/main/java/appeng/block/misc/BlockInterface.java index 2fa5c0b92c2..39576847515 100644 --- a/src/main/java/appeng/block/misc/BlockInterface.java +++ b/src/main/java/appeng/block/misc/BlockInterface.java @@ -18,7 +18,6 @@ package appeng.block.misc; - import appeng.api.util.IOrientable; import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockInterface; @@ -28,64 +27,61 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class BlockInterface extends AEBaseTileBlock -{ +public class BlockInterface extends AEBaseTileBlock { - public BlockInterface() - { - super( Material.iron ); + public BlockInterface() { + super(Material.iron); - this.setTileEntity( TileInterface.class ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } + this.setTileEntity(TileInterface.class); + this.setFeature(EnumSet.of(AEFeature.Core)); + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockInterface getRenderer() - { - return new RenderBlockInterface(); - } + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockInterface getRenderer() { + return new RenderBlockInterface(); + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileInterface tg = this.getTileEntity( w, x, y, z ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_INTERFACE ); - } - return true; - } - return false; - } + final TileInterface tg = this.getTileEntity(w, x, y, z); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_INTERFACE); + } + return true; + } + return false; + } - @Override - protected boolean hasCustomRotation() - { - return true; - } + @Override + protected boolean hasCustomRotation() { + return true; + } - @Override - protected void customRotateBlock( final IOrientable rotatable, final ForgeDirection axis ) - { - if( rotatable instanceof TileInterface ) - { - ( (TileInterface) rotatable ).setSide( axis ); - } - } + @Override + protected void customRotateBlock(final IOrientable rotatable, final ForgeDirection axis) { + if (rotatable instanceof TileInterface) { + ((TileInterface) rotatable).setSide(axis); + } + } } diff --git a/src/main/java/appeng/block/misc/BlockLightDetector.java b/src/main/java/appeng/block/misc/BlockLightDetector.java index 79e16ebeecf..6fe94f5ee2a 100644 --- a/src/main/java/appeng/block/misc/BlockLightDetector.java +++ b/src/main/java/appeng/block/misc/BlockLightDetector.java @@ -18,7 +18,6 @@ package appeng.block.misc; - import appeng.api.util.IOrientable; import appeng.api.util.IOrientableBlock; import appeng.block.AEBaseTileBlock; @@ -29,6 +28,10 @@ import appeng.tile.misc.TileLightDetector; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; @@ -37,133 +40,130 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; - - -public class BlockLightDetector extends AEBaseTileBlock implements IOrientableBlock, ICustomCollision -{ - - public BlockLightDetector() - { - super( Material.circuits ); - - this.setLightOpacity( 0 ); - this.isFullSize = false; - this.isOpaque = false; - - this.setTileEntity( TileLightDetector.class ); - this.setFeature( EnumSet.of( AEFeature.LightDetector ) ); - } - - @Override - public int isProvidingWeakPower( final IBlockAccess w, final int x, final int y, final int z, final int side ) - { - if( w instanceof World && ( (TileLightDetector) this.getTileEntity( w, x, y, z ) ).isReady() ) - { - return ( (World) w ).getBlockLightValue( x, y, z ) - 6; - } - - return 0; - } - - @Override - public void onNeighborChange( final IBlockAccess world, final int x, final int y, final int z, final int tileX, final int tileY, final int tileZ ) - { - super.onNeighborChange( world, x, y, z, tileX, tileY, tileZ ); - - final TileLightDetector tld = this.getTileEntity( world, x, y, z ); - if( tld != null ) - { - tld.updateLight(); - } - } - - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World w, final int x, final int y, final int z, final Random r ) - { - // cancel out lightning - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderQuartzTorch getRenderer() - { - return new RenderQuartzTorch(); - } - - @Override - public boolean isValidOrientation( final World w, final int x, final int y, final int z, final ForgeDirection forward, final ForgeDirection up ) - { - return this.canPlaceAt( w, x, y, z, up.getOpposite() ); - } - - private boolean canPlaceAt( final World w, final int x, final int y, final int z, final ForgeDirection dir ) - { - return w.isSideSolid( x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite(), false ); - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - final ForgeDirection up = this.getOrientable( w, x, y, z ).getUp(); - final double xOff = -0.3 * up.offsetX; - final double yOff = -0.3 * up.offsetY; - final double zOff = -0.3 * up.offsetZ; - return Collections.singletonList( AxisAlignedBB.getBoundingBox( xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7 ) ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - {/* - * double xOff = -0.15 * getUp().offsetX; double yOff = -0.15 * getUp().offsetY; double zOff = -0.15 * - * getUp().offsetZ; out.add( AxisAlignedBB.getBoundingBox( xOff + (double) x + 0.15, yOff + (double) y + 0.15, zOff - * + (double) z + 0.15,// ahh xOff + (double) x + 0.85, yOff + (double) y + 0.85, zOff + (double) z + 0.85 ) ); - */ - } - - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block id ) - { - final ForgeDirection up = this.getOrientable( w, x, y, z ).getUp(); - if( !this.canPlaceAt( w, x, y, z, up.getOpposite() ) ) - { - this.dropTorch( w, x, y, z ); - } - } - - private void dropTorch( final World w, final int x, final int y, final int z ) - { - w.func_147480_a( x, y, z, true ); - // w.destroyBlock( x, y, z, true ); - w.markBlockForUpdate( x, y, z ); - } - - @Override - public boolean canPlaceBlockAt( final World w, final int x, final int y, final int z ) - { - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.canPlaceAt( w, x, y, z, dir ) ) - { - return true; - } - } - return false; - } - - @Override - public boolean usesMetadata() - { - return true; - } - - @Override - public IOrientable getOrientable( final IBlockAccess w, final int x, final int y, final int z ) - { - return new MetaRotation( w, x, y, z ); - } +public class BlockLightDetector extends AEBaseTileBlock implements IOrientableBlock, ICustomCollision { + + public BlockLightDetector() { + super(Material.circuits); + + this.setLightOpacity(0); + this.isFullSize = false; + this.isOpaque = false; + + this.setTileEntity(TileLightDetector.class); + this.setFeature(EnumSet.of(AEFeature.LightDetector)); + } + + @Override + public int isProvidingWeakPower(final IBlockAccess w, final int x, final int y, final int z, final int side) { + if (w instanceof World && ((TileLightDetector) this.getTileEntity(w, x, y, z)).isReady()) { + return ((World) w).getBlockLightValue(x, y, z) - 6; + } + + return 0; + } + + @Override + public void onNeighborChange( + final IBlockAccess world, + final int x, + final int y, + final int z, + final int tileX, + final int tileY, + final int tileZ) { + super.onNeighborChange(world, x, y, z, tileX, tileY, tileZ); + + final TileLightDetector tld = this.getTileEntity(world, x, y, z); + if (tld != null) { + tld.updateLight(); + } + } + + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(final World w, final int x, final int y, final int z, final Random r) { + // cancel out lightning + } + + @Override + @SideOnly(Side.CLIENT) + protected RenderQuartzTorch getRenderer() { + return new RenderQuartzTorch(); + } + + @Override + public boolean isValidOrientation( + final World w, + final int x, + final int y, + final int z, + final ForgeDirection forward, + final ForgeDirection up) { + return this.canPlaceAt(w, x, y, z, up.getOpposite()); + } + + private boolean canPlaceAt(final World w, final int x, final int y, final int z, final ForgeDirection dir) { + return w.isSideSolid(x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite(), false); + } + + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual) { + final ForgeDirection up = this.getOrientable(w, x, y, z).getUp(); + final double xOff = -0.3 * up.offsetX; + final double yOff = -0.3 * up.offsetY; + final double zOff = -0.3 * up.offsetZ; + return Collections.singletonList( + AxisAlignedBB.getBoundingBox(xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7)); + } + + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e) { + /* + * double xOff = -0.15 * getUp().offsetX; double yOff = -0.15 * getUp().offsetY; double zOff = -0.15 * + * getUp().offsetZ; out.add( AxisAlignedBB.getBoundingBox( xOff + (double) x + 0.15, yOff + (double) y + 0.15, zOff + * + (double) z + 0.15,// ahh xOff + (double) x + 0.85, yOff + (double) y + 0.85, zOff + (double) z + 0.85 ) ); + */ + } + + @Override + public void onNeighborBlockChange(final World w, final int x, final int y, final int z, final Block id) { + final ForgeDirection up = this.getOrientable(w, x, y, z).getUp(); + if (!this.canPlaceAt(w, x, y, z, up.getOpposite())) { + this.dropTorch(w, x, y, z); + } + } + + private void dropTorch(final World w, final int x, final int y, final int z) { + w.func_147480_a(x, y, z, true); + // w.destroyBlock( x, y, z, true ); + w.markBlockForUpdate(x, y, z); + } + + @Override + public boolean canPlaceBlockAt(final World w, final int x, final int y, final int z) { + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + if (this.canPlaceAt(w, x, y, z, dir)) { + return true; + } + } + return false; + } + + @Override + public boolean usesMetadata() { + return true; + } + + @Override + public IOrientable getOrientable(final IBlockAccess w, final int x, final int y, final int z) { + return new MetaRotation(w, x, y, z); + } } diff --git a/src/main/java/appeng/block/misc/BlockPaint.java b/src/main/java/appeng/block/misc/BlockPaint.java index f80173f5766..41dca876b84 100644 --- a/src/main/java/appeng/block/misc/BlockPaint.java +++ b/src/main/java/appeng/block/misc/BlockPaint.java @@ -18,7 +18,6 @@ package appeng.block.misc; - import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockPaint; import appeng.core.features.AEFeature; @@ -26,6 +25,9 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.MaterialLiquid; @@ -36,105 +38,89 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; - - -public class BlockPaint extends AEBaseTileBlock -{ - - public BlockPaint() - { - super( new MaterialLiquid( MapColor.airColor ) ); - - this.setTileEntity( TilePaint.class ); - this.setLightOpacity( 0 ); - this.isFullSize = false; - this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.PaintBalls ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockPaint getRenderer() - { - return new RenderBlockPaint(); - } - - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - // do nothing - } - - @Override - public AxisAlignedBB getCollisionBoundingBoxFromPool( final World world, final int x, final int y, final int z ) - { - return null; - } - - @Override - public boolean canCollideCheck( final int metadata, final boolean isHoldingRightClick ) - { - return false; - } - - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block junk ) - { - final TilePaint tp = this.getTileEntity( w, x, y, z ); - - if( tp != null ) - { - tp.onNeighborBlockChange(); - } - } - - @Override - public Item getItemDropped( final int meta, final Random random, final int fortune ) - { - return null; - } - - @Override - public void dropBlockAsItemWithChance( final World world, final int x, final int y, final int z, final int meta, final float chance, final int fortune ) - { - - } - - @Override - public void fillWithRain( final World w, final int x, final int y, final int z ) - { - if( Platform.isServer() ) - { - w.setBlock( x, y, z, Platform.AIR_BLOCK, 0, 3 ); - } - } - - @Override - public int getLightValue( final IBlockAccess w, final int x, final int y, final int z ) - { - final TilePaint tp = this.getTileEntity( w, x, y, z ); - - if( tp != null ) - { - return tp.getLightLevel(); - } - - return 0; - } - - @Override - public boolean isReplaceable( final IBlockAccess world, final int x, final int y, final int z ) - { - return true; - } - - @Override - public boolean isAir( final IBlockAccess world, final int x, final int y, final int z ) - { - return true; - } +public class BlockPaint extends AEBaseTileBlock { + + public BlockPaint() { + super(new MaterialLiquid(MapColor.airColor)); + + this.setTileEntity(TilePaint.class); + this.setLightOpacity(0); + this.isFullSize = false; + this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.PaintBalls)); + } + + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockPaint getRenderer() { + return new RenderBlockPaint(); + } + + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks(final Item item, final CreativeTabs tabs, final List itemStacks) { + // do nothing + } + + @Override + public AxisAlignedBB getCollisionBoundingBoxFromPool(final World world, final int x, final int y, final int z) { + return null; + } + + @Override + public boolean canCollideCheck(final int metadata, final boolean isHoldingRightClick) { + return false; + } + + @Override + public void onNeighborBlockChange(final World w, final int x, final int y, final int z, final Block junk) { + final TilePaint tp = this.getTileEntity(w, x, y, z); + + if (tp != null) { + tp.onNeighborBlockChange(); + } + } + + @Override + public Item getItemDropped(final int meta, final Random random, final int fortune) { + return null; + } + + @Override + public void dropBlockAsItemWithChance( + final World world, + final int x, + final int y, + final int z, + final int meta, + final float chance, + final int fortune) {} + + @Override + public void fillWithRain(final World w, final int x, final int y, final int z) { + if (Platform.isServer()) { + w.setBlock(x, y, z, Platform.AIR_BLOCK, 0, 3); + } + } + + @Override + public int getLightValue(final IBlockAccess w, final int x, final int y, final int z) { + final TilePaint tp = this.getTileEntity(w, x, y, z); + + if (tp != null) { + return tp.getLightLevel(); + } + + return 0; + } + + @Override + public boolean isReplaceable(final IBlockAccess world, final int x, final int y, final int z) { + return true; + } + + @Override + public boolean isAir(final IBlockAccess world, final int x, final int y, final int z) { + return true; + } } diff --git a/src/main/java/appeng/block/misc/BlockQuartzGrowthAccelerator.java b/src/main/java/appeng/block/misc/BlockQuartzGrowthAccelerator.java index 3fcb1b9d2a2..92904c111f5 100644 --- a/src/main/java/appeng/block/misc/BlockQuartzGrowthAccelerator.java +++ b/src/main/java/appeng/block/misc/BlockQuartzGrowthAccelerator.java @@ -18,7 +18,6 @@ package appeng.block.misc; - import appeng.api.util.IOrientableBlock; import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockQuartzAccelerator; @@ -30,122 +29,112 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.Random; - - -public class BlockQuartzGrowthAccelerator extends AEBaseTileBlock implements IOrientableBlock -{ - - public BlockQuartzGrowthAccelerator() - { - super( Material.rock ); - this.setStepSound( Block.soundTypeMetal ); - this.setTileEntity( TileQuartzGrowthAccelerator.class ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockQuartzAccelerator getRenderer() - { - return new RenderBlockQuartzAccelerator(); - } - - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World w, final int x, final int y, final int z, final Random r ) - { - if( !AEConfig.instance.enableEffects ) - { - return; - } - - final TileQuartzGrowthAccelerator cga = this.getTileEntity( w, x, y, z ); - - if( cga != null && cga.isPowered() && CommonHelper.proxy.shouldAddParticles( r ) ) - { - final double d0 = r.nextFloat() - 0.5F; - final double d1 = r.nextFloat() - 0.5F; - - final ForgeDirection up = cga.getUp(); - final ForgeDirection forward = cga.getForward(); - final ForgeDirection west = Platform.crossProduct( forward, up ); - - double rx = 0.5 + x; - double ry = 0.5 + y; - double rz = 0.5 + z; - - rx += up.offsetX * d0; - ry += up.offsetY * d0; - rz += up.offsetZ * d0; - - double dz = 0; - double dx = 0; - switch( r.nextInt( 4 ) ) - { - case 0: - dx = 0.6; - dz = d1; - if( !w.getBlock( x + west.offsetX, y + west.offsetY, z + west.offsetZ ).isAir( w, x + west.offsetX, y + west.offsetY, z + west.offsetZ ) ) - { - return; - } - break; - case 1: - dx = d1; - dz += 0.6; - if( !w.getBlock( x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ ).isAir( w, x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ ) ) - { - return; - } - break; - case 2: - dx = d1; - dz = -0.6; - if( !w.getBlock( x - forward.offsetX, y - forward.offsetY, z - forward.offsetZ ).isAir( w, x - forward.offsetX, y - forward.offsetY, z - forward.offsetZ ) ) - { - return; - } - break; - case 3: - dx = -0.6; - dz = d1; - if( !w.getBlock( x - west.offsetX, y - west.offsetY, z - west.offsetZ ).isAir( w, x - west.offsetX, y - west.offsetY, z - west.offsetZ ) ) - { - return; - } - break; - } - - rx += dx * west.offsetX; - ry += dx * west.offsetY; - rz += dx * west.offsetZ; - - rx += dz * forward.offsetX; - ry += dz * forward.offsetY; - rz += dz * forward.offsetZ; - - final LightningFX fx = new LightningFX( w, rx, ry, rz, 0.0D, 0.0D, 0.0D ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - - @Override - /** - * TODO: remove with 1.8 or later - * - * @Deprecated no longer true, only kept to prevent missing blocks. - */ - @Deprecated - public boolean usesMetadata() - { - return true; - } +public class BlockQuartzGrowthAccelerator extends AEBaseTileBlock implements IOrientableBlock { + + public BlockQuartzGrowthAccelerator() { + super(Material.rock); + this.setStepSound(Block.soundTypeMetal); + this.setTileEntity(TileQuartzGrowthAccelerator.class); + this.setFeature(EnumSet.of(AEFeature.Core)); + } + + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockQuartzAccelerator getRenderer() { + return new RenderBlockQuartzAccelerator(); + } + + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(final World w, final int x, final int y, final int z, final Random r) { + if (!AEConfig.instance.enableEffects) { + return; + } + + final TileQuartzGrowthAccelerator cga = this.getTileEntity(w, x, y, z); + + if (cga != null && cga.isPowered() && CommonHelper.proxy.shouldAddParticles(r)) { + final double d0 = r.nextFloat() - 0.5F; + final double d1 = r.nextFloat() - 0.5F; + + final ForgeDirection up = cga.getUp(); + final ForgeDirection forward = cga.getForward(); + final ForgeDirection west = Platform.crossProduct(forward, up); + + double rx = 0.5 + x; + double ry = 0.5 + y; + double rz = 0.5 + z; + + rx += up.offsetX * d0; + ry += up.offsetY * d0; + rz += up.offsetZ * d0; + + double dz = 0; + double dx = 0; + switch (r.nextInt(4)) { + case 0: + dx = 0.6; + dz = d1; + if (!w.getBlock(x + west.offsetX, y + west.offsetY, z + west.offsetZ) + .isAir(w, x + west.offsetX, y + west.offsetY, z + west.offsetZ)) { + return; + } + break; + case 1: + dx = d1; + dz += 0.6; + if (!w.getBlock(x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ) + .isAir(w, x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ)) { + return; + } + break; + case 2: + dx = d1; + dz = -0.6; + if (!w.getBlock(x - forward.offsetX, y - forward.offsetY, z - forward.offsetZ) + .isAir(w, x - forward.offsetX, y - forward.offsetY, z - forward.offsetZ)) { + return; + } + break; + case 3: + dx = -0.6; + dz = d1; + if (!w.getBlock(x - west.offsetX, y - west.offsetY, z - west.offsetZ) + .isAir(w, x - west.offsetX, y - west.offsetY, z - west.offsetZ)) { + return; + } + break; + } + + rx += dx * west.offsetX; + ry += dx * west.offsetY; + rz += dx * west.offsetZ; + + rx += dz * forward.offsetX; + ry += dz * forward.offsetY; + rz += dz * forward.offsetZ; + + final LightningFX fx = new LightningFX(w, rx, ry, rz, 0.0D, 0.0D, 0.0D); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } + + @Override + /** + * TODO: remove with 1.8 or later + * + * @Deprecated no longer true, only kept to prevent missing blocks. + */ + @Deprecated + public boolean usesMetadata() { + return true; + } } diff --git a/src/main/java/appeng/block/misc/BlockQuartzTorch.java b/src/main/java/appeng/block/misc/BlockQuartzTorch.java index ff164a28518..9f1d819e146 100644 --- a/src/main/java/appeng/block/misc/BlockQuartzTorch.java +++ b/src/main/java/appeng/block/misc/BlockQuartzTorch.java @@ -18,7 +18,6 @@ package appeng.block.misc; - import appeng.api.util.IOrientable; import appeng.api.util.IOrientableBlock; import appeng.block.AEBaseBlock; @@ -31,6 +30,10 @@ import appeng.helpers.MetaRotation; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; @@ -40,130 +43,121 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; - - -public class BlockQuartzTorch extends AEBaseBlock implements IOrientableBlock, ICustomCollision -{ - public BlockQuartzTorch() - { - super( Material.circuits ); - - this.setFeature( EnumSet.of( AEFeature.DecorativeLights ) ); - this.setLightLevel( 0.9375F ); - this.setLightOpacity( 0 ); - this.isFullSize = false; - this.isOpaque = false; - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderQuartzTorch getRenderer() - { - return new RenderQuartzTorch(); - } - - @Override - public boolean isValidOrientation( final World w, final int x, final int y, final int z, final ForgeDirection forward, final ForgeDirection up ) - { - return this.canPlaceAt( w, x, y, z, up.getOpposite() ); - } - - private boolean canPlaceAt( final World w, final int x, final int y, final int z, final ForgeDirection dir ) - { - return w.isSideSolid( x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite(), false ); - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - final ForgeDirection up = this.getOrientable( w, x, y, z ).getUp(); - final double xOff = -0.3 * up.offsetX; - final double yOff = -0.3 * up.offsetY; - final double zOff = -0.3 * up.offsetZ; - return Collections.singletonList( AxisAlignedBB.getBoundingBox( xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7 ) ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - {/* - * double xOff = -0.15 * getUp().offsetX; double yOff = -0.15 * getUp().offsetY; double zOff = -0.15 * - * getUp().offsetZ; out.add( AxisAlignedBB.getBoundingBox( xOff + (double) x + 0.15, yOff + (double) y + 0.15, zOff - * + (double) z + 0.15,// ahh xOff + (double) x + 0.85, yOff + (double) y + 0.85, zOff + (double) z + 0.85 ) ); - */ - } - - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World w, final int x, final int y, final int z, final Random r ) - { - if( !AEConfig.instance.enableEffects ) - { - return; - } - - if( r.nextFloat() < 0.98 ) - { - return; - } - - final ForgeDirection up = this.getOrientable( w, x, y, z ).getUp(); - final double xOff = -0.3 * up.offsetX; - final double yOff = -0.3 * up.offsetY; - final double zOff = -0.3 * up.offsetZ; - for( int bolts = 0; bolts < 3; bolts++ ) - { - if( CommonHelper.proxy.shouldAddParticles( r ) ) - { - final LightningFX fx = new LightningFX( w, xOff + 0.5 + x, yOff + 0.5 + y, zOff + 0.5 + z, 0.0D, 0.0D, 0.0D ); - - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - } - - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block id ) - { - final ForgeDirection up = this.getOrientable( w, x, y, z ).getUp(); - if( !this.canPlaceAt( w, x, y, z, up.getOpposite() ) ) - { - this.dropTorch( w, x, y, z ); - } - } - - private void dropTorch( final World w, final int x, final int y, final int z ) - { - w.func_147480_a( x, y, z, true ); - // w.destroyBlock( x, y, z, true ); - w.markBlockForUpdate( x, y, z ); - } - - @Override - public boolean canPlaceBlockAt( final World w, final int x, final int y, final int z ) - { - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.canPlaceAt( w, x, y, z, dir ) ) - { - return true; - } - } - return false; - } - - @Override - public boolean usesMetadata() - { - return true; - } - - @Override - public IOrientable getOrientable( final IBlockAccess w, final int x, final int y, final int z ) - { - return new MetaRotation( w, x, y, z ); - } +public class BlockQuartzTorch extends AEBaseBlock implements IOrientableBlock, ICustomCollision { + public BlockQuartzTorch() { + super(Material.circuits); + + this.setFeature(EnumSet.of(AEFeature.DecorativeLights)); + this.setLightLevel(0.9375F); + this.setLightOpacity(0); + this.isFullSize = false; + this.isOpaque = false; + } + + @Override + @SideOnly(Side.CLIENT) + protected RenderQuartzTorch getRenderer() { + return new RenderQuartzTorch(); + } + + @Override + public boolean isValidOrientation( + final World w, + final int x, + final int y, + final int z, + final ForgeDirection forward, + final ForgeDirection up) { + return this.canPlaceAt(w, x, y, z, up.getOpposite()); + } + + private boolean canPlaceAt(final World w, final int x, final int y, final int z, final ForgeDirection dir) { + return w.isSideSolid(x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite(), false); + } + + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual) { + final ForgeDirection up = this.getOrientable(w, x, y, z).getUp(); + final double xOff = -0.3 * up.offsetX; + final double yOff = -0.3 * up.offsetY; + final double zOff = -0.3 * up.offsetZ; + return Collections.singletonList( + AxisAlignedBB.getBoundingBox(xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7)); + } + + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e) { + /* + * double xOff = -0.15 * getUp().offsetX; double yOff = -0.15 * getUp().offsetY; double zOff = -0.15 * + * getUp().offsetZ; out.add( AxisAlignedBB.getBoundingBox( xOff + (double) x + 0.15, yOff + (double) y + 0.15, zOff + * + (double) z + 0.15,// ahh xOff + (double) x + 0.85, yOff + (double) y + 0.85, zOff + (double) z + 0.85 ) ); + */ + } + + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(final World w, final int x, final int y, final int z, final Random r) { + if (!AEConfig.instance.enableEffects) { + return; + } + + if (r.nextFloat() < 0.98) { + return; + } + + final ForgeDirection up = this.getOrientable(w, x, y, z).getUp(); + final double xOff = -0.3 * up.offsetX; + final double yOff = -0.3 * up.offsetY; + final double zOff = -0.3 * up.offsetZ; + for (int bolts = 0; bolts < 3; bolts++) { + if (CommonHelper.proxy.shouldAddParticles(r)) { + final LightningFX fx = + new LightningFX(w, xOff + 0.5 + x, yOff + 0.5 + y, zOff + 0.5 + z, 0.0D, 0.0D, 0.0D); + + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } + } + + @Override + public void onNeighborBlockChange(final World w, final int x, final int y, final int z, final Block id) { + final ForgeDirection up = this.getOrientable(w, x, y, z).getUp(); + if (!this.canPlaceAt(w, x, y, z, up.getOpposite())) { + this.dropTorch(w, x, y, z); + } + } + + private void dropTorch(final World w, final int x, final int y, final int z) { + w.func_147480_a(x, y, z, true); + // w.destroyBlock( x, y, z, true ); + w.markBlockForUpdate(x, y, z); + } + + @Override + public boolean canPlaceBlockAt(final World w, final int x, final int y, final int z) { + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + if (this.canPlaceAt(w, x, y, z, dir)) { + return true; + } + } + return false; + } + + @Override + public boolean usesMetadata() { + return true; + } + + @Override + public IOrientable getOrientable(final IBlockAccess w, final int x, final int y, final int z) { + return new MetaRotation(w, x, y, z); + } } diff --git a/src/main/java/appeng/block/misc/BlockSecurity.java b/src/main/java/appeng/block/misc/BlockSecurity.java index 38f6088c9b8..85fec8dd896 100644 --- a/src/main/java/appeng/block/misc/BlockSecurity.java +++ b/src/main/java/appeng/block/misc/BlockSecurity.java @@ -18,7 +18,6 @@ package appeng.block.misc; - import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RendererSecurity; import appeng.core.features.AEFeature; @@ -27,51 +26,51 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class BlockSecurity extends AEBaseTileBlock -{ +public class BlockSecurity extends AEBaseTileBlock { - public BlockSecurity() - { - super( Material.iron ); + public BlockSecurity() { + super(Material.iron); - this.setTileEntity( TileSecurity.class ); - this.setFeature( EnumSet.of( AEFeature.Security ) ); - } + this.setTileEntity(TileSecurity.class); + this.setFeature(EnumSet.of(AEFeature.Security)); + } - @Override - @SideOnly( Side.CLIENT ) - protected RendererSecurity getRenderer() - { - return new RendererSecurity(); - } + @Override + @SideOnly(Side.CLIENT) + protected RendererSecurity getRenderer() { + return new RendererSecurity(); + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileSecurity tg = this.getTileEntity( w, x, y, z ); - if( tg != null ) - { - if( Platform.isClient() ) - { - return true; - } + final TileSecurity tg = this.getTileEntity(w, x, y, z); + if (tg != null) { + if (Platform.isClient()) { + return true; + } - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_SECURITY ); - return true; - } - return false; - } + Platform.openGUI(p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_SECURITY); + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/misc/BlockSkyCompass.java b/src/main/java/appeng/block/misc/BlockSkyCompass.java index 4a1739c5b0f..385754bf2c7 100644 --- a/src/main/java/appeng/block/misc/BlockSkyCompass.java +++ b/src/main/java/appeng/block/misc/BlockSkyCompass.java @@ -18,7 +18,6 @@ package appeng.block.misc; - import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockSkyCompass; import appeng.core.features.AEFeature; @@ -26,6 +25,9 @@ import appeng.tile.misc.TileSkyCompass; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; @@ -36,155 +38,144 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; - - -public class BlockSkyCompass extends AEBaseTileBlock implements ICustomCollision -{ - - public BlockSkyCompass() - { - super( Material.iron ); - this.setTileEntity( TileSkyCompass.class ); - this.isOpaque = this.isFullSize = false; - this.lightOpacity = 0; - this.setFeature( EnumSet.of( AEFeature.MeteoriteCompass ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockSkyCompass getRenderer() - { - return new RenderBlockSkyCompass(); - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getIcon( final int direction, final int metadata ) - { - return Blocks.iron_block.getIcon( direction, metadata ); - } - - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - // :P - } - - @Override - public boolean isValidOrientation( final World w, final int x, final int y, final int z, final ForgeDirection forward, final ForgeDirection up ) - { - final TileSkyCompass sc = this.getTileEntity( w, x, y, z ); - if( sc != null ) - { - return false; - } - return this.canPlaceAt( w, x, y, z, forward.getOpposite() ); - } - - private boolean canPlaceAt( final World w, final int x, final int y, final int z, final ForgeDirection dir ) - { - return w.isSideSolid( x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite(), false ); - } - - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block id ) - { - final TileSkyCompass sc = this.getTileEntity( w, x, y, z ); - final ForgeDirection up = sc.getForward(); - if( !this.canPlaceAt( w, x, y, z, up.getOpposite() ) ) - { - this.dropTorch( w, x, y, z ); - } - } - - private void dropTorch( final World w, final int x, final int y, final int z ) - { - w.func_147480_a( x, y, z, true ); - // w.destroyBlock( x, y, z, true ); - w.markBlockForUpdate( x, y, z ); - } - - @Override - public boolean canPlaceBlockAt( final World w, final int x, final int y, final int z ) - { - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.canPlaceAt( w, x, y, z, dir ) ) - { - return true; - } - } - return false; - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - final TileSkyCompass tile = this.getTileEntity( w, x, y, z ); - if( tile != null ) - { - final ForgeDirection forward = tile.getForward(); - - double minX = 0; - double minY = 0; - double minZ = 0; - double maxX = 1; - double maxY = 1; - double maxZ = 1; - - switch( forward ) - { - case DOWN: - minZ = minX = 5.0 / 16.0; - maxZ = maxX = 11.0 / 16.0; - maxY = 1.0; - minY = 14.0 / 16.0; - break; - case EAST: - minZ = minY = 5.0 / 16.0; - maxZ = maxY = 11.0 / 16.0; - maxX = 2.0 / 16.0; - minX = 0.0; - break; - case NORTH: - minY = minX = 5.0 / 16.0; - maxY = maxX = 11.0 / 16.0; - maxZ = 1.0; - minZ = 14.0 / 16.0; - break; - case SOUTH: - minY = minX = 5.0 / 16.0; - maxY = maxX = 11.0 / 16.0; - maxZ = 2.0 / 16.0; - minZ = 0.0; - break; - case UP: - minZ = minX = 5.0 / 16.0; - maxZ = maxX = 11.0 / 16.0; - maxY = 2.0 / 16.0; - minY = 0.0; - break; - case WEST: - minZ = minY = 5.0 / 16.0; - maxZ = maxY = 11.0 / 16.0; - maxX = 1.0; - minX = 14.0 / 16.0; - break; - default: - break; - } - - return Collections.singletonList( AxisAlignedBB.getBoundingBox( minX, minY, minZ, maxX, maxY, maxZ ) ); - } - return Collections.singletonList( AxisAlignedBB.getBoundingBox( 0.0, 0, 0.0, 1.0, 1.0, 1.0 ) ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - - } +public class BlockSkyCompass extends AEBaseTileBlock implements ICustomCollision { + + public BlockSkyCompass() { + super(Material.iron); + this.setTileEntity(TileSkyCompass.class); + this.isOpaque = this.isFullSize = false; + this.lightOpacity = 0; + this.setFeature(EnumSet.of(AEFeature.MeteoriteCompass)); + } + + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockSkyCompass getRenderer() { + return new RenderBlockSkyCompass(); + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(final int direction, final int metadata) { + return Blocks.iron_block.getIcon(direction, metadata); + } + + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) { + // :P + } + + @Override + public boolean isValidOrientation( + final World w, + final int x, + final int y, + final int z, + final ForgeDirection forward, + final ForgeDirection up) { + final TileSkyCompass sc = this.getTileEntity(w, x, y, z); + if (sc != null) { + return false; + } + return this.canPlaceAt(w, x, y, z, forward.getOpposite()); + } + + private boolean canPlaceAt(final World w, final int x, final int y, final int z, final ForgeDirection dir) { + return w.isSideSolid(x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite(), false); + } + + @Override + public void onNeighborBlockChange(final World w, final int x, final int y, final int z, final Block id) { + final TileSkyCompass sc = this.getTileEntity(w, x, y, z); + final ForgeDirection up = sc.getForward(); + if (!this.canPlaceAt(w, x, y, z, up.getOpposite())) { + this.dropTorch(w, x, y, z); + } + } + + private void dropTorch(final World w, final int x, final int y, final int z) { + w.func_147480_a(x, y, z, true); + // w.destroyBlock( x, y, z, true ); + w.markBlockForUpdate(x, y, z); + } + + @Override + public boolean canPlaceBlockAt(final World w, final int x, final int y, final int z) { + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + if (this.canPlaceAt(w, x, y, z, dir)) { + return true; + } + } + return false; + } + + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual) { + final TileSkyCompass tile = this.getTileEntity(w, x, y, z); + if (tile != null) { + final ForgeDirection forward = tile.getForward(); + + double minX = 0; + double minY = 0; + double minZ = 0; + double maxX = 1; + double maxY = 1; + double maxZ = 1; + + switch (forward) { + case DOWN: + minZ = minX = 5.0 / 16.0; + maxZ = maxX = 11.0 / 16.0; + maxY = 1.0; + minY = 14.0 / 16.0; + break; + case EAST: + minZ = minY = 5.0 / 16.0; + maxZ = maxY = 11.0 / 16.0; + maxX = 2.0 / 16.0; + minX = 0.0; + break; + case NORTH: + minY = minX = 5.0 / 16.0; + maxY = maxX = 11.0 / 16.0; + maxZ = 1.0; + minZ = 14.0 / 16.0; + break; + case SOUTH: + minY = minX = 5.0 / 16.0; + maxY = maxX = 11.0 / 16.0; + maxZ = 2.0 / 16.0; + minZ = 0.0; + break; + case UP: + minZ = minX = 5.0 / 16.0; + maxZ = maxX = 11.0 / 16.0; + maxY = 2.0 / 16.0; + minY = 0.0; + break; + case WEST: + minZ = minY = 5.0 / 16.0; + maxZ = maxY = 11.0 / 16.0; + maxX = 1.0; + minX = 14.0 / 16.0; + break; + default: + break; + } + + return Collections.singletonList(AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ)); + } + return Collections.singletonList(AxisAlignedBB.getBoundingBox(0.0, 0, 0.0, 1.0, 1.0, 1.0)); + } + + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e) {} } diff --git a/src/main/java/appeng/block/misc/BlockTinyTNT.java b/src/main/java/appeng/block/misc/BlockTinyTNT.java index c7648d1446c..113f2237ae4 100644 --- a/src/main/java/appeng/block/misc/BlockTinyTNT.java +++ b/src/main/java/appeng/block/misc/BlockTinyTNT.java @@ -18,7 +18,6 @@ package appeng.block.misc; - import appeng.block.AEBaseBlock; import appeng.client.render.blocks.RenderTinyTNT; import appeng.client.texture.FullIcon; @@ -31,6 +30,9 @@ import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.BlockDispenser; import net.minecraft.block.material.Material; @@ -47,141 +49,140 @@ import net.minecraft.world.Explosion; import net.minecraft.world.World; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; - - -public class BlockTinyTNT extends AEBaseBlock implements ICustomCollision -{ - - public BlockTinyTNT() - { - super( Material.tnt ); - this.setLightOpacity( 1 ); - this.setBlockBounds( 0.25f, 0.0f, 0.25f, 0.75f, 0.5f, 0.75f ); - this.isFullSize = this.isOpaque = false; - this.setStepSound( soundTypeGrass ); - this.setHardness( 0F ); - this.setFeature( EnumSet.of( AEFeature.TinyTNT ) ); - - EntityRegistry.registerModEntity( EntityTinyTNTPrimed.class, "EntityTinyTNTPrimed", EntityIds.get( EntityTinyTNTPrimed.class ), AppEng.instance(), 16, 4, true ); - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderTinyTNT getRenderer() - { - return new RenderTinyTNT(); - } - - @Override - public void postInit() - { - super.postInit(); - BlockDispenser.dispenseBehaviorRegistry.putObject( Item.getItemFromBlock( this ), new DispenserBehaviorTinyTNT() ); - } - - @Override - public IIcon getIcon( final int direction, final int metadata ) - { - return new FullIcon( Blocks.tnt.getIcon( direction, metadata ) ); - } - - @Override - public boolean onBlockActivated( World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ ) - { - if( player.getCurrentEquippedItem() != null && player.getCurrentEquippedItem().getItem() == Items.flint_and_steel ) - { - this.startFuse( w, x, y, z, player ); - w.setBlockToAir( x, y, z ); - player.getCurrentEquippedItem().damageItem( 1, player ); - - return true; - } - - return super.onBlockActivated( w, x, y, z, player, side, hitX, hitY, hitZ ); - } - - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - // no images required. - } - - @Override - public void onBlockAdded( final World w, final int x, final int y, final int z ) - { - super.onBlockAdded( w, x, y, z ); - - if( w.isBlockIndirectlyGettingPowered( x, y, z ) ) - { - this.startFuse( w, x, y, z, null ); - w.setBlockToAir( x, y, z ); - } - } - - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block id ) - { - if( w.isBlockIndirectlyGettingPowered( x, y, z ) ) - { - this.startFuse( w, x, y, z, null ); - w.setBlockToAir( x, y, z ); - } - } - - @Override - public void onBlockDestroyedByExplosion( final World w, final int x, final int y, final int z, final Explosion exp ) - { - if( !w.isRemote ) - { - final EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed( w, x + 0.5F, y + 0.5F, z + 0.5F, exp.getExplosivePlacedBy() ); - primedTinyTNTEntity.fuse = w.rand.nextInt( primedTinyTNTEntity.fuse / 4 ) + primedTinyTNTEntity.fuse / 8; - w.spawnEntityInWorld( primedTinyTNTEntity ); - } - } - - @Override - public void onEntityCollidedWithBlock( final World w, final int x, final int y, final int z, final Entity entity ) - { - if( entity instanceof EntityArrow && !w.isRemote ) - { - final EntityArrow entityarrow = (EntityArrow) entity; - - if( entityarrow.isBurning() ) - { - this.startFuse( w, x, y, z, entityarrow.shootingEntity instanceof EntityLivingBase ? (EntityLivingBase) entityarrow.shootingEntity : null ); - w.setBlockToAir( x, y, z ); - } - } - } - - @Override - public boolean canDropFromExplosion( final Explosion exp ) - { - return false; - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - return Collections.singletonList( AxisAlignedBB.getBoundingBox( 0.25, 0, 0.25, 0.75, 0.5, 0.75 ) ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - out.add( AxisAlignedBB.getBoundingBox( 0.25, 0, 0.25, 0.75, 0.5, 0.75 ) ); - } - - public void startFuse( final World w, final int x, final int y, final int z, final EntityLivingBase igniter ) - { - if( !w.isRemote ) - { - final EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed( w, x + 0.5F, y + 0.5F, z + 0.5F, igniter ); - w.spawnEntityInWorld( primedTinyTNTEntity ); - w.playSoundAtEntity( primedTinyTNTEntity, "game.tnt.primed", 1.0F, 1.0F ); - } - } +public class BlockTinyTNT extends AEBaseBlock implements ICustomCollision { + + public BlockTinyTNT() { + super(Material.tnt); + this.setLightOpacity(1); + this.setBlockBounds(0.25f, 0.0f, 0.25f, 0.75f, 0.5f, 0.75f); + this.isFullSize = this.isOpaque = false; + this.setStepSound(soundTypeGrass); + this.setHardness(0F); + this.setFeature(EnumSet.of(AEFeature.TinyTNT)); + + EntityRegistry.registerModEntity( + EntityTinyTNTPrimed.class, + "EntityTinyTNTPrimed", + EntityIds.get(EntityTinyTNTPrimed.class), + AppEng.instance(), + 16, + 4, + true); + } + + @Override + @SideOnly(Side.CLIENT) + protected RenderTinyTNT getRenderer() { + return new RenderTinyTNT(); + } + + @Override + public void postInit() { + super.postInit(); + BlockDispenser.dispenseBehaviorRegistry.putObject(Item.getItemFromBlock(this), new DispenserBehaviorTinyTNT()); + } + + @Override + public IIcon getIcon(final int direction, final int metadata) { + return new FullIcon(Blocks.tnt.getIcon(direction, metadata)); + } + + @Override + public boolean onBlockActivated( + World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) { + if (player.getCurrentEquippedItem() != null + && player.getCurrentEquippedItem().getItem() == Items.flint_and_steel) { + this.startFuse(w, x, y, z, player); + w.setBlockToAir(x, y, z); + player.getCurrentEquippedItem().damageItem(1, player); + + return true; + } + + return super.onBlockActivated(w, x, y, z, player, side, hitX, hitY, hitZ); + } + + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) { + // no images required. + } + + @Override + public void onBlockAdded(final World w, final int x, final int y, final int z) { + super.onBlockAdded(w, x, y, z); + + if (w.isBlockIndirectlyGettingPowered(x, y, z)) { + this.startFuse(w, x, y, z, null); + w.setBlockToAir(x, y, z); + } + } + + @Override + public void onNeighborBlockChange(final World w, final int x, final int y, final int z, final Block id) { + if (w.isBlockIndirectlyGettingPowered(x, y, z)) { + this.startFuse(w, x, y, z, null); + w.setBlockToAir(x, y, z); + } + } + + @Override + public void onBlockDestroyedByExplosion(final World w, final int x, final int y, final int z, final Explosion exp) { + if (!w.isRemote) { + final EntityTinyTNTPrimed primedTinyTNTEntity = + new EntityTinyTNTPrimed(w, x + 0.5F, y + 0.5F, z + 0.5F, exp.getExplosivePlacedBy()); + primedTinyTNTEntity.fuse = w.rand.nextInt(primedTinyTNTEntity.fuse / 4) + primedTinyTNTEntity.fuse / 8; + w.spawnEntityInWorld(primedTinyTNTEntity); + } + } + + @Override + public void onEntityCollidedWithBlock(final World w, final int x, final int y, final int z, final Entity entity) { + if (entity instanceof EntityArrow && !w.isRemote) { + final EntityArrow entityarrow = (EntityArrow) entity; + + if (entityarrow.isBurning()) { + this.startFuse( + w, + x, + y, + z, + entityarrow.shootingEntity instanceof EntityLivingBase + ? (EntityLivingBase) entityarrow.shootingEntity + : null); + w.setBlockToAir(x, y, z); + } + } + } + + @Override + public boolean canDropFromExplosion(final Explosion exp) { + return false; + } + + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual) { + return Collections.singletonList(AxisAlignedBB.getBoundingBox(0.25, 0, 0.25, 0.75, 0.5, 0.75)); + } + + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e) { + out.add(AxisAlignedBB.getBoundingBox(0.25, 0, 0.25, 0.75, 0.5, 0.75)); + } + + public void startFuse(final World w, final int x, final int y, final int z, final EntityLivingBase igniter) { + if (!w.isRemote) { + final EntityTinyTNTPrimed primedTinyTNTEntity = + new EntityTinyTNTPrimed(w, x + 0.5F, y + 0.5F, z + 0.5F, igniter); + w.spawnEntityInWorld(primedTinyTNTEntity); + w.playSoundAtEntity(primedTinyTNTEntity, "game.tnt.primed", 1.0F, 1.0F); + } + } } diff --git a/src/main/java/appeng/block/misc/BlockVibrationChamber.java b/src/main/java/appeng/block/misc/BlockVibrationChamber.java index b1b7aaa1ad1..18d27d59c28 100644 --- a/src/main/java/appeng/block/misc/BlockVibrationChamber.java +++ b/src/main/java/appeng/block/misc/BlockVibrationChamber.java @@ -18,7 +18,6 @@ package appeng.block.misc; - import appeng.block.AEBaseTileBlock; import appeng.client.texture.ExtraBlockTextures; import appeng.core.AEConfig; @@ -27,6 +26,8 @@ import appeng.tile.AEBaseTile; import appeng.tile.misc.TileVibrationChamber; import appeng.util.Platform; +import java.util.EnumSet; +import java.util.Random; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.IIcon; @@ -34,99 +35,92 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.Random; - - -public final class BlockVibrationChamber extends AEBaseTileBlock -{ - - public BlockVibrationChamber() - { - super( Material.iron ); - this.setTileEntity( TileVibrationChamber.class ); - this.setHardness( 4.2F ); - this.setFeature( EnumSet.of( AEFeature.PowerGen ) ); - } - - @Override - public IIcon getIcon( final IBlockAccess w, final int x, final int y, final int z, final int s ) - { - final IIcon ico = super.getIcon( w, x, y, z, s ); - final TileVibrationChamber tvc = this.getTileEntity( w, x, y, z ); - - if( tvc != null && tvc.isOn && ico == this.getRendererInstance().getTexture( ForgeDirection.SOUTH ) ) - { - return ExtraBlockTextures.BlockVibrationChamberFrontOn.getIcon(); - } - - return ico; - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( player.isSneaking() ) - { - return false; - } - - if( Platform.isServer() ) - { - final TileVibrationChamber tc = this.getTileEntity( w, x, y, z ); - if( tc != null && !player.isSneaking() ) - { - Platform.openGUI( player, tc, ForgeDirection.getOrientation( side ), GuiBridge.GUI_VIBRATION_CHAMBER ); - return true; - } - } - - return true; - } - - @Override - public void randomDisplayTick( final World w, final int x, final int y, final int z, final Random r ) - { - if( !AEConfig.instance.enableEffects ) - { - return; - } - - final AEBaseTile tile = this.getTileEntity( w, x, y, z ); - if( tile instanceof TileVibrationChamber ) - { - final TileVibrationChamber tc = (TileVibrationChamber) tile; - if( tc.isOn ) - { - float f1 = x + 0.5F; - float f2 = y + 0.5F; - float f3 = z + 0.5F; - - final ForgeDirection forward = tc.getForward(); - final ForgeDirection up = tc.getUp(); - - final int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; - final int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; - final int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; - - f1 += forward.offsetX * 0.6; - f2 += forward.offsetY * 0.6; - f3 += forward.offsetZ * 0.6; - - final float ox = r.nextFloat(); - final float oy = r.nextFloat() * 0.2f; - - f1 += up.offsetX * ( -0.3 + oy ); - f2 += up.offsetY * ( -0.3 + oy ); - f3 += up.offsetZ * ( -0.3 + oy ); - - f1 += west_x * ( 0.3 * ox - 0.15 ); - f2 += west_y * ( 0.3 * ox - 0.15 ); - f3 += west_z * ( 0.3 * ox - 0.15 ); - - w.spawnParticle( "smoke", f1, f2, f3, 0.0D, 0.0D, 0.0D ); - w.spawnParticle( "flame", f1, f2, f3, 0.0D, 0.0D, 0.0D ); - } - } - } +public final class BlockVibrationChamber extends AEBaseTileBlock { + + public BlockVibrationChamber() { + super(Material.iron); + this.setTileEntity(TileVibrationChamber.class); + this.setHardness(4.2F); + this.setFeature(EnumSet.of(AEFeature.PowerGen)); + } + + @Override + public IIcon getIcon(final IBlockAccess w, final int x, final int y, final int z, final int s) { + final IIcon ico = super.getIcon(w, x, y, z, s); + final TileVibrationChamber tvc = this.getTileEntity(w, x, y, z); + + if (tvc != null && tvc.isOn && ico == this.getRendererInstance().getTexture(ForgeDirection.SOUTH)) { + return ExtraBlockTextures.BlockVibrationChamberFrontOn.getIcon(); + } + + return ico; + } + + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (player.isSneaking()) { + return false; + } + + if (Platform.isServer()) { + final TileVibrationChamber tc = this.getTileEntity(w, x, y, z); + if (tc != null && !player.isSneaking()) { + Platform.openGUI(player, tc, ForgeDirection.getOrientation(side), GuiBridge.GUI_VIBRATION_CHAMBER); + return true; + } + } + + return true; + } + + @Override + public void randomDisplayTick(final World w, final int x, final int y, final int z, final Random r) { + if (!AEConfig.instance.enableEffects) { + return; + } + + final AEBaseTile tile = this.getTileEntity(w, x, y, z); + if (tile instanceof TileVibrationChamber) { + final TileVibrationChamber tc = (TileVibrationChamber) tile; + if (tc.isOn) { + float f1 = x + 0.5F; + float f2 = y + 0.5F; + float f3 = z + 0.5F; + + final ForgeDirection forward = tc.getForward(); + final ForgeDirection up = tc.getUp(); + + final int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; + final int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; + final int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; + + f1 += forward.offsetX * 0.6; + f2 += forward.offsetY * 0.6; + f3 += forward.offsetZ * 0.6; + + final float ox = r.nextFloat(); + final float oy = r.nextFloat() * 0.2f; + + f1 += up.offsetX * (-0.3 + oy); + f2 += up.offsetY * (-0.3 + oy); + f3 += up.offsetZ * (-0.3 + oy); + + f1 += west_x * (0.3 * ox - 0.15); + f2 += west_y * (0.3 * ox - 0.15); + f3 += west_z * (0.3 * ox - 0.15); + + w.spawnParticle("smoke", f1, f2, f3, 0.0D, 0.0D, 0.0D); + w.spawnParticle("flame", f1, f2, f3, 0.0D, 0.0D, 0.0D); + } + } + } } diff --git a/src/main/java/appeng/block/networking/BlockCableBus.java b/src/main/java/appeng/block/networking/BlockCableBus.java index 66b2085a8ea..140d1b963c3 100644 --- a/src/main/java/appeng/block/networking/BlockCableBus.java +++ b/src/main/java/appeng/block/networking/BlockCableBus.java @@ -18,7 +18,6 @@ package appeng.block.networking; - import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import appeng.api.parts.PartItemStack; @@ -49,6 +48,9 @@ import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; import net.minecraft.block.Block; import net.minecraft.client.particle.EffectRenderer; import net.minecraft.client.particle.EntityDiggingFX; @@ -69,465 +71,438 @@ import powercrystals.minefactoryreloaded.api.rednet.connectivity.IRedNetConnection; import powercrystals.minefactoryreloaded.api.rednet.connectivity.RedNetConnectionType; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; - - -@Interface( iface = "powercrystals.minefactoryreloaded.api.rednet.connectivity.IRedNetConnection", iname = IntegrationType.MFR ) -public class BlockCableBus extends AEBaseTileBlock implements IRedNetConnection -{ - - private static final ICableBusContainer NULL_CABLE_BUS = new NullCableBusContainer(); - private static Class noTesrTile; - private static Class tesrTile; - - /** - * Immibis MB Support. - *

- * It will look for a field named ImmibisMicroblocks_TransformableBlockMarker or - * ImmibisMicroblocks_TransformableTileEntityMarker, modifiers, type, etc can be ignored. - */ - @Reflected - private static final boolean ImmibisMicroblocks_TransformableBlockMarker = true; - - private int myColorMultiplier = 0xffffff; - - public BlockCableBus() - { - super( AEGlassMaterial.INSTANCE ); - this.setLightOpacity( 0 ); - this.isFullSize = this.isOpaque = false; - - // this will actually be overwritten later through setupTile and the combined layers - this.setTileEntity( TileCableBus.class ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } - - @Override - public void randomDisplayTick( final World world, final int x, final int y, final int z, final Random r ) - { - this.cb( world, x, y, z ).randomDisplayTick( world, x, y, z, r ); - } - - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block meh ) - { - this.cb( w, x, y, z ).onNeighborChanged(); - } - - @Override - public Item getItemDropped( final int i, final Random r, final int k ) - { - return null; - } - - @Override - public int getRenderBlockPass() - { - if( AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) ) - { - return 1; - } - return 0; - } - - @Override - public int colorMultiplier( final IBlockAccess world, final int x, final int y, final int z ) - { - return this.myColorMultiplier; - } - - @Override - public int isProvidingWeakPower( final IBlockAccess w, final int x, final int y, final int z, final int side ) - { - return this.cb( w, x, y, z ).isProvidingWeakPower( ForgeDirection.getOrientation( side ).getOpposite() ); - } - - @Override - public boolean canProvidePower() - { - return true; - } - - @Override - public void onEntityCollidedWithBlock( final World w, final int x, final int y, final int z, final Entity e ) - { - this.cb( w, x, y, z ).onEntityCollision( e ); - } - - @Override - public int isProvidingStrongPower( final IBlockAccess w, final int x, final int y, final int z, final int side ) - { - return this.cb( w, x, y, z ).isProvidingStrongPower( ForgeDirection.getOrientation( side ).getOpposite() ); - } - - @Override - public int getLightValue( final IBlockAccess world, final int x, final int y, final int z ) - { - final Block block = world.getBlock( x, y, z ); - if( block != null && block != this ) - { - return block.getLightValue( world, x, y, z ); - } - if( block == null ) - { - return 0; - } - return this.cb( world, x, y, z ).getLightValue(); - } - - @Override - public boolean isLadder( final IBlockAccess world, final int x, final int y, final int z, final EntityLivingBase entity ) - { - return this.cb( world, x, y, z ).isLadder( entity ); - } - - @Override - public boolean isSideSolid( final IBlockAccess w, final int x, final int y, final int z, final ForgeDirection side ) - { - return this.cb( w, x, y, z ).isSolidOnSide( side ); - } - - @Override - public boolean isReplaceable( final IBlockAccess world, final int x, final int y, final int z ) - { - return this.cb( world, x, y, z ).isEmpty(); - } - - @SuppressWarnings( "deprecation" ) - @Override - public boolean removedByPlayer( final World world, final EntityPlayer player, final int x, final int y, final int z ) - { - if( player.capabilities.isCreativeMode ) - { - final AEBaseTile tile = this.getTileEntity( world, x, y, z ); - if( tile != null ) - { - tile.disableDrops(); - } - // maybe ray trace? - } - return super.removedByPlayer( world, player, x, y, z ); - } - - @Override - public boolean canConnectRedstone( final IBlockAccess w, final int x, final int y, final int z, final int side ) - { - switch( side ) - { - case -1: - case 4: - return this.cb( w, x, y, z ).canConnectRedstone( EnumSet.of( ForgeDirection.UP, ForgeDirection.DOWN ) ); - case 0: - return this.cb( w, x, y, z ).canConnectRedstone( EnumSet.of( ForgeDirection.NORTH ) ); - case 1: - return this.cb( w, x, y, z ).canConnectRedstone( EnumSet.of( ForgeDirection.EAST ) ); - case 2: - return this.cb( w, x, y, z ).canConnectRedstone( EnumSet.of( ForgeDirection.SOUTH ) ); - case 3: - return this.cb( w, x, y, z ).canConnectRedstone( EnumSet.of( ForgeDirection.WEST ) ); - } - return false; - } - - @Override - public boolean canRenderInPass( final int pass ) - { - BusRenderHelper.INSTANCE.setPass( pass ); - - if( AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) ) - { - return true; - } - - return pass == 0; - } - - @Override - public ItemStack getPickBlock( final MovingObjectPosition target, final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - final Vec3 v3 = target.hitVec.addVector( -x, -y, -z ); - final SelectedPart sp = this.cb( world, x, y, z ).selectPart( v3 ); - - if( sp.part != null ) - { - return sp.part.getItemStack( PartItemStack.Pick ); - } - else if( sp.facade != null ) - { - return sp.facade.getItemStack(); - } - - return null; - } - - @Override - @SideOnly( Side.CLIENT ) - public boolean addHitEffects( final World world, final MovingObjectPosition target, final EffectRenderer effectRenderer ) - { - final Object object = this.cb( world, target.blockX, target.blockY, target.blockZ ); - if( object instanceof IPartHost ) - { - final IPartHost host = (IPartHost) object; - - for( final ForgeDirection side : ForgeDirection.values() ) - { - final IPart p = host.getPart( side ); - final IIcon ico = this.getIcon( p ); - - if( ico == null ) - { - continue; - } - - final byte b0 = (byte) ( Platform.getRandomInt() % 2 == 0 ? 1 : 0 ); - - for( int i1 = 0; i1 < b0; ++i1 ) - { - for( int j1 = 0; j1 < b0; ++j1 ) - { - for( int k1 = 0; k1 < b0; ++k1 ) - { - final double d0 = target.blockX + ( i1 + 0.5D ) / b0; - final double d1 = target.blockY + ( j1 + 0.5D ) / b0; - final double d2 = target.blockZ + ( k1 + 0.5D ) / b0; - - final double dd0 = target.hitVec.xCoord; - final double dd1 = target.hitVec.yCoord; - final double dd2 = target.hitVec.zCoord; - final EntityDiggingFX fx = ( new EntityDiggingFX( world, dd0, dd1, dd2, d0 - target.blockX - 0.5D, d1 - target.blockY - 0.5D, d2 - target.blockZ - 0.5D, this, 0 ) ).applyColourMultiplier( target.blockX, target.blockY, target.blockZ ); - - fx.setParticleIcon( ico ); - - effectRenderer.addEffect( fx ); - } - } - } - } - } - - return true; - } - - @Override - @SideOnly( Side.CLIENT ) - public boolean addDestroyEffects( final World world, final int x, final int y, final int z, final int meta, final EffectRenderer effectRenderer ) - { - final Object object = this.cb( world, x, y, z ); - if( object instanceof IPartHost ) - { - final IPartHost host = (IPartHost) object; - - for( final ForgeDirection side : ForgeDirection.values() ) - { - final IPart p = host.getPart( side ); - final IIcon ico = this.getIcon( p ); - - if( ico == null ) - { - continue; - } - - final byte b0 = 3; - - for( int i1 = 0; i1 < b0; ++i1 ) - { - for( int j1 = 0; j1 < b0; ++j1 ) - { - for( int k1 = 0; k1 < b0; ++k1 ) - { - final double d0 = x + ( i1 + 0.5D ) / b0; - final double d1 = y + ( j1 + 0.5D ) / b0; - final double d2 = z + ( k1 + 0.5D ) / b0; - final EntityDiggingFX fx = ( new EntityDiggingFX( world, d0, d1, d2, d0 - x - 0.5D, d1 - y - 0.5D, d2 - z - 0.5D, this, meta ) ).applyColourMultiplier( x, y, z ); - - fx.setParticleIcon( ico ); - - effectRenderer.addEffect( fx ); - } - } - } - } - } - - return true; - } - - @Override - public void onNeighborChange( final IBlockAccess w, final int x, final int y, final int z, final int tileX, final int tileY, final int tileZ ) - { - if( Platform.isServer() ) - { - this.cb( w, x, y, z ).onNeighborChanged(); - } - } - - private IIcon getIcon( final IPart p ) - { - if( p == null ) - { - return null; - } - - try - { - final IIcon ico = p.getBreakingTexture(); - if( ico != null ) - { - return ico; - } - } - catch( final Throwable t ) - { - // nothing. - } - - final ItemStack is = p.getItemStack( PartItemStack.Network ); - if( is == null || is.getItem() == null ) - { - return null; - } - - return is.getItem().getIcon( is, 0 ); - } - - private ICableBusContainer cb( final IBlockAccess w, final int x, final int y, final int z ) - { - final TileEntity te = w.getTileEntity( x, y, z ); - ICableBusContainer out = null; - - if( te instanceof TileCableBus ) - { - out = ( (TileCableBus) te ).getCableBus(); - } - else if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.FMP ) ) - { - out = ( (IFMP) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.FMP ) ).getCableContainer( te ); - } - - return out == null ? NULL_CABLE_BUS : out; - } - - @Override - @SideOnly( Side.CLIENT ) - protected RendererCableBus getRenderer() - { - return new RendererCableBus(); - } - - @Override - public IIcon getIcon( final IBlockAccess w, final int x, final int y, final int z, final int s ) - { - return this.getIcon( s, 0 ); - } - - @Override - public IIcon getIcon( final int direction, final int metadata ) - { - final IIcon i = super.getIcon( direction, metadata ); - if( i != null ) - { - return i; - } - - return ExtraBlockTextures.BlockQuartzGlassB.getIcon(); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - return this.cb( w, x, y, z ).activate( player, Vec3.createVectorHelper( hitX, hitY, hitZ ) ); - } - - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - - } - - @Override - public boolean recolourBlock( final World world, final int x, final int y, final int z, final ForgeDirection side, final int colour ) - { - return this.recolourBlock( world, x, y, z, side, colour, null ); - } - - public boolean recolourBlock( final World world, final int x, final int y, final int z, final ForgeDirection side, final int colour, final EntityPlayer who ) - { - try - { - return this.cb( world, x, y, z ).recolourBlock( side, AEColor.values()[colour], who ); - } - catch( final Throwable ignored ) - { - } - return false; - } - - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - // do nothing - } - - @Override - public T getTileEntity( final IBlockAccess w, final int x, final int y, final int z ) - { - final TileEntity te = w.getTileEntity( x, y, z ); - - if( noTesrTile.isInstance( te ) ) - { - return (T) te; - } - - if( tesrTile != null && tesrTile.isInstance( te ) ) - { - return (T) te; - } - - return null; - } - - @Override - protected void setFeature( final EnumSet f ) - { - final AECableBusFeatureHandler featureHandler = new AECableBusFeatureHandler( f, this, this.featureSubName ); - this.setHandler( featureHandler ); - } - - public void setupTile() - { - noTesrTile = Api.INSTANCE.partHelper().getCombinedInstance( TileCableBus.class.getName() ); - this.setTileEntity( noTesrTile ); - GameRegistry.registerTileEntity( noTesrTile, "BlockCableBus" ); - if( Platform.isClient() ) - { - tesrTile = Api.INSTANCE.partHelper().getCombinedInstance( TileCableBusTESR.class.getName() ); - GameRegistry.registerTileEntity( tesrTile, "ClientOnly_TESR_CableBus" ); - CommonHelper.proxy.bindTileEntitySpecialRenderer( tesrTile, this ); - } - } - - @Override - @Method( iname = IntegrationType.MFR ) - public RedNetConnectionType getConnectionType( final World world, final int x, final int y, final int z, final ForgeDirection side ) - { - return this.cb( world, x, y, z ).canConnectRedstone( EnumSet.allOf( ForgeDirection.class ) ) ? RedNetConnectionType.CableSingle : RedNetConnectionType.None; - } - - public void setRenderColor( final int color ) - { - this.myColorMultiplier = color; - } - - public static Class getTesrTile() - { - return BlockCableBus.tesrTile; - } - - public static Class getNoTesrTile() - { - return BlockCableBus.noTesrTile; - } +@Interface( + iface = "powercrystals.minefactoryreloaded.api.rednet.connectivity.IRedNetConnection", + iname = IntegrationType.MFR) +public class BlockCableBus extends AEBaseTileBlock implements IRedNetConnection { + + private static final ICableBusContainer NULL_CABLE_BUS = new NullCableBusContainer(); + private static Class noTesrTile; + private static Class tesrTile; + + /** + * Immibis MB Support. + *

+ * It will look for a field named ImmibisMicroblocks_TransformableBlockMarker or + * ImmibisMicroblocks_TransformableTileEntityMarker, modifiers, type, etc can be ignored. + */ + @Reflected + private static final boolean ImmibisMicroblocks_TransformableBlockMarker = true; + + private int myColorMultiplier = 0xffffff; + + public BlockCableBus() { + super(AEGlassMaterial.INSTANCE); + this.setLightOpacity(0); + this.isFullSize = this.isOpaque = false; + + // this will actually be overwritten later through setupTile and the combined layers + this.setTileEntity(TileCableBus.class); + this.setFeature(EnumSet.of(AEFeature.Core)); + } + + @Override + public void randomDisplayTick(final World world, final int x, final int y, final int z, final Random r) { + this.cb(world, x, y, z).randomDisplayTick(world, x, y, z, r); + } + + @Override + public void onNeighborBlockChange(final World w, final int x, final int y, final int z, final Block meh) { + this.cb(w, x, y, z).onNeighborChanged(); + } + + @Override + public Item getItemDropped(final int i, final Random r, final int k) { + return null; + } + + @Override + public int getRenderBlockPass() { + if (AEConfig.instance.isFeatureEnabled(AEFeature.AlphaPass)) { + return 1; + } + return 0; + } + + @Override + public int colorMultiplier(final IBlockAccess world, final int x, final int y, final int z) { + return this.myColorMultiplier; + } + + @Override + public int isProvidingWeakPower(final IBlockAccess w, final int x, final int y, final int z, final int side) { + return this.cb(w, x, y, z) + .isProvidingWeakPower(ForgeDirection.getOrientation(side).getOpposite()); + } + + @Override + public boolean canProvidePower() { + return true; + } + + @Override + public void onEntityCollidedWithBlock(final World w, final int x, final int y, final int z, final Entity e) { + this.cb(w, x, y, z).onEntityCollision(e); + } + + @Override + public int isProvidingStrongPower(final IBlockAccess w, final int x, final int y, final int z, final int side) { + return this.cb(w, x, y, z) + .isProvidingStrongPower(ForgeDirection.getOrientation(side).getOpposite()); + } + + @Override + public int getLightValue(final IBlockAccess world, final int x, final int y, final int z) { + final Block block = world.getBlock(x, y, z); + if (block != null && block != this) { + return block.getLightValue(world, x, y, z); + } + if (block == null) { + return 0; + } + return this.cb(world, x, y, z).getLightValue(); + } + + @Override + public boolean isLadder( + final IBlockAccess world, final int x, final int y, final int z, final EntityLivingBase entity) { + return this.cb(world, x, y, z).isLadder(entity); + } + + @Override + public boolean isSideSolid(final IBlockAccess w, final int x, final int y, final int z, final ForgeDirection side) { + return this.cb(w, x, y, z).isSolidOnSide(side); + } + + @Override + public boolean isReplaceable(final IBlockAccess world, final int x, final int y, final int z) { + return this.cb(world, x, y, z).isEmpty(); + } + + @SuppressWarnings("deprecation") + @Override + public boolean removedByPlayer( + final World world, final EntityPlayer player, final int x, final int y, final int z) { + if (player.capabilities.isCreativeMode) { + final AEBaseTile tile = this.getTileEntity(world, x, y, z); + if (tile != null) { + tile.disableDrops(); + } + // maybe ray trace? + } + return super.removedByPlayer(world, player, x, y, z); + } + + @Override + public boolean canConnectRedstone(final IBlockAccess w, final int x, final int y, final int z, final int side) { + switch (side) { + case -1: + case 4: + return this.cb(w, x, y, z).canConnectRedstone(EnumSet.of(ForgeDirection.UP, ForgeDirection.DOWN)); + case 0: + return this.cb(w, x, y, z).canConnectRedstone(EnumSet.of(ForgeDirection.NORTH)); + case 1: + return this.cb(w, x, y, z).canConnectRedstone(EnumSet.of(ForgeDirection.EAST)); + case 2: + return this.cb(w, x, y, z).canConnectRedstone(EnumSet.of(ForgeDirection.SOUTH)); + case 3: + return this.cb(w, x, y, z).canConnectRedstone(EnumSet.of(ForgeDirection.WEST)); + } + return false; + } + + @Override + public boolean canRenderInPass(final int pass) { + BusRenderHelper.INSTANCE.setPass(pass); + + if (AEConfig.instance.isFeatureEnabled(AEFeature.AlphaPass)) { + return true; + } + + return pass == 0; + } + + @Override + public ItemStack getPickBlock( + final MovingObjectPosition target, + final World world, + final int x, + final int y, + final int z, + final EntityPlayer player) { + final Vec3 v3 = target.hitVec.addVector(-x, -y, -z); + final SelectedPart sp = this.cb(world, x, y, z).selectPart(v3); + + if (sp.part != null) { + return sp.part.getItemStack(PartItemStack.Pick); + } else if (sp.facade != null) { + return sp.facade.getItemStack(); + } + + return null; + } + + @Override + @SideOnly(Side.CLIENT) + public boolean addHitEffects( + final World world, final MovingObjectPosition target, final EffectRenderer effectRenderer) { + final Object object = this.cb(world, target.blockX, target.blockY, target.blockZ); + if (object instanceof IPartHost) { + final IPartHost host = (IPartHost) object; + + for (final ForgeDirection side : ForgeDirection.values()) { + final IPart p = host.getPart(side); + final IIcon ico = this.getIcon(p); + + if (ico == null) { + continue; + } + + final byte b0 = (byte) (Platform.getRandomInt() % 2 == 0 ? 1 : 0); + + for (int i1 = 0; i1 < b0; ++i1) { + for (int j1 = 0; j1 < b0; ++j1) { + for (int k1 = 0; k1 < b0; ++k1) { + final double d0 = target.blockX + (i1 + 0.5D) / b0; + final double d1 = target.blockY + (j1 + 0.5D) / b0; + final double d2 = target.blockZ + (k1 + 0.5D) / b0; + + final double dd0 = target.hitVec.xCoord; + final double dd1 = target.hitVec.yCoord; + final double dd2 = target.hitVec.zCoord; + final EntityDiggingFX fx = (new EntityDiggingFX( + world, + dd0, + dd1, + dd2, + d0 - target.blockX - 0.5D, + d1 - target.blockY - 0.5D, + d2 - target.blockZ - 0.5D, + this, + 0)) + .applyColourMultiplier(target.blockX, target.blockY, target.blockZ); + + fx.setParticleIcon(ico); + + effectRenderer.addEffect(fx); + } + } + } + } + } + + return true; + } + + @Override + @SideOnly(Side.CLIENT) + public boolean addDestroyEffects( + final World world, + final int x, + final int y, + final int z, + final int meta, + final EffectRenderer effectRenderer) { + final Object object = this.cb(world, x, y, z); + if (object instanceof IPartHost) { + final IPartHost host = (IPartHost) object; + + for (final ForgeDirection side : ForgeDirection.values()) { + final IPart p = host.getPart(side); + final IIcon ico = this.getIcon(p); + + if (ico == null) { + continue; + } + + final byte b0 = 3; + + for (int i1 = 0; i1 < b0; ++i1) { + for (int j1 = 0; j1 < b0; ++j1) { + for (int k1 = 0; k1 < b0; ++k1) { + final double d0 = x + (i1 + 0.5D) / b0; + final double d1 = y + (j1 + 0.5D) / b0; + final double d2 = z + (k1 + 0.5D) / b0; + final EntityDiggingFX fx = (new EntityDiggingFX( + world, d0, d1, d2, d0 - x - 0.5D, d1 - y - 0.5D, d2 - z - 0.5D, this, meta)) + .applyColourMultiplier(x, y, z); + + fx.setParticleIcon(ico); + + effectRenderer.addEffect(fx); + } + } + } + } + } + + return true; + } + + @Override + public void onNeighborChange( + final IBlockAccess w, + final int x, + final int y, + final int z, + final int tileX, + final int tileY, + final int tileZ) { + if (Platform.isServer()) { + this.cb(w, x, y, z).onNeighborChanged(); + } + } + + private IIcon getIcon(final IPart p) { + if (p == null) { + return null; + } + + try { + final IIcon ico = p.getBreakingTexture(); + if (ico != null) { + return ico; + } + } catch (final Throwable t) { + // nothing. + } + + final ItemStack is = p.getItemStack(PartItemStack.Network); + if (is == null || is.getItem() == null) { + return null; + } + + return is.getItem().getIcon(is, 0); + } + + private ICableBusContainer cb(final IBlockAccess w, final int x, final int y, final int z) { + final TileEntity te = w.getTileEntity(x, y, z); + ICableBusContainer out = null; + + if (te instanceof TileCableBus) { + out = ((TileCableBus) te).getCableBus(); + } else if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.FMP)) { + out = ((IFMP) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.FMP)).getCableContainer(te); + } + + return out == null ? NULL_CABLE_BUS : out; + } + + @Override + @SideOnly(Side.CLIENT) + protected RendererCableBus getRenderer() { + return new RendererCableBus(); + } + + @Override + public IIcon getIcon(final IBlockAccess w, final int x, final int y, final int z, final int s) { + return this.getIcon(s, 0); + } + + @Override + public IIcon getIcon(final int direction, final int metadata) { + final IIcon i = super.getIcon(direction, metadata); + if (i != null) { + return i; + } + + return ExtraBlockTextures.BlockQuartzGlassB.getIcon(); + } + + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + return this.cb(w, x, y, z).activate(player, Vec3.createVectorHelper(hitX, hitY, hitZ)); + } + + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) {} + + @Override + public boolean recolourBlock( + final World world, final int x, final int y, final int z, final ForgeDirection side, final int colour) { + return this.recolourBlock(world, x, y, z, side, colour, null); + } + + public boolean recolourBlock( + final World world, + final int x, + final int y, + final int z, + final ForgeDirection side, + final int colour, + final EntityPlayer who) { + try { + return this.cb(world, x, y, z).recolourBlock(side, AEColor.values()[colour], who); + } catch (final Throwable ignored) { + } + return false; + } + + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks(final Item item, final CreativeTabs tabs, final List itemStacks) { + // do nothing + } + + @Override + public T getTileEntity(final IBlockAccess w, final int x, final int y, final int z) { + final TileEntity te = w.getTileEntity(x, y, z); + + if (noTesrTile.isInstance(te)) { + return (T) te; + } + + if (tesrTile != null && tesrTile.isInstance(te)) { + return (T) te; + } + + return null; + } + + @Override + protected void setFeature(final EnumSet f) { + final AECableBusFeatureHandler featureHandler = new AECableBusFeatureHandler(f, this, this.featureSubName); + this.setHandler(featureHandler); + } + + public void setupTile() { + noTesrTile = Api.INSTANCE.partHelper().getCombinedInstance(TileCableBus.class.getName()); + this.setTileEntity(noTesrTile); + GameRegistry.registerTileEntity(noTesrTile, "BlockCableBus"); + if (Platform.isClient()) { + tesrTile = Api.INSTANCE.partHelper().getCombinedInstance(TileCableBusTESR.class.getName()); + GameRegistry.registerTileEntity(tesrTile, "ClientOnly_TESR_CableBus"); + CommonHelper.proxy.bindTileEntitySpecialRenderer(tesrTile, this); + } + } + + @Override + @Method(iname = IntegrationType.MFR) + public RedNetConnectionType getConnectionType( + final World world, final int x, final int y, final int z, final ForgeDirection side) { + return this.cb(world, x, y, z).canConnectRedstone(EnumSet.allOf(ForgeDirection.class)) + ? RedNetConnectionType.CableSingle + : RedNetConnectionType.None; + } + + public void setRenderColor(final int color) { + this.myColorMultiplier = color; + } + + public static Class getTesrTile() { + return BlockCableBus.tesrTile; + } + + public static Class getNoTesrTile() { + return BlockCableBus.noTesrTile; + } } diff --git a/src/main/java/appeng/block/networking/BlockController.java b/src/main/java/appeng/block/networking/BlockController.java index 9290f06c3c9..f21f8a0e71d 100644 --- a/src/main/java/appeng/block/networking/BlockController.java +++ b/src/main/java/appeng/block/networking/BlockController.java @@ -18,45 +18,37 @@ package appeng.block.networking; - import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockController; import appeng.core.features.AEFeature; import appeng.tile.networking.TileController; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.world.World; -import java.util.EnumSet; - - -public class BlockController extends AEBaseTileBlock -{ - - public BlockController() - { - super( Material.iron ); - this.setTileEntity( TileController.class ); - this.setHardness( 6 ); - this.setFeature( EnumSet.of( AEFeature.Channels ) ); - } - - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block neighborBlock ) - { - final TileController tc = this.getTileEntity( w, x, y, z ); - if( tc != null ) - { - tc.onNeighborChange( false ); - } - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockController getRenderer() - { - return new RenderBlockController(); - } +public class BlockController extends AEBaseTileBlock { + + public BlockController() { + super(Material.iron); + this.setTileEntity(TileController.class); + this.setHardness(6); + this.setFeature(EnumSet.of(AEFeature.Channels)); + } + + @Override + public void onNeighborBlockChange(final World w, final int x, final int y, final int z, final Block neighborBlock) { + final TileController tc = this.getTileEntity(w, x, y, z); + if (tc != null) { + tc.onNeighborChange(false); + } + } + + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockController getRenderer() { + return new RenderBlockController(); + } } diff --git a/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java b/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java index 92f22510e38..284a9bd4c0f 100644 --- a/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java +++ b/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java @@ -18,22 +18,17 @@ package appeng.block.networking; - import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; import appeng.helpers.AEGlassMaterial; import appeng.tile.networking.TileCreativeEnergyCell; - import java.util.EnumSet; +public class BlockCreativeEnergyCell extends AEBaseTileBlock { -public class BlockCreativeEnergyCell extends AEBaseTileBlock -{ - - public BlockCreativeEnergyCell() - { - super( AEGlassMaterial.INSTANCE ); - this.setTileEntity( TileCreativeEnergyCell.class ); - this.setFeature( EnumSet.of( AEFeature.Creative ) ); - } + public BlockCreativeEnergyCell() { + super(AEGlassMaterial.INSTANCE); + this.setTileEntity(TileCreativeEnergyCell.class); + this.setFeature(EnumSet.of(AEFeature.Creative)); + } } diff --git a/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java b/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java index aae2cfc4ad3..a91f08be7bc 100644 --- a/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java +++ b/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java @@ -18,53 +18,45 @@ package appeng.block.networking; - import appeng.api.config.PowerMultiplier; import appeng.client.texture.ExtraBlockTextures; import appeng.core.features.AEFeature; import appeng.tile.networking.TileDenseEnergyCell; -import net.minecraft.util.IIcon; - import java.util.EnumSet; +import net.minecraft.util.IIcon; - -public class BlockDenseEnergyCell extends BlockEnergyCell -{ - - public BlockDenseEnergyCell() - { - this.setTileEntity( TileDenseEnergyCell.class ); - this.setFeature( EnumSet.of( AEFeature.DenseEnergyCells ) ); - } - - @Override - public IIcon getIcon( final int direction, final int metadata ) - { - switch( metadata ) - { - case 0: - return ExtraBlockTextures.MEDenseEnergyCell0.getIcon(); - case 1: - return ExtraBlockTextures.MEDenseEnergyCell1.getIcon(); - case 2: - return ExtraBlockTextures.MEDenseEnergyCell2.getIcon(); - case 3: - return ExtraBlockTextures.MEDenseEnergyCell3.getIcon(); - case 4: - return ExtraBlockTextures.MEDenseEnergyCell4.getIcon(); - case 5: - return ExtraBlockTextures.MEDenseEnergyCell5.getIcon(); - case 6: - return ExtraBlockTextures.MEDenseEnergyCell6.getIcon(); - case 7: - return ExtraBlockTextures.MEDenseEnergyCell7.getIcon(); - } - return super.getIcon( direction, metadata ); - } - - @Override - public double getMaxPower() - { - return 200000.0 * 8.0 * PowerMultiplier.CONFIG.multiplier; - } +public class BlockDenseEnergyCell extends BlockEnergyCell { + + public BlockDenseEnergyCell() { + this.setTileEntity(TileDenseEnergyCell.class); + this.setFeature(EnumSet.of(AEFeature.DenseEnergyCells)); + } + + @Override + public IIcon getIcon(final int direction, final int metadata) { + switch (metadata) { + case 0: + return ExtraBlockTextures.MEDenseEnergyCell0.getIcon(); + case 1: + return ExtraBlockTextures.MEDenseEnergyCell1.getIcon(); + case 2: + return ExtraBlockTextures.MEDenseEnergyCell2.getIcon(); + case 3: + return ExtraBlockTextures.MEDenseEnergyCell3.getIcon(); + case 4: + return ExtraBlockTextures.MEDenseEnergyCell4.getIcon(); + case 5: + return ExtraBlockTextures.MEDenseEnergyCell5.getIcon(); + case 6: + return ExtraBlockTextures.MEDenseEnergyCell6.getIcon(); + case 7: + return ExtraBlockTextures.MEDenseEnergyCell7.getIcon(); + } + return super.getIcon(direction, metadata); + } + + @Override + public double getMaxPower() { + return 200000.0 * 8.0 * PowerMultiplier.CONFIG.multiplier; + } } diff --git a/src/main/java/appeng/block/networking/BlockEnergyAcceptor.java b/src/main/java/appeng/block/networking/BlockEnergyAcceptor.java index 36272491ce8..8d8a7a70139 100644 --- a/src/main/java/appeng/block/networking/BlockEnergyAcceptor.java +++ b/src/main/java/appeng/block/networking/BlockEnergyAcceptor.java @@ -18,22 +18,17 @@ package appeng.block.networking; - import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; import appeng.tile.networking.TileEnergyAcceptor; -import net.minecraft.block.material.Material; - import java.util.EnumSet; +import net.minecraft.block.material.Material; +public class BlockEnergyAcceptor extends AEBaseTileBlock { -public class BlockEnergyAcceptor extends AEBaseTileBlock -{ - - public BlockEnergyAcceptor() - { - super( Material.iron ); - this.setTileEntity( TileEnergyAcceptor.class ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } + public BlockEnergyAcceptor() { + super(Material.iron); + this.setTileEntity(TileEnergyAcceptor.class); + this.setFeature(EnumSet.of(AEFeature.Core)); + } } diff --git a/src/main/java/appeng/block/networking/BlockEnergyCell.java b/src/main/java/appeng/block/networking/BlockEnergyCell.java index bb0ca62eb87..25a16038cf5 100644 --- a/src/main/java/appeng/block/networking/BlockEnergyCell.java +++ b/src/main/java/appeng/block/networking/BlockEnergyCell.java @@ -18,7 +18,6 @@ package appeng.block.networking; - import appeng.api.config.PowerMultiplier; import appeng.block.AEBaseItemBlock; import appeng.block.AEBaseItemBlockChargeable; @@ -31,81 +30,71 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import java.util.List; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.IIcon; -import java.util.EnumSet; -import java.util.List; - - -public class BlockEnergyCell extends AEBaseTileBlock -{ +public class BlockEnergyCell extends AEBaseTileBlock { - public BlockEnergyCell() - { - super( AEGlassMaterial.INSTANCE ); + public BlockEnergyCell() { + super(AEGlassMaterial.INSTANCE); - this.setTileEntity( TileEnergyCell.class ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } + this.setTileEntity(TileEnergyCell.class); + this.setFeature(EnumSet.of(AEFeature.Core)); + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockEnergyCube getRenderer() - { - return new RenderBlockEnergyCube(); - } + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockEnergyCube getRenderer() { + return new RenderBlockEnergyCube(); + } - @Override - public IIcon getIcon( final int direction, final int metadata ) - { - switch( metadata ) - { - case 0: - return ExtraBlockTextures.MEEnergyCell0.getIcon(); - case 1: - return ExtraBlockTextures.MEEnergyCell1.getIcon(); - case 2: - return ExtraBlockTextures.MEEnergyCell2.getIcon(); - case 3: - return ExtraBlockTextures.MEEnergyCell3.getIcon(); - case 4: - return ExtraBlockTextures.MEEnergyCell4.getIcon(); - case 5: - return ExtraBlockTextures.MEEnergyCell5.getIcon(); - case 6: - return ExtraBlockTextures.MEEnergyCell6.getIcon(); - case 7: - return ExtraBlockTextures.MEEnergyCell7.getIcon(); - } - return super.getIcon( direction, metadata ); - } + @Override + public IIcon getIcon(final int direction, final int metadata) { + switch (metadata) { + case 0: + return ExtraBlockTextures.MEEnergyCell0.getIcon(); + case 1: + return ExtraBlockTextures.MEEnergyCell1.getIcon(); + case 2: + return ExtraBlockTextures.MEEnergyCell2.getIcon(); + case 3: + return ExtraBlockTextures.MEEnergyCell3.getIcon(); + case 4: + return ExtraBlockTextures.MEEnergyCell4.getIcon(); + case 5: + return ExtraBlockTextures.MEEnergyCell5.getIcon(); + case 6: + return ExtraBlockTextures.MEEnergyCell6.getIcon(); + case 7: + return ExtraBlockTextures.MEEnergyCell7.getIcon(); + } + return super.getIcon(direction, metadata); + } - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - super.getCheckedSubBlocks( item, tabs, itemStacks ); + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks(final Item item, final CreativeTabs tabs, final List itemStacks) { + super.getCheckedSubBlocks(item, tabs, itemStacks); - final ItemStack charged = new ItemStack( this, 1 ); - final NBTTagCompound tag = Platform.openNbtData( charged ); - tag.setDouble( "internalCurrentPower", this.getMaxPower() ); - tag.setDouble( "internalMaxPower", this.getMaxPower() ); + final ItemStack charged = new ItemStack(this, 1); + final NBTTagCompound tag = Platform.openNbtData(charged); + tag.setDouble("internalCurrentPower", this.getMaxPower()); + tag.setDouble("internalMaxPower", this.getMaxPower()); - itemStacks.add( charged ); - } + itemStacks.add(charged); + } - public double getMaxPower() - { - return 200000.0 * PowerMultiplier.CONFIG.multiplier; - } + public double getMaxPower() { + return 200000.0 * PowerMultiplier.CONFIG.multiplier; + } - @Override - public Class getItemBlockClass() - { - return AEBaseItemBlockChargeable.class; - } + @Override + public Class getItemBlockClass() { + return AEBaseItemBlockChargeable.class; + } } diff --git a/src/main/java/appeng/block/networking/BlockWireless.java b/src/main/java/appeng/block/networking/BlockWireless.java index 690da0d1f70..3e43ab44f7c 100644 --- a/src/main/java/appeng/block/networking/BlockWireless.java +++ b/src/main/java/appeng/block/networking/BlockWireless.java @@ -18,7 +18,6 @@ package appeng.block.networking; - import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockWireless; import appeng.core.features.AEFeature; @@ -29,178 +28,179 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; - - -public class BlockWireless extends AEBaseTileBlock implements ICustomCollision -{ - - public BlockWireless() - { - super( AEGlassMaterial.INSTANCE ); - this.setTileEntity( TileWireless.class ); - this.setLightOpacity( 0 ); - this.isFullSize = false; - this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.Core, AEFeature.WirelessAccessTerminal ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockWireless getRenderer() - { - return new RenderBlockWireless(); - } - - @Override - public boolean onBlockActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - final TileWireless tg = this.getTileEntity( w, x, y, z ); - - if( tg != null && !p.isSneaking() ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_WIRELESS ); - } - return true; - } - - return super.onBlockActivated( w, x, y, z, p, side, hitX, hitY, hitZ ); - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - final TileWireless tile = this.getTileEntity( w, x, y, z ); - if( tile != null ) - { - final ForgeDirection forward = tile.getForward(); - - double minX = 0; - double minY = 0; - double minZ = 0; - double maxX = 1; - double maxY = 1; - double maxZ = 1; - - switch( forward ) - { - case DOWN: - minZ = minX = 3.0 / 16.0; - maxZ = maxX = 13.0 / 16.0; - maxY = 1.0; - minY = 5.0 / 16.0; - break; - case EAST: - minZ = minY = 3.0 / 16.0; - maxZ = maxY = 13.0 / 16.0; - maxX = 11.0 / 16.0; - minX = 0.0; - break; - case NORTH: - minY = minX = 3.0 / 16.0; - maxY = maxX = 13.0 / 16.0; - maxZ = 1.0; - minZ = 5.0 / 16.0; - break; - case SOUTH: - minY = minX = 3.0 / 16.0; - maxY = maxX = 13.0 / 16.0; - maxZ = 11.0 / 16.0; - minZ = 0.0; - break; - case UP: - minZ = minX = 3.0 / 16.0; - maxZ = maxX = 13.0 / 16.0; - maxY = 11.0 / 16.0; - minY = 0.0; - break; - case WEST: - minZ = minY = 3.0 / 16.0; - maxZ = maxY = 13.0 / 16.0; - maxX = 1.0; - minX = 5.0 / 16.0; - break; - default: - break; - } - - return Collections.singletonList( AxisAlignedBB.getBoundingBox( minX, minY, minZ, maxX, maxY, maxZ ) ); - } - return Collections.singletonList( AxisAlignedBB.getBoundingBox( 0.0, 0, 0.0, 1.0, 1.0, 1.0 ) ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - final TileWireless tile = this.getTileEntity( w, x, y, z ); - if( tile != null ) - { - final ForgeDirection forward = tile.getForward(); - - double minX = 0; - double minY = 0; - double minZ = 0; - double maxX = 1; - double maxY = 1; - double maxZ = 1; - - switch( forward ) - { - case DOWN: - minZ = minX = 3.0 / 16.0; - maxZ = maxX = 13.0 / 16.0; - maxY = 1.0; - minY = 5.0 / 16.0; - break; - case EAST: - minZ = minY = 3.0 / 16.0; - maxZ = maxY = 13.0 / 16.0; - maxX = 11.0 / 16.0; - minX = 0.0; - break; - case NORTH: - minY = minX = 3.0 / 16.0; - maxY = maxX = 13.0 / 16.0; - maxZ = 1.0; - minZ = 5.0 / 16.0; - break; - case SOUTH: - minY = minX = 3.0 / 16.0; - maxY = maxX = 13.0 / 16.0; - maxZ = 11.0 / 16.0; - minZ = 0.0; - break; - case UP: - minZ = minX = 3.0 / 16.0; - maxZ = maxX = 13.0 / 16.0; - maxY = 11.0 / 16.0; - minY = 0.0; - break; - case WEST: - minZ = minY = 3.0 / 16.0; - maxZ = maxY = 13.0 / 16.0; - maxX = 1.0; - minX = 5.0 / 16.0; - break; - default: - break; - } - - out.add( AxisAlignedBB.getBoundingBox( minX, minY, minZ, maxX, maxY, maxZ ) ); - } - else - { - out.add( AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, 1.0, 1.0, 1.0 ) ); - } - } +public class BlockWireless extends AEBaseTileBlock implements ICustomCollision { + + public BlockWireless() { + super(AEGlassMaterial.INSTANCE); + this.setTileEntity(TileWireless.class); + this.setLightOpacity(0); + this.isFullSize = false; + this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.Core, AEFeature.WirelessAccessTerminal)); + } + + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockWireless getRenderer() { + return new RenderBlockWireless(); + } + + @Override + public boolean onBlockActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + final TileWireless tg = this.getTileEntity(w, x, y, z); + + if (tg != null && !p.isSneaking()) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_WIRELESS); + } + return true; + } + + return super.onBlockActivated(w, x, y, z, p, side, hitX, hitY, hitZ); + } + + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual) { + final TileWireless tile = this.getTileEntity(w, x, y, z); + if (tile != null) { + final ForgeDirection forward = tile.getForward(); + + double minX = 0; + double minY = 0; + double minZ = 0; + double maxX = 1; + double maxY = 1; + double maxZ = 1; + + switch (forward) { + case DOWN: + minZ = minX = 3.0 / 16.0; + maxZ = maxX = 13.0 / 16.0; + maxY = 1.0; + minY = 5.0 / 16.0; + break; + case EAST: + minZ = minY = 3.0 / 16.0; + maxZ = maxY = 13.0 / 16.0; + maxX = 11.0 / 16.0; + minX = 0.0; + break; + case NORTH: + minY = minX = 3.0 / 16.0; + maxY = maxX = 13.0 / 16.0; + maxZ = 1.0; + minZ = 5.0 / 16.0; + break; + case SOUTH: + minY = minX = 3.0 / 16.0; + maxY = maxX = 13.0 / 16.0; + maxZ = 11.0 / 16.0; + minZ = 0.0; + break; + case UP: + minZ = minX = 3.0 / 16.0; + maxZ = maxX = 13.0 / 16.0; + maxY = 11.0 / 16.0; + minY = 0.0; + break; + case WEST: + minZ = minY = 3.0 / 16.0; + maxZ = maxY = 13.0 / 16.0; + maxX = 1.0; + minX = 5.0 / 16.0; + break; + default: + break; + } + + return Collections.singletonList(AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ)); + } + return Collections.singletonList(AxisAlignedBB.getBoundingBox(0.0, 0, 0.0, 1.0, 1.0, 1.0)); + } + + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e) { + final TileWireless tile = this.getTileEntity(w, x, y, z); + if (tile != null) { + final ForgeDirection forward = tile.getForward(); + + double minX = 0; + double minY = 0; + double minZ = 0; + double maxX = 1; + double maxY = 1; + double maxZ = 1; + + switch (forward) { + case DOWN: + minZ = minX = 3.0 / 16.0; + maxZ = maxX = 13.0 / 16.0; + maxY = 1.0; + minY = 5.0 / 16.0; + break; + case EAST: + minZ = minY = 3.0 / 16.0; + maxZ = maxY = 13.0 / 16.0; + maxX = 11.0 / 16.0; + minX = 0.0; + break; + case NORTH: + minY = minX = 3.0 / 16.0; + maxY = maxX = 13.0 / 16.0; + maxZ = 1.0; + minZ = 5.0 / 16.0; + break; + case SOUTH: + minY = minX = 3.0 / 16.0; + maxY = maxX = 13.0 / 16.0; + maxZ = 11.0 / 16.0; + minZ = 0.0; + break; + case UP: + minZ = minX = 3.0 / 16.0; + maxZ = maxX = 13.0 / 16.0; + maxY = 11.0 / 16.0; + minY = 0.0; + break; + case WEST: + minZ = minY = 3.0 / 16.0; + maxZ = maxY = 13.0 / 16.0; + maxX = 1.0; + minX = 5.0 / 16.0; + break; + default: + break; + } + + out.add(AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ)); + } else { + out.add(AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.0, 1.0, 1.0, 1.0)); + } + } } diff --git a/src/main/java/appeng/block/qnb/BlockQuantumBase.java b/src/main/java/appeng/block/qnb/BlockQuantumBase.java index 81a6ab0583c..c3b282e02d0 100644 --- a/src/main/java/appeng/block/qnb/BlockQuantumBase.java +++ b/src/main/java/appeng/block/qnb/BlockQuantumBase.java @@ -18,7 +18,6 @@ package appeng.block.qnb; - import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderQNB; import appeng.core.features.AEFeature; @@ -26,54 +25,45 @@ import appeng.tile.qnb.TileQuantumBridge; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.world.World; -import java.util.EnumSet; - - -public abstract class BlockQuantumBase extends AEBaseTileBlock implements ICustomCollision -{ - - public BlockQuantumBase( final Material mat ) - { - super( mat ); - this.setTileEntity( TileQuantumBridge.class ); - final float shave = 2.0f / 16.0f; - this.setBlockBounds( shave, shave, shave, 1.0f - shave, 1.0f - shave, 1.0f - shave ); - this.setLightOpacity( 0 ); - this.isFullSize = this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.QuantumNetworkBridge ) ); - } +public abstract class BlockQuantumBase extends AEBaseTileBlock implements ICustomCollision { - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block pointlessNumber ) - { - final TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); - if( bridge != null ) - { - bridge.neighborUpdate(); - } - } + public BlockQuantumBase(final Material mat) { + super(mat); + this.setTileEntity(TileQuantumBridge.class); + final float shave = 2.0f / 16.0f; + this.setBlockBounds(shave, shave, shave, 1.0f - shave, 1.0f - shave, 1.0f - shave); + this.setLightOpacity(0); + this.isFullSize = this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.QuantumNetworkBridge)); + } - @Override - public void breakBlock( final World w, final int x, final int y, final int z, final Block a, final int b ) - { - final TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); - if( bridge != null ) - { - bridge.breakCluster(); - } + @Override + public void onNeighborBlockChange( + final World w, final int x, final int y, final int z, final Block pointlessNumber) { + final TileQuantumBridge bridge = this.getTileEntity(w, x, y, z); + if (bridge != null) { + bridge.neighborUpdate(); + } + } - super.breakBlock( w, x, y, z, a, b ); - } + @Override + public void breakBlock(final World w, final int x, final int y, final int z, final Block a, final int b) { + final TileQuantumBridge bridge = this.getTileEntity(w, x, y, z); + if (bridge != null) { + bridge.breakCluster(); + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderQNB getRenderer() - { - return new RenderQNB(); - } + super.breakBlock(w, x, y, z, a, b); + } + @Override + @SideOnly(Side.CLIENT) + protected RenderQNB getRenderer() { + return new RenderQNB(); + } } diff --git a/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java b/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java index b27ed494b30..e297c366543 100644 --- a/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java +++ b/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java @@ -18,7 +18,6 @@ package appeng.block.qnb; - import appeng.client.EffectType; import appeng.core.CommonHelper; import appeng.core.sync.GuiBridge; @@ -27,73 +26,78 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Collections; +import java.util.List; +import java.util.Random; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.List; -import java.util.Random; - - -public class BlockQuantumLinkChamber extends BlockQuantumBase -{ +public class BlockQuantumLinkChamber extends BlockQuantumBase { - public BlockQuantumLinkChamber() - { - super( AEGlassMaterial.INSTANCE ); - } + public BlockQuantumLinkChamber() { + super(AEGlassMaterial.INSTANCE); + } - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World w, final int bx, final int by, final int bz, final Random r ) - { - final TileQuantumBridge bridge = this.getTileEntity( w, bx, by, bz ); - if( bridge != null ) - { - if( bridge.hasQES() ) - { - if( CommonHelper.proxy.shouldAddParticles( r ) ) - { - CommonHelper.proxy.spawnEffect( EffectType.Energy, w, bx + 0.5, by + 0.5, bz + 0.5, null ); - } - } - } - } + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(final World w, final int bx, final int by, final int bz, final Random r) { + final TileQuantumBridge bridge = this.getTileEntity(w, bx, by, bz); + if (bridge != null) { + if (bridge.hasQES()) { + if (CommonHelper.proxy.shouldAddParticles(r)) { + CommonHelper.proxy.spawnEffect(EffectType.Energy, w, bx + 0.5, by + 0.5, bz + 0.5, null); + } + } + } + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileQuantumBridge tg = this.getTileEntity( w, x, y, z ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_QNB ); - } - return true; - } - return false; - } + final TileQuantumBridge tg = this.getTileEntity(w, x, y, z); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_QNB); + } + return true; + } + return false; + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - final double onePixel = 2.0 / 16.0; - return Collections.singletonList( AxisAlignedBB.getBoundingBox( onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel ) ); - } + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual) { + final double onePixel = 2.0 / 16.0; + return Collections.singletonList(AxisAlignedBB.getBoundingBox( + onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel)); + } - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - final double onePixel = 2.0 / 16.0; - out.add( AxisAlignedBB.getBoundingBox( onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel ) ); - } + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e) { + final double onePixel = 2.0 / 16.0; + out.add(AxisAlignedBB.getBoundingBox( + onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel)); + } } diff --git a/src/main/java/appeng/block/qnb/BlockQuantumRing.java b/src/main/java/appeng/block/qnb/BlockQuantumRing.java index 8eeccebe8b9..b0c7f0ffa6e 100644 --- a/src/main/java/appeng/block/qnb/BlockQuantumRing.java +++ b/src/main/java/appeng/block/qnb/BlockQuantumRing.java @@ -18,54 +18,51 @@ package appeng.block.qnb; - import appeng.tile.qnb.TileQuantumBridge; +import java.util.Collections; +import java.util.List; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; -import java.util.Collections; -import java.util.List; - - -public class BlockQuantumRing extends BlockQuantumBase -{ +public class BlockQuantumRing extends BlockQuantumBase { - public BlockQuantumRing() - { - super( Material.iron ); - } + public BlockQuantumRing() { + super(Material.iron); + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - double onePixel = 2.0 / 16.0; - final TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); - if( bridge != null && bridge.isCorner() ) - { - onePixel = 4.0 / 16.0; - } - else if( bridge != null && bridge.isFormed() ) - { - onePixel = 1.0 / 16.0; - } - return Collections.singletonList( AxisAlignedBB.getBoundingBox( onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel ) ); - } + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual) { + double onePixel = 2.0 / 16.0; + final TileQuantumBridge bridge = this.getTileEntity(w, x, y, z); + if (bridge != null && bridge.isCorner()) { + onePixel = 4.0 / 16.0; + } else if (bridge != null && bridge.isFormed()) { + onePixel = 1.0 / 16.0; + } + return Collections.singletonList(AxisAlignedBB.getBoundingBox( + onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel)); + } - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - double onePixel = 2.0 / 16.0; - final TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); - if( bridge != null && bridge.isCorner() ) - { - onePixel = 4.0 / 16.0; - } - else if( bridge != null && bridge.isFormed() ) - { - onePixel = 1.0 / 16.0; - } - out.add( AxisAlignedBB.getBoundingBox( onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel ) ); - } + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e) { + double onePixel = 2.0 / 16.0; + final TileQuantumBridge bridge = this.getTileEntity(w, x, y, z); + if (bridge != null && bridge.isCorner()) { + onePixel = 4.0 / 16.0; + } else if (bridge != null && bridge.isFormed()) { + onePixel = 1.0 / 16.0; + } + out.add(AxisAlignedBB.getBoundingBox( + onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel)); + } } diff --git a/src/main/java/appeng/block/solids/BlockFluix.java b/src/main/java/appeng/block/solids/BlockFluix.java index df0e1aa564e..a1745855385 100644 --- a/src/main/java/appeng/block/solids/BlockFluix.java +++ b/src/main/java/appeng/block/solids/BlockFluix.java @@ -18,19 +18,14 @@ package appeng.block.solids; - import appeng.block.AEDecorativeBlock; import appeng.core.features.AEFeature; -import net.minecraft.block.material.Material; - import java.util.EnumSet; +import net.minecraft.block.material.Material; - -public class BlockFluix extends AEDecorativeBlock -{ - public BlockFluix() - { - super( Material.rock ); - this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class BlockFluix extends AEDecorativeBlock { + public BlockFluix() { + super(Material.rock); + this.setFeature(EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/solids/BlockQuartz.java b/src/main/java/appeng/block/solids/BlockQuartz.java index 47cdf61c989..9162e822653 100644 --- a/src/main/java/appeng/block/solids/BlockQuartz.java +++ b/src/main/java/appeng/block/solids/BlockQuartz.java @@ -18,20 +18,15 @@ package appeng.block.solids; - import appeng.block.AEDecorativeBlock; import appeng.core.features.AEFeature; -import net.minecraft.block.material.Material; - import java.util.EnumSet; +import net.minecraft.block.material.Material; +public class BlockQuartz extends AEDecorativeBlock { -public class BlockQuartz extends AEDecorativeBlock -{ - - public BlockQuartz() - { - super( Material.rock ); - this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } + public BlockQuartz() { + super(Material.rock); + this.setFeature(EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/solids/BlockQuartzChiseled.java b/src/main/java/appeng/block/solids/BlockQuartzChiseled.java index 008be1f16ae..e0cf0541aff 100644 --- a/src/main/java/appeng/block/solids/BlockQuartzChiseled.java +++ b/src/main/java/appeng/block/solids/BlockQuartzChiseled.java @@ -18,20 +18,15 @@ package appeng.block.solids; - import appeng.block.AEDecorativeBlock; import appeng.core.features.AEFeature; -import net.minecraft.block.material.Material; - import java.util.EnumSet; +import net.minecraft.block.material.Material; +public class BlockQuartzChiseled extends AEDecorativeBlock { -public class BlockQuartzChiseled extends AEDecorativeBlock -{ - - public BlockQuartzChiseled() - { - super( Material.rock ); - this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } + public BlockQuartzChiseled() { + super(Material.rock); + this.setFeature(EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/solids/BlockQuartzGlass.java b/src/main/java/appeng/block/solids/BlockQuartzGlass.java index b7d4b607ab6..b059146c2a2 100644 --- a/src/main/java/appeng/block/solids/BlockQuartzGlass.java +++ b/src/main/java/appeng/block/solids/BlockQuartzGlass.java @@ -18,47 +18,38 @@ package appeng.block.solids; - import appeng.block.AEBaseBlock; import appeng.client.render.blocks.RenderQuartzGlass; import appeng.core.features.AEFeature; import appeng.helpers.AEGlassMaterial; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.block.material.Material; import net.minecraft.world.IBlockAccess; -import java.util.EnumSet; - - -public class BlockQuartzGlass extends AEBaseBlock -{ - public BlockQuartzGlass() - { - super( Material.glass ); - this.setLightOpacity( 0 ); - this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - public RenderQuartzGlass getRenderer() - { - return new RenderQuartzGlass(); - } - - @Override - public boolean shouldSideBeRendered( final IBlockAccess w, final int x, final int y, final int z, final int side ) - { - final Material mat = w.getBlock( x, y, z ).getMaterial(); - if( mat == Material.glass || mat == AEGlassMaterial.INSTANCE ) - { - if( w.getBlock( x, y, z ).getRenderType() == this.getRenderType() ) - { - return false; - } - } - return super.shouldSideBeRendered( w, x, y, z, side ); - } +public class BlockQuartzGlass extends AEBaseBlock { + public BlockQuartzGlass() { + super(Material.glass); + this.setLightOpacity(0); + this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } + + @Override + @SideOnly(Side.CLIENT) + public RenderQuartzGlass getRenderer() { + return new RenderQuartzGlass(); + } + + @Override + public boolean shouldSideBeRendered(final IBlockAccess w, final int x, final int y, final int z, final int side) { + final Material mat = w.getBlock(x, y, z).getMaterial(); + if (mat == Material.glass || mat == AEGlassMaterial.INSTANCE) { + if (w.getBlock(x, y, z).getRenderType() == this.getRenderType()) { + return false; + } + } + return super.shouldSideBeRendered(w, x, y, z, side); + } } diff --git a/src/main/java/appeng/block/solids/BlockQuartzLamp.java b/src/main/java/appeng/block/solids/BlockQuartzLamp.java index 7162f4bc9f4..feb91cb1b05 100644 --- a/src/main/java/appeng/block/solids/BlockQuartzLamp.java +++ b/src/main/java/appeng/block/solids/BlockQuartzLamp.java @@ -18,48 +18,40 @@ package appeng.block.solids; - import appeng.client.render.effects.VibrantFX; import appeng.core.AEConfig; import appeng.core.CommonHelper; import appeng.core.features.AEFeature; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import net.minecraft.client.Minecraft; -import net.minecraft.world.World; - import java.util.EnumSet; import java.util.Random; +import net.minecraft.client.Minecraft; +import net.minecraft.world.World; +public class BlockQuartzLamp extends BlockQuartzGlass { -public class BlockQuartzLamp extends BlockQuartzGlass -{ - - public BlockQuartzLamp() - { - this.setLightLevel( 1.0f ); - this.setBlockTextureName( "BlockQuartzGlass" ); - this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks, AEFeature.DecorativeLights ) ); - } + public BlockQuartzLamp() { + this.setLightLevel(1.0f); + this.setBlockTextureName("BlockQuartzGlass"); + this.setFeature(EnumSet.of(AEFeature.DecorativeQuartzBlocks, AEFeature.DecorativeLights)); + } - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World w, final int x, final int y, final int z, final Random r ) - { - if( !AEConfig.instance.enableEffects ) - { - return; - } + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(final World w, final int x, final int y, final int z, final Random r) { + if (!AEConfig.instance.enableEffects) { + return; + } - if( CommonHelper.proxy.shouldAddParticles( r ) ) - { - final double d0 = ( r.nextFloat() - 0.5F ) * 0.96D; - final double d1 = ( r.nextFloat() - 0.5F ) * 0.96D; - final double d2 = ( r.nextFloat() - 0.5F ) * 0.96D; + if (CommonHelper.proxy.shouldAddParticles(r)) { + final double d0 = (r.nextFloat() - 0.5F) * 0.96D; + final double d1 = (r.nextFloat() - 0.5F) * 0.96D; + final double d2 = (r.nextFloat() - 0.5F) * 0.96D; - final VibrantFX fx = new VibrantFX( w, 0.5 + x + d0, 0.5 + y + d1, 0.5 + z + d2, 0.0D, 0.0D, 0.0D ); + final VibrantFX fx = new VibrantFX(w, 0.5 + x + d0, 0.5 + y + d1, 0.5 + z + d2, 0.0D, 0.0D, 0.0D); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } } diff --git a/src/main/java/appeng/block/solids/BlockQuartzPillar.java b/src/main/java/appeng/block/solids/BlockQuartzPillar.java index a2476cad322..cbf60edd71d 100644 --- a/src/main/java/appeng/block/solids/BlockQuartzPillar.java +++ b/src/main/java/appeng/block/solids/BlockQuartzPillar.java @@ -18,36 +18,29 @@ package appeng.block.solids; - import appeng.api.util.IOrientable; import appeng.api.util.IOrientableBlock; import appeng.block.AEBaseBlock; import appeng.core.features.AEFeature; import appeng.helpers.MetaRotation; +import java.util.EnumSet; import net.minecraft.block.material.Material; import net.minecraft.world.IBlockAccess; -import java.util.EnumSet; - - -public class BlockQuartzPillar extends AEBaseBlock implements IOrientableBlock -{ +public class BlockQuartzPillar extends AEBaseBlock implements IOrientableBlock { - public BlockQuartzPillar() - { - super( Material.rock ); - this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } + public BlockQuartzPillar() { + super(Material.rock); + this.setFeature(EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } - @Override - public boolean usesMetadata() - { - return true; - } + @Override + public boolean usesMetadata() { + return true; + } - @Override - public IOrientable getOrientable( final IBlockAccess w, final int x, final int y, final int z ) - { - return new MetaRotation( w, x, y, z ); - } + @Override + public IOrientable getOrientable(final IBlockAccess w, final int x, final int y, final int z) { + return new MetaRotation(w, x, y, z); + } } diff --git a/src/main/java/appeng/block/solids/BlockSkyStone.java b/src/main/java/appeng/block/solids/BlockSkyStone.java index 1d689968caf..b43aa9d1c5c 100644 --- a/src/main/java/appeng/block/solids/BlockSkyStone.java +++ b/src/main/java/appeng/block/solids/BlockSkyStone.java @@ -18,7 +18,6 @@ package appeng.block.solids; - import appeng.api.util.IOrientable; import appeng.api.util.IOrientableBlock; import appeng.block.AEBaseBlock; @@ -30,6 +29,8 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; @@ -44,173 +45,149 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerEvent; -import java.util.EnumSet; -import java.util.List; - - -public class BlockSkyStone extends AEBaseBlock implements IOrientableBlock -{ - private static final float BLOCK_RESISTANCE = 150.0f; - private static final double BREAK_SPEAK_SCALAR = 0.1; - private static final double BREAK_SPEAK_THRESHOLD = 7.0; - - @SideOnly( Side.CLIENT ) - private IIcon block; - - @SideOnly( Side.CLIENT ) - private IIcon brick; - - @SideOnly( Side.CLIENT ) - private IIcon smallBrick; - - public BlockSkyStone() - { - super( Material.rock ); - this.setHardness( 50 ); - this.hasSubtypes = true; - this.blockResistance = BLOCK_RESISTANCE; - this.setHarvestLevel( "pickaxe", 3, 0 ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - - MinecraftForge.EVENT_BUS.register( this ); - } - - @SubscribeEvent - public void breakFaster( final PlayerEvent.BreakSpeed event ) - { - if( event.block == this && event.entityPlayer != null ) - { - final ItemStack is = event.entityPlayer.inventory.getCurrentItem(); - int level = -1; - - if( is != null && is.getItem() != null ) - { - level = is.getItem().getHarvestLevel( is, "pickaxe" ); - } - - if( event.metadata > 0 || level >= 3 || event.originalSpeed > BREAK_SPEAK_THRESHOLD ) - { - event.newSpeed /= BREAK_SPEAK_SCALAR; - } - } - } - - @Override - public int damageDropped( final int meta ) - { - return meta; - } - - @Override - public ItemStack getPickBlock( final MovingObjectPosition target, final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - final ItemStack is = super.getPickBlock( target, world, x, y, z, player ); - is.setItemDamage( world.getBlockMetadata( x, y, z ) ); - - return is; - } - - @Override - public void onBlockAdded( final World w, final int x, final int y, final int z ) - { - super.onBlockAdded( w, x, y, z ); - if( Platform.isServer() ) - { - WorldData.instance().compassData().service().updateArea( w, x, y, z ); - } - } - - @Override - public boolean usesMetadata() - { - return false; - } - - @Override - public IOrientable getOrientable( final IBlockAccess w, final int x, final int y, final int z ) - { - if( w.getBlockMetadata( x, y, z ) == 0 ) - { - return new LocationRotation( w, x, y, z ); - } - - return new NullRotation(); - } - - @Override - public String getUnlocalizedName( final ItemStack is ) - { - if( is.getItemDamage() == 1 ) - { - return this.getUnlocalizedName() + ".Block"; - } - - if( is.getItemDamage() == 2 ) - { - return this.getUnlocalizedName() + ".Brick"; - } - - if( is.getItemDamage() == 3 ) - { - return this.getUnlocalizedName() + ".SmallBrick"; - } - - return this.getUnlocalizedName(); - } - - @Override - @SideOnly( Side.CLIENT ) - public void registerBlockIcons( final IIconRegister ir ) - { - super.registerBlockIcons( ir ); - this.block = ir.registerIcon( this.getTextureName() + ".Block" ); - this.brick = ir.registerIcon( this.getTextureName() + ".Brick" ); - this.smallBrick = ir.registerIcon( this.getTextureName() + ".SmallBrick" ); - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getIcon( final int direction, final int metadata ) - { - if( metadata == 1 ) - { - return this.block; - } - if( metadata == 2 ) - { - return this.brick; - } - if( metadata == 3 ) - { - return this.smallBrick; - } - return super.getIcon( direction, metadata ); - } - - @Override - public void setRenderStateByMeta( final int metadata ) - { - this.getRendererInstance().setTemporaryRenderIcon( this.getIcon( 0, metadata ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - super.getCheckedSubBlocks( item, tabs, itemStacks ); - - itemStacks.add( new ItemStack( item, 1, 1 ) ); - itemStacks.add( new ItemStack( item, 1, 2 ) ); - itemStacks.add( new ItemStack( item, 1, 3 ) ); - } - - @Override - public void breakBlock( final World w, final int x, final int y, final int z, final Block b, final int metadata ) - { - super.breakBlock( w, x, y, z, b, metadata ); - if( Platform.isServer() ) - { - WorldData.instance().compassData().service().updateArea( w, x, y, z ); - } - } +public class BlockSkyStone extends AEBaseBlock implements IOrientableBlock { + private static final float BLOCK_RESISTANCE = 150.0f; + private static final double BREAK_SPEAK_SCALAR = 0.1; + private static final double BREAK_SPEAK_THRESHOLD = 7.0; + + @SideOnly(Side.CLIENT) + private IIcon block; + + @SideOnly(Side.CLIENT) + private IIcon brick; + + @SideOnly(Side.CLIENT) + private IIcon smallBrick; + + public BlockSkyStone() { + super(Material.rock); + this.setHardness(50); + this.hasSubtypes = true; + this.blockResistance = BLOCK_RESISTANCE; + this.setHarvestLevel("pickaxe", 3, 0); + this.setFeature(EnumSet.of(AEFeature.Core)); + + MinecraftForge.EVENT_BUS.register(this); + } + + @SubscribeEvent + public void breakFaster(final PlayerEvent.BreakSpeed event) { + if (event.block == this && event.entityPlayer != null) { + final ItemStack is = event.entityPlayer.inventory.getCurrentItem(); + int level = -1; + + if (is != null && is.getItem() != null) { + level = is.getItem().getHarvestLevel(is, "pickaxe"); + } + + if (event.metadata > 0 || level >= 3 || event.originalSpeed > BREAK_SPEAK_THRESHOLD) { + event.newSpeed /= BREAK_SPEAK_SCALAR; + } + } + } + + @Override + public int damageDropped(final int meta) { + return meta; + } + + @Override + public ItemStack getPickBlock( + final MovingObjectPosition target, + final World world, + final int x, + final int y, + final int z, + final EntityPlayer player) { + final ItemStack is = super.getPickBlock(target, world, x, y, z, player); + is.setItemDamage(world.getBlockMetadata(x, y, z)); + + return is; + } + + @Override + public void onBlockAdded(final World w, final int x, final int y, final int z) { + super.onBlockAdded(w, x, y, z); + if (Platform.isServer()) { + WorldData.instance().compassData().service().updateArea(w, x, y, z); + } + } + + @Override + public boolean usesMetadata() { + return false; + } + + @Override + public IOrientable getOrientable(final IBlockAccess w, final int x, final int y, final int z) { + if (w.getBlockMetadata(x, y, z) == 0) { + return new LocationRotation(w, x, y, z); + } + + return new NullRotation(); + } + + @Override + public String getUnlocalizedName(final ItemStack is) { + if (is.getItemDamage() == 1) { + return this.getUnlocalizedName() + ".Block"; + } + + if (is.getItemDamage() == 2) { + return this.getUnlocalizedName() + ".Brick"; + } + + if (is.getItemDamage() == 3) { + return this.getUnlocalizedName() + ".SmallBrick"; + } + + return this.getUnlocalizedName(); + } + + @Override + @SideOnly(Side.CLIENT) + public void registerBlockIcons(final IIconRegister ir) { + super.registerBlockIcons(ir); + this.block = ir.registerIcon(this.getTextureName() + ".Block"); + this.brick = ir.registerIcon(this.getTextureName() + ".Brick"); + this.smallBrick = ir.registerIcon(this.getTextureName() + ".SmallBrick"); + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(final int direction, final int metadata) { + if (metadata == 1) { + return this.block; + } + if (metadata == 2) { + return this.brick; + } + if (metadata == 3) { + return this.smallBrick; + } + return super.getIcon(direction, metadata); + } + + @Override + public void setRenderStateByMeta(final int metadata) { + this.getRendererInstance().setTemporaryRenderIcon(this.getIcon(0, metadata)); + } + + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks(final Item item, final CreativeTabs tabs, final List itemStacks) { + super.getCheckedSubBlocks(item, tabs, itemStacks); + + itemStacks.add(new ItemStack(item, 1, 1)); + itemStacks.add(new ItemStack(item, 1, 2)); + itemStacks.add(new ItemStack(item, 1, 3)); + } + + @Override + public void breakBlock(final World w, final int x, final int y, final int z, final Block b, final int metadata) { + super.breakBlock(w, x, y, z, b, metadata); + if (Platform.isServer()) { + WorldData.instance().compassData().service().updateArea(w, x, y, z); + } + } } diff --git a/src/main/java/appeng/block/solids/OreQuartz.java b/src/main/java/appeng/block/solids/OreQuartz.java index a86cd72a467..0025f8cb664 100644 --- a/src/main/java/appeng/block/solids/OreQuartz.java +++ b/src/main/java/appeng/block/solids/OreQuartz.java @@ -18,7 +18,6 @@ package appeng.block.solids; - import appeng.api.AEApi; import appeng.api.exceptions.MissingDefinition; import appeng.block.AEBaseBlock; @@ -26,6 +25,9 @@ import appeng.core.features.AEFeature; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import java.util.Random; +import javax.annotation.Nullable; import net.minecraft.block.material.Material; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -33,135 +35,124 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import javax.annotation.Nullable; -import java.util.EnumSet; -import java.util.Random; - - -public class OreQuartz extends AEBaseBlock -{ - private int boostBrightnessLow; - private int boostBrightnessHigh; - private boolean enhanceBrightness; - - public OreQuartz() - { - super( Material.rock ); - this.setHardness( 3.0F ); - this.setResistance( 5.0F ); - this.boostBrightnessLow = 0; - this.boostBrightnessHigh = 1; - this.enhanceBrightness = false; - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderQuartzOre getRenderer() - { - return new RenderQuartzOre(); - } - - @Override - public int getMixedBrightnessForBlock( final IBlockAccess par1iBlockAccess, final int par2, final int par3, final int par4 ) - { - int j1 = super.getMixedBrightnessForBlock( par1iBlockAccess, par2, par3, par4 ); - if( this.enhanceBrightness ) - { - j1 = Math.max( j1 >> 20, j1 >> 4 ); - - if( j1 > 4 ) - { - j1 += this.boostBrightnessHigh; - } - else - { - j1 += this.boostBrightnessLow; - } - - if( j1 > 15 ) - { - j1 = 15; - } - return j1 << 20 | j1 << 4; - } - return j1; - } - - @Override - public int quantityDropped( final Random rand ) - { - return 1 + rand.nextInt( 2 ); - } - - @Nullable - @Override - public Item getItemDropped( final int id, final Random rand, final int meta ) - { - for( final Item crystalItem : AEApi.instance().definitions().materials().certusQuartzCrystal().maybeItem().asSet() ) - { - return crystalItem; - } - - throw new MissingDefinition( "Tried to access certus quartz crystal, even though they are disabled" ); - } - - @Override - public void dropBlockAsItemWithChance( final World w, final int x, final int y, final int z, final int blockID, final float something, final int meta ) - { - super.dropBlockAsItemWithChance( w, x, y, z, blockID, something, meta ); - - if( this.getItemDropped( blockID, w.rand, meta ) != Item.getItemFromBlock( this ) ) - { - final int xp = MathHelper.getRandomIntegerInRange( w.rand, 2, 5 ); - - this.dropXpOnBlockBreak( w, x, y, z, xp ); - } - } - - @Override - public int damageDropped( final int id ) - { - for( final ItemStack crystalStack : AEApi.instance().definitions().materials().certusQuartzCrystal().maybeStack( 1 ).asSet() ) - { - return crystalStack.getItemDamage(); - } - - throw new MissingDefinition( "Tried to access certus quartz crystal, even though they are disabled" ); - } - - @Override - public int quantityDroppedWithBonus( final int fortune, final Random rand ) - { - if( fortune > 0 && Item.getItemFromBlock( this ) != this.getItemDropped( 0, rand, fortune ) ) - { - int j = rand.nextInt( fortune + 2 ) - 1; - - if( j < 0 ) - { - j = 0; - } - - return this.quantityDropped( rand ) * ( j + 1 ); - } - else - { - return this.quantityDropped( rand ); - } - } - - void setBoostBrightnessLow( final int boostBrightnessLow ) - { - this.boostBrightnessLow = boostBrightnessLow; - } - - void setBoostBrightnessHigh( final int boostBrightnessHigh ) - { - this.boostBrightnessHigh = boostBrightnessHigh; - } - - public void setEnhanceBrightness( final boolean enhanceBrightness ) - { - this.enhanceBrightness = enhanceBrightness; - } +public class OreQuartz extends AEBaseBlock { + private int boostBrightnessLow; + private int boostBrightnessHigh; + private boolean enhanceBrightness; + + public OreQuartz() { + super(Material.rock); + this.setHardness(3.0F); + this.setResistance(5.0F); + this.boostBrightnessLow = 0; + this.boostBrightnessHigh = 1; + this.enhanceBrightness = false; + this.setFeature(EnumSet.of(AEFeature.Core)); + } + + @Override + @SideOnly(Side.CLIENT) + protected RenderQuartzOre getRenderer() { + return new RenderQuartzOre(); + } + + @Override + public int getMixedBrightnessForBlock( + final IBlockAccess par1iBlockAccess, final int par2, final int par3, final int par4) { + int j1 = super.getMixedBrightnessForBlock(par1iBlockAccess, par2, par3, par4); + if (this.enhanceBrightness) { + j1 = Math.max(j1 >> 20, j1 >> 4); + + if (j1 > 4) { + j1 += this.boostBrightnessHigh; + } else { + j1 += this.boostBrightnessLow; + } + + if (j1 > 15) { + j1 = 15; + } + return j1 << 20 | j1 << 4; + } + return j1; + } + + @Override + public int quantityDropped(final Random rand) { + return 1 + rand.nextInt(2); + } + + @Nullable + @Override + public Item getItemDropped(final int id, final Random rand, final int meta) { + for (final Item crystalItem : AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystal() + .maybeItem() + .asSet()) { + return crystalItem; + } + + throw new MissingDefinition("Tried to access certus quartz crystal, even though they are disabled"); + } + + @Override + public void dropBlockAsItemWithChance( + final World w, + final int x, + final int y, + final int z, + final int blockID, + final float something, + final int meta) { + super.dropBlockAsItemWithChance(w, x, y, z, blockID, something, meta); + + if (this.getItemDropped(blockID, w.rand, meta) != Item.getItemFromBlock(this)) { + final int xp = MathHelper.getRandomIntegerInRange(w.rand, 2, 5); + + this.dropXpOnBlockBreak(w, x, y, z, xp); + } + } + + @Override + public int damageDropped(final int id) { + for (final ItemStack crystalStack : AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystal() + .maybeStack(1) + .asSet()) { + return crystalStack.getItemDamage(); + } + + throw new MissingDefinition("Tried to access certus quartz crystal, even though they are disabled"); + } + + @Override + public int quantityDroppedWithBonus(final int fortune, final Random rand) { + if (fortune > 0 && Item.getItemFromBlock(this) != this.getItemDropped(0, rand, fortune)) { + int j = rand.nextInt(fortune + 2) - 1; + + if (j < 0) { + j = 0; + } + + return this.quantityDropped(rand) * (j + 1); + } else { + return this.quantityDropped(rand); + } + } + + void setBoostBrightnessLow(final int boostBrightnessLow) { + this.boostBrightnessLow = boostBrightnessLow; + } + + void setBoostBrightnessHigh(final int boostBrightnessHigh) { + this.boostBrightnessHigh = boostBrightnessHigh; + } + + public void setEnhanceBrightness(final boolean enhanceBrightness) { + this.enhanceBrightness = enhanceBrightness; + } } diff --git a/src/main/java/appeng/block/solids/OreQuartzCharged.java b/src/main/java/appeng/block/solids/OreQuartzCharged.java index ec30cf0cf0b..8d76b702680 100644 --- a/src/main/java/appeng/block/solids/OreQuartzCharged.java +++ b/src/main/java/appeng/block/solids/OreQuartzCharged.java @@ -18,7 +18,6 @@ package appeng.block.solids; - import appeng.api.AEApi; import appeng.api.exceptions.MissingDefinition; import appeng.client.render.effects.ChargedOreFX; @@ -26,89 +25,87 @@ import appeng.core.CommonHelper; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Random; +import javax.annotation.Nullable; import net.minecraft.client.Minecraft; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import javax.annotation.Nullable; -import java.util.Random; - - -public class OreQuartzCharged extends OreQuartz -{ +public class OreQuartzCharged extends OreQuartz { - public OreQuartzCharged() - { - this.setBoostBrightnessLow( 2 ); - this.setBoostBrightnessHigh( 5 ); - } + public OreQuartzCharged() { + this.setBoostBrightnessLow(2); + this.setBoostBrightnessHigh(5); + } - @Nullable - @Override - public Item getItemDropped( final int id, final Random rand, final int meta ) - { - for( final Item charged : AEApi.instance().definitions().materials().certusQuartzCrystalCharged().maybeItem().asSet() ) - { - return charged; - } + @Nullable + @Override + public Item getItemDropped(final int id, final Random rand, final int meta) { + for (final Item charged : AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystalCharged() + .maybeItem() + .asSet()) { + return charged; + } - throw new MissingDefinition( "Tried to access charged certus quartz crystal, even though they are disabled" ); - } + throw new MissingDefinition("Tried to access charged certus quartz crystal, even though they are disabled"); + } - @Override - public int damageDropped( final int id ) - { - for( final ItemStack crystalStack : AEApi.instance().definitions().materials().certusQuartzCrystalCharged().maybeStack( 1 ).asSet() ) - { - return crystalStack.getItemDamage(); - } + @Override + public int damageDropped(final int id) { + for (final ItemStack crystalStack : AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystalCharged() + .maybeStack(1) + .asSet()) { + return crystalStack.getItemDamage(); + } - throw new MissingDefinition( "Tried to access charged certus quartz crystal, even though they are disabled" ); - } + throw new MissingDefinition("Tried to access charged certus quartz crystal, even though they are disabled"); + } - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World w, final int x, final int y, final int z, final Random r ) - { - if( !AEConfig.instance.enableEffects ) - { - return; - } + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(final World w, final int x, final int y, final int z, final Random r) { + if (!AEConfig.instance.enableEffects) { + return; + } - double xOff = ( r.nextFloat() ); - double yOff = ( r.nextFloat() ); - double zOff = ( r.nextFloat() ); + double xOff = (r.nextFloat()); + double yOff = (r.nextFloat()); + double zOff = (r.nextFloat()); - switch( r.nextInt( 6 ) ) - { - case 0: - xOff = -0.01; - break; - case 1: - yOff = -0.01; - break; - case 2: - xOff = -0.01; - break; - case 3: - zOff = -0.01; - break; - case 4: - xOff = 1.01; - break; - case 5: - yOff = 1.01; - break; - case 6: - zOff = 1.01; - break; - } + switch (r.nextInt(6)) { + case 0: + xOff = -0.01; + break; + case 1: + yOff = -0.01; + break; + case 2: + xOff = -0.01; + break; + case 3: + zOff = -0.01; + break; + case 4: + xOff = 1.01; + break; + case 5: + yOff = 1.01; + break; + case 6: + zOff = 1.01; + break; + } - if( CommonHelper.proxy.shouldAddParticles( r ) ) - { - final ChargedOreFX fx = new ChargedOreFX( w, x + xOff, y + yOff, z + zOff, 0.0f, 0.0f, 0.0f ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } + if (CommonHelper.proxy.shouldAddParticles(r)) { + final ChargedOreFX fx = new ChargedOreFX(w, x + xOff, y + yOff, z + zOff, 0.0f, 0.0f, 0.0f); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } } diff --git a/src/main/java/appeng/block/spatial/BlockMatrixFrame.java b/src/main/java/appeng/block/spatial/BlockMatrixFrame.java index 2a09b5cc509..17275bc9b15 100644 --- a/src/main/java/appeng/block/spatial/BlockMatrixFrame.java +++ b/src/main/java/appeng/block/spatial/BlockMatrixFrame.java @@ -18,13 +18,15 @@ package appeng.block.spatial; - import appeng.block.AEBaseBlock; import appeng.client.render.blocks.RenderNull; import appeng.core.features.AEFeature; import appeng.helpers.ICustomCollision; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.List; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; @@ -36,72 +38,64 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.List; - - -public class BlockMatrixFrame extends AEBaseBlock implements ICustomCollision -{ - - public BlockMatrixFrame() - { - super( Material.anvil ); - this.setResistance( 6000000.0F ); - this.setBlockUnbreakable(); - this.setLightOpacity( 0 ); - this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.SpatialIO ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderNull getRenderer() - { - return new RenderNull(); - } - - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - - } - - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - // do nothing - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - return Arrays.asList( new AxisAlignedBB[] {} );// AxisAlignedBB.getBoundingBox( 0.25, 0, 0.25, 0.75, 0.5, 0.75 ) - // } ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - out.add( AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, 1.0, 1.0, 1.0 ) ); - } - - @Override - public boolean canPlaceBlockAt( final World world, final int x, final int y, final int z ) - { - return false; - } - - @Override - public void onBlockExploded( final World world, final int x, final int y, final int z, final Explosion explosion ) - { - // Don't explode. - } - - @Override - public boolean canEntityDestroy( final IBlockAccess world, final int x, final int y, final int z, final Entity entity ) - { - return false; - } +public class BlockMatrixFrame extends AEBaseBlock implements ICustomCollision { + + public BlockMatrixFrame() { + super(Material.anvil); + this.setResistance(6000000.0F); + this.setBlockUnbreakable(); + this.setLightOpacity(0); + this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.SpatialIO)); + } + + @Override + @SideOnly(Side.CLIENT) + protected RenderNull getRenderer() { + return new RenderNull(); + } + + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) {} + + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks(final Item item, final CreativeTabs tabs, final List itemStacks) { + // do nothing + } + + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual) { + return Arrays.asList(new AxisAlignedBB[] {}); // AxisAlignedBB.getBoundingBox( 0.25, 0, 0.25, 0.75, 0.5, 0.75 ) + // } ); + } + + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e) { + out.add(AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.0, 1.0, 1.0, 1.0)); + } + + @Override + public boolean canPlaceBlockAt(final World world, final int x, final int y, final int z) { + return false; + } + + @Override + public void onBlockExploded(final World world, final int x, final int y, final int z, final Explosion explosion) { + // Don't explode. + } + + @Override + public boolean canEntityDestroy( + final IBlockAccess world, final int x, final int y, final int z, final Entity entity) { + return false; + } } diff --git a/src/main/java/appeng/block/spatial/BlockSpatialIOPort.java b/src/main/java/appeng/block/spatial/BlockSpatialIOPort.java index 4c6a00e302f..2325ee44db6 100644 --- a/src/main/java/appeng/block/spatial/BlockSpatialIOPort.java +++ b/src/main/java/appeng/block/spatial/BlockSpatialIOPort.java @@ -18,58 +18,56 @@ package appeng.block.spatial; - import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; import appeng.core.sync.GuiBridge; import appeng.tile.spatial.TileSpatialIOPort; import appeng.util.Platform; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class BlockSpatialIOPort extends AEBaseTileBlock -{ +public class BlockSpatialIOPort extends AEBaseTileBlock { - public BlockSpatialIOPort() - { - super( Material.iron ); - this.setTileEntity( TileSpatialIOPort.class ); - this.setFeature( EnumSet.of( AEFeature.SpatialIO ) ); - } + public BlockSpatialIOPort() { + super(Material.iron); + this.setTileEntity(TileSpatialIOPort.class); + this.setFeature(EnumSet.of(AEFeature.SpatialIO)); + } - @Override - public final void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block junk ) - { - final TileSpatialIOPort te = this.getTileEntity( w, x, y, z ); - if( te != null ) - { - te.updateRedstoneState(); - } - } + @Override + public final void onNeighborBlockChange(final World w, final int x, final int y, final int z, final Block junk) { + final TileSpatialIOPort te = this.getTileEntity(w, x, y, z); + if (te != null) { + te.updateRedstoneState(); + } + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileSpatialIOPort tg = this.getTileEntity( w, x, y, z ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_SPATIAL_IO_PORT ); - } - return true; - } - return false; - } + final TileSpatialIOPort tg = this.getTileEntity(w, x, y, z); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_SPATIAL_IO_PORT); + } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/spatial/BlockSpatialPylon.java b/src/main/java/appeng/block/spatial/BlockSpatialPylon.java index f715a64ecfd..5cce92d92a8 100644 --- a/src/main/java/appeng/block/spatial/BlockSpatialPylon.java +++ b/src/main/java/appeng/block/spatial/BlockSpatialPylon.java @@ -18,7 +18,6 @@ package appeng.block.spatial; - import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderSpatialPylon; import appeng.core.features.AEFeature; @@ -26,48 +25,39 @@ import appeng.tile.spatial.TileSpatialPylon; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import java.util.EnumSet; - - -public class BlockSpatialPylon extends AEBaseTileBlock -{ - - public BlockSpatialPylon() - { - super( AEGlassMaterial.INSTANCE ); - this.setTileEntity( TileSpatialPylon.class ); - this.setFeature( EnumSet.of( AEFeature.SpatialIO ) ); - } - - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block junk ) - { - final TileSpatialPylon tsp = this.getTileEntity( w, x, y, z ); - if( tsp != null ) - { - tsp.onNeighborBlockChange(); - } - } - - @Override - public int getLightValue( final IBlockAccess w, final int x, final int y, final int z ) - { - final TileSpatialPylon tsp = this.getTileEntity( w, x, y, z ); - if( tsp != null ) - { - return tsp.getLightValue(); - } - return super.getLightValue( w, x, y, z ); - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderSpatialPylon getRenderer() - { - return new RenderSpatialPylon(); - } +public class BlockSpatialPylon extends AEBaseTileBlock { + + public BlockSpatialPylon() { + super(AEGlassMaterial.INSTANCE); + this.setTileEntity(TileSpatialPylon.class); + this.setFeature(EnumSet.of(AEFeature.SpatialIO)); + } + + @Override + public void onNeighborBlockChange(final World w, final int x, final int y, final int z, final Block junk) { + final TileSpatialPylon tsp = this.getTileEntity(w, x, y, z); + if (tsp != null) { + tsp.onNeighborBlockChange(); + } + } + + @Override + public int getLightValue(final IBlockAccess w, final int x, final int y, final int z) { + final TileSpatialPylon tsp = this.getTileEntity(w, x, y, z); + if (tsp != null) { + return tsp.getLightValue(); + } + return super.getLightValue(w, x, y, z); + } + + @Override + @SideOnly(Side.CLIENT) + protected RenderSpatialPylon getRenderer() { + return new RenderSpatialPylon(); + } } diff --git a/src/main/java/appeng/block/stair/ChiseledQuartzStairBlock.java b/src/main/java/appeng/block/stair/ChiseledQuartzStairBlock.java index 90a580cc497..cfdab0d4543 100644 --- a/src/main/java/appeng/block/stair/ChiseledQuartzStairBlock.java +++ b/src/main/java/appeng/block/stair/ChiseledQuartzStairBlock.java @@ -18,18 +18,13 @@ package appeng.block.stair; - import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; -import net.minecraft.block.Block; - import java.util.EnumSet; +import net.minecraft.block.Block; - -public class ChiseledQuartzStairBlock extends AEBaseStairBlock -{ - public ChiseledQuartzStairBlock( final Block block ) - { - super( block, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class ChiseledQuartzStairBlock extends AEBaseStairBlock { + public ChiseledQuartzStairBlock(final Block block) { + super(block, 0, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/stair/FluixStairBlock.java b/src/main/java/appeng/block/stair/FluixStairBlock.java index 328b2613d14..5f2f7e9a2e6 100644 --- a/src/main/java/appeng/block/stair/FluixStairBlock.java +++ b/src/main/java/appeng/block/stair/FluixStairBlock.java @@ -18,18 +18,13 @@ package appeng.block.stair; - import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; -import net.minecraft.block.Block; - import java.util.EnumSet; +import net.minecraft.block.Block; - -public class FluixStairBlock extends AEBaseStairBlock -{ - public FluixStairBlock( final Block block ) - { - super( block, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class FluixStairBlock extends AEBaseStairBlock { + public FluixStairBlock(final Block block) { + super(block, 0, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/stair/QuartzPillarStairBlock.java b/src/main/java/appeng/block/stair/QuartzPillarStairBlock.java index f1454f6f95d..8f84de43d92 100644 --- a/src/main/java/appeng/block/stair/QuartzPillarStairBlock.java +++ b/src/main/java/appeng/block/stair/QuartzPillarStairBlock.java @@ -18,18 +18,13 @@ package appeng.block.stair; - import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; -import net.minecraft.block.Block; - import java.util.EnumSet; +import net.minecraft.block.Block; - -public class QuartzPillarStairBlock extends AEBaseStairBlock -{ - public QuartzPillarStairBlock( final Block block ) - { - super( block, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class QuartzPillarStairBlock extends AEBaseStairBlock { + public QuartzPillarStairBlock(final Block block) { + super(block, 0, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/stair/QuartzStairBlock.java b/src/main/java/appeng/block/stair/QuartzStairBlock.java index 7b784916eb9..69ac289d225 100644 --- a/src/main/java/appeng/block/stair/QuartzStairBlock.java +++ b/src/main/java/appeng/block/stair/QuartzStairBlock.java @@ -18,18 +18,13 @@ package appeng.block.stair; - import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; -import net.minecraft.block.Block; - import java.util.EnumSet; +import net.minecraft.block.Block; - -public class QuartzStairBlock extends AEBaseStairBlock -{ - public QuartzStairBlock( final Block block ) - { - super( block, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class QuartzStairBlock extends AEBaseStairBlock { + public QuartzStairBlock(final Block block) { + super(block, 0, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/stair/SkyStoneBlockStairBlock.java b/src/main/java/appeng/block/stair/SkyStoneBlockStairBlock.java index 05bca2b53e6..05f0ff39dc5 100644 --- a/src/main/java/appeng/block/stair/SkyStoneBlockStairBlock.java +++ b/src/main/java/appeng/block/stair/SkyStoneBlockStairBlock.java @@ -18,18 +18,13 @@ package appeng.block.stair; - import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; -import net.minecraft.block.Block; - import java.util.EnumSet; +import net.minecraft.block.Block; - -public class SkyStoneBlockStairBlock extends AEBaseStairBlock -{ - public SkyStoneBlockStairBlock( final Block block, final Integer meta ) - { - super( block, meta, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class SkyStoneBlockStairBlock extends AEBaseStairBlock { + public SkyStoneBlockStairBlock(final Block block, final Integer meta) { + super(block, meta, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/stair/SkyStoneBrickStairBlock.java b/src/main/java/appeng/block/stair/SkyStoneBrickStairBlock.java index 46f78362feb..12489a7b8ee 100644 --- a/src/main/java/appeng/block/stair/SkyStoneBrickStairBlock.java +++ b/src/main/java/appeng/block/stair/SkyStoneBrickStairBlock.java @@ -18,18 +18,13 @@ package appeng.block.stair; - import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; -import net.minecraft.block.Block; - import java.util.EnumSet; +import net.minecraft.block.Block; - -public class SkyStoneBrickStairBlock extends AEBaseStairBlock -{ - public SkyStoneBrickStairBlock( final Block block, final Integer meta ) - { - super( block, meta, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } -} \ No newline at end of file +public class SkyStoneBrickStairBlock extends AEBaseStairBlock { + public SkyStoneBrickStairBlock(final Block block, final Integer meta) { + super(block, meta, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } +} diff --git a/src/main/java/appeng/block/stair/SkyStoneSmallBrickStairBlock.java b/src/main/java/appeng/block/stair/SkyStoneSmallBrickStairBlock.java index bf8338d5007..6baf40fc698 100644 --- a/src/main/java/appeng/block/stair/SkyStoneSmallBrickStairBlock.java +++ b/src/main/java/appeng/block/stair/SkyStoneSmallBrickStairBlock.java @@ -18,18 +18,13 @@ package appeng.block.stair; - import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; -import net.minecraft.block.Block; - import java.util.EnumSet; +import net.minecraft.block.Block; - -public class SkyStoneSmallBrickStairBlock extends AEBaseStairBlock -{ - public SkyStoneSmallBrickStairBlock( final Block block, final int meta ) - { - super( block, meta, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } -} \ No newline at end of file +public class SkyStoneSmallBrickStairBlock extends AEBaseStairBlock { + public SkyStoneSmallBrickStairBlock(final Block block, final int meta) { + super(block, meta, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } +} diff --git a/src/main/java/appeng/block/stair/SkyStoneStairBlock.java b/src/main/java/appeng/block/stair/SkyStoneStairBlock.java index bd83831131f..29ac8854b2b 100644 --- a/src/main/java/appeng/block/stair/SkyStoneStairBlock.java +++ b/src/main/java/appeng/block/stair/SkyStoneStairBlock.java @@ -18,18 +18,13 @@ package appeng.block.stair; - import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; -import net.minecraft.block.Block; - import java.util.EnumSet; +import net.minecraft.block.Block; - -public class SkyStoneStairBlock extends AEBaseStairBlock -{ - public SkyStoneStairBlock( final Block block, final Integer meta ) - { - super( block, meta, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class SkyStoneStairBlock extends AEBaseStairBlock { + public SkyStoneStairBlock(final Block block, final Integer meta) { + super(block, meta, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/storage/BlockChest.java b/src/main/java/appeng/block/storage/BlockChest.java index 92d04ebb644..94467cf0cb2 100644 --- a/src/main/java/appeng/block/storage/BlockChest.java +++ b/src/main/java/appeng/block/storage/BlockChest.java @@ -18,7 +18,6 @@ package appeng.block.storage; - import appeng.api.AEApi; import appeng.api.storage.ICellHandler; import appeng.block.AEBaseTileBlock; @@ -30,65 +29,60 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class BlockChest extends AEBaseTileBlock -{ +public class BlockChest extends AEBaseTileBlock { - public BlockChest() - { - super( Material.iron ); - this.setTileEntity( TileChest.class ); - this.setFeature( EnumSet.of( AEFeature.StorageCells, AEFeature.MEChest ) ); - } + public BlockChest() { + super(Material.iron); + this.setTileEntity(TileChest.class); + this.setFeature(EnumSet.of(AEFeature.StorageCells, AEFeature.MEChest)); + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderMEChest getRenderer() - { - return new RenderMEChest(); - } + @Override + @SideOnly(Side.CLIENT) + protected RenderMEChest getRenderer() { + return new RenderMEChest(); + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - final TileChest tg = this.getTileEntity( w, x, y, z ); - if( tg != null && !p.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + final TileChest tg = this.getTileEntity(w, x, y, z); + if (tg != null && !p.isSneaking()) { + if (Platform.isClient()) { + return true; + } - if( side != tg.getUp().ordinal() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_CHEST ); - } - else - { - final ItemStack cell = tg.getStackInSlot( 1 ); - if( cell != null ) - { - final ICellHandler ch = AEApi.instance().registries().cell().getHandler( cell ); + if (side != tg.getUp().ordinal()) { + Platform.openGUI(p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_CHEST); + } else { + final ItemStack cell = tg.getStackInSlot(1); + if (cell != null) { + final ICellHandler ch = AEApi.instance().registries().cell().getHandler(cell); - tg.openGui( p, ch, cell, side ); - } - else - { - p.addChatMessage( PlayerMessages.ChestCannotReadStorageCell.get() ); - } - } + tg.openGui(p, ch, cell, side); + } else { + p.addChatMessage(PlayerMessages.ChestCannotReadStorageCell.get()); + } + } - return true; - } + return true; + } - return false; - } + return false; + } } diff --git a/src/main/java/appeng/block/storage/BlockDrive.java b/src/main/java/appeng/block/storage/BlockDrive.java index c2058a6c455..1ea430c9dcc 100644 --- a/src/main/java/appeng/block/storage/BlockDrive.java +++ b/src/main/java/appeng/block/storage/BlockDrive.java @@ -18,7 +18,6 @@ package appeng.block.storage; - import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderDrive; import appeng.core.features.AEFeature; @@ -27,48 +26,48 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class BlockDrive extends AEBaseTileBlock -{ +public class BlockDrive extends AEBaseTileBlock { - public BlockDrive() - { - super( Material.iron ); - this.setTileEntity( TileDrive.class ); - this.setFeature( EnumSet.of( AEFeature.StorageCells, AEFeature.MEDrive ) ); - } + public BlockDrive() { + super(Material.iron); + this.setTileEntity(TileDrive.class); + this.setFeature(EnumSet.of(AEFeature.StorageCells, AEFeature.MEDrive)); + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderDrive getRenderer() - { - return new RenderDrive(); - } + @Override + @SideOnly(Side.CLIENT) + protected RenderDrive getRenderer() { + return new RenderDrive(); + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileDrive tg = this.getTileEntity( w, x, y, z ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_DRIVE ); - } - return true; - } - return false; - } + final TileDrive tg = this.getTileEntity(w, x, y, z); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_DRIVE); + } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/storage/BlockIOPort.java b/src/main/java/appeng/block/storage/BlockIOPort.java index 7228e5675c8..3a3368c1971 100644 --- a/src/main/java/appeng/block/storage/BlockIOPort.java +++ b/src/main/java/appeng/block/storage/BlockIOPort.java @@ -18,58 +18,56 @@ package appeng.block.storage; - import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; import appeng.core.sync.GuiBridge; import appeng.tile.storage.TileIOPort; import appeng.util.Platform; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class BlockIOPort extends AEBaseTileBlock -{ +public class BlockIOPort extends AEBaseTileBlock { - public BlockIOPort() - { - super( Material.iron ); - this.setTileEntity( TileIOPort.class ); - this.setFeature( EnumSet.of( AEFeature.StorageCells, AEFeature.IOPort ) ); - } + public BlockIOPort() { + super(Material.iron); + this.setTileEntity(TileIOPort.class); + this.setFeature(EnumSet.of(AEFeature.StorageCells, AEFeature.IOPort)); + } - @Override - public final void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block junk ) - { - final TileIOPort te = this.getTileEntity( w, x, y, z ); - if( te != null ) - { - te.updateRedstoneState(); - } - } + @Override + public final void onNeighborBlockChange(final World w, final int x, final int y, final int z, final Block junk) { + final TileIOPort te = this.getTileEntity(w, x, y, z); + if (te != null) { + te.updateRedstoneState(); + } + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (p.isSneaking()) { + return false; + } - final TileIOPort tg = this.getTileEntity( w, x, y, z ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_IOPORT ); - } - return true; - } - return false; - } + final TileIOPort tg = this.getTileEntity(w, x, y, z); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI(p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_IOPORT); + } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/storage/BlockSkyChest.java b/src/main/java/appeng/block/storage/BlockSkyChest.java index 039aedf68ab..dc1b44c7fb7 100644 --- a/src/main/java/appeng/block/storage/BlockSkyChest.java +++ b/src/main/java/appeng/block/storage/BlockSkyChest.java @@ -18,7 +18,6 @@ package appeng.block.storage; - import appeng.api.AEApi; import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockSkyChest; @@ -29,6 +28,9 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; @@ -44,133 +46,138 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; - - -public class BlockSkyChest extends AEBaseTileBlock implements ICustomCollision -{ - - private static final double AABB_OFFSET_BOTTOM = .0625d; - private static final double AABB_OFFSET_SIDES = 0; - private static final double AABB_OFFSET_TOP = .125d; - - public BlockSkyChest() - { - super( Material.rock ); - this.setTileEntity( TileSkyChest.class ); - this.isOpaque = this.isFullSize = false; - this.hasSubtypes = true; - this.lightOpacity = 0; - this.setHardness( 50 ); - this.blockResistance = 150.0f; - this.setFeature( EnumSet.of( AEFeature.Core, AEFeature.SkyStoneChests ) ); - } - - @Override - public int damageDropped( final int metadata ) - { - return metadata; - } - - - @Override - public ItemStack getPickBlock( final MovingObjectPosition target, final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - final ItemStack is = super.getPickBlock( target, world, x, y, z, player ); - is.setItemDamage( world.getBlockMetadata( x, y, z ) ); - - return is; - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockSkyChest getRenderer() - { - return new RenderBlockSkyChest(); - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getIcon( final int direction, final int metadata ) - { - for( final Block skyStoneBlock : AEApi.instance().definitions().blocks().skyStone().maybeBlock().asSet() ) - { - return skyStoneBlock.getIcon( direction, metadata ); - } - - return Blocks.stone.getIcon( direction, metadata ); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getTileEntity( w, x, y, z ), ForgeDirection.getOrientation( side ), GuiBridge.GUI_SKYCHEST ); - } - - return true; - } - - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - } - - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - super.getCheckedSubBlocks( item, tabs, itemStacks ); - - itemStacks.add( new ItemStack( item, 1, 1 ) ); - } - - @Override - public String getUnlocalizedName( final ItemStack is ) - { - if( is.getItemDamage() == 1 ) - { - return this.getUnlocalizedName() + ".Block"; - } - - return this.getUnlocalizedName(); - } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity thePlayer, final boolean isVisual ) - { - return Collections.singletonList( computeAABB( w, x, y, z ) ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - out.add( computeAABB( w, x, y, z ) ); - } - - private AxisAlignedBB computeAABB( final World w, final int x, final int y, final int z ) - { - final TileSkyChest sk = this.getTileEntity( w, x, y, z ); - ForgeDirection o = ForgeDirection.UP; - - if( sk != null ) - o = sk.getUp(); - - final double offsetX = o.offsetX == 0 ? AABB_OFFSET_BOTTOM : AABB_OFFSET_SIDES; - final double offsetY = o.offsetY == 0 ? AABB_OFFSET_BOTTOM : AABB_OFFSET_SIDES; - final double offsetZ = o.offsetZ == 0 ? AABB_OFFSET_BOTTOM : AABB_OFFSET_SIDES; - - // x/z needs to be multiplied by -1, thus we simply add not substract. - final double minX = Math.max( 0.0, offsetX + o.offsetX * AABB_OFFSET_TOP ); - final double minY = Math.max( 0.0, offsetY - o.offsetY * AABB_OFFSET_TOP ); - final double minZ = Math.max( 0.0, offsetZ + o.offsetZ * AABB_OFFSET_TOP ); - - final double maxX = Math.min( 1.0, ( 1.0 - offsetX ) + o.offsetX * AABB_OFFSET_TOP ); - final double maxY = Math.min( 1.0, ( 1.0 - offsetY ) - o.offsetY * AABB_OFFSET_TOP ); - final double maxZ = Math.min( 1.0, ( 1.0 - offsetZ ) + o.offsetZ * AABB_OFFSET_TOP ); - - return AxisAlignedBB.getBoundingBox( minX, minY, minZ, maxX, maxY, maxZ ); - } +public class BlockSkyChest extends AEBaseTileBlock implements ICustomCollision { + + private static final double AABB_OFFSET_BOTTOM = .0625d; + private static final double AABB_OFFSET_SIDES = 0; + private static final double AABB_OFFSET_TOP = .125d; + + public BlockSkyChest() { + super(Material.rock); + this.setTileEntity(TileSkyChest.class); + this.isOpaque = this.isFullSize = false; + this.hasSubtypes = true; + this.lightOpacity = 0; + this.setHardness(50); + this.blockResistance = 150.0f; + this.setFeature(EnumSet.of(AEFeature.Core, AEFeature.SkyStoneChests)); + } + + @Override + public int damageDropped(final int metadata) { + return metadata; + } + + @Override + public ItemStack getPickBlock( + final MovingObjectPosition target, + final World world, + final int x, + final int y, + final int z, + final EntityPlayer player) { + final ItemStack is = super.getPickBlock(target, world, x, y, z, player); + is.setItemDamage(world.getBlockMetadata(x, y, z)); + + return is; + } + + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockSkyChest getRenderer() { + return new RenderBlockSkyChest(); + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(final int direction, final int metadata) { + for (final Block skyStoneBlock : + AEApi.instance().definitions().blocks().skyStone().maybeBlock().asSet()) { + return skyStoneBlock.getIcon(direction, metadata); + } + + return Blocks.stone.getIcon(direction, metadata); + } + + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (Platform.isServer()) { + Platform.openGUI( + player, + this.getTileEntity(w, x, y, z), + ForgeDirection.getOrientation(side), + GuiBridge.GUI_SKYCHEST); + } + + return true; + } + + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) {} + + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks(final Item item, final CreativeTabs tabs, final List itemStacks) { + super.getCheckedSubBlocks(item, tabs, itemStacks); + + itemStacks.add(new ItemStack(item, 1, 1)); + } + + @Override + public String getUnlocalizedName(final ItemStack is) { + if (is.getItemDamage() == 1) { + return this.getUnlocalizedName() + ".Block"; + } + + return this.getUnlocalizedName(); + } + + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, final int x, final int y, final int z, final Entity thePlayer, final boolean isVisual) { + return Collections.singletonList(computeAABB(w, x, y, z)); + } + + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e) { + out.add(computeAABB(w, x, y, z)); + } + + private AxisAlignedBB computeAABB(final World w, final int x, final int y, final int z) { + final TileSkyChest sk = this.getTileEntity(w, x, y, z); + ForgeDirection o = ForgeDirection.UP; + + if (sk != null) o = sk.getUp(); + + final double offsetX = o.offsetX == 0 ? AABB_OFFSET_BOTTOM : AABB_OFFSET_SIDES; + final double offsetY = o.offsetY == 0 ? AABB_OFFSET_BOTTOM : AABB_OFFSET_SIDES; + final double offsetZ = o.offsetZ == 0 ? AABB_OFFSET_BOTTOM : AABB_OFFSET_SIDES; + + // x/z needs to be multiplied by -1, thus we simply add not substract. + final double minX = Math.max(0.0, offsetX + o.offsetX * AABB_OFFSET_TOP); + final double minY = Math.max(0.0, offsetY - o.offsetY * AABB_OFFSET_TOP); + final double minZ = Math.max(0.0, offsetZ + o.offsetZ * AABB_OFFSET_TOP); + + final double maxX = Math.min(1.0, (1.0 - offsetX) + o.offsetX * AABB_OFFSET_TOP); + final double maxY = Math.min(1.0, (1.0 - offsetY) - o.offsetY * AABB_OFFSET_TOP); + final double maxZ = Math.min(1.0, (1.0 - offsetZ) + o.offsetZ * AABB_OFFSET_TOP); + + return AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); + } } diff --git a/src/main/java/appeng/client/ActionKey.java b/src/main/java/appeng/client/ActionKey.java index d9f7410b970..50756635431 100644 --- a/src/main/java/appeng/client/ActionKey.java +++ b/src/main/java/appeng/client/ActionKey.java @@ -2,25 +2,20 @@ import org.lwjgl.input.Keyboard; - -public enum ActionKey -{ - TOGGLE_FOCUS( Keyboard.KEY_TAB ); +public enum ActionKey { + TOGGLE_FOCUS(Keyboard.KEY_TAB); private final int defaultKey; - ActionKey(int defaultKey) - { + ActionKey(int defaultKey) { this.defaultKey = defaultKey; } - public String getTranslationKey() - { + public String getTranslationKey() { return "key." + this.name().toLowerCase() + ".desc"; } - public int getDefaultKey() - { + public int getDefaultKey() { return this.defaultKey; } } diff --git a/src/main/java/appeng/client/ClientHelper.java b/src/main/java/appeng/client/ClientHelper.java index b672449dc2f..dbce5981db4 100644 --- a/src/main/java/appeng/client/ClientHelper.java +++ b/src/main/java/appeng/client/ClientHelper.java @@ -18,7 +18,6 @@ package appeng.client; - import appeng.api.parts.CableRenderMode; import appeng.api.util.AEColor; import appeng.block.AEBaseBlock; @@ -49,6 +48,11 @@ import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.client.registry.RenderingRegistry; import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import java.io.IOException; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Random; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; @@ -74,400 +78,350 @@ import net.minecraftforge.common.MinecraftForge; import org.lwjgl.opengl.GL11; -import java.io.IOException; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; -import java.util.Random; - - -public class ClientHelper extends ServerHelper -{ - private final static String KEY_CATEGORY = "key.appliedenergistics2.category"; - - private final EnumMap bindings = new EnumMap<>( ActionKey.class ); - - private static final RenderItem ITEM_RENDERER = new RenderItem(); - private static final RenderBlocks BLOCK_RENDERER = new RenderBlocks(); - - @SubscribeEvent - public void postPlayerRender( final RenderLivingEvent.Pre p ) - { - final PlayerColor player = TickHandler.INSTANCE.getPlayerColors().get( p.entity.getEntityId() ); - if( player != null ) - { - final AEColor col = player.myColor; - - final float r = 0xff & ( col.mediumVariant >> 16 ); - final float g = 0xff & ( col.mediumVariant >> 8 ); - final float b = 0xff & ( col.mediumVariant ); - GL11.glColor3f( r / 255.0f, g / 255.0f, b / 255.0f ); - } - } - - @Override - public void init() - { - MinecraftForge.EVENT_BUS.register( this ); - - for( ActionKey key : ActionKey.values() ) - { - final KeyBinding binding = new KeyBinding( key.getTranslationKey(), key.getDefaultKey(), KEY_CATEGORY ); - ClientRegistry.registerKeyBinding( binding ); - this.bindings.put( key, binding ); - } - } - - @SubscribeEvent - public void renderWorldLastEvent( RenderWorldLastEvent event) { - HighlighterHandler.tick(event); - } - - @Override - public World getWorld() - { - if( Platform.isClient() ) - { - return Minecraft.getMinecraft().theWorld; - } - else - { - return super.getWorld(); - } - } - - @Override - public void bindTileEntitySpecialRenderer( final Class tile, final AEBaseBlock blk ) - { - final BaseBlockRender bbr = blk.getRendererInstance().getRendererInstance(); - if( bbr.hasTESR() && tile != null ) - { - ClientRegistry.bindTileEntitySpecialRenderer( tile, new TESRWrapper( bbr ) ); - } - } - - @Override - public List getPlayers() - { - if( Platform.isClient() ) - { - final List o = new ArrayList(); - o.add( Minecraft.getMinecraft().thePlayer ); - return o; - } - else - { - return super.getPlayers(); - } - } - - @Override - public void spawnEffect( final EffectType effect, final World worldObj, final double posX, final double posY, final double posZ, final Object o ) - { - if( AEConfig.instance.enableEffects ) - { - switch( effect ) - { - case Assembler: - this.spawnAssembler( worldObj, posX, posY, posZ, o ); - return; - case Vibrant: - this.spawnVibrant( worldObj, posX, posY, posZ ); - return; - case Crafting: - this.spawnCrafting( worldObj, posX, posY, posZ ); - return; - case Energy: - this.spawnEnergy( worldObj, posX, posY, posZ ); - return; - case Lightning: - this.spawnLightning( worldObj, posX, posY, posZ ); - return; - case LightningArc: - this.spawnLightningArc( worldObj, posX, posY, posZ, (Vec3) o ); - return; - default: - } - } - } - - private void spawnAssembler( final World worldObj, final double posX, final double posY, final double posZ, final Object o ) - { - final PacketAssemblerAnimation paa = (PacketAssemblerAnimation) o; - - final AssemblerFX fx = new AssemblerFX( Minecraft.getMinecraft().theWorld, posX, posY, posZ, 0.0D, 0.0D, 0.0D, paa.rate, paa.is ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - - private void spawnVibrant( final World w, final double x, final double y, final double z ) - { - if( CommonHelper.proxy.shouldAddParticles( Platform.getRandom() ) ) - { - final double d0 = ( Platform.getRandomFloat() - 0.5F ) * 0.26D; - final double d1 = ( Platform.getRandomFloat() - 0.5F ) * 0.26D; - final double d2 = ( Platform.getRandomFloat() - 0.5F ) * 0.26D; - - final VibrantFX fx = new VibrantFX( w, x + d0, y + d1, z + d2, 0.0D, 0.0D, 0.0D ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - - private void spawnCrafting( final World w, final double posX, final double posY, final double posZ ) - { - final float x = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; - final float y = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; - final float z = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; - - final CraftingFx fx = new CraftingFx( w, posX + x, posY + y, posZ + z, Items.diamond ); - - fx.motionX = -x * 0.2; - fx.motionY = -y * 0.2; - fx.motionZ = -z * 0.2; - - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - - private void spawnEnergy( final World w, final double posX, final double posY, final double posZ ) - { - final float x = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; - final float y = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; - final float z = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; - - final EnergyFx fx = new EnergyFx( w, posX + x, posY + y, posZ + z, Items.diamond ); - - fx.motionX = -x * 0.1; - fx.motionY = -y * 0.1; - fx.motionZ = -z * 0.1; - - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - - private void spawnLightning( final World worldObj, final double posX, final double posY, final double posZ ) - { - final LightningFX fx = new LightningFX( worldObj, posX, posY + 0.3f, posZ, 0.0f, 0.0f, 0.0f ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - - private void spawnLightningArc( final World worldObj, final double posX, final double posY, final double posZ, final Vec3 second ) - { - final LightningFX fx = new LightningArcFX( worldObj, posX, posY, posZ, second.xCoord, second.yCoord, second.zCoord, 0.0f, 0.0f, 0.0f ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - - @Override - public boolean shouldAddParticles( final Random r ) - { - final int setting = Minecraft.getMinecraft().gameSettings.particleSetting; - if( setting == 2 ) - { - return false; - } - if( setting == 0 ) - { - return true; - } - return r.nextInt( 2 * ( setting + 1 ) ) == 0; - } - - @Override - public MovingObjectPosition getMOP() - { - return Minecraft.getMinecraft().objectMouseOver; - } - - @Override - public void doRenderItem( final ItemStack itemstack, final World w ) - { - if( itemstack != null ) - { - final EntityItem entityitem = new EntityItem( w, 0.0D, 0.0D, 0.0D, itemstack ); - entityitem.getEntityItem().stackSize = 1; - - // set all this stuff and then do shit? meh? - entityitem.hoverStart = 0; - entityitem.age = 0; - entityitem.rotationYaw = 0; - - GL11.glPushMatrix(); - GL11.glTranslatef( 0, -0.04F, 0 ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - // GL11.glDisable( GL11.GL_CULL_FACE ); - - if( itemstack.isItemEnchanted() || itemstack.getItem().requiresMultipleRenderPasses() ) - { - GL11.glTranslatef( 0.0f, -0.05f, -0.25f ); - GL11.glScalef( 1.0f / 1.5f, 1.0f / 1.5f, 1.0f / 1.5f ); - // GL11.glTranslated( -8.0, -12.2, -10.6 ); - GL11.glScalef( 1.0f, -1.0f, 0.005f ); - // GL11.glScalef( 1.0f , -1.0f, 1.0f ); - - final Block block = Block.getBlockFromItem( itemstack.getItem() ); - if( ( itemstack.getItemSpriteNumber() == 0 && block != null && RenderBlocks.renderItemIn3d( block.getRenderType() ) ) ) - { - GL11.glRotatef( 25.0f, 1.0f, 0.0f, 0.0f ); - GL11.glRotatef( 15.0f, 0.0f, 1.0f, 0.0f ); - GL11.glRotatef( 30.0f, 0.0f, 1.0f, 0.0f ); - } - - final IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer( itemstack, IItemRenderer.ItemRenderType.ENTITY ); - if( customRenderer != null && !( itemstack.getItem() instanceof ItemBlock ) ) - { - if( customRenderer.shouldUseRenderHelper( IItemRenderer.ItemRenderType.ENTITY, itemstack, IItemRenderer.ItemRendererHelper.BLOCK_3D ) ) - { - GL11.glTranslatef( 0, -0.04F, 0 ); - GL11.glScalef( 0.7f, 0.7f, 0.7f ); - GL11.glRotatef( 35, 1, 0, 0 ); - GL11.glRotatef( 45, 0, 1, 0 ); - GL11.glRotatef( -90, 0, 1, 0 ); - } - } - else if( itemstack.getItem() instanceof ItemBlock ) - { - GL11.glTranslatef( 0, -0.04F, 0 ); - GL11.glScalef( 1.1f, 1.1f, 1.1f ); - GL11.glRotatef( -90, 0, 1, 0 ); - } - else - { - GL11.glTranslatef( 0, -0.14F, 0 ); - GL11.glScalef( 0.8f, 0.8f, 0.8f ); - } - - RenderItem.renderInFrame = true; - RenderManager.instance.renderEntityWithPosYaw( entityitem, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F ); - RenderItem.renderInFrame = false; - } - else - { - GL11.glScalef( 1.0f / 42.0f, 1.0f / 42.0f, 1.0f / 42.0f ); - GL11.glTranslated( -8.0, -10.2, -10.4 ); - GL11.glScalef( 1.0f, 1.0f, 0.005f ); - - RenderItem.renderInFrame = false; - final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - if( !ForgeHooksClient.renderInventoryItem( BLOCK_RENDERER, Minecraft.getMinecraft().renderEngine, itemstack, true, 0, 0, 0 ) ) - { - ITEM_RENDERER.renderItemIntoGUI( fr, Minecraft.getMinecraft().renderEngine, itemstack, 0, 0, false ); - } - } - - GL11.glPopMatrix(); - } - } - - @Override - public void postInit() - { - RenderingRegistry.registerBlockHandler( WorldRender.INSTANCE ); - RenderManager.instance.entityRenderMap.put( EntityTinyTNTPrimed.class, new RenderTinyTNTPrimed() ); - RenderManager.instance.entityRenderMap.put( EntityFloatingItem.class, new RenderFloatingItem() ); - } - - @Override - public CableRenderMode getRenderMode() - { - if( Platform.isServer() ) - { - return super.getRenderMode(); - } - - final Minecraft mc = Minecraft.getMinecraft(); - final EntityPlayer player = mc.thePlayer; - - return this.renderModeForPlayer( player ); - } - - @Override - public void triggerUpdates() - { - final Minecraft mc = Minecraft.getMinecraft(); - if( mc == null || mc.thePlayer == null || mc.theWorld == null ) - { - return; - } - - final EntityPlayer player = mc.thePlayer; - - final int x = (int) player.posX; - final int y = (int) player.posY; - final int z = (int) player.posZ; - - final int range = 16 * 16; - - mc.theWorld.markBlockRangeForRenderUpdate( x - range, y - range, z - range, x + range, y + range, z + range ); - } - - @Override - public void missingCoreMod() - { - throw new MissingCoreMod(); - } - - @SubscribeEvent - public void wheelEvent( final MouseEvent me ) - { - if( me.isCanceled() || me.dwheel == 0 ) - { - return; - } - - final Minecraft mc = Minecraft.getMinecraft(); - final EntityPlayer player = mc.thePlayer; - final ItemStack is = player.getHeldItem(); - - if( is != null && is.getItem() instanceof IMouseWheelItem && player.isSneaking() ) - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "Item", me.dwheel > 0 ? "WheelUp" : "WheelDown" ) ); - me.setCanceled( true ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - - @SubscribeEvent - public void updateTextureSheet( final TextureStitchEvent.Pre ev ) - { - if( ev.map.getTextureType() == 1 ) - { - for( final ExtraItemTextures et : ExtraItemTextures.values() ) - { - et.registerIcon( ev.map ); - } - } - - if( ev.map.getTextureType() == 0 ) - { - for( final ExtraBlockTextures et : ExtraBlockTextures.values() ) - { - et.registerIcon( ev.map ); - } - - for( final CableBusTextures cb : CableBusTextures.values() ) - { - cb.registerIcon( ev.map ); - } - } - } - - @Override - public boolean isKeyPressed( ActionKey key ) - { - return this.bindings.get( key ).isPressed(); - } - - @Override - public boolean isActionKey( ActionKey key, int pressedKeyCode ) - { - return isActiveAndMatches( this.bindings.get( key ), pressedKeyCode ); - } - - private boolean isActiveAndMatches(KeyBinding keyBinding, int keyCode) { -// return keyCode != 0 && keyCode == keyBinding.getKeyCode() && keyBinding.getKeyConflictContext().isActive() && keyBinding.getKeyModifier().isActive(keyBinding.getKeyConflictContext()); - return keyCode != 0 && keyCode == keyBinding.getKeyCode(); - } -} \ No newline at end of file +public class ClientHelper extends ServerHelper { + private static final String KEY_CATEGORY = "key.appliedenergistics2.category"; + + private final EnumMap bindings = new EnumMap<>(ActionKey.class); + + private static final RenderItem ITEM_RENDERER = new RenderItem(); + private static final RenderBlocks BLOCK_RENDERER = new RenderBlocks(); + + @SubscribeEvent + public void postPlayerRender(final RenderLivingEvent.Pre p) { + final PlayerColor player = TickHandler.INSTANCE.getPlayerColors().get(p.entity.getEntityId()); + if (player != null) { + final AEColor col = player.myColor; + + final float r = 0xff & (col.mediumVariant >> 16); + final float g = 0xff & (col.mediumVariant >> 8); + final float b = 0xff & (col.mediumVariant); + GL11.glColor3f(r / 255.0f, g / 255.0f, b / 255.0f); + } + } + + @Override + public void init() { + MinecraftForge.EVENT_BUS.register(this); + + for (ActionKey key : ActionKey.values()) { + final KeyBinding binding = new KeyBinding(key.getTranslationKey(), key.getDefaultKey(), KEY_CATEGORY); + ClientRegistry.registerKeyBinding(binding); + this.bindings.put(key, binding); + } + } + + @SubscribeEvent + public void renderWorldLastEvent(RenderWorldLastEvent event) { + HighlighterHandler.tick(event); + } + + @Override + public World getWorld() { + if (Platform.isClient()) { + return Minecraft.getMinecraft().theWorld; + } else { + return super.getWorld(); + } + } + + @Override + public void bindTileEntitySpecialRenderer(final Class tile, final AEBaseBlock blk) { + final BaseBlockRender bbr = blk.getRendererInstance().getRendererInstance(); + if (bbr.hasTESR() && tile != null) { + ClientRegistry.bindTileEntitySpecialRenderer(tile, new TESRWrapper(bbr)); + } + } + + @Override + public List getPlayers() { + if (Platform.isClient()) { + final List o = new ArrayList(); + o.add(Minecraft.getMinecraft().thePlayer); + return o; + } else { + return super.getPlayers(); + } + } + + @Override + public void spawnEffect( + final EffectType effect, + final World worldObj, + final double posX, + final double posY, + final double posZ, + final Object o) { + if (AEConfig.instance.enableEffects) { + switch (effect) { + case Assembler: + this.spawnAssembler(worldObj, posX, posY, posZ, o); + return; + case Vibrant: + this.spawnVibrant(worldObj, posX, posY, posZ); + return; + case Crafting: + this.spawnCrafting(worldObj, posX, posY, posZ); + return; + case Energy: + this.spawnEnergy(worldObj, posX, posY, posZ); + return; + case Lightning: + this.spawnLightning(worldObj, posX, posY, posZ); + return; + case LightningArc: + this.spawnLightningArc(worldObj, posX, posY, posZ, (Vec3) o); + return; + default: + } + } + } + + private void spawnAssembler( + final World worldObj, final double posX, final double posY, final double posZ, final Object o) { + final PacketAssemblerAnimation paa = (PacketAssemblerAnimation) o; + + final AssemblerFX fx = new AssemblerFX( + Minecraft.getMinecraft().theWorld, posX, posY, posZ, 0.0D, 0.0D, 0.0D, paa.rate, paa.is); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + + private void spawnVibrant(final World w, final double x, final double y, final double z) { + if (CommonHelper.proxy.shouldAddParticles(Platform.getRandom())) { + final double d0 = (Platform.getRandomFloat() - 0.5F) * 0.26D; + final double d1 = (Platform.getRandomFloat() - 0.5F) * 0.26D; + final double d2 = (Platform.getRandomFloat() - 0.5F) * 0.26D; + + final VibrantFX fx = new VibrantFX(w, x + d0, y + d1, z + d2, 0.0D, 0.0D, 0.0D); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } + + private void spawnCrafting(final World w, final double posX, final double posY, final double posZ) { + final float x = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; + final float y = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; + final float z = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; + + final CraftingFx fx = new CraftingFx(w, posX + x, posY + y, posZ + z, Items.diamond); + + fx.motionX = -x * 0.2; + fx.motionY = -y * 0.2; + fx.motionZ = -z * 0.2; + + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + + private void spawnEnergy(final World w, final double posX, final double posY, final double posZ) { + final float x = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; + final float y = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; + final float z = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; + + final EnergyFx fx = new EnergyFx(w, posX + x, posY + y, posZ + z, Items.diamond); + + fx.motionX = -x * 0.1; + fx.motionY = -y * 0.1; + fx.motionZ = -z * 0.1; + + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + + private void spawnLightning(final World worldObj, final double posX, final double posY, final double posZ) { + final LightningFX fx = new LightningFX(worldObj, posX, posY + 0.3f, posZ, 0.0f, 0.0f, 0.0f); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + + private void spawnLightningArc( + final World worldObj, final double posX, final double posY, final double posZ, final Vec3 second) { + final LightningFX fx = new LightningArcFX( + worldObj, posX, posY, posZ, second.xCoord, second.yCoord, second.zCoord, 0.0f, 0.0f, 0.0f); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + + @Override + public boolean shouldAddParticles(final Random r) { + final int setting = Minecraft.getMinecraft().gameSettings.particleSetting; + if (setting == 2) { + return false; + } + if (setting == 0) { + return true; + } + return r.nextInt(2 * (setting + 1)) == 0; + } + + @Override + public MovingObjectPosition getMOP() { + return Minecraft.getMinecraft().objectMouseOver; + } + + @Override + public void doRenderItem(final ItemStack itemstack, final World w) { + if (itemstack != null) { + final EntityItem entityitem = new EntityItem(w, 0.0D, 0.0D, 0.0D, itemstack); + entityitem.getEntityItem().stackSize = 1; + + // set all this stuff and then do shit? meh? + entityitem.hoverStart = 0; + entityitem.age = 0; + entityitem.rotationYaw = 0; + + GL11.glPushMatrix(); + GL11.glTranslatef(0, -0.04F, 0); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + // GL11.glDisable( GL11.GL_CULL_FACE ); + + if (itemstack.isItemEnchanted() || itemstack.getItem().requiresMultipleRenderPasses()) { + GL11.glTranslatef(0.0f, -0.05f, -0.25f); + GL11.glScalef(1.0f / 1.5f, 1.0f / 1.5f, 1.0f / 1.5f); + // GL11.glTranslated( -8.0, -12.2, -10.6 ); + GL11.glScalef(1.0f, -1.0f, 0.005f); + // GL11.glScalef( 1.0f , -1.0f, 1.0f ); + + final Block block = Block.getBlockFromItem(itemstack.getItem()); + if ((itemstack.getItemSpriteNumber() == 0 + && block != null + && RenderBlocks.renderItemIn3d(block.getRenderType()))) { + GL11.glRotatef(25.0f, 1.0f, 0.0f, 0.0f); + GL11.glRotatef(15.0f, 0.0f, 1.0f, 0.0f); + GL11.glRotatef(30.0f, 0.0f, 1.0f, 0.0f); + } + + final IItemRenderer customRenderer = + MinecraftForgeClient.getItemRenderer(itemstack, IItemRenderer.ItemRenderType.ENTITY); + if (customRenderer != null && !(itemstack.getItem() instanceof ItemBlock)) { + if (customRenderer.shouldUseRenderHelper( + IItemRenderer.ItemRenderType.ENTITY, + itemstack, + IItemRenderer.ItemRendererHelper.BLOCK_3D)) { + GL11.glTranslatef(0, -0.04F, 0); + GL11.glScalef(0.7f, 0.7f, 0.7f); + GL11.glRotatef(35, 1, 0, 0); + GL11.glRotatef(45, 0, 1, 0); + GL11.glRotatef(-90, 0, 1, 0); + } + } else if (itemstack.getItem() instanceof ItemBlock) { + GL11.glTranslatef(0, -0.04F, 0); + GL11.glScalef(1.1f, 1.1f, 1.1f); + GL11.glRotatef(-90, 0, 1, 0); + } else { + GL11.glTranslatef(0, -0.14F, 0); + GL11.glScalef(0.8f, 0.8f, 0.8f); + } + + RenderItem.renderInFrame = true; + RenderManager.instance.renderEntityWithPosYaw(entityitem, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F); + RenderItem.renderInFrame = false; + } else { + GL11.glScalef(1.0f / 42.0f, 1.0f / 42.0f, 1.0f / 42.0f); + GL11.glTranslated(-8.0, -10.2, -10.4); + GL11.glScalef(1.0f, 1.0f, 0.005f); + + RenderItem.renderInFrame = false; + final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + if (!ForgeHooksClient.renderInventoryItem( + BLOCK_RENDERER, Minecraft.getMinecraft().renderEngine, itemstack, true, 0, 0, 0)) { + ITEM_RENDERER.renderItemIntoGUI(fr, Minecraft.getMinecraft().renderEngine, itemstack, 0, 0, false); + } + } + + GL11.glPopMatrix(); + } + } + + @Override + public void postInit() { + RenderingRegistry.registerBlockHandler(WorldRender.INSTANCE); + RenderManager.instance.entityRenderMap.put(EntityTinyTNTPrimed.class, new RenderTinyTNTPrimed()); + RenderManager.instance.entityRenderMap.put(EntityFloatingItem.class, new RenderFloatingItem()); + } + + @Override + public CableRenderMode getRenderMode() { + if (Platform.isServer()) { + return super.getRenderMode(); + } + + final Minecraft mc = Minecraft.getMinecraft(); + final EntityPlayer player = mc.thePlayer; + + return this.renderModeForPlayer(player); + } + + @Override + public void triggerUpdates() { + final Minecraft mc = Minecraft.getMinecraft(); + if (mc == null || mc.thePlayer == null || mc.theWorld == null) { + return; + } + + final EntityPlayer player = mc.thePlayer; + + final int x = (int) player.posX; + final int y = (int) player.posY; + final int z = (int) player.posZ; + + final int range = 16 * 16; + + mc.theWorld.markBlockRangeForRenderUpdate(x - range, y - range, z - range, x + range, y + range, z + range); + } + + @Override + public void missingCoreMod() { + throw new MissingCoreMod(); + } + + @SubscribeEvent + public void wheelEvent(final MouseEvent me) { + if (me.isCanceled() || me.dwheel == 0) { + return; + } + + final Minecraft mc = Minecraft.getMinecraft(); + final EntityPlayer player = mc.thePlayer; + final ItemStack is = player.getHeldItem(); + + if (is != null && is.getItem() instanceof IMouseWheelItem && player.isSneaking()) { + try { + NetworkHandler.instance.sendToServer( + new PacketValueConfig("Item", me.dwheel > 0 ? "WheelUp" : "WheelDown")); + me.setCanceled(true); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + + @SubscribeEvent + public void updateTextureSheet(final TextureStitchEvent.Pre ev) { + if (ev.map.getTextureType() == 1) { + for (final ExtraItemTextures et : ExtraItemTextures.values()) { + et.registerIcon(ev.map); + } + } + + if (ev.map.getTextureType() == 0) { + for (final ExtraBlockTextures et : ExtraBlockTextures.values()) { + et.registerIcon(ev.map); + } + + for (final CableBusTextures cb : CableBusTextures.values()) { + cb.registerIcon(ev.map); + } + } + } + + @Override + public boolean isKeyPressed(ActionKey key) { + return this.bindings.get(key).isPressed(); + } + + @Override + public boolean isActionKey(ActionKey key, int pressedKeyCode) { + return isActiveAndMatches(this.bindings.get(key), pressedKeyCode); + } + + private boolean isActiveAndMatches(KeyBinding keyBinding, int keyCode) { + // return keyCode != 0 && keyCode == keyBinding.getKeyCode() && keyBinding.getKeyConflictContext().isActive() + // && keyBinding.getKeyModifier().isActive(keyBinding.getKeyConflictContext()); + return keyCode != 0 && keyCode == keyBinding.getKeyCode(); + } +} diff --git a/src/main/java/appeng/client/EffectType.java b/src/main/java/appeng/client/EffectType.java index 8929909e5f6..bcae1a14d3e 100644 --- a/src/main/java/appeng/client/EffectType.java +++ b/src/main/java/appeng/client/EffectType.java @@ -18,8 +18,11 @@ package appeng.client; - -public enum EffectType -{ - Energy, Lightning, Vibrant, Crafting, Assembler, LightningArc +public enum EffectType { + Energy, + Lightning, + Vibrant, + Crafting, + Assembler, + LightningArc } diff --git a/src/main/java/appeng/client/gui/AEBaseGui.java b/src/main/java/appeng/client/gui/AEBaseGui.java index f85e65ca389..912b55010b2 100644 --- a/src/main/java/appeng/client/gui/AEBaseGui.java +++ b/src/main/java/appeng/client/gui/AEBaseGui.java @@ -18,7 +18,6 @@ package appeng.client.gui; - import appeng.api.storage.data.IAEItemStack; import appeng.client.gui.widgets.GuiScrollbar; import appeng.client.gui.widgets.ITooltip; @@ -31,8 +30,8 @@ import appeng.container.slot.AppEngSlot.hasCalculatedValidness; import appeng.core.AELog; import appeng.core.AppEng; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketInventoryAction; import appeng.core.sync.packets.PacketSwapSlots; @@ -45,6 +44,11 @@ import com.google.common.base.Joiner; import com.google.common.base.Stopwatch; import cpw.mods.fml.common.ObfuscationReflectionHelper; +import java.io.IOException; +import java.text.DecimalFormat; +import java.text.ParseException; +import java.util.*; +import java.util.concurrent.TimeUnit; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.inventory.GuiContainer; @@ -61,991 +65,851 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import java.io.IOException; -import java.text.DecimalFormat; -import java.text.ParseException; -import java.util.*; -import java.util.concurrent.TimeUnit; +public abstract class AEBaseGui extends GuiContainer { + private static boolean switchingGuis; + private final List meSlots = new LinkedList(); + // drag y + private final Set drag_click = new HashSet(); + private final AppEngRenderItem aeRenderItem = new AppEngRenderItem(); + private GuiScrollbar scrollBar = null; + private boolean disableShiftClick = false; + private Stopwatch dbl_clickTimer = Stopwatch.createStarted(); + private ItemStack dbl_whichItem; + private Slot bl_clicked; + private boolean subGui; + + public AEBaseGui(final Container container) { + super(container); + this.subGui = switchingGuis; + switchingGuis = false; + } + + protected static String join(final Collection toolTip, final String delimiter) { + final Joiner joiner = Joiner.on(delimiter); + + return joiner.join(toolTip); + } + + protected int getQty(final GuiButton btn) { + try { + final DecimalFormat df = new DecimalFormat("+#;-#"); + return df.parse(btn.displayString).intValue(); + } catch (final ParseException e) { + return 0; + } + } + + public boolean isSubGui() { + return this.subGui; + } + + @Override + public void initGui() { + super.initGui(); + + final List slots = this.getInventorySlots(); + final Iterator i = slots.iterator(); + while (i.hasNext()) { + if (i.next() instanceof SlotME) { + i.remove(); + } + } + + for (final InternalSlotME me : this.meSlots) { + slots.add(new SlotME(me)); + } + } + + @SuppressWarnings("unchecked") + private List getInventorySlots() { + return this.inventorySlots.inventorySlots; + } + + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { + super.drawScreen(mouseX, mouseY, btn); + + for (final Object c : this.buttonList) { + if (c instanceof ITooltip) { + handleTooltip(mouseX, mouseY, (ITooltip) c); + } + } + } + + protected void handleTooltip(int mouseX, int mouseY, ITooltip tooltip) { + final int x = tooltip.xPos(); // ((GuiImgButton) c).xPosition; + int y = tooltip.yPos(); // ((GuiImgButton) c).yPosition; + + if (x < mouseX && x + tooltip.getWidth() > mouseX && tooltip.isVisible()) { + if (y < mouseY && y + tooltip.getHeight() > mouseY) { + if (y < 15) { + y = 15; + } + + final String msg = tooltip.getMessage(); + if (msg != null && !"".equals(msg)) { + this.drawTooltip(x + 11, y + 4, 0, msg); + } + } + } + } + + public void drawTooltip(final int par2, final int par3, final int forceWidth, final String message) { + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + final String[] var4 = message.split("\n"); + + if (var4.length > 0) { + int var5 = 0; + int var6; + int var7; + + for (var6 = 0; var6 < var4.length; ++var6) { + var7 = this.fontRendererObj.getStringWidth(var4[var6]); + + if (var7 > var5) { + var5 = var7; + } + } + + var6 = par2 + 12; + var7 = par3 - 12; + int var9 = 8; + + if (var4.length > 1) { + var9 += 2 + (var4.length - 1) * 10; + } + + if (this.guiTop + var7 + var9 + 6 > this.height) { + var7 = this.height - var9 - this.guiTop - 6; + } + + if (forceWidth > 0) { + var5 = forceWidth; + } + + this.zLevel = 300.0F; + itemRender.zLevel = 300.0F; + final int var10 = -267386864; + this.drawGradientRect(var6 - 3, var7 - 4, var6 + var5 + 3, var7 - 3, var10, var10); + this.drawGradientRect(var6 - 3, var7 + var9 + 3, var6 + var5 + 3, var7 + var9 + 4, var10, var10); + this.drawGradientRect(var6 - 3, var7 - 3, var6 + var5 + 3, var7 + var9 + 3, var10, var10); + this.drawGradientRect(var6 - 4, var7 - 3, var6 - 3, var7 + var9 + 3, var10, var10); + this.drawGradientRect(var6 + var5 + 3, var7 - 3, var6 + var5 + 4, var7 + var9 + 3, var10, var10); + final int var11 = 1347420415; + final int var12 = (var11 & 16711422) >> 1 | var11 & -16777216; + this.drawGradientRect(var6 - 3, var7 - 3 + 1, var6 - 3 + 1, var7 + var9 + 3 - 1, var11, var12); + this.drawGradientRect(var6 + var5 + 2, var7 - 3 + 1, var6 + var5 + 3, var7 + var9 + 3 - 1, var11, var12); + this.drawGradientRect(var6 - 3, var7 - 3, var6 + var5 + 3, var7 - 3 + 1, var11, var11); + this.drawGradientRect(var6 - 3, var7 + var9 + 2, var6 + var5 + 3, var7 + var9 + 3, var12, var12); + + for (int var13 = 0; var13 < var4.length; ++var13) { + String var14 = var4[var13]; + + if (var13 == 0) { + var14 = '\u00a7' + Integer.toHexString(15) + var14; + } else { + var14 = "\u00a77" + var14; + } + + this.fontRendererObj.drawStringWithShadow(var14, var6, var7, -1); + + if (var13 == 0) { + var7 += 2; + } + + var7 += 10; + } + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + } + GL11.glPopAttrib(); + } + + @Override + protected final void drawGuiContainerForegroundLayer(final int x, final int y) { + final int ox = this.guiLeft; // (width - xSize) / 2; + final int oy = this.guiTop; // (height - ySize) / 2; + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + if (this.getScrollBar() != null) { + this.getScrollBar().draw(this); + } + + this.drawFG(ox, oy, x, y); + } + + public abstract void drawFG(int offsetX, int offsetY, int mouseX, int mouseY); + + @Override + protected final void drawGuiContainerBackgroundLayer(final float f, final int x, final int y) { + final int ox = this.guiLeft; // (width - xSize) / 2; + final int oy = this.guiTop; // (height - ySize) / 2; + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + this.drawBG(ox, oy, x, y); + + final List slots = this.getInventorySlots(); + for (final Slot slot : slots) { + if (slot instanceof OptionalSlotFake) { + final OptionalSlotFake fs = (OptionalSlotFake) slot; + if (fs.renderDisabled()) { + if (fs.isEnabled()) { + this.drawTexturedModalRect( + ox + fs.xDisplayPosition - 1, + oy + fs.yDisplayPosition - 1, + fs.getSourceX() - 1, + fs.getSourceY() - 1, + 18, + 18); + } else { + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.4F); + GL11.glEnable(GL11.GL_BLEND); + this.drawTexturedModalRect( + ox + fs.xDisplayPosition - 1, + oy + fs.yDisplayPosition - 1, + fs.getSourceX() - 1, + fs.getSourceY() - 1, + 18, + 18); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glPopAttrib(); + } + } + } + } + } -public abstract class AEBaseGui extends GuiContainer -{ - private static boolean switchingGuis; - private final List meSlots = new LinkedList(); - // drag y - private final Set drag_click = new HashSet(); - private final AppEngRenderItem aeRenderItem = new AppEngRenderItem(); - private GuiScrollbar scrollBar = null; - private boolean disableShiftClick = false; - private Stopwatch dbl_clickTimer = Stopwatch.createStarted(); - private ItemStack dbl_whichItem; - private Slot bl_clicked; - private boolean subGui; - - public AEBaseGui( final Container container ) - { - super( container ); - this.subGui = switchingGuis; - switchingGuis = false; - } - - protected static String join( final Collection toolTip, final String delimiter ) - { - final Joiner joiner = Joiner.on( delimiter ); - - return joiner.join( toolTip ); - } - - protected int getQty( final GuiButton btn ) - { - try - { - final DecimalFormat df = new DecimalFormat( "+#;-#" ); - return df.parse( btn.displayString ).intValue(); - } - catch( final ParseException e ) - { - return 0; - } - } - - public boolean isSubGui() - { - return this.subGui; - } - - @Override - public void initGui() - { - super.initGui(); - - final List slots = this.getInventorySlots(); - final Iterator i = slots.iterator(); - while( i.hasNext() ) - { - if( i.next() instanceof SlotME ) - { - i.remove(); - } - } - - for( final InternalSlotME me : this.meSlots ) - { - slots.add( new SlotME( me ) ); - } - } - - @SuppressWarnings( "unchecked" ) - private List getInventorySlots() - { - return this.inventorySlots.inventorySlots; - } - - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { - super.drawScreen( mouseX, mouseY, btn ); - - for( final Object c : this.buttonList ) - { - if( c instanceof ITooltip ) - { - handleTooltip(mouseX, mouseY, (ITooltip) c); - } - } - } - - protected void handleTooltip(int mouseX, int mouseY, ITooltip tooltip) { - final int x = tooltip.xPos(); // ((GuiImgButton) c).xPosition; - int y = tooltip.yPos(); // ((GuiImgButton) c).yPosition; - - if( x < mouseX && x + tooltip.getWidth() > mouseX && tooltip.isVisible() ) - { - if( y < mouseY && y + tooltip.getHeight() > mouseY) - { - if( y < 15 ) - { - y = 15; - } - - final String msg = tooltip.getMessage(); - if( msg != null && !"".equals(msg)) - { - this.drawTooltip( x + 11, y + 4, 0, msg ); - } - } - } - } - - public void drawTooltip( final int par2, final int par3, final int forceWidth, final String message ) - { - GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - RenderHelper.disableStandardItemLighting(); - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL11.GL_DEPTH_TEST ); - final String[] var4 = message.split( "\n" ); - - if( var4.length > 0 ) - { - int var5 = 0; - int var6; - int var7; - - for( var6 = 0; var6 < var4.length; ++var6 ) - { - var7 = this.fontRendererObj.getStringWidth( var4[var6] ); - - if( var7 > var5 ) - { - var5 = var7; - } - } - - var6 = par2 + 12; - var7 = par3 - 12; - int var9 = 8; - - if( var4.length > 1 ) - { - var9 += 2 + ( var4.length - 1 ) * 10; - } - - if( this.guiTop + var7 + var9 + 6 > this.height ) - { - var7 = this.height - var9 - this.guiTop - 6; - } - - if( forceWidth > 0 ) - { - var5 = forceWidth; - } - - this.zLevel = 300.0F; - itemRender.zLevel = 300.0F; - final int var10 = -267386864; - this.drawGradientRect( var6 - 3, var7 - 4, var6 + var5 + 3, var7 - 3, var10, var10 ); - this.drawGradientRect( var6 - 3, var7 + var9 + 3, var6 + var5 + 3, var7 + var9 + 4, var10, var10 ); - this.drawGradientRect( var6 - 3, var7 - 3, var6 + var5 + 3, var7 + var9 + 3, var10, var10 ); - this.drawGradientRect( var6 - 4, var7 - 3, var6 - 3, var7 + var9 + 3, var10, var10 ); - this.drawGradientRect( var6 + var5 + 3, var7 - 3, var6 + var5 + 4, var7 + var9 + 3, var10, var10 ); - final int var11 = 1347420415; - final int var12 = ( var11 & 16711422 ) >> 1 | var11 & -16777216; - this.drawGradientRect( var6 - 3, var7 - 3 + 1, var6 - 3 + 1, var7 + var9 + 3 - 1, var11, var12 ); - this.drawGradientRect( var6 + var5 + 2, var7 - 3 + 1, var6 + var5 + 3, var7 + var9 + 3 - 1, var11, var12 ); - this.drawGradientRect( var6 - 3, var7 - 3, var6 + var5 + 3, var7 - 3 + 1, var11, var11 ); - this.drawGradientRect( var6 - 3, var7 + var9 + 2, var6 + var5 + 3, var7 + var9 + 3, var12, var12 ); - - for( int var13 = 0; var13 < var4.length; ++var13 ) - { - String var14 = var4[var13]; - - if( var13 == 0 ) - { - var14 = '\u00a7' + Integer.toHexString( 15 ) + var14; - } - else - { - var14 = "\u00a77" + var14; - } - - this.fontRendererObj.drawStringWithShadow( var14, var6, var7, -1 ); - - if( var13 == 0 ) - { - var7 += 2; - } - - var7 += 10; - } - - this.zLevel = 0.0F; - itemRender.zLevel = 0.0F; - } - GL11.glPopAttrib(); - } - - @Override - protected final void drawGuiContainerForegroundLayer( final int x, final int y ) - { - final int ox = this.guiLeft; // (width - xSize) / 2; - final int oy = this.guiTop; // (height - ySize) / 2; - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - - if( this.getScrollBar() != null ) - { - this.getScrollBar().draw( this ); - } - - this.drawFG( ox, oy, x, y ); - } - - public abstract void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ); - - @Override - protected final void drawGuiContainerBackgroundLayer( final float f, final int x, final int y ) - { - final int ox = this.guiLeft; // (width - xSize) / 2; - final int oy = this.guiTop; // (height - ySize) / 2; - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - this.drawBG( ox, oy, x, y ); - - final List slots = this.getInventorySlots(); - for( final Slot slot : slots ) - { - if( slot instanceof OptionalSlotFake ) - { - final OptionalSlotFake fs = (OptionalSlotFake) slot; - if( fs.renderDisabled() ) - { - if( fs.isEnabled() ) - { - this.drawTexturedModalRect( ox + fs.xDisplayPosition - 1, oy + fs.yDisplayPosition - 1, fs.getSourceX() - 1, fs.getSourceY() - 1, 18, - 18 ); - } - else - { - GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 0.4F ); - GL11.glEnable( GL11.GL_BLEND ); - this.drawTexturedModalRect( ox + fs.xDisplayPosition - 1, oy + fs.yDisplayPosition - 1, fs.getSourceX() - 1, fs.getSourceY() - 1, 18, 18 ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - GL11.glPopAttrib(); - } - } - } - } - } - - @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) - { - this.drag_click.clear(); - - if( btn == 1 ) - { - for( final Object o : this.buttonList ) - { - final GuiButton guibutton = (GuiButton) o; - if( guibutton.mousePressed( this.mc, xCoord, yCoord ) ) - { - super.mouseClicked( xCoord, yCoord, 0 ); - return; - } - } - } - - if( this.getScrollBar() != null ) - { - this.getScrollBar().click( this, xCoord - this.guiLeft, yCoord - this.guiTop ); - } - - super.mouseClicked( xCoord, yCoord, btn ); - } - - @Override - protected void mouseClickMove( final int x, final int y, final int c, final long d ) - { - final Slot slot = this.getSlot( x, y ); - final ItemStack itemstack = this.mc.thePlayer.inventory.getItemStack(); - - if( this.getScrollBar() != null ) - { - this.getScrollBar().click( this, x - this.guiLeft, y - this.guiTop ); - } - - if( slot instanceof SlotFake && itemstack != null ) - { - this.drag_click.add( slot ); - if( this.drag_click.size() > 1 ) - { - for( final Slot dr : this.drag_click ) - { - final PacketInventoryAction p = new PacketInventoryAction( c == 0 ? InventoryAction.PICKUP_OR_SET_DOWN : InventoryAction.PLACE_SINGLE, dr.slotNumber, 0 ); - NetworkHandler.instance.sendToServer( p ); - } - } - } - else if( slot instanceof SlotDisconnected ) - { - this.drag_click.add( slot ); - if( this.drag_click.size() > 1 ) - { - if( itemstack != null ) - { - for( final Slot dr : this.drag_click ) - { - if( slot.getStack() == null) - { - InventoryAction action = InventoryAction.SPLIT_OR_PLACE_SINGLE; - final PacketInventoryAction p = new PacketInventoryAction( action, dr.getSlotIndex(), ( (SlotDisconnected) slot ).getSlot().getId() ); - NetworkHandler.instance.sendToServer( p ); - } - } - } - - else if( isShiftKeyDown() ) - { - for( final Slot dr : this.drag_click ) - { - InventoryAction action = null; - if( slot.getStack() != null ) - { - action = InventoryAction.SHIFT_CLICK; - } - if( action != null ) - { - final PacketInventoryAction p = new PacketInventoryAction( action, dr.getSlotIndex(), ( (SlotDisconnected) slot ).getSlot().getId() ); - NetworkHandler.instance.sendToServer( p ); - } - } - } - } - } - else - { - super.mouseClickMove( x, y, c, d ); - } - } - - @Override - protected void handleMouseClick( final Slot slot, final int slotIdx, final int ctrlDown, final int mouseButton ) - { - final EntityPlayer player = Minecraft.getMinecraft().thePlayer; - - if( mouseButton == 3) - { - if( slot instanceof OptionalSlotFake || slot instanceof SlotFakeCraftingMatrix ) - { - if( slot.getHasStack() ) - { + @Override + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) { + this.drag_click.clear(); + + if (btn == 1) { + for (final Object o : this.buttonList) { + final GuiButton guibutton = (GuiButton) o; + if (guibutton.mousePressed(this.mc, xCoord, yCoord)) { + super.mouseClicked(xCoord, yCoord, 0); + return; + } + } + } + + if (this.getScrollBar() != null) { + this.getScrollBar().click(this, xCoord - this.guiLeft, yCoord - this.guiTop); + } + + super.mouseClicked(xCoord, yCoord, btn); + } + + @Override + protected void mouseClickMove(final int x, final int y, final int c, final long d) { + final Slot slot = this.getSlot(x, y); + final ItemStack itemstack = this.mc.thePlayer.inventory.getItemStack(); + + if (this.getScrollBar() != null) { + this.getScrollBar().click(this, x - this.guiLeft, y - this.guiTop); + } + + if (slot instanceof SlotFake && itemstack != null) { + this.drag_click.add(slot); + if (this.drag_click.size() > 1) { + for (final Slot dr : this.drag_click) { + final PacketInventoryAction p = new PacketInventoryAction( + c == 0 ? InventoryAction.PICKUP_OR_SET_DOWN : InventoryAction.PLACE_SINGLE, + dr.slotNumber, + 0); + NetworkHandler.instance.sendToServer(p); + } + } + } else if (slot instanceof SlotDisconnected) { + this.drag_click.add(slot); + if (this.drag_click.size() > 1) { + if (itemstack != null) { + for (final Slot dr : this.drag_click) { + if (slot.getStack() == null) { + InventoryAction action = InventoryAction.SPLIT_OR_PLACE_SINGLE; + final PacketInventoryAction p = new PacketInventoryAction( + action, + dr.getSlotIndex(), + ((SlotDisconnected) slot).getSlot().getId()); + NetworkHandler.instance.sendToServer(p); + } + } + } else if (isShiftKeyDown()) { + for (final Slot dr : this.drag_click) { + InventoryAction action = null; + if (slot.getStack() != null) { + action = InventoryAction.SHIFT_CLICK; + } + if (action != null) { + final PacketInventoryAction p = new PacketInventoryAction( + action, + dr.getSlotIndex(), + ((SlotDisconnected) slot).getSlot().getId()); + NetworkHandler.instance.sendToServer(p); + } + } + } + } + } else { + super.mouseClickMove(x, y, c, d); + } + } + + @Override + protected void handleMouseClick(final Slot slot, final int slotIdx, final int ctrlDown, final int mouseButton) { + final EntityPlayer player = Minecraft.getMinecraft().thePlayer; + + if (mouseButton == 3) { + if (slot instanceof OptionalSlotFake || slot instanceof SlotFakeCraftingMatrix) { + if (slot.getHasStack()) { InventoryAction action = InventoryAction.SET_PATTERN_VALUE; IAEItemStack stack = AEItemStack.create(slot.getStack()); - ( (AEBaseContainer) this.inventorySlots ).setTargetStack( stack ); - final PacketInventoryAction p = new PacketInventoryAction( action, slotIdx, 0 ); - NetworkHandler.instance.sendToServer( p ); + ((AEBaseContainer) this.inventorySlots).setTargetStack(stack); + final PacketInventoryAction p = new PacketInventoryAction(action, slotIdx, 0); + NetworkHandler.instance.sendToServer(p); return; } } - }else { + } else { - if( slot instanceof SlotFake ) - { - final InventoryAction action = ctrlDown == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; + if (slot instanceof SlotFake) { + final InventoryAction action = + ctrlDown == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; - if( this.drag_click.size() > 1 ) - { + if (this.drag_click.size() > 1) { return; } - final PacketInventoryAction p = new PacketInventoryAction( action, slotIdx, 0 ); - NetworkHandler.instance.sendToServer( p ); + final PacketInventoryAction p = new PacketInventoryAction(action, slotIdx, 0); + NetworkHandler.instance.sendToServer(p); + + return; + } + } + + if (slot instanceof SlotPatternTerm) { + if (mouseButton == 6) { + return; // prevent weird double clicks.. + } + + try { + NetworkHandler.instance.sendToServer(((SlotPatternTerm) slot).getRequest(isShiftKeyDown())); + } catch (final IOException e) { + AELog.debug(e); + } + } else if (slot instanceof SlotCraftingTerm) { + if (mouseButton == 6) { + return; // prevent weird double clicks.. + } + + InventoryAction action = null; + if (isShiftKeyDown()) { + action = InventoryAction.CRAFT_SHIFT; + } else { + // Craft stack on right-click, craft single on left-click + action = (mouseButton == 1) ? InventoryAction.CRAFT_STACK : InventoryAction.CRAFT_ITEM; + } + + final PacketInventoryAction p = new PacketInventoryAction(action, slotIdx, 0); + NetworkHandler.instance.sendToServer(p); + + return; + } + + if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) { + if (this.enableSpaceClicking() && !(slot instanceof SlotPatternTerm)) { + IAEItemStack stack = null; + if (slot instanceof SlotME) { + stack = ((SlotME) slot).getAEStack(); + } + + int slotNum = this.getInventorySlots().size(); + if (!(slot instanceof SlotME) && slot != null) { + slotNum = slot.slotNumber; + } + + ((AEBaseContainer) this.inventorySlots).setTargetStack(stack); + final PacketInventoryAction p = new PacketInventoryAction(InventoryAction.MOVE_REGION, slotNum, 0); + NetworkHandler.instance.sendToServer(p); return; } + } + + if (slot instanceof SlotDisconnected) { + if (this.drag_click.size() > 1) { + return; + } + + InventoryAction action = null; + + switch (mouseButton) { + case 0: // pickup / set-down. + { + ItemStack heldStack = player.inventory.getItemStack(); + if (slot.getStack() == null && heldStack != null) + action = InventoryAction.SPLIT_OR_PLACE_SINGLE; + else if (slot.getStack() != null && (heldStack == null || heldStack.stackSize <= 1)) + action = InventoryAction.PICKUP_OR_SET_DOWN; + } + break; + case 1: + action = ctrlDown == 1 ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK; + break; + + case 3: // creative dupe: + if (player.capabilities.isCreativeMode) { + action = InventoryAction.CREATIVE_DUPLICATE; + } + + break; + + default: + case 4: // drop item: + case 6: + } + + if (action != null) { + final PacketInventoryAction p = new PacketInventoryAction( + action, + slot.getSlotIndex(), + ((SlotDisconnected) slot).getSlot().getId()); + NetworkHandler.instance.sendToServer(p); + } + + return; + } + + if (slot instanceof SlotME) { + InventoryAction action = null; + IAEItemStack stack = null; + + switch (mouseButton) { + case 0: // pickup / set-down. + action = ctrlDown == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; + stack = ((SlotME) slot).getAEStack(); + + if (stack != null + && action == InventoryAction.PICKUP_OR_SET_DOWN + && stack.getStackSize() == 0 + && player.inventory.getItemStack() == null) { + action = InventoryAction.AUTO_CRAFT; + } + + break; + case 1: + action = ctrlDown == 1 ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK; + stack = ((SlotME) slot).getAEStack(); + break; + + case 3: // creative dupe: + stack = ((SlotME) slot).getAEStack(); + if (stack != null && stack.isCraftable()) { + action = InventoryAction.AUTO_CRAFT; + } else if (player.capabilities.isCreativeMode) { + final IAEItemStack slotItem = ((SlotME) slot).getAEStack(); + if (slotItem != null) { + action = InventoryAction.CREATIVE_DUPLICATE; + } + } + break; + + default: + case 4: // drop item: + case 6: + } + + if (action != null) { + ((AEBaseContainer) this.inventorySlots).setTargetStack(stack); + final PacketInventoryAction p = new PacketInventoryAction( + action, this.getInventorySlots().size(), 0); + NetworkHandler.instance.sendToServer(p); + } + + return; + } + + if (!this.disableShiftClick && isShiftKeyDown()) { + this.disableShiftClick = true; + + if (this.dbl_whichItem == null + || this.bl_clicked != slot + || this.dbl_clickTimer.elapsed(TimeUnit.MILLISECONDS) > 150) { + // some simple double click logic. + this.bl_clicked = slot; + this.dbl_clickTimer = Stopwatch.createStarted(); + if (slot != null) { + this.dbl_whichItem = slot.getHasStack() ? slot.getStack().copy() : null; + } else { + this.dbl_whichItem = null; + } + } else if (this.dbl_whichItem != null) { + // a replica of the weird broken vanilla feature. + + final List slots = this.getInventorySlots(); + for (final Slot inventorySlot : slots) { + if (inventorySlot != null + && inventorySlot.canTakeStack(this.mc.thePlayer) + && inventorySlot.getHasStack() + && inventorySlot.inventory == slot.inventory + && Container.func_94527_a(inventorySlot, this.dbl_whichItem, true)) { + this.handleMouseClick(inventorySlot, inventorySlot.slotNumber, ctrlDown, 1); + } + } + } + + this.disableShiftClick = false; + } + + super.handleMouseClick(slot, slotIdx, ctrlDown, mouseButton); + } + + @Override + protected boolean checkHotbarKeys(final int keyCode) { + final Slot theSlot; + + try { + theSlot = ObfuscationReflectionHelper.getPrivateValue( + GuiContainer.class, this, "theSlot", "field_147006_u", "f"); + } catch (final Throwable t) { + return false; + } + + if (this.mc.thePlayer.inventory.getItemStack() == null && theSlot != null) { + for (int j = 0; j < 9; ++j) { + if (keyCode == this.mc.gameSettings.keyBindsHotbar[j].getKeyCode()) { + final List slots = this.getInventorySlots(); + for (final Slot s : slots) { + if (s.getSlotIndex() == j + && s.inventory == ((AEBaseContainer) this.inventorySlots).getPlayerInv()) { + if (!s.canTakeStack(((AEBaseContainer) this.inventorySlots).getPlayerInv().player)) { + return false; + } + } + } + + if (theSlot.getSlotStackLimit() == 64) { + this.handleMouseClick(theSlot, theSlot.slotNumber, j, 2); + return true; + } else { + for (final Slot s : slots) { + if (s.getSlotIndex() == j + && s.inventory == ((AEBaseContainer) this.inventorySlots).getPlayerInv()) { + NetworkHandler.instance.sendToServer( + new PacketSwapSlots(s.slotNumber, theSlot.slotNumber)); + return true; + } + } + } + } + } + } + return false; + } + + @Override + public void onGuiClosed() { + super.onGuiClosed(); + this.subGui = true; // in case the gui is reopened later ( i'm looking at you NEI ) + } + + protected Slot getSlot(final int mouseX, final int mouseY) { + final List slots = this.getInventorySlots(); + for (final Slot slot : slots) { + // isPointInRegion + if (this.func_146978_c(slot.xDisplayPosition, slot.yDisplayPosition, 16, 16, mouseX, mouseY)) { + return slot; + } } - if( slot instanceof SlotPatternTerm ) - { - if( mouseButton == 6 ) - { - return; // prevent weird double clicks.. - } - - try - { - NetworkHandler.instance.sendToServer( ( (SlotPatternTerm) slot ).getRequest( isShiftKeyDown() ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - else if( slot instanceof SlotCraftingTerm ) - { - if( mouseButton == 6 ) - { - return; // prevent weird double clicks.. - } - - InventoryAction action = null; - if( isShiftKeyDown() ) - { - action = InventoryAction.CRAFT_SHIFT; - } - else - { - // Craft stack on right-click, craft single on left-click - action = ( mouseButton == 1 ) ? InventoryAction.CRAFT_STACK : InventoryAction.CRAFT_ITEM; - } - - final PacketInventoryAction p = new PacketInventoryAction( action, slotIdx, 0 ); - NetworkHandler.instance.sendToServer( p ); - - return; - } - - if( Keyboard.isKeyDown( Keyboard.KEY_SPACE ) ) - { - if( this.enableSpaceClicking() && !( slot instanceof SlotPatternTerm ) ) - { - IAEItemStack stack = null; - if( slot instanceof SlotME ) - { - stack = ( (SlotME) slot ).getAEStack(); - } - - int slotNum = this.getInventorySlots().size(); - - if( !( slot instanceof SlotME ) && slot != null ) - { - slotNum = slot.slotNumber; - } - - ( (AEBaseContainer) this.inventorySlots ).setTargetStack( stack ); - final PacketInventoryAction p = new PacketInventoryAction( InventoryAction.MOVE_REGION, slotNum, 0 ); - NetworkHandler.instance.sendToServer( p ); - return; - } - } - - if( slot instanceof SlotDisconnected ) - { - if( this.drag_click.size() > 1 ) - { - return; - } - - InventoryAction action = null; - - switch( mouseButton ) - { - case 0: // pickup / set-down. - { - ItemStack heldStack = player.inventory.getItemStack(); - if (slot.getStack() == null && heldStack != null) - action = InventoryAction.SPLIT_OR_PLACE_SINGLE; - else if (slot.getStack() != null && (heldStack == null || heldStack.stackSize <= 1)) - action = InventoryAction.PICKUP_OR_SET_DOWN; - } - break; - case 1: - action = ctrlDown == 1 ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK; - break; - - case 3: // creative dupe: - - if( player.capabilities.isCreativeMode ) - { - action = InventoryAction.CREATIVE_DUPLICATE; - } - - break; - - default: - case 4: // drop item: - case 6: - } - - if( action != null ) - { - final PacketInventoryAction p = new PacketInventoryAction( action, slot.getSlotIndex(), ( (SlotDisconnected) slot ).getSlot().getId() ); - NetworkHandler.instance.sendToServer( p ); - } - - return; - } - - if( slot instanceof SlotME ) - { - InventoryAction action = null; - IAEItemStack stack = null; - - switch( mouseButton ) - { - case 0: // pickup / set-down. - action = ctrlDown == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; - stack = ( (SlotME) slot ).getAEStack(); - - if( stack != null && action == InventoryAction.PICKUP_OR_SET_DOWN && stack.getStackSize() == 0 && player.inventory.getItemStack() == null ) - { - action = InventoryAction.AUTO_CRAFT; - } - - break; - case 1: - action = ctrlDown == 1 ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK; - stack = ( (SlotME) slot ).getAEStack(); - break; - - case 3: // creative dupe: - - stack = ( (SlotME) slot ).getAEStack(); - if( stack != null && stack.isCraftable() ) - { - action = InventoryAction.AUTO_CRAFT; - } - else if( player.capabilities.isCreativeMode ) - { - final IAEItemStack slotItem = ( (SlotME) slot ).getAEStack(); - if( slotItem != null ) - { - action = InventoryAction.CREATIVE_DUPLICATE; - } - } - break; - - default: - case 4: // drop item: - case 6: - } - - if( action != null ) - { - ( (AEBaseContainer) this.inventorySlots ).setTargetStack( stack ); - final PacketInventoryAction p = new PacketInventoryAction( action, this.getInventorySlots().size(), 0 ); - NetworkHandler.instance.sendToServer( p ); - } - - return; - } - - if( !this.disableShiftClick && isShiftKeyDown() ) - { - this.disableShiftClick = true; - - if( this.dbl_whichItem == null || this.bl_clicked != slot || this.dbl_clickTimer.elapsed( TimeUnit.MILLISECONDS ) > 150 ) - { - // some simple double click logic. - this.bl_clicked = slot; - this.dbl_clickTimer = Stopwatch.createStarted(); - if( slot != null ) - { - this.dbl_whichItem = slot.getHasStack() ? slot.getStack().copy() : null; - } - else - { - this.dbl_whichItem = null; - } - } - else if( this.dbl_whichItem != null ) - { - // a replica of the weird broken vanilla feature. - - final List slots = this.getInventorySlots(); - for( final Slot inventorySlot : slots ) - { - if( inventorySlot != null && inventorySlot.canTakeStack( - this.mc.thePlayer ) && inventorySlot.getHasStack() && inventorySlot.inventory == slot.inventory && Container.func_94527_a( - inventorySlot, this.dbl_whichItem, true ) ) - { - this.handleMouseClick( inventorySlot, inventorySlot.slotNumber, ctrlDown, 1 ); - } - } - } - - this.disableShiftClick = false; - } - - super.handleMouseClick( slot, slotIdx, ctrlDown, mouseButton ); - } - - @Override - protected boolean checkHotbarKeys( final int keyCode ) - { - final Slot theSlot; - - try - { - theSlot = ObfuscationReflectionHelper.getPrivateValue( GuiContainer.class, this, "theSlot", "field_147006_u", "f" ); - } - catch( final Throwable t ) - { - return false; - } - - if( this.mc.thePlayer.inventory.getItemStack() == null && theSlot != null ) - { - for( int j = 0; j < 9; ++j ) - { - if( keyCode == this.mc.gameSettings.keyBindsHotbar[j].getKeyCode() ) - { - final List slots = this.getInventorySlots(); - for( final Slot s : slots ) - { - if( s.getSlotIndex() == j && s.inventory == ( (AEBaseContainer) this.inventorySlots ).getPlayerInv() ) - { - if( !s.canTakeStack( ( (AEBaseContainer) this.inventorySlots ).getPlayerInv().player ) ) - { - return false; - } - } - } - - if( theSlot.getSlotStackLimit() == 64 ) - { - this.handleMouseClick( theSlot, theSlot.slotNumber, j, 2 ); - return true; - } - else - { - for( final Slot s : slots ) - { - if( s.getSlotIndex() == j && s.inventory == ( (AEBaseContainer) this.inventorySlots ).getPlayerInv() ) - { - NetworkHandler.instance.sendToServer( new PacketSwapSlots( s.slotNumber, theSlot.slotNumber ) ); - return true; - } - } - } - } - } - } - - return false; - } - - @Override - public void onGuiClosed() - { - super.onGuiClosed(); - this.subGui = true; // in case the gui is reopened later ( i'm looking at you NEI ) - } - - protected Slot getSlot( final int mouseX, final int mouseY ) - { - final List slots = this.getInventorySlots(); - for( final Slot slot : slots ) - { - // isPointInRegion - if( this.func_146978_c( slot.xDisplayPosition, slot.yDisplayPosition, 16, 16, mouseX, mouseY ) ) - { - return slot; - } - } - - return null; - } - - public abstract void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ); - - @Override - public void handleMouseInput() - { - super.handleMouseInput(); - - final int wheel = Mouse.getEventDWheel(); - - if (wheel != 0) { - final int x = Mouse.getEventX() * this.width / this.mc.displayWidth; - final int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; - - if (isShiftKeyDown()) { - this.mouseWheelEvent(x, y, wheel / Math.abs(wheel)); - } else if (this.getScrollBar() != null) { - final GuiScrollbar scrollBar = this.getScrollBar(); - - if ( - x > this.guiLeft && - y - this.guiTop > scrollBar.getTop() && - x <= this.guiLeft + this.xSize && - y - this.guiTop <= scrollBar.getTop() + scrollBar.getHeight() - ) { - this.getScrollBar().wheel(wheel); - } - - } - - } - - } - - private void mouseWheelEvent( final int x, final int y, final int wheel ) - { - final Slot slot = this.getSlot( x, y ); - if( slot instanceof SlotME ) - { - final IAEItemStack item = ( (SlotME) slot ).getAEStack(); - if( item != null ) - { - ( (AEBaseContainer) this.inventorySlots ).setTargetStack( item ); - final InventoryAction direction = wheel > 0 ? InventoryAction.ROLL_DOWN : InventoryAction.ROLL_UP; - final int times = Math.abs( wheel ); - final int inventorySize = this.getInventorySlots().size(); - for( int h = 0; h < times; h++ ) - { - final PacketInventoryAction p = new PacketInventoryAction( direction, inventorySize, 0 ); - NetworkHandler.instance.sendToServer( p ); - } - } - } - } - - protected boolean enableSpaceClicking() - { - return true; - } - - public void bindTexture( final String base, final String file ) - { - final ResourceLocation loc = new ResourceLocation( base, "textures/" + file ); - this.mc.getTextureManager().bindTexture( loc ); - } - - public void drawItem( final int x, final int y, final ItemStack is ) - { - this.zLevel = 100.0F; - itemRender.zLevel = 100.0F; - - GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glEnable( GL11.GL_DEPTH_TEST ); - RenderHelper.enableGUIStandardItemLighting(); - itemRender.renderItemAndEffectIntoGUI( this.fontRendererObj, this.mc.renderEngine, is, x, y ); - GL11.glPopAttrib(); - - itemRender.zLevel = 0.0F; - this.zLevel = 0.0F; - } - - protected String getGuiDisplayName( final String in ) - { - return this.hasCustomInventoryName() ? this.getInventoryName() : in; - } - - private boolean hasCustomInventoryName() - { - if( this.inventorySlots instanceof AEBaseContainer ) - { - return ( (AEBaseContainer) this.inventorySlots ).getCustomName() != null; - } - return false; - } - - private String getInventoryName() - { - return ( (AEBaseContainer) this.inventorySlots ).getCustomName(); - } - - private void drawSlot( final Slot s ) - { - if( s instanceof SlotME || s instanceof SlotFake) - { - final RenderItem pIR = this.setItemRender( this.aeRenderItem ); - try - { - this.zLevel = 100.0F; - itemRender.zLevel = 100.0F; - - if( !this.isPowered() ) - { - GL11.glDisable( GL11.GL_LIGHTING ); - drawRect( s.xDisplayPosition, s.yDisplayPosition, 16 + s.xDisplayPosition, 16 + s.yDisplayPosition, GuiColors.ItemSlotOverlayUnpowered.getColor() ); - GL11.glEnable( GL11.GL_LIGHTING ); - } - - this.zLevel = 0.0F; - itemRender.zLevel = 0.0F; - - this.aeRenderItem.setAeStack( Platform.getAEStackInSlot( s ) ); - - this.safeDrawSlot( s ); - } - catch( final Exception err ) - { - AELog.warn( "[AppEng] AE prevented crash while drawing slot: " + err.toString() ); - } - this.setItemRender( pIR ); - return; - } - else - { - try - { - final ItemStack is = s.getStack(); - if( s instanceof AppEngSlot && ( ( (AppEngSlot) s ).renderIconWithItem() || is == null ) && ( ( (AppEngSlot) s ).shouldDisplay() ) ) - { - final AppEngSlot aes = (AppEngSlot) s; - if( aes.getIcon() >= 0 ) - { - this.bindTexture( "guis/states.png" ); - - GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); - final Tessellator tessellator = Tessellator.instance; - try - { - final int uv_y = (int) Math.floor( aes.getIcon() / 16 ); - final int uv_x = aes.getIcon() - uv_y * 16; - - GL11.glEnable( GL11.GL_BLEND ); - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glEnable( GL11.GL_TEXTURE_2D ); - GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - final float par1 = aes.xDisplayPosition; - final float par2 = aes.yDisplayPosition; - final float par3 = uv_x * 16; - final float par4 = uv_y * 16; - - tessellator.startDrawingQuads(); - tessellator.setColorRGBA_F( 1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon() ); - final float f1 = 0.00390625F; - final float f = 0.00390625F; - final float par6 = 16; - tessellator.addVertexWithUV( par1 + 0, par2 + par6, this.zLevel, ( par3 + 0 ) * f, ( par4 + par6 ) * f1 ); - final float par5 = 16; - tessellator.addVertexWithUV( par1 + par5, par2 + par6, this.zLevel, ( par3 + par5 ) * f, ( par4 + par6 ) * f1 ); - tessellator.addVertexWithUV( par1 + par5, par2 + 0, this.zLevel, ( par3 + par5 ) * f, ( par4 + 0 ) * f1 ); - tessellator.addVertexWithUV( par1 + 0, par2 + 0, this.zLevel, ( par3 + 0 ) * f, ( par4 + 0 ) * f1 ); - tessellator.setColorRGBA_F( 1.0f, 1.0f, 1.0f, 1.0f ); - tessellator.draw(); - - } - catch( final Exception err ) - { - } - GL11.glPopAttrib(); - } - } - - if( is != null && s instanceof AppEngSlot ) - { - if( ( (AppEngSlot) s ).getIsValid() == hasCalculatedValidness.NotAvailable ) - { - boolean isValid = s.isItemValid( - is ) || s instanceof SlotOutput || s instanceof AppEngCraftingSlot || s instanceof SlotDisabled || s instanceof SlotInaccessible || s instanceof SlotFake || s instanceof SlotRestrictedInput || s instanceof SlotDisconnected; - if( isValid && s instanceof SlotRestrictedInput ) - { - try - { - isValid = ( (SlotRestrictedInput) s ).isValid( is, this.mc.theWorld ); - } - catch( final Exception err ) - { - AELog.debug( err ); - } - } - ( (AppEngSlot) s ).setIsValid( isValid ? hasCalculatedValidness.Valid : hasCalculatedValidness.Invalid ); - } - - if( ( (AppEngSlot) s ).getIsValid() == hasCalculatedValidness.Invalid ) - { - this.zLevel = 100.0F; - itemRender.zLevel = 100.0F; - - GL11.glDisable( GL11.GL_LIGHTING ); - drawRect( s.xDisplayPosition, s.yDisplayPosition, 16 + s.xDisplayPosition, 16 + s.yDisplayPosition, GuiColors.ItemSlotOverlayInvalid.getColor() ); - GL11.glEnable( GL11.GL_LIGHTING ); - - this.zLevel = 0.0F; - itemRender.zLevel = 0.0F; - } - } - - if( s instanceof AppEngSlot ) - { - ( (AppEngSlot) s ).setDisplay( true ); - this.safeDrawSlot( s ); - } - else - { - this.safeDrawSlot( s ); - } - - return; - } - catch( final Exception err ) - { - AELog.warn( "[AppEng] AE prevented crash while drawing slot: " + err.toString() ); - } - } - // do the usual for non-ME Slots. - this.safeDrawSlot( s ); - } - - private RenderItem setItemRender( final RenderItem item ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.NEI ) ) - { - return ( (INEI) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.NEI ) ).setItemRender( item ); - } - else - { - final RenderItem ri = itemRender; - itemRender = item; - return ri; - } - } - - protected boolean isPowered() - { - return true; - } - - private void safeDrawSlot( final Slot s ) - { - try - { - GuiContainer.class.getDeclaredMethod( "func_146977_a_original", Slot.class ).invoke( this, s ); - } - catch( final Exception err ) - { - } - } - - public void bindTexture( final String file ) - { - final ResourceLocation loc = new ResourceLocation( AppEng.MOD_ID, "textures/" + file ); - this.mc.getTextureManager().bindTexture( loc ); - } - - public void func_146977_a( final Slot s ) - { - this.drawSlot( s ); - } - - protected GuiScrollbar getScrollBar() - { - return this.scrollBar; - } - - protected void setScrollBar( final GuiScrollbar myScrollBar ) - { - this.scrollBar = myScrollBar; - } - - protected List getMeSlots() - { - return this.meSlots; - } - - public static final synchronized boolean isSwitchingGuis() - { - return switchingGuis; - } - - public static final synchronized void setSwitchingGuis( final boolean switchingGuis ) - { - AEBaseGui.switchingGuis = switchingGuis; - } - protected void addItemTooltip(ItemStack is, List lineList) - { - if (isShiftKeyDown()) - { - List l = is.getTooltip(this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips); - if (!l.isEmpty()) - l.remove(0); - lineList.addAll(l); - } - else - { - lineList.add(GuiText.HoldShiftForTooltip.getLocal()); - } - - } + return null; + } + + public abstract void drawBG(int offsetX, int offsetY, int mouseX, int mouseY); + + @Override + public void handleMouseInput() { + super.handleMouseInput(); + + final int wheel = Mouse.getEventDWheel(); + + if (wheel != 0) { + final int x = Mouse.getEventX() * this.width / this.mc.displayWidth; + final int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; + + if (isShiftKeyDown()) { + this.mouseWheelEvent(x, y, wheel / Math.abs(wheel)); + } else if (this.getScrollBar() != null) { + final GuiScrollbar scrollBar = this.getScrollBar(); + + if (x > this.guiLeft + && y - this.guiTop > scrollBar.getTop() + && x <= this.guiLeft + this.xSize + && y - this.guiTop <= scrollBar.getTop() + scrollBar.getHeight()) { + this.getScrollBar().wheel(wheel); + } + } + } + } + + private void mouseWheelEvent(final int x, final int y, final int wheel) { + final Slot slot = this.getSlot(x, y); + if (slot instanceof SlotME) { + final IAEItemStack item = ((SlotME) slot).getAEStack(); + if (item != null) { + ((AEBaseContainer) this.inventorySlots).setTargetStack(item); + final InventoryAction direction = wheel > 0 ? InventoryAction.ROLL_DOWN : InventoryAction.ROLL_UP; + final int times = Math.abs(wheel); + final int inventorySize = this.getInventorySlots().size(); + for (int h = 0; h < times; h++) { + final PacketInventoryAction p = new PacketInventoryAction(direction, inventorySize, 0); + NetworkHandler.instance.sendToServer(p); + } + } + } + } + + protected boolean enableSpaceClicking() { + return true; + } + + public void bindTexture(final String base, final String file) { + final ResourceLocation loc = new ResourceLocation(base, "textures/" + file); + this.mc.getTextureManager().bindTexture(loc); + } + + public void drawItem(final int x, final int y, final ItemStack is) { + this.zLevel = 100.0F; + itemRender.zLevel = 100.0F; + + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glEnable(GL11.GL_DEPTH_TEST); + RenderHelper.enableGUIStandardItemLighting(); + itemRender.renderItemAndEffectIntoGUI(this.fontRendererObj, this.mc.renderEngine, is, x, y); + GL11.glPopAttrib(); + + itemRender.zLevel = 0.0F; + this.zLevel = 0.0F; + } + + protected String getGuiDisplayName(final String in) { + return this.hasCustomInventoryName() ? this.getInventoryName() : in; + } + + private boolean hasCustomInventoryName() { + if (this.inventorySlots instanceof AEBaseContainer) { + return ((AEBaseContainer) this.inventorySlots).getCustomName() != null; + } + return false; + } + + private String getInventoryName() { + return ((AEBaseContainer) this.inventorySlots).getCustomName(); + } + + private void drawSlot(final Slot s) { + if (s instanceof SlotME || s instanceof SlotFake) { + final RenderItem pIR = this.setItemRender(this.aeRenderItem); + try { + this.zLevel = 100.0F; + itemRender.zLevel = 100.0F; + + if (!this.isPowered()) { + GL11.glDisable(GL11.GL_LIGHTING); + drawRect( + s.xDisplayPosition, + s.yDisplayPosition, + 16 + s.xDisplayPosition, + 16 + s.yDisplayPosition, + GuiColors.ItemSlotOverlayUnpowered.getColor()); + GL11.glEnable(GL11.GL_LIGHTING); + } + + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + + this.aeRenderItem.setAeStack(Platform.getAEStackInSlot(s)); + + this.safeDrawSlot(s); + } catch (final Exception err) { + AELog.warn("[AppEng] AE prevented crash while drawing slot: " + err.toString()); + } + this.setItemRender(pIR); + return; + } else { + try { + final ItemStack is = s.getStack(); + if (s instanceof AppEngSlot + && (((AppEngSlot) s).renderIconWithItem() || is == null) + && (((AppEngSlot) s).shouldDisplay())) { + final AppEngSlot aes = (AppEngSlot) s; + if (aes.getIcon() >= 0) { + this.bindTexture("guis/states.png"); + + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + final Tessellator tessellator = Tessellator.instance; + try { + final int uv_y = (int) Math.floor(aes.getIcon() / 16); + final int uv_x = aes.getIcon() - uv_y * 16; + + GL11.glEnable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + final float par1 = aes.xDisplayPosition; + final float par2 = aes.yDisplayPosition; + final float par3 = uv_x * 16; + final float par4 = uv_y * 16; + + tessellator.startDrawingQuads(); + tessellator.setColorRGBA_F(1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon()); + final float f1 = 0.00390625F; + final float f = 0.00390625F; + final float par6 = 16; + tessellator.addVertexWithUV( + par1 + 0, par2 + par6, this.zLevel, (par3 + 0) * f, (par4 + par6) * f1); + final float par5 = 16; + tessellator.addVertexWithUV( + par1 + par5, par2 + par6, this.zLevel, (par3 + par5) * f, (par4 + par6) * f1); + tessellator.addVertexWithUV( + par1 + par5, par2 + 0, this.zLevel, (par3 + par5) * f, (par4 + 0) * f1); + tessellator.addVertexWithUV( + par1 + 0, par2 + 0, this.zLevel, (par3 + 0) * f, (par4 + 0) * f1); + tessellator.setColorRGBA_F(1.0f, 1.0f, 1.0f, 1.0f); + tessellator.draw(); + + } catch (final Exception err) { + } + GL11.glPopAttrib(); + } + } + + if (is != null && s instanceof AppEngSlot) { + if (((AppEngSlot) s).getIsValid() == hasCalculatedValidness.NotAvailable) { + boolean isValid = s.isItemValid(is) + || s instanceof SlotOutput + || s instanceof AppEngCraftingSlot + || s instanceof SlotDisabled + || s instanceof SlotInaccessible + || s instanceof SlotFake + || s instanceof SlotRestrictedInput + || s instanceof SlotDisconnected; + if (isValid && s instanceof SlotRestrictedInput) { + try { + isValid = ((SlotRestrictedInput) s).isValid(is, this.mc.theWorld); + } catch (final Exception err) { + AELog.debug(err); + } + } + ((AppEngSlot) s) + .setIsValid(isValid ? hasCalculatedValidness.Valid : hasCalculatedValidness.Invalid); + } + + if (((AppEngSlot) s).getIsValid() == hasCalculatedValidness.Invalid) { + this.zLevel = 100.0F; + itemRender.zLevel = 100.0F; + + GL11.glDisable(GL11.GL_LIGHTING); + drawRect( + s.xDisplayPosition, + s.yDisplayPosition, + 16 + s.xDisplayPosition, + 16 + s.yDisplayPosition, + GuiColors.ItemSlotOverlayInvalid.getColor()); + GL11.glEnable(GL11.GL_LIGHTING); + + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + } + } + + if (s instanceof AppEngSlot) { + ((AppEngSlot) s).setDisplay(true); + this.safeDrawSlot(s); + } else { + this.safeDrawSlot(s); + } + + return; + } catch (final Exception err) { + AELog.warn("[AppEng] AE prevented crash while drawing slot: " + err.toString()); + } + } + // do the usual for non-ME Slots. + this.safeDrawSlot(s); + } + + private RenderItem setItemRender(final RenderItem item) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.NEI)) { + return ((INEI) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.NEI)).setItemRender(item); + } else { + final RenderItem ri = itemRender; + itemRender = item; + return ri; + } + } + + protected boolean isPowered() { + return true; + } + + private void safeDrawSlot(final Slot s) { + try { + GuiContainer.class + .getDeclaredMethod("func_146977_a_original", Slot.class) + .invoke(this, s); + } catch (final Exception err) { + } + } + + public void bindTexture(final String file) { + final ResourceLocation loc = new ResourceLocation(AppEng.MOD_ID, "textures/" + file); + this.mc.getTextureManager().bindTexture(loc); + } + + public void func_146977_a(final Slot s) { + this.drawSlot(s); + } + + protected GuiScrollbar getScrollBar() { + return this.scrollBar; + } + + protected void setScrollBar(final GuiScrollbar myScrollBar) { + this.scrollBar = myScrollBar; + } + + protected List getMeSlots() { + return this.meSlots; + } + + public static final synchronized boolean isSwitchingGuis() { + return switchingGuis; + } + + public static final synchronized void setSwitchingGuis(final boolean switchingGuis) { + AEBaseGui.switchingGuis = switchingGuis; + } + + protected void addItemTooltip(ItemStack is, List lineList) { + if (isShiftKeyDown()) { + List l = is.getTooltip(this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips); + if (!l.isEmpty()) l.remove(0); + lineList.addAll(l); + } else { + lineList.add(GuiText.HoldShiftForTooltip.getLocal()); + } + } } diff --git a/src/main/java/appeng/client/gui/AEBaseMEGui.java b/src/main/java/appeng/client/gui/AEBaseMEGui.java index cb6e74e065c..87c0883d3e4 100644 --- a/src/main/java/appeng/client/gui/AEBaseMEGui.java +++ b/src/main/java/appeng/client/gui/AEBaseMEGui.java @@ -18,128 +18,112 @@ package appeng.client.gui; - import appeng.api.storage.data.IAEItemStack; import appeng.client.me.SlotME; import appeng.container.slot.SlotFake; import appeng.core.AEConfig; import appeng.core.localization.ButtonToolTips; import appeng.util.Platform; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; - import java.text.NumberFormat; import java.util.List; import java.util.Locale; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +public abstract class AEBaseMEGui extends AEBaseGui { -public abstract class AEBaseMEGui extends AEBaseGui -{ - - public AEBaseMEGui( final Container container ) - { - super( container ); - } + public AEBaseMEGui(final Container container) { + super(container); + } - public List handleItemTooltip( final ItemStack stack, final int mouseX, final int mouseY, final List currentToolTip ) - { - if( stack != null ) - { - final Slot s = this.getSlot( mouseX, mouseY ); + public List handleItemTooltip( + final ItemStack stack, final int mouseX, final int mouseY, final List currentToolTip) { + if (stack != null) { + final Slot s = this.getSlot(mouseX, mouseY); final boolean isSlotME = s instanceof SlotME; - if( isSlotME || s instanceof SlotFake) - { - final int BigNumber = AEConfig.instance.useTerminalUseLargeFont() ? 999 : 9999; - - IAEItemStack myStack = null; - - try - { - myStack = Platform.getAEStackInSlot( s ); - } - catch( final Throwable ignore ) - { - } - - if( myStack != null ) - { - if( myStack.getStackSize() > BigNumber || ( myStack.getStackSize() > 1 && stack.isItemDamaged() ) ) - { - final String local = isSlotME ? ButtonToolTips.ItemsStored.getLocal() : ButtonToolTips.ItemCount.getLocal(); - final String formattedAmount = NumberFormat.getNumberInstance( Locale.US ).format( myStack.getStackSize() ); - final String format = String.format( local, formattedAmount ); - - currentToolTip.add( "\u00a77" + format ); - } - - if( myStack.getCountRequestable() > 0 ) - { - final String local = ButtonToolTips.ItemsRequestable.getLocal(); - final String formattedAmount = NumberFormat.getNumberInstance( Locale.US ).format( myStack.getCountRequestable() ); - final String format = String.format( local, formattedAmount ); - - currentToolTip.add( "\u00a77" + format ); - } - } - else if( stack.stackSize > BigNumber || ( stack.stackSize > 1 && stack.isItemDamaged() ) ) - { - final String local = ButtonToolTips.ItemsStored.getLocal(); - final String formattedAmount = NumberFormat.getNumberInstance( Locale.US ).format( stack.stackSize ); - final String format = String.format( local, formattedAmount ); - - currentToolTip.add( "\u00a77" + format ); - } - } - } - return currentToolTip; - } - - // Vanilla version... - // protected void drawItemStackTooltip(ItemStack stack, int x, int y) - @Override - protected void renderToolTip( final ItemStack stack, final int x, final int y ) - { - final Slot s = this.getSlot( x, y ); - if( ( s instanceof SlotME || s instanceof SlotFake ) && stack != null ) - { - final int BigNumber = AEConfig.instance.useTerminalUseLargeFont() ? 999 : 9999; - - IAEItemStack myStack = null; - - try - { - myStack = Platform.getAEStackInSlot( s ); - } - catch( final Throwable ignore ) - { - } - - if( myStack != null ) - { - @SuppressWarnings( "unchecked" ) final List currentToolTip = stack.getTooltip( this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips ); - - if( myStack.getStackSize() > BigNumber || ( myStack.getStackSize() > 1 && stack.isItemDamaged() ) ) - { - currentToolTip.add( "Items Stored: " + NumberFormat.getNumberInstance( Locale.US ).format( myStack.getStackSize() ) ); - } - - if( myStack.getCountRequestable() > 0 ) - { - currentToolTip.add( "Items Requestable: " + NumberFormat.getNumberInstance( Locale.US ).format( myStack.getCountRequestable() ) ); - } - - this.drawTooltip( x, y, 0, join( currentToolTip, "\n" ) ); - } - else if( stack.stackSize > BigNumber ) - { - final List var4 = stack.getTooltip( this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips ); - var4.add( "Items Stored: " + NumberFormat.getNumberInstance( Locale.US ).format( stack.stackSize ) ); - this.drawTooltip( x, y, 0, join( var4, "\n" ) ); - return; - } - } - super.renderToolTip( stack, x, y ); - // super.drawItemStackTooltip( stack, x, y ); - } -} \ No newline at end of file + if (isSlotME || s instanceof SlotFake) { + final int BigNumber = AEConfig.instance.useTerminalUseLargeFont() ? 999 : 9999; + + IAEItemStack myStack = null; + + try { + myStack = Platform.getAEStackInSlot(s); + } catch (final Throwable ignore) { + } + + if (myStack != null) { + if (myStack.getStackSize() > BigNumber || (myStack.getStackSize() > 1 && stack.isItemDamaged())) { + final String local = + isSlotME ? ButtonToolTips.ItemsStored.getLocal() : ButtonToolTips.ItemCount.getLocal(); + final String formattedAmount = + NumberFormat.getNumberInstance(Locale.US).format(myStack.getStackSize()); + final String format = String.format(local, formattedAmount); + + currentToolTip.add("\u00a77" + format); + } + + if (myStack.getCountRequestable() > 0) { + final String local = ButtonToolTips.ItemsRequestable.getLocal(); + final String formattedAmount = + NumberFormat.getNumberInstance(Locale.US).format(myStack.getCountRequestable()); + final String format = String.format(local, formattedAmount); + + currentToolTip.add("\u00a77" + format); + } + } else if (stack.stackSize > BigNumber || (stack.stackSize > 1 && stack.isItemDamaged())) { + final String local = ButtonToolTips.ItemsStored.getLocal(); + final String formattedAmount = + NumberFormat.getNumberInstance(Locale.US).format(stack.stackSize); + final String format = String.format(local, formattedAmount); + + currentToolTip.add("\u00a77" + format); + } + } + } + return currentToolTip; + } + + // Vanilla version... + // protected void drawItemStackTooltip(ItemStack stack, int x, int y) + @Override + protected void renderToolTip(final ItemStack stack, final int x, final int y) { + final Slot s = this.getSlot(x, y); + if ((s instanceof SlotME || s instanceof SlotFake) && stack != null) { + final int BigNumber = AEConfig.instance.useTerminalUseLargeFont() ? 999 : 9999; + + IAEItemStack myStack = null; + + try { + myStack = Platform.getAEStackInSlot(s); + } catch (final Throwable ignore) { + } + + if (myStack != null) { + @SuppressWarnings("unchecked") + final List currentToolTip = + stack.getTooltip(this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips); + + if (myStack.getStackSize() > BigNumber || (myStack.getStackSize() > 1 && stack.isItemDamaged())) { + currentToolTip.add("Items Stored: " + + NumberFormat.getNumberInstance(Locale.US).format(myStack.getStackSize())); + } + + if (myStack.getCountRequestable() > 0) { + currentToolTip.add("Items Requestable: " + + NumberFormat.getNumberInstance(Locale.US).format(myStack.getCountRequestable())); + } + + this.drawTooltip(x, y, 0, join(currentToolTip, "\n")); + } else if (stack.stackSize > BigNumber) { + final List var4 = stack.getTooltip(this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips); + var4.add("Items Stored: " + + NumberFormat.getNumberInstance(Locale.US).format(stack.stackSize)); + this.drawTooltip(x, y, 0, join(var4, "\n")); + return; + } + } + super.renderToolTip(stack, x, y); + // super.drawItemStackTooltip( stack, x, y ); + } +} diff --git a/src/main/java/appeng/client/gui/GuiNull.java b/src/main/java/appeng/client/gui/GuiNull.java index e8ac394d62b..fc3bb1ac2a1 100644 --- a/src/main/java/appeng/client/gui/GuiNull.java +++ b/src/main/java/appeng/client/gui/GuiNull.java @@ -18,26 +18,17 @@ package appeng.client.gui; - import net.minecraft.inventory.Container; +public class GuiNull extends AEBaseGui { -public class GuiNull extends AEBaseGui -{ - - public GuiNull( final Container container ) - { - super( container ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - } + public GuiNull(final Container container) { + super(container); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) {} - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) {} } diff --git a/src/main/java/appeng/client/gui/config/AEConfigGui.java b/src/main/java/appeng/client/gui/config/AEConfigGui.java index f395aa3819c..229a86c069d 100644 --- a/src/main/java/appeng/client/gui/config/AEConfigGui.java +++ b/src/main/java/appeng/client/gui/config/AEConfigGui.java @@ -18,54 +18,50 @@ package appeng.client.gui.config; - import appeng.core.AEConfig; import appeng.core.AppEng; import cpw.mods.fml.client.config.GuiConfig; import cpw.mods.fml.client.config.IConfigElement; +import java.util.ArrayList; +import java.util.List; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.ConfigElement; -import java.util.ArrayList; -import java.util.List; - - -public class AEConfigGui extends GuiConfig -{ +public class AEConfigGui extends GuiConfig { - public AEConfigGui( final GuiScreen parent ) - { - super( parent, getConfigElements(), AppEng.MOD_ID, false, false, GuiConfig.getAbridgedConfigPath( AEConfig.instance.getFilePath() ) ); - } + public AEConfigGui(final GuiScreen parent) { + super( + parent, + getConfigElements(), + AppEng.MOD_ID, + false, + false, + GuiConfig.getAbridgedConfigPath(AEConfig.instance.getFilePath())); + } - private static List getConfigElements() - { - final List list = new ArrayList(); + private static List getConfigElements() { + final List list = new ArrayList(); - for( final String cat : AEConfig.instance.getCategoryNames() ) - { - if( cat.equals( "versionchecker" ) ) - { - continue; - } + for (final String cat : AEConfig.instance.getCategoryNames()) { + if (cat.equals("versionchecker")) { + continue; + } - if( cat.equals( "settings" ) ) - { - continue; - } + if (cat.equals("settings")) { + continue; + } - final ConfigCategory cc = AEConfig.instance.getCategory( cat ); + final ConfigCategory cc = AEConfig.instance.getCategory(cat); - if( cc.isChild() ) - { - continue; - } + if (cc.isChild()) { + continue; + } - final ConfigElement ce = new ConfigElement( cc ); - list.add( ce ); - } + final ConfigElement ce = new ConfigElement(cc); + list.add(ce); + } - return list; - } + return list; + } } diff --git a/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java b/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java index 4bd5034722e..57fee0d34a9 100644 --- a/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java +++ b/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java @@ -18,38 +18,28 @@ package appeng.client.gui.config; - import cpw.mods.fml.client.IModGuiFactory; +import java.util.Set; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; -import java.util.Set; - - -public class AEConfigGuiFactory implements IModGuiFactory -{ - - @Override - public void initialize( final Minecraft minecraftInstance ) - { +public class AEConfigGuiFactory implements IModGuiFactory { - } + @Override + public void initialize(final Minecraft minecraftInstance) {} - @Override - public Class mainConfigGuiClass() - { - return AEConfigGui.class; - } + @Override + public Class mainConfigGuiClass() { + return AEConfigGui.class; + } - @Override - public Set runtimeGuiCategories() - { - return null; - } + @Override + public Set runtimeGuiCategories() { + return null; + } - @Override - public RuntimeOptionGuiHandler getHandlerFor( final RuntimeOptionCategoryElement element ) - { - return null; - } + @Override + public RuntimeOptionGuiHandler getHandlerFor(final RuntimeOptionCategoryElement element) { + return null; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCellWorkbench.java b/src/main/java/appeng/client/gui/implementations/GuiCellWorkbench.java index ede9b4bc9d8..88e035776c6 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCellWorkbench.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCellWorkbench.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.config.*; import appeng.api.implementations.items.IUpgradeModule; import appeng.client.gui.widgets.GuiImgButton; @@ -29,181 +28,153 @@ import appeng.core.sync.packets.PacketValueConfig; import appeng.tile.misc.TileCellWorkbench; import appeng.util.Platform; +import java.io.IOException; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import org.lwjgl.input.Mouse; -import java.io.IOException; - - -public class GuiCellWorkbench extends GuiUpgradeable -{ - - private final ContainerCellWorkbench workbench; - - private GuiImgButton clear; - private GuiImgButton partition; - private GuiToggleButton copyMode; - - public GuiCellWorkbench( final InventoryPlayer inventoryPlayer, final TileCellWorkbench te ) - { - super( new ContainerCellWorkbench( inventoryPlayer, te ) ); - this.workbench = (ContainerCellWorkbench) this.inventorySlots; - this.ySize = 251; - } - - @Override - protected void addButtons() - { - this.clear = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.ACTIONS, ActionItems.CLOSE ); - this.partition = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH ); - this.copyMode = new GuiToggleButton( this.guiLeft - 18, this.guiTop + 48, 11 * 16 + 5, 12 * 16 + 5, GuiText.CopyMode.getLocal(), GuiText.CopyModeDesc.getLocal() ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 68, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.oreFilter = new GuiImgButton( this.guiLeft - 18, this.guiTop + 68, Settings.ACTIONS, ActionItems.ORE_FILTER ); - - this.buttonList.add( this.fuzzyMode ); - this.buttonList.add( this.partition ); - this.buttonList.add( this.clear ); - this.buttonList.add( this.copyMode ); - this.buttonList.add( this.oreFilter ); - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.handleButtonVisibility(); - - this.bindTexture( this.getBackground() ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, 211 - 34, this.ySize ); - if( this.drawUpgrades() ) - { - if( this.workbench.availableUpgrades() <= 8 ) - { - this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 7 + this.workbench.availableUpgrades() * 18 ); - this.drawTexturedModalRect( offsetX + 177, offsetY + ( 7 + ( this.workbench.availableUpgrades() ) * 18 ), 177, 151, 35, 7 ); - } - else if( this.workbench.availableUpgrades() <= 16 ) - { - this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 7 + 8 * 18 ); - this.drawTexturedModalRect( offsetX + 177, offsetY + ( 7 + ( 8 ) * 18 ), 177, 151, 35, 7 ); - - final int dx = this.workbench.availableUpgrades() - 8; - this.drawTexturedModalRect( offsetX + 177 + 27, offsetY, 186, 0, 35 - 8, 7 + dx * 18 ); - if( dx == 8 ) - { - this.drawTexturedModalRect( offsetX + 177 + 27, offsetY + ( 7 + ( dx ) * 18 ), 186, 151, 35 - 8, 7 ); - } - else - { - this.drawTexturedModalRect( offsetX + 177 + 27 + 4, offsetY + ( 7 + ( dx ) * 18 ), 186 + 4, 151, 35 - 8, 7 ); - } - } - else - { - this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 7 + 8 * 18 ); - this.drawTexturedModalRect( offsetX + 177, offsetY + ( 7 + ( 8 ) * 18 ), 177, 151, 35, 7 ); - - this.drawTexturedModalRect( offsetX + 177 + 27, offsetY, 186, 0, 35 - 8, 7 + 8 * 18 ); - this.drawTexturedModalRect( offsetX + 177 + 27, offsetY + ( 7 + ( 8 ) * 18 ), 186, 151, 35 - 8, 7 ); - - final int dx = this.workbench.availableUpgrades() - 16; - this.drawTexturedModalRect( offsetX + 177 + 27 + 18, offsetY, 186, 0, 35 - 8, 7 + dx * 18 ); - if( dx == 8 ) - { - this.drawTexturedModalRect( offsetX + 177 + 27 + 18, offsetY + ( 7 + ( dx ) * 18 ), 186, 151, 35 - 8, 7 ); - } - else - { - this.drawTexturedModalRect( offsetX + 177 + 27 + 18 + 4, offsetY + ( 7 + ( dx ) * 18 ), 186 + 4, 151, 35 - 8, 7 ); - } - } - } - if( this.hasToolbox() ) - { - this.drawTexturedModalRect( offsetX + 178, offsetY + this.ySize - 90, 178, 161, 68, 68 ); - } - } - - @Override - protected void handleButtonVisibility() - { - this.copyMode.setState( this.workbench.getCopyMode() == CopyMode.CLEAR_ON_REMOVE ); - - boolean hasFuzzy = false; - boolean hasOreFilter = false; - final IInventory inv = this.workbench.getCellUpgradeInventory(); - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - final ItemStack is = inv.getStackInSlot( x ); - if( is != null && is.getItem() instanceof IUpgradeModule ) - { - if( ( (IUpgradeModule) is.getItem() ).getType( is ) == Upgrades.FUZZY ) - { - hasFuzzy = true; - } - if( ( (IUpgradeModule) is.getItem() ).getType( is ) == Upgrades.ORE_FILTER ) - { - hasOreFilter = true; - } - } - } - this.fuzzyMode.setVisibility( !hasOreFilter && hasFuzzy ); - this.oreFilter.setVisibility( hasOreFilter ); - } - - @Override - protected String getBackground() - { - return "guis/cellworkbench.png"; - } - - @Override - protected boolean drawUpgrades() - { - return this.workbench.availableUpgrades() > 0; - } - - @Override - protected GuiText getName() - { - return GuiText.CellWorkbench; - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - try - { - if( btn == this.copyMode ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "CellWorkbench.Action", "CopyMode" ) ); - } - else if( btn == this.partition ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "CellWorkbench.Action", "Partition" ) ); - } - else if( btn == this.clear ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "CellWorkbench.Action", "Clear" ) ); - } - else if( btn == this.fuzzyMode ) - { - final boolean backwards = Mouse.isButtonDown( 1 ); - - FuzzyMode fz = (FuzzyMode) this.fuzzyMode.getCurrentValue(); - fz = Platform.rotateEnum( fz, backwards, Settings.FUZZY_MODE.getPossibleValues() ); - - NetworkHandler.instance.sendToServer( new PacketValueConfig( "CellWorkbench.Fuzzy", fz.name() ) ); - } - else - { - super.actionPerformed( btn ); - } - } - catch( final IOException ignored ) - { - } - } +public class GuiCellWorkbench extends GuiUpgradeable { + + private final ContainerCellWorkbench workbench; + + private GuiImgButton clear; + private GuiImgButton partition; + private GuiToggleButton copyMode; + + public GuiCellWorkbench(final InventoryPlayer inventoryPlayer, final TileCellWorkbench te) { + super(new ContainerCellWorkbench(inventoryPlayer, te)); + this.workbench = (ContainerCellWorkbench) this.inventorySlots; + this.ySize = 251; + } + + @Override + protected void addButtons() { + this.clear = new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.ACTIONS, ActionItems.CLOSE); + this.partition = new GuiImgButton(this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH); + this.copyMode = new GuiToggleButton( + this.guiLeft - 18, + this.guiTop + 48, + 11 * 16 + 5, + 12 * 16 + 5, + GuiText.CopyMode.getLocal(), + GuiText.CopyModeDesc.getLocal()); + this.fuzzyMode = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 68, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.oreFilter = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 68, Settings.ACTIONS, ActionItems.ORE_FILTER); + + this.buttonList.add(this.fuzzyMode); + this.buttonList.add(this.partition); + this.buttonList.add(this.clear); + this.buttonList.add(this.copyMode); + this.buttonList.add(this.oreFilter); + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.handleButtonVisibility(); + + this.bindTexture(this.getBackground()); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, 211 - 34, this.ySize); + if (this.drawUpgrades()) { + if (this.workbench.availableUpgrades() <= 8) { + this.drawTexturedModalRect( + offsetX + 177, offsetY, 177, 0, 35, 7 + this.workbench.availableUpgrades() * 18); + this.drawTexturedModalRect( + offsetX + 177, offsetY + (7 + (this.workbench.availableUpgrades()) * 18), 177, 151, 35, 7); + } else if (this.workbench.availableUpgrades() <= 16) { + this.drawTexturedModalRect(offsetX + 177, offsetY, 177, 0, 35, 7 + 8 * 18); + this.drawTexturedModalRect(offsetX + 177, offsetY + (7 + (8) * 18), 177, 151, 35, 7); + + final int dx = this.workbench.availableUpgrades() - 8; + this.drawTexturedModalRect(offsetX + 177 + 27, offsetY, 186, 0, 35 - 8, 7 + dx * 18); + if (dx == 8) { + this.drawTexturedModalRect(offsetX + 177 + 27, offsetY + (7 + (dx) * 18), 186, 151, 35 - 8, 7); + } else { + this.drawTexturedModalRect( + offsetX + 177 + 27 + 4, offsetY + (7 + (dx) * 18), 186 + 4, 151, 35 - 8, 7); + } + } else { + this.drawTexturedModalRect(offsetX + 177, offsetY, 177, 0, 35, 7 + 8 * 18); + this.drawTexturedModalRect(offsetX + 177, offsetY + (7 + (8) * 18), 177, 151, 35, 7); + + this.drawTexturedModalRect(offsetX + 177 + 27, offsetY, 186, 0, 35 - 8, 7 + 8 * 18); + this.drawTexturedModalRect(offsetX + 177 + 27, offsetY + (7 + (8) * 18), 186, 151, 35 - 8, 7); + + final int dx = this.workbench.availableUpgrades() - 16; + this.drawTexturedModalRect(offsetX + 177 + 27 + 18, offsetY, 186, 0, 35 - 8, 7 + dx * 18); + if (dx == 8) { + this.drawTexturedModalRect(offsetX + 177 + 27 + 18, offsetY + (7 + (dx) * 18), 186, 151, 35 - 8, 7); + } else { + this.drawTexturedModalRect( + offsetX + 177 + 27 + 18 + 4, offsetY + (7 + (dx) * 18), 186 + 4, 151, 35 - 8, 7); + } + } + } + if (this.hasToolbox()) { + this.drawTexturedModalRect(offsetX + 178, offsetY + this.ySize - 90, 178, 161, 68, 68); + } + } + + @Override + protected void handleButtonVisibility() { + this.copyMode.setState(this.workbench.getCopyMode() == CopyMode.CLEAR_ON_REMOVE); + + boolean hasFuzzy = false; + boolean hasOreFilter = false; + final IInventory inv = this.workbench.getCellUpgradeInventory(); + for (int x = 0; x < inv.getSizeInventory(); x++) { + final ItemStack is = inv.getStackInSlot(x); + if (is != null && is.getItem() instanceof IUpgradeModule) { + if (((IUpgradeModule) is.getItem()).getType(is) == Upgrades.FUZZY) { + hasFuzzy = true; + } + if (((IUpgradeModule) is.getItem()).getType(is) == Upgrades.ORE_FILTER) { + hasOreFilter = true; + } + } + } + this.fuzzyMode.setVisibility(!hasOreFilter && hasFuzzy); + this.oreFilter.setVisibility(hasOreFilter); + } + + @Override + protected String getBackground() { + return "guis/cellworkbench.png"; + } + + @Override + protected boolean drawUpgrades() { + return this.workbench.availableUpgrades() > 0; + } + + @Override + protected GuiText getName() { + return GuiText.CellWorkbench; + } + + @Override + protected void actionPerformed(final GuiButton btn) { + try { + if (btn == this.copyMode) { + NetworkHandler.instance.sendToServer(new PacketValueConfig("CellWorkbench.Action", "CopyMode")); + } else if (btn == this.partition) { + NetworkHandler.instance.sendToServer(new PacketValueConfig("CellWorkbench.Action", "Partition")); + } else if (btn == this.clear) { + NetworkHandler.instance.sendToServer(new PacketValueConfig("CellWorkbench.Action", "Clear")); + } else if (btn == this.fuzzyMode) { + final boolean backwards = Mouse.isButtonDown(1); + + FuzzyMode fz = (FuzzyMode) this.fuzzyMode.getCurrentValue(); + fz = Platform.rotateEnum(fz, backwards, Settings.FUZZY_MODE.getPossibleValues()); + + NetworkHandler.instance.sendToServer(new PacketValueConfig("CellWorkbench.Fuzzy", fz.name())); + } else { + super.actionPerformed(btn); + } + } catch (final IOException ignored) { + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiChest.java b/src/main/java/appeng/client/gui/implementations/GuiChest.java index 51650e709d3..93abd114563 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiChest.java +++ b/src/main/java/appeng/client/gui/implementations/GuiChest.java @@ -18,12 +18,11 @@ package appeng.client.gui.implementations; - import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiTabButton; import appeng.container.implementations.ContainerChest; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.GuiBridge; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketSwitchGuis; @@ -31,48 +30,44 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; +public class GuiChest extends AEBaseGui { -public class GuiChest extends AEBaseGui -{ - - private GuiTabButton priority; + private GuiTabButton priority; - public GuiChest( final InventoryPlayer inventoryPlayer, final TileChest te ) - { - super( new ContainerChest( inventoryPlayer, te ) ); - this.ySize = 166; - } + public GuiChest(final InventoryPlayer inventoryPlayer, final TileChest te) { + super(new ContainerChest(inventoryPlayer, te)); + this.ySize = 166; + } - @Override - protected void actionPerformed( final GuiButton par1GuiButton ) - { - super.actionPerformed( par1GuiButton ); + @Override + protected void actionPerformed(final GuiButton par1GuiButton) { + super.actionPerformed(par1GuiButton); - if( par1GuiButton == this.priority ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - } + if (par1GuiButton == this.priority) { + NetworkHandler.instance.sendToServer(new PacketSwitchGuis(GuiBridge.GUI_PRIORITY)); + } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender ) ); - } + this.buttonList.add( + this.priority = new GuiTabButton( + this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender)); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.Chest.getLocal() ), 8, 6, GuiColors.ChestTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.ChestInventory.getColor() ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.Chest.getLocal()), 8, 6, GuiColors.ChestTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.ChestInventory.getColor()); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/chest.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/chest.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCondenser.java b/src/main/java/appeng/client/gui/implementations/GuiCondenser.java index 24cdf01b3b5..2e8b47b296b 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCondenser.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCondenser.java @@ -18,15 +18,14 @@ package appeng.client.gui.implementations; - import appeng.api.config.Settings; import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiImgButton; import appeng.client.gui.widgets.GuiProgressBar; import appeng.client.gui.widgets.GuiProgressBar.Direction; import appeng.container.implementations.ContainerCondenser; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketConfigButton; import appeng.tile.misc.TileCondenser; @@ -34,62 +33,67 @@ import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Mouse; - -public class GuiCondenser extends AEBaseGui -{ - - private final ContainerCondenser cvc; - private GuiProgressBar pb; - private GuiImgButton mode; - - public GuiCondenser( final InventoryPlayer inventoryPlayer, final TileCondenser te ) - { - super( new ContainerCondenser( inventoryPlayer, te ) ); - this.cvc = (ContainerCondenser) this.inventorySlots; - this.ySize = 197; - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - final boolean backwards = Mouse.isButtonDown( 1 ); - - if( this.mode == btn ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( Settings.CONDENSER_OUTPUT, backwards ) ); - } - } - - @Override - public void initGui() - { - super.initGui(); - - this.pb = new GuiProgressBar( this.cvc, "guis/condenser.png", 120 + this.guiLeft, 25 + this.guiTop, 178, 25, 6, 18, Direction.VERTICAL, GuiText.StoredEnergy.getLocal() ); - - this.mode = new GuiImgButton( 128 + this.guiLeft, 52 + this.guiTop, Settings.CONDENSER_OUTPUT, this.cvc.getOutput() ); - - this.buttonList.add( this.pb ); - this.buttonList.add( this.mode ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.Condenser.getLocal() ), 8, 6, GuiColors.CondenserTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.CondenserInventory.getColor() ); - - this.mode.set( this.cvc.getOutput() ); - this.mode.setFillVar( String.valueOf( this.cvc.getOutput().requiredPower ) ); - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/condenser.png" ); - - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } +public class GuiCondenser extends AEBaseGui { + + private final ContainerCondenser cvc; + private GuiProgressBar pb; + private GuiImgButton mode; + + public GuiCondenser(final InventoryPlayer inventoryPlayer, final TileCondenser te) { + super(new ContainerCondenser(inventoryPlayer, te)); + this.cvc = (ContainerCondenser) this.inventorySlots; + this.ySize = 197; + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + final boolean backwards = Mouse.isButtonDown(1); + + if (this.mode == btn) { + NetworkHandler.instance.sendToServer(new PacketConfigButton(Settings.CONDENSER_OUTPUT, backwards)); + } + } + + @Override + public void initGui() { + super.initGui(); + + this.pb = new GuiProgressBar( + this.cvc, + "guis/condenser.png", + 120 + this.guiLeft, + 25 + this.guiTop, + 178, + 25, + 6, + 18, + Direction.VERTICAL, + GuiText.StoredEnergy.getLocal()); + + this.mode = + new GuiImgButton(128 + this.guiLeft, 52 + this.guiTop, Settings.CONDENSER_OUTPUT, this.cvc.getOutput()); + + this.buttonList.add(this.pb); + this.buttonList.add(this.mode); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.Condenser.getLocal()), 8, 6, GuiColors.CondenserTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.CondenserInventory.getColor()); + + this.mode.set(this.cvc.getOutput()); + this.mode.setFillVar(String.valueOf(this.cvc.getOutput().requiredPower)); + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/condenser.png"); + + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftAmount.java b/src/main/java/appeng/client/gui/implementations/GuiCraftAmount.java index 4d522f3cfe3..a828f541bcb 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftAmount.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftAmount.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; import appeng.api.definitions.IParts; @@ -28,8 +27,8 @@ import appeng.container.AEBaseContainer; import appeng.container.implementations.ContainerCraftAmount; import appeng.core.AEConfig; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.GuiBridge; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketCraftRequest; @@ -47,228 +46,200 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; +public class GuiCraftAmount extends AEBaseGui { + private GuiTextField amountToCraft; + private GuiTabButton originalGuiBtn; + + private GuiButton next; + + private GuiButton plus1; + private GuiButton plus10; + private GuiButton plus100; + private GuiButton plus1000; + private GuiButton minus1; + private GuiButton minus10; + private GuiButton minus100; + private GuiButton minus1000; + + private GuiBridge originalGui; + + @Reflected + public GuiCraftAmount(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(new ContainerCraftAmount(inventoryPlayer, te)); + } + + @Override + @SuppressWarnings("unchecked") + public void initGui() { + super.initGui(); + + final int a = AEConfig.instance.craftItemsByStackAmounts(0); + final int b = AEConfig.instance.craftItemsByStackAmounts(1); + final int c = AEConfig.instance.craftItemsByStackAmounts(2); + final int d = AEConfig.instance.craftItemsByStackAmounts(3); + + this.buttonList.add(this.plus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 26, 22, 20, "+" + a)); + this.buttonList.add(this.plus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 26, 28, 20, "+" + b)); + this.buttonList.add(this.plus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 26, 32, 20, "+" + c)); + this.buttonList.add(this.plus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 26, 38, 20, "+" + d)); + + this.buttonList.add(this.minus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 75, 22, 20, "-" + a)); + this.buttonList.add(this.minus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 75, 28, 20, "-" + b)); + this.buttonList.add(this.minus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 75, 32, 20, "-" + c)); + this.buttonList.add(this.minus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 75, 38, 20, "-" + d)); + + this.buttonList.add( + this.next = new GuiButton(0, this.guiLeft + 128, this.guiTop + 51, 38, 20, GuiText.Next.getLocal())); + + ItemStack myIcon = null; + final Object target = ((AEBaseContainer) this.inventorySlots).getTarget(); + final IDefinitions definitions = AEApi.instance().definitions(); + final IParts parts = definitions.parts(); + + if (target instanceof WirelessTerminalGuiObject) { + for (final ItemStack wirelessTerminalStack : + definitions.items().wirelessTerminal().maybeStack(1).asSet()) { + myIcon = wirelessTerminalStack; + } + + this.originalGui = GuiBridge.GUI_WIRELESS_TERM; + } + + if (target instanceof PartTerminal) { + for (final ItemStack stack : parts.terminal().maybeStack(1).asSet()) { + myIcon = stack; + } + this.originalGui = GuiBridge.GUI_ME; + } -public class GuiCraftAmount extends AEBaseGui -{ - private GuiTextField amountToCraft; - private GuiTabButton originalGuiBtn; - - private GuiButton next; - - private GuiButton plus1; - private GuiButton plus10; - private GuiButton plus100; - private GuiButton plus1000; - private GuiButton minus1; - private GuiButton minus10; - private GuiButton minus100; - private GuiButton minus1000; - - private GuiBridge originalGui; - - @Reflected - public GuiCraftAmount( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( new ContainerCraftAmount( inventoryPlayer, te ) ); - } - - @Override - @SuppressWarnings( "unchecked" ) - public void initGui() - { - super.initGui(); - - final int a = AEConfig.instance.craftItemsByStackAmounts( 0 ); - final int b = AEConfig.instance.craftItemsByStackAmounts( 1 ); - final int c = AEConfig.instance.craftItemsByStackAmounts( 2 ); - final int d = AEConfig.instance.craftItemsByStackAmounts( 3 ); - - this.buttonList.add( this.plus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 26, 22, 20, "+" + a ) ); - this.buttonList.add( this.plus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 26, 28, 20, "+" + b ) ); - this.buttonList.add( this.plus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 26, 32, 20, "+" + c ) ); - this.buttonList.add( this.plus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 26, 38, 20, "+" + d ) ); - - this.buttonList.add( this.minus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 75, 22, 20, "-" + a ) ); - this.buttonList.add( this.minus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 75, 28, 20, "-" + b ) ); - this.buttonList.add( this.minus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 75, 32, 20, "-" + c ) ); - this.buttonList.add( this.minus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 75, 38, 20, "-" + d ) ); - - this.buttonList.add( this.next = new GuiButton( 0, this.guiLeft + 128, this.guiTop + 51, 38, 20, GuiText.Next.getLocal() ) ); - - ItemStack myIcon = null; - final Object target = ( (AEBaseContainer) this.inventorySlots ).getTarget(); - final IDefinitions definitions = AEApi.instance().definitions(); - final IParts parts = definitions.parts(); - - if( target instanceof WirelessTerminalGuiObject ) - { - for( final ItemStack wirelessTerminalStack : definitions.items().wirelessTerminal().maybeStack( 1 ).asSet() ) - { - myIcon = wirelessTerminalStack; - } - - this.originalGui = GuiBridge.GUI_WIRELESS_TERM; - } - - if( target instanceof PartTerminal ) - { - for( final ItemStack stack : parts.terminal().maybeStack( 1 ).asSet() ) - { - myIcon = stack; - } - this.originalGui = GuiBridge.GUI_ME; - } - - if( target instanceof PartCraftingTerminal ) - { - for( final ItemStack stack : parts.craftingTerminal().maybeStack( 1 ).asSet() ) - { - myIcon = stack; - } - this.originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; - } - - if( target instanceof PartPatternTerminal ) - { - for( final ItemStack stack : parts.patternTerminal().maybeStack( 1 ).asSet() ) - { - myIcon = stack; - } - this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL; - } - - if( target instanceof PartPatternTerminalEx) - { - for( final ItemStack stack : parts.patternTerminalEx().maybeStack( 1 ).asSet() ) - { - myIcon = stack; - } - this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL_EX; - } - - if( this.originalGui != null && myIcon != null ) - { - this.buttonList.add( this.originalGuiBtn = new GuiTabButton( this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), itemRender ) ); - } - - this.amountToCraft = new GuiTextField( this.fontRendererObj, this.guiLeft + 62, this.guiTop + 57, 59, this.fontRendererObj.FONT_HEIGHT); - this.amountToCraft.setEnableBackgroundDrawing( false ); - this.amountToCraft.setMaxStringLength( 16 ); - this.amountToCraft.setTextColor( GuiColors.CraftAmountToCraft.getColor() ); - this.amountToCraft.setVisible( true ); - this.amountToCraft.setFocused( true ); - this.amountToCraft.setText( "1" ); - this.amountToCraft.setSelectionPos(0); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( GuiText.SelectAmount.getLocal(), 8, 6, GuiColors.CraftAmountSelectAmount.getColor() ); - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.next.displayString = isShiftKeyDown() ? GuiText.Start.getLocal() : GuiText.Next.getLocal(); - - this.bindTexture( "guis/craftAmt.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - - try - { + if (target instanceof PartCraftingTerminal) { + for (final ItemStack stack : parts.craftingTerminal().maybeStack(1).asSet()) { + myIcon = stack; + } + this.originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; + } + + if (target instanceof PartPatternTerminal) { + for (final ItemStack stack : parts.patternTerminal().maybeStack(1).asSet()) { + myIcon = stack; + } + this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL; + } + + if (target instanceof PartPatternTerminalEx) { + for (final ItemStack stack : parts.patternTerminalEx().maybeStack(1).asSet()) { + myIcon = stack; + } + this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL_EX; + } + + if (this.originalGui != null && myIcon != null) { + this.buttonList.add( + this.originalGuiBtn = new GuiTabButton( + this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), itemRender)); + } + + this.amountToCraft = new GuiTextField( + this.fontRendererObj, this.guiLeft + 62, this.guiTop + 57, 59, this.fontRendererObj.FONT_HEIGHT); + this.amountToCraft.setEnableBackgroundDrawing(false); + this.amountToCraft.setMaxStringLength(16); + this.amountToCraft.setTextColor(GuiColors.CraftAmountToCraft.getColor()); + this.amountToCraft.setVisible(true); + this.amountToCraft.setFocused(true); + this.amountToCraft.setText("1"); + this.amountToCraft.setSelectionPos(0); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + GuiText.SelectAmount.getLocal(), 8, 6, GuiColors.CraftAmountSelectAmount.getColor()); + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.next.displayString = isShiftKeyDown() ? GuiText.Start.getLocal() : GuiText.Next.getLocal(); + + this.bindTexture("guis/craftAmt.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + + try { String out = this.amountToCraft.getText(); - double resultD = Calculator.conversion( out ); + double resultD = Calculator.conversion(out); int resultI; - if( resultD <= 0 || Double.isNaN( resultD ) ) { + if (resultD <= 0 || Double.isNaN(resultD)) { resultI = 0; - } - else { + } else { resultI = (int) ArithHelper.round(resultD, 0); } - this.next.enabled = resultI > 0; - } - catch( final NumberFormatException e ) - { - this.next.enabled = false; - } - - this.amountToCraft.drawTextBox(); - } - - @Override - protected void keyTyped( final char character, final int key ) - { - if( !this.checkHotbarKeys( key ) ) - { - if( key == 28 ) - { - this.actionPerformed( this.next ); - } - this.amountToCraft.textboxKeyTyped( character, key ); - super.keyTyped( character, key ); - } - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - try - { - - if( btn == this.originalGuiBtn ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.originalGui ) ); - } - - if( btn == this.next && btn.enabled ) - { - double resultD = Calculator.conversion( this.amountToCraft.getText() ); + this.next.enabled = resultI > 0; + } catch (final NumberFormatException e) { + this.next.enabled = false; + } + + this.amountToCraft.drawTextBox(); + } + + @Override + protected void keyTyped(final char character, final int key) { + if (!this.checkHotbarKeys(key)) { + if (key == 28) { + this.actionPerformed(this.next); + } + this.amountToCraft.textboxKeyTyped(character, key); + super.keyTyped(character, key); + } + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + try { + + if (btn == this.originalGuiBtn) { + NetworkHandler.instance.sendToServer(new PacketSwitchGuis(this.originalGui)); + } + + if (btn == this.next && btn.enabled) { + double resultD = Calculator.conversion(this.amountToCraft.getText()); int resultI; - if( resultD <= 0 || Double.isNaN( resultD ) ) { + if (resultD <= 0 || Double.isNaN(resultD)) { resultI = 1; - } - else { + } else { resultI = (int) ArithHelper.round(resultD, 0); } - NetworkHandler.instance.sendToServer( new PacketCraftRequest( resultI, isShiftKeyDown() ) ); - } - } - catch( final NumberFormatException e ) - { - // nope.. - this.amountToCraft.setText( "1" ); - } - - final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; - final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; - - if( isPlus || isMinus ) - { - this.addQty( this.getQty( btn ) ); - } - } - - private void addQty( final int i ) - { - try - { - String out = this.amountToCraft.getText(); - - double resultD = Calculator.conversion( out ); + NetworkHandler.instance.sendToServer(new PacketCraftRequest(resultI, isShiftKeyDown())); + } + } catch (final NumberFormatException e) { + // nope.. + this.amountToCraft.setText("1"); + } + + final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; + final boolean isMinus = + btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; + + if (isPlus || isMinus) { + this.addQty(this.getQty(btn)); + } + } + + private void addQty(final int i) { + try { + String out = this.amountToCraft.getText(); + + double resultD = Calculator.conversion(out); int resultI; - if( resultD <= 0 || Double.isNaN( resultD ) ) { + if (resultD <= 0 || Double.isNaN(resultD)) { resultI = 0; - } - else { + } else { resultI = (int) ArithHelper.round(resultD, 0); } @@ -277,22 +248,19 @@ private void addQty( final int i ) } resultI += i; - if( resultI < 1 ) { + if (resultI < 1) { resultI = 1; } - out = Integer.toString( resultI ); + out = Integer.toString(resultI); - this.amountToCraft.setText( out ); - } - catch( final NumberFormatException e ) - { - // :P - } - } + this.amountToCraft.setText(out); + } catch (final NumberFormatException e) { + // :P + } + } - protected String getBackground() - { - return "guis/craftAmt.png"; - } + protected String getBackground() { + return "guis/craftAmt.png"; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java b/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java index b1a2002d86b..3cc720ecc07 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.AEApi; import appeng.api.storage.ITerminalHost; import appeng.api.storage.data.IAEItemStack; @@ -30,8 +29,8 @@ import appeng.container.implementations.ContainerCraftConfirm; import appeng.container.implementations.CraftingCPUStatus; import appeng.core.AELog; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.GuiBridge; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketSwitchGuis; @@ -44,566 +43,516 @@ import appeng.util.Platform; import appeng.util.ReadableNumberConverter; import com.google.common.base.Joiner; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; -import org.lwjgl.input.Mouse; -import org.lwjgl.opengl.GL11; - -import java.io.IOException; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; +public class GuiCraftConfirm extends AEBaseGui implements ICraftingCPUTableHolder { -public class GuiCraftConfirm extends AEBaseGui implements ICraftingCPUTableHolder -{ - - private final ContainerCraftConfirm ccc; + private final ContainerCraftConfirm ccc; private final GuiCraftingCPUTable cpuTable; - private final int rows = 5; + private final int rows = 5; - private final IItemList storage = AEApi.instance().storage().createItemList(); - private final IItemList pending = AEApi.instance().storage().createItemList(); - private final IItemList missing = AEApi.instance().storage().createItemList(); + private final IItemList storage = AEApi.instance().storage().createItemList(); + private final IItemList pending = AEApi.instance().storage().createItemList(); + private final IItemList missing = AEApi.instance().storage().createItemList(); - private final List visual = new ArrayList(); + private final List visual = new ArrayList(); - private GuiBridge OriginalGui; - private GuiButton cancel; - private GuiButton start; - private GuiButton selectCPU; - private int tooltip = -1; - private ItemStack hoveredStack; + private GuiBridge OriginalGui; + private GuiButton cancel; + private GuiButton start; + private GuiButton selectCPU; + private int tooltip = -1; + private ItemStack hoveredStack; - public GuiCraftConfirm( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( new ContainerCraftConfirm( inventoryPlayer, te ) ); - this.xSize = 238; - this.ySize = 206; + public GuiCraftConfirm(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(new ContainerCraftConfirm(inventoryPlayer, te)); + this.xSize = 238; + this.ySize = 206; - final GuiScrollbar scrollbar = new GuiScrollbar(); - this.setScrollBar( scrollbar ); + final GuiScrollbar scrollbar = new GuiScrollbar(); + this.setScrollBar(scrollbar); - this.cpuTable = new GuiCraftingCPUTable( this, ((ContainerCraftConfirm) inventorySlots).cpuTable ); + this.cpuTable = new GuiCraftingCPUTable(this, ((ContainerCraftConfirm) inventorySlots).cpuTable); - this.ccc = (ContainerCraftConfirm) this.inventorySlots; + this.ccc = (ContainerCraftConfirm) this.inventorySlots; - if( te instanceof WirelessTerminalGuiObject ) - { - this.OriginalGui = GuiBridge.GUI_WIRELESS_TERM; - } + if (te instanceof WirelessTerminalGuiObject) { + this.OriginalGui = GuiBridge.GUI_WIRELESS_TERM; + } - if( te instanceof PartTerminal ) - { - this.OriginalGui = GuiBridge.GUI_ME; - } + if (te instanceof PartTerminal) { + this.OriginalGui = GuiBridge.GUI_ME; + } - if( te instanceof PartCraftingTerminal ) - { - this.OriginalGui = GuiBridge.GUI_CRAFTING_TERMINAL; - } + if (te instanceof PartCraftingTerminal) { + this.OriginalGui = GuiBridge.GUI_CRAFTING_TERMINAL; + } - if( te instanceof PartPatternTerminal ) - { - this.OriginalGui = GuiBridge.GUI_PATTERN_TERMINAL; - } + if (te instanceof PartPatternTerminal) { + this.OriginalGui = GuiBridge.GUI_PATTERN_TERMINAL; + } - if( te instanceof PartPatternTerminalEx) - { - this.OriginalGui = GuiBridge.GUI_PATTERN_TERMINAL_EX; - } - } + if (te instanceof PartPatternTerminalEx) { + this.OriginalGui = GuiBridge.GUI_PATTERN_TERMINAL_EX; + } + } @Override - public GuiCraftingCPUTable getCPUTable() - { + public GuiCraftingCPUTable getCPUTable() { return cpuTable; } - boolean isAutoStart() - { - return ( (ContainerCraftConfirm) this.inventorySlots ).isAutoStart(); - } - - @Override - public void initGui() - { - super.initGui(); - - this.start = new GuiButton( 0, this.guiLeft + 162, this.guiTop + this.ySize - 25, 50, 20, GuiText.Start.getLocal() ); - this.start.enabled = false; - this.buttonList.add( this.start ); - - this.selectCPU = new GuiButton( 0, this.guiLeft + ( 219 - 180 ) / 2, this.guiTop + this.ySize - 68, 180, 20, GuiText.CraftingCPU.getLocal() + ": " + GuiText.Automatic ); - this.selectCPU.enabled = false; - this.buttonList.add( this.selectCPU ); + boolean isAutoStart() { + return ((ContainerCraftConfirm) this.inventorySlots).isAutoStart(); + } - this.cancel = new GuiButton( 0, this.guiLeft + 6, this.guiTop + this.ySize - 25, 50, 20, GuiText.Cancel.getLocal() ); - this.buttonList.add( this.cancel ); - } + @Override + public void initGui() { + super.initGui(); + + this.start = + new GuiButton(0, this.guiLeft + 162, this.guiTop + this.ySize - 25, 50, 20, GuiText.Start.getLocal()); + this.start.enabled = false; + this.buttonList.add(this.start); + + this.selectCPU = new GuiButton( + 0, + this.guiLeft + (219 - 180) / 2, + this.guiTop + this.ySize - 68, + 180, + 20, + GuiText.CraftingCPU.getLocal() + ": " + GuiText.Automatic); + this.selectCPU.enabled = false; + this.buttonList.add(this.selectCPU); + + this.cancel = + new GuiButton(0, this.guiLeft + 6, this.guiTop + this.ySize - 25, 50, 20, GuiText.Cancel.getLocal()); + this.buttonList.add(this.cancel); + } - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { - this.updateCPUButtonText(); + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { + this.updateCPUButtonText(); - cpuTable.drawScreen( ); + cpuTable.drawScreen(); - this.start.enabled = !( this.ccc.hasNoCPU() || this.isSimulation() ); + this.start.enabled = !(this.ccc.hasNoCPU() || this.isSimulation()); if (this.start.enabled) { CraftingCPUStatus selected = this.cpuTable.getContainer().getSelectedCPU(); if (selected == null || selected.getStorage() < this.ccc.getUsedBytes() || selected.isBusy()) { this.start.enabled = false; } } - this.selectCPU.enabled = !this.isSimulation(); - - final int gx = ( this.width - this.xSize ) / 2; - final int gy = ( this.height - this.ySize ) / 2; - - this.tooltip = -1; - - final int offY = 23; - int y = 0; - int x = 0; - for( int z = 0; z <= 4 * 5; z++ ) - { - final int minX = gx + 9 + x * 67; - final int minY = gy + 22 + y * offY; - - if( minX < mouseX && minX + 67 > mouseX ) - { - if( minY < mouseY && minY + offY - 2 > mouseY ) - { - this.tooltip = z; - break; - } - } - - x++; - - if( x > 2 ) - { - y++; - x = 0; - } - } - - super.drawScreen( mouseX, mouseY, btn ); - } - - private void updateCPUButtonText() - { - String btnTextText = GuiText.CraftingCPU.getLocal() + ": " + GuiText.Automatic.getLocal(); - if( this.ccc.getSelectedCpu() >= 0 )// && status.selectedCpu < status.cpus.size() ) - { - if( this.ccc.getName().length() > 0 ) - { - final String name = this.ccc.getName().substring( 0, Math.min( 20, this.ccc.getName().length() ) ); - btnTextText = GuiText.CraftingCPU.getLocal() + ": " + name; - } - else - { - btnTextText = GuiText.CraftingCPU.getLocal() + ": #" + this.ccc.getSelectedCpu(); - } - } - - if( this.ccc.hasNoCPU() ) - { - btnTextText = GuiText.NoCraftingCPUs.getLocal(); - } - - this.selectCPU.displayString = btnTextText; - } - - private boolean isSimulation() - { - return ( (ContainerCraftConfirm) this.inventorySlots ).isSimulation(); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - cpuTable.drawFG( offsetX, offsetY, mouseX, mouseY, guiLeft, guiTop ); - - final long BytesUsed = this.ccc.getUsedBytes(); - final String byteUsed = NumberFormat.getInstance().format( BytesUsed ); - final String Add = BytesUsed > 0 ? ( byteUsed + ' ' + GuiText.BytesUsed.getLocal() ) : GuiText.CalculatingWait.getLocal(); - this.fontRendererObj.drawString( GuiText.CraftingPlan.getLocal() + " - " + Add, 8, 7, GuiColors.CraftConfirmCraftingPlan.getColor() ); - - String dsp = null; - - if( this.isSimulation() ) - { - dsp = GuiText.Simulation.getLocal(); - } - else - { - dsp = this.ccc.getCpuAvailableBytes() > 0 ? ( GuiText.Bytes.getLocal() + ": " + this.ccc.getCpuAvailableBytes() + " : " + GuiText.CoProcessors.getLocal() + ": " + this.ccc.getCpuCoProcessors() ) : GuiText.Bytes.getLocal() + ": N/A : " + GuiText.CoProcessors.getLocal() + ": N/A"; - } - - final int offset = ( 219 - this.fontRendererObj.getStringWidth( dsp ) ) / 2; - this.fontRendererObj.drawString( dsp, offset, 165, GuiColors.CraftConfirmSimulation.getColor() ); - - final int sectionLength = 67; - - int x = 0; - int y = 0; - final int xo = 9; - final int yo = 22; - final int viewStart = this.getScrollBar().getCurrentScroll() * 3; - final int viewEnd = viewStart + 3 * this.rows; - - String dspToolTip = ""; - final List lineList = new LinkedList(); - int toolPosX = 0; - int toolPosY = 0; - hoveredStack = null; + this.selectCPU.enabled = !this.isSimulation(); + + final int gx = (this.width - this.xSize) / 2; + final int gy = (this.height - this.ySize) / 2; + + this.tooltip = -1; + + final int offY = 23; + int y = 0; + int x = 0; + for (int z = 0; z <= 4 * 5; z++) { + final int minX = gx + 9 + x * 67; + final int minY = gy + 22 + y * offY; + + if (minX < mouseX && minX + 67 > mouseX) { + if (minY < mouseY && minY + offY - 2 > mouseY) { + this.tooltip = z; + break; + } + } + + x++; + + if (x > 2) { + y++; + x = 0; + } + } + + super.drawScreen(mouseX, mouseY, btn); + } + + private void updateCPUButtonText() { + String btnTextText = GuiText.CraftingCPU.getLocal() + ": " + GuiText.Automatic.getLocal(); + if (this.ccc.getSelectedCpu() >= 0) // && status.selectedCpu < status.cpus.size() ) + { + if (this.ccc.getName().length() > 0) { + final String name = this.ccc + .getName() + .substring(0, Math.min(20, this.ccc.getName().length())); + btnTextText = GuiText.CraftingCPU.getLocal() + ": " + name; + } else { + btnTextText = GuiText.CraftingCPU.getLocal() + ": #" + this.ccc.getSelectedCpu(); + } + } + + if (this.ccc.hasNoCPU()) { + btnTextText = GuiText.NoCraftingCPUs.getLocal(); + } + + this.selectCPU.displayString = btnTextText; + } + + private boolean isSimulation() { + return ((ContainerCraftConfirm) this.inventorySlots).isSimulation(); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + cpuTable.drawFG(offsetX, offsetY, mouseX, mouseY, guiLeft, guiTop); + + final long BytesUsed = this.ccc.getUsedBytes(); + final String byteUsed = NumberFormat.getInstance().format(BytesUsed); + final String Add = + BytesUsed > 0 ? (byteUsed + ' ' + GuiText.BytesUsed.getLocal()) : GuiText.CalculatingWait.getLocal(); + this.fontRendererObj.drawString( + GuiText.CraftingPlan.getLocal() + " - " + Add, 8, 7, GuiColors.CraftConfirmCraftingPlan.getColor()); + + String dsp = null; + + if (this.isSimulation()) { + dsp = GuiText.Simulation.getLocal(); + } else { + dsp = this.ccc.getCpuAvailableBytes() > 0 + ? (GuiText.Bytes.getLocal() + ": " + this.ccc.getCpuAvailableBytes() + " : " + + GuiText.CoProcessors.getLocal() + ": " + this.ccc.getCpuCoProcessors()) + : GuiText.Bytes.getLocal() + ": N/A : " + GuiText.CoProcessors.getLocal() + ": N/A"; + } + + final int offset = (219 - this.fontRendererObj.getStringWidth(dsp)) / 2; + this.fontRendererObj.drawString(dsp, offset, 165, GuiColors.CraftConfirmSimulation.getColor()); + + final int sectionLength = 67; + + int x = 0; + int y = 0; + final int xo = 9; + final int yo = 22; + final int viewStart = this.getScrollBar().getCurrentScroll() * 3; + final int viewEnd = viewStart + 3 * this.rows; + + String dspToolTip = ""; + final List lineList = new LinkedList(); + int toolPosX = 0; + int toolPosY = 0; + hoveredStack = null; final ReadableNumberConverter converter = ReadableNumberConverter.INSTANCE; - final int offY = 23; - - for( int z = viewStart; z < Math.min( viewEnd, this.visual.size() ); z++ ) - { - final IAEItemStack refStack = this.visual.get( z );// repo.getReferenceItem( z ); - if( refStack != null ) - { - GL11.glPushMatrix(); - GL11.glScaled( 0.5, 0.5, 0.5 ); - - final IAEItemStack stored = this.storage.findPrecise( refStack ); - final IAEItemStack pendingStack = this.pending.findPrecise( refStack ); - final IAEItemStack missingStack = this.missing.findPrecise( refStack ); - - int lines = 0; - - if( stored != null && stored.getStackSize() > 0 ) - { - lines++; - } - if( pendingStack != null && pendingStack.getStackSize() > 0 ) - { - lines++; - } - if( pendingStack != null && pendingStack.getStackSize() > 0 ) - { - lines++; - } - - final int negY = ( ( lines - 1 ) * 5 ) / 2; - int downY = 0; - - if( stored != null && stored.getStackSize() > 0 ) - { - String str = GuiText.FromStorage.getLocal() + ": " + converter.toWideReadableForm(stored.getStackSize()); - final int w = 4 + this.fontRendererObj.getStringWidth( str ); - this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + sectionLength ) + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + yo + 6 - negY + downY ) * 2, GuiColors.CraftConfirmFromStorage.getColor() ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.FromStorage.getLocal() + ": " + NumberFormat.getInstance().format( stored.getStackSize() ) ); - } - - downY += 5; - } - - boolean red = false; - if( missingStack != null && missingStack.getStackSize() > 0 ) - { - String str = GuiText.Missing.getLocal() + ": " + converter.toWideReadableForm( missingStack.getStackSize() ); - final int w = 4 + this.fontRendererObj.getStringWidth( str ); - this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + sectionLength ) + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + yo + 6 - negY + downY ) * 2, GuiColors.CraftConfirmMissing.getColor()); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.Missing.getLocal() + ": " + NumberFormat.getInstance().format( missingStack.getStackSize() ) ); - } - - red = true; - downY += 5; - } - - if( pendingStack != null && pendingStack.getStackSize() > 0 ) - { - String str = GuiText.ToCraft.getLocal() + ": " + converter.toWideReadableForm( pendingStack.getStackSize() ); - final int w = 4 + this.fontRendererObj.getStringWidth( str ); - this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + sectionLength ) + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + yo + 6 - negY + downY ) * 2, GuiColors.CraftConfirmToCraft.getColor() ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.ToCraft.getLocal() + ": " + NumberFormat.getInstance().format( pendingStack.getStackSize() ) ); - } - } - - GL11.glPopMatrix(); - final int posX = x * ( 1 + sectionLength ) + xo + sectionLength - 19; - final int posY = y * offY + yo; - - final ItemStack is = refStack.copy().getItemStack(); - - if( this.tooltip == z - viewStart ) - { - dspToolTip = Platform.getItemDisplayName( is ); - if( lineList.size() > 0 ) - { - addItemTooltip(is, lineList); - dspToolTip = dspToolTip + '\n' + Joiner.on( "\n" ).join( lineList ); - } - - toolPosX = x * ( 1 + sectionLength ) + xo + sectionLength - 8; - toolPosY = y * offY + yo; - - hoveredStack = is; - } - - this.drawItem( posX, posY, is ); - - if( red ) - { - final int startX = x * ( 1 + sectionLength ) + xo; - final int startY = posY - 4; - drawRect( startX, startY, startX + sectionLength, startY + offY, GuiColors.CraftConfirmMissingItem.getColor() ); - } - - x++; - - if( x > 2 ) - { - y++; - x = 0; - } - } - } - - if( this.tooltip >= 0 && dspToolTip.length() > 0 ) - { - this.drawTooltip( toolPosX, toolPosY + 10, 0, dspToolTip ); - } - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - cpuTable.drawBG( offsetX, offsetY ); - this.setScrollBar(); - this.bindTexture( "guis/craftingreport.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - private void setScrollBar() - { - final int size = this.visual.size(); - - this.getScrollBar().setTop( 19 ).setLeft( 218 ).setHeight( 114 ); - this.getScrollBar().setRange( 0, ( size + 2 ) / 3 - this.rows, 1 ); - } - - public void postUpdate( final List list, final byte ref ) - { - switch( ref ) - { - case 0: - for( final IAEItemStack l : list ) - { - this.handleInput( this.storage, l ); - } - break; - - case 1: - for( final IAEItemStack l : list ) - { - this.handleInput( this.pending, l ); - } - break; - - case 2: - for( final IAEItemStack l : list ) - { - this.handleInput( this.missing, l ); - } - break; - } - - for( final IAEItemStack l : list ) - { - final long amt = this.getTotal( l ); - - if( amt <= 0 ) - { - this.deleteVisualStack( l ); - } - else - { - final IAEItemStack is = this.findVisualStack( l ); - is.setStackSize( amt ); - } - } - - this.setScrollBar(); - } - - private void handleInput( final IItemList s, final IAEItemStack l ) - { - IAEItemStack a = s.findPrecise( l ); - - if( l.getStackSize() <= 0 ) - { - if( a != null ) - { - a.reset(); - } - } - else - { - if( a == null ) - { - s.add( l.copy() ); - a = s.findPrecise( l ); - } - - if( a != null ) - { - a.setStackSize( l.getStackSize() ); - } - } - } - - private long getTotal( final IAEItemStack is ) - { - final IAEItemStack a = this.storage.findPrecise( is ); - final IAEItemStack c = this.pending.findPrecise( is ); - final IAEItemStack m = this.missing.findPrecise( is ); - - long total = 0; - - if( a != null ) - { - total += a.getStackSize(); - } - - if( c != null ) - { - total += c.getStackSize(); - } - - if( m != null ) - { - total += m.getStackSize(); - } - - return total; - } - - private void deleteVisualStack( final IAEItemStack l ) - { - final Iterator i = this.visual.iterator(); - while( i.hasNext() ) - { - final IAEItemStack o = i.next(); - if( o.equals( l ) ) - { - i.remove(); - return; - } - } - } - - private IAEItemStack findVisualStack( final IAEItemStack l ) - { - for( final IAEItemStack o : this.visual ) - { - if( o.equals( l ) ) - { - return o; - } - } - - final IAEItemStack stack = l.copy(); - this.visual.add( stack ); - return stack; - } - - @Override - protected void keyTyped( final char character, final int key ) - { - if( !this.checkHotbarKeys( key ) ) - { - if( key == 28 ) - { - this.actionPerformed( this.start ); - } - super.keyTyped( character, key ); - } - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - final boolean backwards = Mouse.isButtonDown( 1 ); - - if( btn == this.selectCPU ) - { - cpuTable.cycleCPU(backwards); - } - - if( btn == this.cancel ) - { - switchToOriginalGUI(); - } - - if( btn == this.start ) - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "Terminal.Start", "Start" ) ); - } - catch( final Throwable e ) - { - AELog.debug( e ); - } - } - } - - public void switchToOriginalGUI() - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.OriginalGui ) ); + final int offY = 23; + + for (int z = viewStart; z < Math.min(viewEnd, this.visual.size()); z++) { + final IAEItemStack refStack = this.visual.get(z); // repo.getReferenceItem( z ); + if (refStack != null) { + GL11.glPushMatrix(); + GL11.glScaled(0.5, 0.5, 0.5); + + final IAEItemStack stored = this.storage.findPrecise(refStack); + final IAEItemStack pendingStack = this.pending.findPrecise(refStack); + final IAEItemStack missingStack = this.missing.findPrecise(refStack); + + int lines = 0; + + if (stored != null && stored.getStackSize() > 0) { + lines++; + } + if (pendingStack != null && pendingStack.getStackSize() > 0) { + lines++; + } + if (pendingStack != null && pendingStack.getStackSize() > 0) { + lines++; + } + + final int negY = ((lines - 1) * 5) / 2; + int downY = 0; + + if (stored != null && stored.getStackSize() > 0) { + String str = + GuiText.FromStorage.getLocal() + ": " + converter.toWideReadableForm(stored.getStackSize()); + final int w = 4 + this.fontRendererObj.getStringWidth(str); + this.fontRendererObj.drawString( + str, + (int) ((x * (1 + sectionLength) + xo + sectionLength - 19 - (w * 0.5)) * 2), + (y * offY + yo + 6 - negY + downY) * 2, + GuiColors.CraftConfirmFromStorage.getColor()); + + if (this.tooltip == z - viewStart) { + lineList.add(GuiText.FromStorage.getLocal() + ": " + + NumberFormat.getInstance().format(stored.getStackSize())); + } + + downY += 5; + } + + boolean red = false; + if (missingStack != null && missingStack.getStackSize() > 0) { + String str = GuiText.Missing.getLocal() + ": " + + converter.toWideReadableForm(missingStack.getStackSize()); + final int w = 4 + this.fontRendererObj.getStringWidth(str); + this.fontRendererObj.drawString( + str, + (int) ((x * (1 + sectionLength) + xo + sectionLength - 19 - (w * 0.5)) * 2), + (y * offY + yo + 6 - negY + downY) * 2, + GuiColors.CraftConfirmMissing.getColor()); + + if (this.tooltip == z - viewStart) { + lineList.add(GuiText.Missing.getLocal() + ": " + + NumberFormat.getInstance().format(missingStack.getStackSize())); + } + + red = true; + downY += 5; + } + + if (pendingStack != null && pendingStack.getStackSize() > 0) { + String str = GuiText.ToCraft.getLocal() + ": " + + converter.toWideReadableForm(pendingStack.getStackSize()); + final int w = 4 + this.fontRendererObj.getStringWidth(str); + this.fontRendererObj.drawString( + str, + (int) ((x * (1 + sectionLength) + xo + sectionLength - 19 - (w * 0.5)) * 2), + (y * offY + yo + 6 - negY + downY) * 2, + GuiColors.CraftConfirmToCraft.getColor()); + + if (this.tooltip == z - viewStart) { + lineList.add(GuiText.ToCraft.getLocal() + ": " + + NumberFormat.getInstance().format(pendingStack.getStackSize())); + } + } + + GL11.glPopMatrix(); + final int posX = x * (1 + sectionLength) + xo + sectionLength - 19; + final int posY = y * offY + yo; + + final ItemStack is = refStack.copy().getItemStack(); + + if (this.tooltip == z - viewStart) { + dspToolTip = Platform.getItemDisplayName(is); + if (lineList.size() > 0) { + addItemTooltip(is, lineList); + dspToolTip = dspToolTip + '\n' + Joiner.on("\n").join(lineList); + } + + toolPosX = x * (1 + sectionLength) + xo + sectionLength - 8; + toolPosY = y * offY + yo; + + hoveredStack = is; + } + + this.drawItem(posX, posY, is); + + if (red) { + final int startX = x * (1 + sectionLength) + xo; + final int startY = posY - 4; + drawRect( + startX, + startY, + startX + sectionLength, + startY + offY, + GuiColors.CraftConfirmMissingItem.getColor()); + } + + x++; + + if (x > 2) { + y++; + x = 0; + } + } + } + + if (this.tooltip >= 0 && dspToolTip.length() > 0) { + this.drawTooltip(toolPosX, toolPosY + 10, 0, dspToolTip); + } } - public ItemStack getHoveredStack() { - return hoveredStack; - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + cpuTable.drawBG(offsetX, offsetY); + this.setScrollBar(); + this.bindTexture("guis/craftingreport.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } + + private void setScrollBar() { + final int size = this.visual.size(); + + this.getScrollBar().setTop(19).setLeft(218).setHeight(114); + this.getScrollBar().setRange(0, (size + 2) / 3 - this.rows, 1); + } + + public void postUpdate(final List list, final byte ref) { + switch (ref) { + case 0: + for (final IAEItemStack l : list) { + this.handleInput(this.storage, l); + } + break; + + case 1: + for (final IAEItemStack l : list) { + this.handleInput(this.pending, l); + } + break; + + case 2: + for (final IAEItemStack l : list) { + this.handleInput(this.missing, l); + } + break; + } + + for (final IAEItemStack l : list) { + final long amt = this.getTotal(l); + + if (amt <= 0) { + this.deleteVisualStack(l); + } else { + final IAEItemStack is = this.findVisualStack(l); + is.setStackSize(amt); + } + } + + this.setScrollBar(); + } + + private void handleInput(final IItemList s, final IAEItemStack l) { + IAEItemStack a = s.findPrecise(l); + + if (l.getStackSize() <= 0) { + if (a != null) { + a.reset(); + } + } else { + if (a == null) { + s.add(l.copy()); + a = s.findPrecise(l); + } + + if (a != null) { + a.setStackSize(l.getStackSize()); + } + } + } + + private long getTotal(final IAEItemStack is) { + final IAEItemStack a = this.storage.findPrecise(is); + final IAEItemStack c = this.pending.findPrecise(is); + final IAEItemStack m = this.missing.findPrecise(is); + + long total = 0; + + if (a != null) { + total += a.getStackSize(); + } + + if (c != null) { + total += c.getStackSize(); + } + + if (m != null) { + total += m.getStackSize(); + } + + return total; + } + + private void deleteVisualStack(final IAEItemStack l) { + final Iterator i = this.visual.iterator(); + while (i.hasNext()) { + final IAEItemStack o = i.next(); + if (o.equals(l)) { + i.remove(); + return; + } + } + } + + private IAEItemStack findVisualStack(final IAEItemStack l) { + for (final IAEItemStack o : this.visual) { + if (o.equals(l)) { + return o; + } + } + + final IAEItemStack stack = l.copy(); + this.visual.add(stack); + return stack; + } + + @Override + protected void keyTyped(final char character, final int key) { + if (!this.checkHotbarKeys(key)) { + if (key == 28) { + this.actionPerformed(this.start); + } + super.keyTyped(character, key); + } + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + final boolean backwards = Mouse.isButtonDown(1); + + if (btn == this.selectCPU) { + cpuTable.cycleCPU(backwards); + } + + if (btn == this.cancel) { + switchToOriginalGUI(); + } + + if (btn == this.start) { + try { + NetworkHandler.instance.sendToServer(new PacketValueConfig("Terminal.Start", "Start")); + } catch (final Throwable e) { + AELog.debug(e); + } + } + } + + public void switchToOriginalGUI() { + NetworkHandler.instance.sendToServer(new PacketSwitchGuis(this.OriginalGui)); + } + + public ItemStack getHoveredStack() { + return hoveredStack; + } @Override - protected void mouseClicked( int xCoord, int yCoord, int btn ) - { - super.mouseClicked( xCoord, yCoord, btn ); - cpuTable.mouseClicked( xCoord - guiLeft, yCoord - guiTop, btn ); + protected void mouseClicked(int xCoord, int yCoord, int btn) { + super.mouseClicked(xCoord, yCoord, btn); + cpuTable.mouseClicked(xCoord - guiLeft, yCoord - guiTop, btn); } @Override - protected void mouseClickMove( int x, int y, int c, long d ) - { - super.mouseClickMove( x, y, c, d ); - cpuTable.mouseClickMove( x - guiLeft, y - guiTop ); + protected void mouseClickMove(int x, int y, int c, long d) { + super.mouseClickMove(x, y, c, d); + cpuTable.mouseClickMove(x - guiLeft, y - guiTop); } @Override - public void handleMouseInput() - { - if ( cpuTable.handleMouseInput(guiLeft, guiTop) ) - { + public void handleMouseInput() { + if (cpuTable.handleMouseInput(guiLeft, guiTop)) { return; } super.handleMouseInput(); } - public boolean hideItemPanelSlot( int x, int y, int w, int h ) - { - return cpuTable.hideItemPanelSlot(x - guiLeft, y - guiTop, w, h ); + public boolean hideItemPanelSlot(int x, int y, int w, int h) { + return cpuTable.hideItemPanelSlot(x - guiLeft, y - guiTop, w, h); } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java b/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java index 986d097df21..c1f121e4acd 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java @@ -18,480 +18,440 @@ package appeng.client.gui.implementations; - import appeng.api.AEApi; import appeng.api.config.SortDir; import appeng.api.config.SortOrder; import appeng.api.config.ViewItems; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; -import appeng.api.util.AEColor; import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiScrollbar; import appeng.client.gui.widgets.ISortSource; import appeng.container.implementations.ContainerCraftingCPU; import appeng.core.AEConfig; import appeng.core.AELog; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; import appeng.util.Platform; import appeng.util.ReadableNumberConverter; import com.google.common.base.Joiner; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; -import org.apache.commons.lang3.time.DurationFormatUtils; -import org.lwjgl.opengl.GL11; - import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import org.apache.commons.lang3.time.DurationFormatUtils; +import org.lwjgl.opengl.GL11; - -public class GuiCraftingCPU extends AEBaseGui implements ISortSource -{ - private static final int GUI_HEIGHT = 184; - private static final int GUI_WIDTH = 238; - - private static final int DISPLAYED_ROWS = 6; - - private static final int SECTION_LENGTH = 67; - - private static final int SCROLLBAR_TOP = 19; - private static final int SCROLLBAR_LEFT = 218; - private static final int SCROLLBAR_HEIGHT = 137; - - private static final int CANCEL_LEFT_OFFSET = 163; - private static final int CANCEL_TOP_OFFSET = 25; - private static final int CANCEL_HEIGHT = 20; - private static final int CANCEL_WIDTH = 50; - - private static final int TITLE_TOP_OFFSET = 7; - private static final int TITLE_LEFT_OFFSET = 8; - - private static final int ITEMSTACK_LEFT_OFFSET = 9; - private static final int ITEMSTACK_TOP_OFFSET = 22; - - private final ContainerCraftingCPU craftingCpu; - - private IItemList storage = AEApi.instance().storage().createItemList(); - private IItemList active = AEApi.instance().storage().createItemList(); - private IItemList pending = AEApi.instance().storage().createItemList(); - - private List visual = new ArrayList(); - private GuiButton cancel; - private int tooltip = -1; - private ItemStack hoveredStack; - - public GuiCraftingCPU( final InventoryPlayer inventoryPlayer, final Object te ) - { - this( new ContainerCraftingCPU( inventoryPlayer, te ) ); - } - - protected GuiCraftingCPU( final ContainerCraftingCPU container ) - { - super( container ); - this.craftingCpu = container; - this.ySize = GUI_HEIGHT; - this.xSize = GUI_WIDTH; - - final GuiScrollbar scrollbar = new GuiScrollbar(); - this.setScrollBar( scrollbar ); - } - - public void clearItems() - { - this.storage = AEApi.instance().storage().createItemList(); - this.active = AEApi.instance().storage().createItemList(); - this.pending = AEApi.instance().storage().createItemList(); - this.visual = new ArrayList(); - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - if( this.cancel == btn ) - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "TileCrafting.Cancel", "Cancel" ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - - @Override - public void initGui() - { - super.initGui(); - this.setScrollBar(); - this.cancel = new GuiButton( 0, this.guiLeft + CANCEL_LEFT_OFFSET, this.guiTop + this.ySize - CANCEL_TOP_OFFSET, CANCEL_WIDTH, CANCEL_HEIGHT, GuiText.Cancel.getLocal() ); - this.buttonList.add( this.cancel ); - } - - private void setScrollBar() - { - final int size = this.visual.size(); - - this.getScrollBar().setTop( SCROLLBAR_TOP ).setLeft( SCROLLBAR_LEFT ).setHeight( SCROLLBAR_HEIGHT ); - this.getScrollBar().setRange( 0, ( size + 2 ) / 3 - DISPLAYED_ROWS, 1 ); - } - - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { - this.cancel.enabled = !this.visual.isEmpty(); - - final int gx = ( this.width - this.xSize ) / 2; - final int gy = ( this.height - this.ySize ) / 2; - - this.tooltip = -1; - - final int offY = 23; - int y = 0; - int x = 0; - for( int z = 0; z <= 4 * 5; z++ ) - { - final int minX = gx + 9 + x * 67; - final int minY = gy + 22 + y * offY; - - if( minX < mouseX && minX + 67 > mouseX ) - { - if( minY < mouseY && minY + offY - 2 > mouseY ) - { - this.tooltip = z; - break; - } - } - - x++; - - if( x > 2 ) - { - y++; - x = 0; - } - } - - super.drawScreen( mouseX, mouseY, btn ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - String title = this.getGuiDisplayName( GuiText.CraftingStatus.getLocal() ); - - if( this.craftingCpu.getEstimatedTime() > 0 && !this.visual.isEmpty() ) - { - final long etaInMilliseconds = TimeUnit.MILLISECONDS.convert( this.craftingCpu.getEstimatedTime(), TimeUnit.NANOSECONDS ); - final String etaTimeText = DurationFormatUtils.formatDuration( etaInMilliseconds, GuiText.ETAFormat.getLocal() ); - title += " - " + etaTimeText; - } - - this.fontRendererObj.drawString( title, TITLE_LEFT_OFFSET, TITLE_TOP_OFFSET, GuiColors.CraftingCPUTitle.getColor() ); - - int x = 0; - int y = 0; - final int viewStart = this.getScrollBar().getCurrentScroll() * 3; - final int viewEnd = viewStart + 3 * 6; - - String dspToolTip = ""; - final List lineList = new LinkedList(); - int toolPosX = 0; - int toolPosY = 0; - - hoveredStack = null; - - final int offY = 23; - - final ReadableNumberConverter converter = ReadableNumberConverter.INSTANCE; - for( int z = viewStart; z < Math.min( viewEnd, this.visual.size() ); z++ ) - { - final IAEItemStack refStack = this.visual.get( z );// repo.getReferenceItem( z ); - if( refStack != null ) - { - GL11.glPushMatrix(); - GL11.glScaled( 0.5, 0.5, 0.5 ); - - final IAEItemStack stored = this.storage.findPrecise( refStack ); - final IAEItemStack activeStack = this.active.findPrecise( refStack ); - final IAEItemStack pendingStack = this.pending.findPrecise( refStack ); - - int lines = 0; - - if( stored != null && stored.getStackSize() > 0 ) - { - lines++; - } - boolean active = false; - if( activeStack != null && activeStack.getStackSize() > 0 ) - { - lines++; - active = true; - } - boolean scheduled = false; - if( pendingStack != null && pendingStack.getStackSize() > 0 ) - { - lines++; - scheduled = true; - } - - if( AEConfig.instance.useColoredCraftingStatus && ( active || scheduled ) ) - { - final int bgColor = active ? GuiColors.CraftingCPUActive.getColor() : GuiColors.CraftingCPUInactive.getColor(); - final int startX = ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET ) * 2; - final int startY = ( ( y * offY + ITEMSTACK_TOP_OFFSET ) - 3 ) * 2; - drawRect( startX, startY, startX + ( SECTION_LENGTH * 2 ), startY + ( offY * 2 ) - 2, bgColor ); - } - - final int negY = ( ( lines - 1 ) * 5 ) / 2; - int downY = 0; - - if( stored != null && stored.getStackSize() > 0 ) - { - final String str = GuiText.Stored.getLocal() + ": " + converter.toWideReadableForm( stored.getStackSize() ); - final int w = 4 + this.fontRendererObj.getStringWidth( str ); - this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY ) * 2, GuiColors.CraftingCPUStored.getColor() ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.Stored.getLocal() + ": " + Long.toString( stored.getStackSize() ) ); - } - - downY += 5; - } - - if( activeStack != null && activeStack.getStackSize() > 0 ) - { - final String str = GuiText.Crafting.getLocal() + ": " + converter.toWideReadableForm( activeStack.getStackSize() ); - final int w = 4 + this.fontRendererObj.getStringWidth( str ); - - this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY ) * 2, GuiColors.CraftingCPUAmount.getColor() ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.Crafting.getLocal() + ": " + Long.toString( activeStack.getStackSize() ) ); - } - - downY += 5; - } - - if( pendingStack != null && pendingStack.getStackSize() > 0 ) - { - final String str = GuiText.Scheduled.getLocal() + ": " + converter.toWideReadableForm( pendingStack.getStackSize() ); - final int w = 4 + this.fontRendererObj.getStringWidth( str ); - - this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY ) * 2, GuiColors.CraftingCPUScheduled.getColor() ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.Scheduled.getLocal() + ": " + Long.toString( pendingStack.getStackSize() ) ); - } - } - - GL11.glPopMatrix(); - final int posX = x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19; - final int posY = y * offY + ITEMSTACK_TOP_OFFSET; - - final ItemStack is = refStack.copy().getItemStack(); - - if( this.tooltip == z - viewStart ) - { - dspToolTip = Platform.getItemDisplayName( is ); - - if( lineList.size() > 0 ) - { - addItemTooltip(is, lineList); - dspToolTip = dspToolTip + '\n' + Joiner.on( "\n" ).join( lineList ); - } - - toolPosX = x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 8; - toolPosY = y * offY + ITEMSTACK_TOP_OFFSET; - - hoveredStack = is; - } - - this.drawItem( posX, posY, is ); - - x++; - - if( x > 2 ) - { - y++; - x = 0; - } - } - } - - if( this.tooltip >= 0 && dspToolTip.length() > 0 ) - { - this.drawTooltip( toolPosX, toolPosY + 10, 0, dspToolTip ); - } - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/craftingcpu.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - public void postUpdate( final List list, final byte ref ) - { - switch( ref ) - { - case 0: - for( final IAEItemStack l : list ) - { - this.handleInput( this.storage, l ); - } - break; - - case 1: - for( final IAEItemStack l : list ) - { - this.handleInput( this.active, l ); - } - break; - - case 2: - for( final IAEItemStack l : list ) - { - this.handleInput( this.pending, l ); - } - break; - } - - for( final IAEItemStack l : list ) - { - final long amt = this.getTotal( l ); - - if( amt <= 0 ) - { - this.deleteVisualStack( l ); - } - else - { - final IAEItemStack is = this.findVisualStack( l ); - is.setStackSize( amt ); - } - } - - this.setScrollBar(); - } - - private void handleInput( final IItemList s, final IAEItemStack l ) - { - IAEItemStack a = s.findPrecise( l ); - - if( l.getStackSize() <= 0 ) - { - if( a != null ) - { - a.reset(); - } - } - else - { - if( a == null ) - { - s.add( l.copy() ); - a = s.findPrecise( l ); - } - - if( a != null ) - { - a.setStackSize( l.getStackSize() ); - } - } - } - - private long getTotal( final IAEItemStack is ) - { - final IAEItemStack a = this.storage.findPrecise( is ); - final IAEItemStack b = this.active.findPrecise( is ); - final IAEItemStack c = this.pending.findPrecise( is ); - - long total = 0; - - if( a != null ) - { - total += a.getStackSize(); - } - - if( b != null ) - { - total += b.getStackSize(); - } - - if( c != null ) - { - total += c.getStackSize(); - } - - return total; - } - - private void deleteVisualStack( final IAEItemStack l ) - { - final Iterator i = this.visual.iterator(); - - while( i.hasNext() ) - { - final IAEItemStack o = i.next(); - if( o.equals( l ) ) - { - i.remove(); - return; - } - } - } - - private IAEItemStack findVisualStack( final IAEItemStack l ) - { - for( final IAEItemStack o : this.visual ) - { - if( o.equals( l ) ) - { - return o; - } - } - - final IAEItemStack stack = l.copy(); - this.visual.add( stack ); - - return stack; - } - - @Override - public Enum getSortBy() - { - return SortOrder.NAME; - } - - @Override - public Enum getSortDir() - { - return SortDir.ASCENDING; - } - - @Override - public Enum getSortDisplay() - { - return ViewItems.ALL; - } - - public ItemStack getHoveredStack() { - return hoveredStack; - } +public class GuiCraftingCPU extends AEBaseGui implements ISortSource { + private static final int GUI_HEIGHT = 184; + private static final int GUI_WIDTH = 238; + + private static final int DISPLAYED_ROWS = 6; + + private static final int SECTION_LENGTH = 67; + + private static final int SCROLLBAR_TOP = 19; + private static final int SCROLLBAR_LEFT = 218; + private static final int SCROLLBAR_HEIGHT = 137; + + private static final int CANCEL_LEFT_OFFSET = 163; + private static final int CANCEL_TOP_OFFSET = 25; + private static final int CANCEL_HEIGHT = 20; + private static final int CANCEL_WIDTH = 50; + + private static final int TITLE_TOP_OFFSET = 7; + private static final int TITLE_LEFT_OFFSET = 8; + + private static final int ITEMSTACK_LEFT_OFFSET = 9; + private static final int ITEMSTACK_TOP_OFFSET = 22; + + private final ContainerCraftingCPU craftingCpu; + + private IItemList storage = AEApi.instance().storage().createItemList(); + private IItemList active = AEApi.instance().storage().createItemList(); + private IItemList pending = AEApi.instance().storage().createItemList(); + + private List visual = new ArrayList(); + private GuiButton cancel; + private int tooltip = -1; + private ItemStack hoveredStack; + + public GuiCraftingCPU(final InventoryPlayer inventoryPlayer, final Object te) { + this(new ContainerCraftingCPU(inventoryPlayer, te)); + } + + protected GuiCraftingCPU(final ContainerCraftingCPU container) { + super(container); + this.craftingCpu = container; + this.ySize = GUI_HEIGHT; + this.xSize = GUI_WIDTH; + + final GuiScrollbar scrollbar = new GuiScrollbar(); + this.setScrollBar(scrollbar); + } + + public void clearItems() { + this.storage = AEApi.instance().storage().createItemList(); + this.active = AEApi.instance().storage().createItemList(); + this.pending = AEApi.instance().storage().createItemList(); + this.visual = new ArrayList(); + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + if (this.cancel == btn) { + try { + NetworkHandler.instance.sendToServer(new PacketValueConfig("TileCrafting.Cancel", "Cancel")); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + + @Override + public void initGui() { + super.initGui(); + this.setScrollBar(); + this.cancel = new GuiButton( + 0, + this.guiLeft + CANCEL_LEFT_OFFSET, + this.guiTop + this.ySize - CANCEL_TOP_OFFSET, + CANCEL_WIDTH, + CANCEL_HEIGHT, + GuiText.Cancel.getLocal()); + this.buttonList.add(this.cancel); + } + + private void setScrollBar() { + final int size = this.visual.size(); + + this.getScrollBar().setTop(SCROLLBAR_TOP).setLeft(SCROLLBAR_LEFT).setHeight(SCROLLBAR_HEIGHT); + this.getScrollBar().setRange(0, (size + 2) / 3 - DISPLAYED_ROWS, 1); + } + + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { + this.cancel.enabled = !this.visual.isEmpty(); + + final int gx = (this.width - this.xSize) / 2; + final int gy = (this.height - this.ySize) / 2; + + this.tooltip = -1; + + final int offY = 23; + int y = 0; + int x = 0; + for (int z = 0; z <= 4 * 5; z++) { + final int minX = gx + 9 + x * 67; + final int minY = gy + 22 + y * offY; + + if (minX < mouseX && minX + 67 > mouseX) { + if (minY < mouseY && minY + offY - 2 > mouseY) { + this.tooltip = z; + break; + } + } + + x++; + + if (x > 2) { + y++; + x = 0; + } + } + + super.drawScreen(mouseX, mouseY, btn); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + String title = this.getGuiDisplayName(GuiText.CraftingStatus.getLocal()); + + if (this.craftingCpu.getEstimatedTime() > 0 && !this.visual.isEmpty()) { + final long etaInMilliseconds = + TimeUnit.MILLISECONDS.convert(this.craftingCpu.getEstimatedTime(), TimeUnit.NANOSECONDS); + final String etaTimeText = + DurationFormatUtils.formatDuration(etaInMilliseconds, GuiText.ETAFormat.getLocal()); + title += " - " + etaTimeText; + } + + this.fontRendererObj.drawString( + title, TITLE_LEFT_OFFSET, TITLE_TOP_OFFSET, GuiColors.CraftingCPUTitle.getColor()); + + int x = 0; + int y = 0; + final int viewStart = this.getScrollBar().getCurrentScroll() * 3; + final int viewEnd = viewStart + 3 * 6; + + String dspToolTip = ""; + final List lineList = new LinkedList(); + int toolPosX = 0; + int toolPosY = 0; + + hoveredStack = null; + + final int offY = 23; + + final ReadableNumberConverter converter = ReadableNumberConverter.INSTANCE; + for (int z = viewStart; z < Math.min(viewEnd, this.visual.size()); z++) { + final IAEItemStack refStack = this.visual.get(z); // repo.getReferenceItem( z ); + if (refStack != null) { + GL11.glPushMatrix(); + GL11.glScaled(0.5, 0.5, 0.5); + + final IAEItemStack stored = this.storage.findPrecise(refStack); + final IAEItemStack activeStack = this.active.findPrecise(refStack); + final IAEItemStack pendingStack = this.pending.findPrecise(refStack); + + int lines = 0; + + if (stored != null && stored.getStackSize() > 0) { + lines++; + } + boolean active = false; + if (activeStack != null && activeStack.getStackSize() > 0) { + lines++; + active = true; + } + boolean scheduled = false; + if (pendingStack != null && pendingStack.getStackSize() > 0) { + lines++; + scheduled = true; + } + + if (AEConfig.instance.useColoredCraftingStatus && (active || scheduled)) { + final int bgColor = + active ? GuiColors.CraftingCPUActive.getColor() : GuiColors.CraftingCPUInactive.getColor(); + final int startX = (x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET) * 2; + final int startY = ((y * offY + ITEMSTACK_TOP_OFFSET) - 3) * 2; + drawRect(startX, startY, startX + (SECTION_LENGTH * 2), startY + (offY * 2) - 2, bgColor); + } + + final int negY = ((lines - 1) * 5) / 2; + int downY = 0; + + if (stored != null && stored.getStackSize() > 0) { + final String str = + GuiText.Stored.getLocal() + ": " + converter.toWideReadableForm(stored.getStackSize()); + final int w = 4 + this.fontRendererObj.getStringWidth(str); + this.fontRendererObj.drawString( + str, + (int) ((x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - (w * 0.5)) + * 2), + (y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY) * 2, + GuiColors.CraftingCPUStored.getColor()); + + if (this.tooltip == z - viewStart) { + lineList.add(GuiText.Stored.getLocal() + ": " + Long.toString(stored.getStackSize())); + } + + downY += 5; + } + + if (activeStack != null && activeStack.getStackSize() > 0) { + final String str = GuiText.Crafting.getLocal() + ": " + + converter.toWideReadableForm(activeStack.getStackSize()); + final int w = 4 + this.fontRendererObj.getStringWidth(str); + + this.fontRendererObj.drawString( + str, + (int) ((x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - (w * 0.5)) + * 2), + (y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY) * 2, + GuiColors.CraftingCPUAmount.getColor()); + + if (this.tooltip == z - viewStart) { + lineList.add(GuiText.Crafting.getLocal() + ": " + Long.toString(activeStack.getStackSize())); + } + + downY += 5; + } + + if (pendingStack != null && pendingStack.getStackSize() > 0) { + final String str = GuiText.Scheduled.getLocal() + ": " + + converter.toWideReadableForm(pendingStack.getStackSize()); + final int w = 4 + this.fontRendererObj.getStringWidth(str); + + this.fontRendererObj.drawString( + str, + (int) ((x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - (w * 0.5)) + * 2), + (y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY) * 2, + GuiColors.CraftingCPUScheduled.getColor()); + + if (this.tooltip == z - viewStart) { + lineList.add(GuiText.Scheduled.getLocal() + ": " + Long.toString(pendingStack.getStackSize())); + } + } + + GL11.glPopMatrix(); + final int posX = x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19; + final int posY = y * offY + ITEMSTACK_TOP_OFFSET; + + final ItemStack is = refStack.copy().getItemStack(); + + if (this.tooltip == z - viewStart) { + dspToolTip = Platform.getItemDisplayName(is); + + if (lineList.size() > 0) { + addItemTooltip(is, lineList); + dspToolTip = dspToolTip + '\n' + Joiner.on("\n").join(lineList); + } + + toolPosX = x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 8; + toolPosY = y * offY + ITEMSTACK_TOP_OFFSET; + + hoveredStack = is; + } + + this.drawItem(posX, posY, is); + + x++; + + if (x > 2) { + y++; + x = 0; + } + } + } + + if (this.tooltip >= 0 && dspToolTip.length() > 0) { + this.drawTooltip(toolPosX, toolPosY + 10, 0, dspToolTip); + } + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/craftingcpu.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } + + public void postUpdate(final List list, final byte ref) { + switch (ref) { + case 0: + for (final IAEItemStack l : list) { + this.handleInput(this.storage, l); + } + break; + + case 1: + for (final IAEItemStack l : list) { + this.handleInput(this.active, l); + } + break; + + case 2: + for (final IAEItemStack l : list) { + this.handleInput(this.pending, l); + } + break; + } + + for (final IAEItemStack l : list) { + final long amt = this.getTotal(l); + + if (amt <= 0) { + this.deleteVisualStack(l); + } else { + final IAEItemStack is = this.findVisualStack(l); + is.setStackSize(amt); + } + } + + this.setScrollBar(); + } + + private void handleInput(final IItemList s, final IAEItemStack l) { + IAEItemStack a = s.findPrecise(l); + + if (l.getStackSize() <= 0) { + if (a != null) { + a.reset(); + } + } else { + if (a == null) { + s.add(l.copy()); + a = s.findPrecise(l); + } + + if (a != null) { + a.setStackSize(l.getStackSize()); + } + } + } + + private long getTotal(final IAEItemStack is) { + final IAEItemStack a = this.storage.findPrecise(is); + final IAEItemStack b = this.active.findPrecise(is); + final IAEItemStack c = this.pending.findPrecise(is); + + long total = 0; + + if (a != null) { + total += a.getStackSize(); + } + + if (b != null) { + total += b.getStackSize(); + } + + if (c != null) { + total += c.getStackSize(); + } + + return total; + } + + private void deleteVisualStack(final IAEItemStack l) { + final Iterator i = this.visual.iterator(); + + while (i.hasNext()) { + final IAEItemStack o = i.next(); + if (o.equals(l)) { + i.remove(); + return; + } + } + } + + private IAEItemStack findVisualStack(final IAEItemStack l) { + for (final IAEItemStack o : this.visual) { + if (o.equals(l)) { + return o; + } + } + + final IAEItemStack stack = l.copy(); + this.visual.add(stack); + + return stack; + } + + @Override + public Enum getSortBy() { + return SortOrder.NAME; + } + + @Override + public Enum getSortDir() { + return SortDir.ASCENDING; + } + + @Override + public Enum getSortDisplay() { + return ViewItems.ALL; + } + + public ItemStack getHoveredStack() { + return hoveredStack; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftingStatus.java b/src/main/java/appeng/client/gui/implementations/GuiCraftingStatus.java index e1c21b2d233..93537f32b9f 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftingStatus.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftingStatus.java @@ -19,10 +19,8 @@ /** * */ - package appeng.client.gui.implementations; - import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; import appeng.api.definitions.IParts; @@ -31,7 +29,6 @@ import appeng.client.gui.widgets.GuiTabButton; import appeng.client.gui.widgets.ICraftingCPUTableHolder; import appeng.container.implementations.ContainerCraftingStatus; -import appeng.container.implementations.CraftingCPUStatus; import appeng.core.localization.GuiText; import appeng.core.sync.GuiBridge; import appeng.core.sync.network.NetworkHandler; @@ -46,195 +43,173 @@ import net.minecraft.item.ItemStack; import org.lwjgl.input.Mouse; -import java.util.List; +public class GuiCraftingStatus extends GuiCraftingCPU implements ICraftingCPUTableHolder { + private final ContainerCraftingStatus status; + private GuiButton selectCPU; + private final GuiCraftingCPUTable cpuTable; + private GuiTabButton originalGuiBtn; + private GuiBridge originalGui; + private ItemStack myIcon = null; -public class GuiCraftingStatus extends GuiCraftingCPU implements ICraftingCPUTableHolder -{ - private final ContainerCraftingStatus status; - private GuiButton selectCPU; - private final GuiCraftingCPUTable cpuTable; + public GuiCraftingStatus(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(new ContainerCraftingStatus(inventoryPlayer, te)); + + this.status = (ContainerCraftingStatus) this.inventorySlots; + final Object target = this.status.getTarget(); + final IDefinitions definitions = AEApi.instance().definitions(); + final IParts parts = definitions.parts(); - private GuiTabButton originalGuiBtn; - private GuiBridge originalGui; - private ItemStack myIcon = null; - - public GuiCraftingStatus( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( new ContainerCraftingStatus( inventoryPlayer, te ) ); - - this.status = (ContainerCraftingStatus) this.inventorySlots; - final Object target = this.status.getTarget(); - final IDefinitions definitions = AEApi.instance().definitions(); - final IParts parts = definitions.parts(); - - cpuTable = new GuiCraftingCPUTable(this, this.status.getCPUTable() ); - - if( target instanceof WirelessTerminalGuiObject ) - { - for( final ItemStack wirelessTerminalStack : definitions.items().wirelessTerminal().maybeStack( 1 ).asSet() ) - { - this.myIcon = wirelessTerminalStack; - } - - this.originalGui = GuiBridge.GUI_WIRELESS_TERM; - } - - if( target instanceof PartTerminal ) - { - for( final ItemStack stack : parts.terminal().maybeStack( 1 ).asSet() ) - { - this.myIcon = stack; - } - this.originalGui = GuiBridge.GUI_ME; - } - - if( target instanceof PartCraftingTerminal ) - { - for( final ItemStack stack : parts.craftingTerminal().maybeStack( 1 ).asSet() ) - { - this.myIcon = stack; - } - this.originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; - } - - if( target instanceof PartPatternTerminal ) - { - for( final ItemStack stack : parts.patternTerminal().maybeStack( 1 ).asSet() ) - { - this.myIcon = stack; - } - this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL; - } - if( target instanceof PartPatternTerminalEx) - { - for( final ItemStack stack : parts.patternTerminalEx().maybeStack( 1 ).asSet() ) - { - this.myIcon = stack; - } - this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL_EX; - } - } + cpuTable = new GuiCraftingCPUTable(this, this.status.getCPUTable()); + + if (target instanceof WirelessTerminalGuiObject) { + for (final ItemStack wirelessTerminalStack : + definitions.items().wirelessTerminal().maybeStack(1).asSet()) { + this.myIcon = wirelessTerminalStack; + } + + this.originalGui = GuiBridge.GUI_WIRELESS_TERM; + } + + if (target instanceof PartTerminal) { + for (final ItemStack stack : parts.terminal().maybeStack(1).asSet()) { + this.myIcon = stack; + } + this.originalGui = GuiBridge.GUI_ME; + } + + if (target instanceof PartCraftingTerminal) { + for (final ItemStack stack : parts.craftingTerminal().maybeStack(1).asSet()) { + this.myIcon = stack; + } + this.originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; + } + + if (target instanceof PartPatternTerminal) { + for (final ItemStack stack : parts.patternTerminal().maybeStack(1).asSet()) { + this.myIcon = stack; + } + this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL; + } + if (target instanceof PartPatternTerminalEx) { + for (final ItemStack stack : parts.patternTerminalEx().maybeStack(1).asSet()) { + this.myIcon = stack; + } + this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL_EX; + } + } @Override - public GuiCraftingCPUTable getCPUTable() - { + public GuiCraftingCPUTable getCPUTable() { return cpuTable; } @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean backwards = Mouse.isButtonDown(1); - if( btn == this.selectCPU ) - { + if (btn == this.selectCPU) { cpuTable.cycleCPU(backwards); } - if( btn == this.originalGuiBtn ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.originalGui ) ); - } - } - - @Override - public void initGui() - { - super.initGui(); - - this.selectCPU = new GuiButton( 0, this.guiLeft + 8, this.guiTop + this.ySize - 25, 150, 20, GuiText.CraftingCPU.getLocal() + ": " + GuiText.NoCraftingCPUs ); - this.buttonList.add( this.selectCPU ); - - if( this.myIcon != null ) - { - this.buttonList.add( this.originalGuiBtn = new GuiTabButton( this.guiLeft + 213, this.guiTop - 4, this.myIcon, this.myIcon.getDisplayName(), itemRender ) ); - this.originalGuiBtn.setHideEdge( 13 ); - } - } - - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { - this.cpuTable.drawScreen( ); - this.updateCPUButtonText(); - super.drawScreen( mouseX, mouseY, btn ); - } + if (btn == this.originalGuiBtn) { + NetworkHandler.instance.sendToServer(new PacketSwitchGuis(this.originalGui)); + } + } + + @Override + public void initGui() { + super.initGui(); + + this.selectCPU = new GuiButton( + 0, + this.guiLeft + 8, + this.guiTop + this.ySize - 25, + 150, + 20, + GuiText.CraftingCPU.getLocal() + ": " + GuiText.NoCraftingCPUs); + this.buttonList.add(this.selectCPU); + + if (this.myIcon != null) { + this.buttonList.add( + this.originalGuiBtn = new GuiTabButton( + this.guiLeft + 213, + this.guiTop - 4, + this.myIcon, + this.myIcon.getDisplayName(), + itemRender)); + this.originalGuiBtn.setHideEdge(13); + } + } + + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { + this.cpuTable.drawScreen(); + this.updateCPUButtonText(); + super.drawScreen(mouseX, mouseY, btn); + } @Override - public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ) - { - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - this.cpuTable.drawFG( offsetX, offsetY, mouseX, mouseY, guiLeft, guiTop ); + public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) { + super.drawFG(offsetX, offsetY, mouseX, mouseY); + this.cpuTable.drawFG(offsetX, offsetY, mouseX, mouseY, guiLeft, guiTop); } @Override - public void drawBG( int offsetX, int offsetY, int mouseX, int mouseY ) - { - super.drawBG( offsetX, offsetY, mouseX, mouseY ); - this.cpuTable.drawBG( offsetX, offsetY ); + public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) { + super.drawBG(offsetX, offsetY, mouseX, mouseY); + this.cpuTable.drawBG(offsetX, offsetY); } @Override - protected void mouseClicked( int xCoord, int yCoord, int btn ) - { - super.mouseClicked( xCoord, yCoord, btn ); - cpuTable.mouseClicked( xCoord - guiLeft, yCoord - guiTop, btn ); + protected void mouseClicked(int xCoord, int yCoord, int btn) { + super.mouseClicked(xCoord, yCoord, btn); + cpuTable.mouseClicked(xCoord - guiLeft, yCoord - guiTop, btn); } @Override - protected void mouseClickMove( int x, int y, int c, long d ) - { - super.mouseClickMove( x, y, c, d ); - cpuTable.mouseClickMove( x - guiLeft, y - guiTop ); + protected void mouseClickMove(int x, int y, int c, long d) { + super.mouseClickMove(x, y, c, d); + cpuTable.mouseClickMove(x - guiLeft, y - guiTop); } @Override - public void handleMouseInput() - { - if ( cpuTable.handleMouseInput(guiLeft, guiTop) ) { + public void handleMouseInput() { + if (cpuTable.handleMouseInput(guiLeft, guiTop)) { return; } super.handleMouseInput(); } - public boolean hideItemPanelSlot( int x, int y, int w, int h ) - { - return cpuTable.hideItemPanelSlot(x - guiLeft, y - guiTop, w, h ); + public boolean hideItemPanelSlot(int x, int y, int w, int h) { + return cpuTable.hideItemPanelSlot(x - guiLeft, y - guiTop, w, h); } - private void updateCPUButtonText() - { - String btnTextText = GuiText.NoCraftingJobs.getLocal(); + private void updateCPUButtonText() { + String btnTextText = GuiText.NoCraftingJobs.getLocal(); final int selectedSerial = this.cpuTable.getContainer().selectedCpuSerial; - if( selectedSerial >= 0 ) - { + if (selectedSerial >= 0) { String selectedCPUName = cpuTable.getSelectedCPUName(); - if( selectedCPUName != null && selectedCPUName.length() > 0 ) - { - final String name = selectedCPUName.substring( 0, Math.min( 20, selectedCPUName.length() ) ); - btnTextText = GuiText.CPUs.getLocal() + ": " + name; - } - else - { - btnTextText = GuiText.CPUs.getLocal() + ": #" + selectedSerial; - } - } - - if( this.status.getCPUs().isEmpty() ) - { - btnTextText = GuiText.NoCraftingJobs.getLocal(); - } - - this.selectCPU.displayString = btnTextText; - } - - @Override - protected String getGuiDisplayName( final String in ) - { - return in; // the cup name is on the button - } + if (selectedCPUName != null && selectedCPUName.length() > 0) { + final String name = selectedCPUName.substring(0, Math.min(20, selectedCPUName.length())); + btnTextText = GuiText.CPUs.getLocal() + ": " + name; + } else { + btnTextText = GuiText.CPUs.getLocal() + ": #" + selectedSerial; + } + } + + if (this.status.getCPUs().isEmpty()) { + btnTextText = GuiText.NoCraftingJobs.getLocal(); + } + + this.selectCPU.displayString = btnTextText; + } + + @Override + protected String getGuiDisplayName(final String in) { + return in; // the cup name is on the button + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftingTerm.java b/src/main/java/appeng/client/gui/implementations/GuiCraftingTerm.java index 246ee62073c..d012d3ab232 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftingTerm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftingTerm.java @@ -18,15 +18,14 @@ package appeng.client.gui.implementations; - import appeng.api.config.ActionItems; import appeng.api.config.Settings; import appeng.api.storage.ITerminalHost; import appeng.client.gui.widgets.GuiImgButton; import appeng.container.implementations.ContainerCraftingTerm; import appeng.container.slot.SlotCraftingMatrix; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketInventoryAction; import appeng.helpers.InventoryAction; @@ -35,61 +34,56 @@ import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; +public class GuiCraftingTerm extends GuiMEMonitorable { -public class GuiCraftingTerm extends GuiMEMonitorable -{ - - private GuiImgButton clearBtn; + private GuiImgButton clearBtn; - public GuiCraftingTerm( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( inventoryPlayer, te, new ContainerCraftingTerm( inventoryPlayer, te ) ); - this.setReservedSpace( 73 ); - } + public GuiCraftingTerm(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(inventoryPlayer, te, new ContainerCraftingTerm(inventoryPlayer, te)); + this.setReservedSpace(73); + } - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - if( this.clearBtn == btn ) - { - Slot s = null; - final Container c = this.inventorySlots; - for( final Object j : c.inventorySlots ) - { - if( j instanceof SlotCraftingMatrix ) - { - s = (Slot) j; - } - } + if (this.clearBtn == btn) { + Slot s = null; + final Container c = this.inventorySlots; + for (final Object j : c.inventorySlots) { + if (j instanceof SlotCraftingMatrix) { + s = (Slot) j; + } + } - if( s != null ) - { - final PacketInventoryAction p = new PacketInventoryAction( InventoryAction.MOVE_REGION, s.slotNumber, 0 ); - NetworkHandler.instance.sendToServer( p ); - } - } - } + if (s != null) { + final PacketInventoryAction p = new PacketInventoryAction(InventoryAction.MOVE_REGION, s.slotNumber, 0); + NetworkHandler.instance.sendToServer(p); + } + } + } - @Override - public void initGui() - { - super.initGui(); - this.buttonList.add( this.clearBtn = new GuiImgButton( this.guiLeft + 92, this.guiTop + this.ySize - 156, Settings.ACTIONS, ActionItems.STASH ) ); - this.clearBtn.setHalfSize( true ); - } + @Override + public void initGui() { + super.initGui(); + this.buttonList.add( + this.clearBtn = new GuiImgButton( + this.guiLeft + 92, this.guiTop + this.ySize - 156, Settings.ACTIONS, ActionItems.STASH)); + this.clearBtn.setHalfSize(true); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - this.fontRendererObj.drawString( GuiText.CraftingTerminal.getLocal(), 8, this.ySize - 96 + 1 - this.getReservedSpace(), GuiColors.CraftingTerminalTitle.getColor() ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + super.drawFG(offsetX, offsetY, mouseX, mouseY); + this.fontRendererObj.drawString( + GuiText.CraftingTerminal.getLocal(), + 8, + this.ySize - 96 + 1 - this.getReservedSpace(), + GuiColors.CraftingTerminalTitle.getColor()); + } - @Override - protected String getBackground() - { - return "guis/crafting.png"; - } + @Override + protected String getBackground() { + return "guis/crafting.png"; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiDrive.java b/src/main/java/appeng/client/gui/implementations/GuiDrive.java index 4d076a0175f..2f038a9724b 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiDrive.java +++ b/src/main/java/appeng/client/gui/implementations/GuiDrive.java @@ -18,12 +18,11 @@ package appeng.client.gui.implementations; - import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiTabButton; import appeng.container.implementations.ContainerDrive; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.GuiBridge; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketSwitchGuis; @@ -31,48 +30,44 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; +public class GuiDrive extends AEBaseGui { -public class GuiDrive extends AEBaseGui -{ - - private GuiTabButton priority; + private GuiTabButton priority; - public GuiDrive( final InventoryPlayer inventoryPlayer, final TileDrive te ) - { - super( new ContainerDrive( inventoryPlayer, te ) ); - this.ySize = 199; - } + public GuiDrive(final InventoryPlayer inventoryPlayer, final TileDrive te) { + super(new ContainerDrive(inventoryPlayer, te)); + this.ySize = 199; + } - @Override - protected void actionPerformed( final GuiButton par1GuiButton ) - { - super.actionPerformed( par1GuiButton ); + @Override + protected void actionPerformed(final GuiButton par1GuiButton) { + super.actionPerformed(par1GuiButton); - if( par1GuiButton == this.priority ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - } + if (par1GuiButton == this.priority) { + NetworkHandler.instance.sendToServer(new PacketSwitchGuis(GuiBridge.GUI_PRIORITY)); + } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender ) ); - } + this.buttonList.add( + this.priority = new GuiTabButton( + this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender)); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.Drive.getLocal() ), 8, 6, GuiColors.DriveTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.DriveInventory.getColor() ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.Drive.getLocal()), 8, 6, GuiColors.DriveTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.DriveInventory.getColor()); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/drive.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/drive.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiFormationPlane.java b/src/main/java/appeng/client/gui/implementations/GuiFormationPlane.java index 702edca2bf1..efb9cef4c28 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiFormationPlane.java +++ b/src/main/java/appeng/client/gui/implementations/GuiFormationPlane.java @@ -18,15 +18,14 @@ package appeng.client.gui.implementations; - import appeng.api.config.FuzzyMode; import appeng.api.config.Settings; import appeng.api.config.YesNo; import appeng.client.gui.widgets.GuiImgButton; import appeng.client.gui.widgets.GuiTabButton; import appeng.container.implementations.ContainerFormationPlane; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.GuiBridge; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketConfigButton; @@ -36,68 +35,64 @@ import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Mouse; - -public class GuiFormationPlane extends GuiUpgradeable -{ - - private GuiTabButton priority; - private GuiImgButton placeMode; - - public GuiFormationPlane( final InventoryPlayer inventoryPlayer, final PartFormationPlane te ) - { - super( new ContainerFormationPlane( inventoryPlayer, te ) ); - this.ySize = 251; - } - - @Override - protected void addButtons() - { - this.placeMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.PLACE_BLOCK, YesNo.YES ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - - this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender ) ); - - this.buttonList.add( this.placeMode ); - this.buttonList.add( this.fuzzyMode ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.FormationPlane.getLocal() ), 8, 6, GuiColors.FormationPlaneTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.FormationPlaneInventory.getColor() ); - - if( this.fuzzyMode != null ) - { - this.fuzzyMode.set( this.cvb.getFuzzyMode() ); - } - - if( this.placeMode != null ) - { - this.placeMode.set( ( (ContainerFormationPlane) this.cvb ).getPlaceMode() ); - } - } - - @Override - protected String getBackground() - { - return "guis/storagebus.png"; - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - final boolean backwards = Mouse.isButtonDown( 1 ); - - if( btn == this.priority ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - else if( btn == this.placeMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.placeMode.getSetting(), backwards ) ); - } - } +public class GuiFormationPlane extends GuiUpgradeable { + + private GuiTabButton priority; + private GuiImgButton placeMode; + + public GuiFormationPlane(final InventoryPlayer inventoryPlayer, final PartFormationPlane te) { + super(new ContainerFormationPlane(inventoryPlayer, te)); + this.ySize = 251; + } + + @Override + protected void addButtons() { + this.placeMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 28, Settings.PLACE_BLOCK, YesNo.YES); + this.fuzzyMode = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 48, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + + this.buttonList.add( + this.priority = new GuiTabButton( + this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender)); + + this.buttonList.add(this.placeMode); + this.buttonList.add(this.fuzzyMode); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.FormationPlane.getLocal()), + 8, + 6, + GuiColors.FormationPlaneTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.FormationPlaneInventory.getColor()); + + if (this.fuzzyMode != null) { + this.fuzzyMode.set(this.cvb.getFuzzyMode()); + } + + if (this.placeMode != null) { + this.placeMode.set(((ContainerFormationPlane) this.cvb).getPlaceMode()); + } + } + + @Override + protected String getBackground() { + return "guis/storagebus.png"; + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + final boolean backwards = Mouse.isButtonDown(1); + + if (btn == this.priority) { + NetworkHandler.instance.sendToServer(new PacketSwitchGuis(GuiBridge.GUI_PRIORITY)); + } else if (btn == this.placeMode) { + NetworkHandler.instance.sendToServer(new PacketConfigButton(this.placeMode.getSetting(), backwards)); + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiGrinder.java b/src/main/java/appeng/client/gui/implementations/GuiGrinder.java index 77afcf0dbf8..b8aa785c90b 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiGrinder.java +++ b/src/main/java/appeng/client/gui/implementations/GuiGrinder.java @@ -18,35 +18,31 @@ package appeng.client.gui.implementations; - import appeng.client.gui.AEBaseGui; import appeng.container.implementations.ContainerGrinder; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.tile.grindstone.TileGrinder; import net.minecraft.entity.player.InventoryPlayer; - -public class GuiGrinder extends AEBaseGui -{ - - public GuiGrinder( final InventoryPlayer inventoryPlayer, final TileGrinder te ) - { - super( new ContainerGrinder( inventoryPlayer, te ) ); - this.ySize = 176; - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.GrindStone.getLocal() ), 8, 6, GuiColors.GrindStoneTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.GrindStoneInventory.getColor() ); - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/grinder.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } +public class GuiGrinder extends AEBaseGui { + + public GuiGrinder(final InventoryPlayer inventoryPlayer, final TileGrinder te) { + super(new ContainerGrinder(inventoryPlayer, te)); + this.ySize = 176; + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.GrindStone.getLocal()), 8, 6, GuiColors.GrindStoneTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.GrindStoneInventory.getColor()); + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/grinder.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiIOPort.java b/src/main/java/appeng/client/gui/implementations/GuiIOPort.java index c7f1e4ad971..09aff142dfa 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiIOPort.java +++ b/src/main/java/appeng/client/gui/implementations/GuiIOPort.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.AEApi; import appeng.api.config.FullnessMode; import appeng.api.config.OperationMode; @@ -27,8 +26,8 @@ import appeng.api.definitions.IDefinitions; import appeng.client.gui.widgets.GuiImgButton; import appeng.container.implementations.ContainerIOPort; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketConfigButton; import appeng.tile.storage.TileIOPort; @@ -37,93 +36,85 @@ import net.minecraft.item.ItemStack; import org.lwjgl.input.Mouse; - -public class GuiIOPort extends GuiUpgradeable -{ - - private GuiImgButton fullMode; - private GuiImgButton operationMode; - - public GuiIOPort( final InventoryPlayer inventoryPlayer, final TileIOPort te ) - { - super( new ContainerIOPort( inventoryPlayer, te ) ); - this.ySize = 166; - } - - @Override - @SuppressWarnings( "unchecked" ) - protected void addButtons() - { - this.redstoneMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.fullMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.FULLNESS_MODE, FullnessMode.EMPTY ); - this.operationMode = new GuiImgButton( this.guiLeft + 80, this.guiTop + 17, Settings.OPERATION_MODE, OperationMode.EMPTY ); - - this.buttonList.add( this.operationMode ); - this.buttonList.add( this.redstoneMode ); - this.buttonList.add( this.fullMode ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.IOPort.getLocal() ), 8, 6, GuiColors.IOPortTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.IOPortInventory.getColor() ); - - if( this.redstoneMode != null ) - { - this.redstoneMode.set( this.cvb.getRedStoneMode() ); - } - - if( this.operationMode != null ) - { - this.operationMode.set( ( (ContainerIOPort) this.cvb ).getOperationMode() ); - } - - if( this.fullMode != null ) - { - this.fullMode.set( ( (ContainerIOPort) this.cvb ).getFullMode() ); - } - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - super.drawBG( offsetX, offsetY, mouseX, mouseY ); - - final IDefinitions definitions = AEApi.instance().definitions(); - - for( final ItemStack cell1kStack : definitions.items().cell1k().maybeStack( 1 ).asSet() ) - { - this.drawItem( offsetX + 66 - 8, offsetY + 17, cell1kStack ); - } - - for( final ItemStack driveStack : definitions.blocks().drive().maybeStack( 1 ).asSet() ) - { - this.drawItem( offsetX + 94 + 8, offsetY + 17, driveStack ); - } - } - - @Override - protected String getBackground() - { - return "guis/ioport.png"; - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - final boolean backwards = Mouse.isButtonDown( 1 ); - - if( btn == this.fullMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.fullMode.getSetting(), backwards ) ); - } - - if( btn == this.operationMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.operationMode.getSetting(), backwards ) ); - } - } +public class GuiIOPort extends GuiUpgradeable { + + private GuiImgButton fullMode; + private GuiImgButton operationMode; + + public GuiIOPort(final InventoryPlayer inventoryPlayer, final TileIOPort te) { + super(new ContainerIOPort(inventoryPlayer, te)); + this.ySize = 166; + } + + @Override + @SuppressWarnings("unchecked") + protected void addButtons() { + this.redstoneMode = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 28, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.fullMode = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.FULLNESS_MODE, FullnessMode.EMPTY); + this.operationMode = + new GuiImgButton(this.guiLeft + 80, this.guiTop + 17, Settings.OPERATION_MODE, OperationMode.EMPTY); + + this.buttonList.add(this.operationMode); + this.buttonList.add(this.redstoneMode); + this.buttonList.add(this.fullMode); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.IOPort.getLocal()), 8, 6, GuiColors.IOPortTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.IOPortInventory.getColor()); + + if (this.redstoneMode != null) { + this.redstoneMode.set(this.cvb.getRedStoneMode()); + } + + if (this.operationMode != null) { + this.operationMode.set(((ContainerIOPort) this.cvb).getOperationMode()); + } + + if (this.fullMode != null) { + this.fullMode.set(((ContainerIOPort) this.cvb).getFullMode()); + } + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + super.drawBG(offsetX, offsetY, mouseX, mouseY); + + final IDefinitions definitions = AEApi.instance().definitions(); + + for (final ItemStack cell1kStack : + definitions.items().cell1k().maybeStack(1).asSet()) { + this.drawItem(offsetX + 66 - 8, offsetY + 17, cell1kStack); + } + + for (final ItemStack driveStack : + definitions.blocks().drive().maybeStack(1).asSet()) { + this.drawItem(offsetX + 94 + 8, offsetY + 17, driveStack); + } + } + + @Override + protected String getBackground() { + return "guis/ioport.png"; + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + final boolean backwards = Mouse.isButtonDown(1); + + if (btn == this.fullMode) { + NetworkHandler.instance.sendToServer(new PacketConfigButton(this.fullMode.getSetting(), backwards)); + } + + if (btn == this.operationMode) { + NetworkHandler.instance.sendToServer(new PacketConfigButton(this.operationMode.getSetting(), backwards)); + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiInscriber.java b/src/main/java/appeng/client/gui/implementations/GuiInscriber.java index 8c332249ece..76cff8f7987 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiInscriber.java +++ b/src/main/java/appeng/client/gui/implementations/GuiInscriber.java @@ -18,76 +18,67 @@ package appeng.client.gui.implementations; - import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiProgressBar; import appeng.client.gui.widgets.GuiProgressBar.Direction; import appeng.container.implementations.ContainerInscriber; import appeng.container.implementations.ContainerUpgradeable; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.tile.misc.TileInscriber; import net.minecraft.entity.player.InventoryPlayer; - -public class GuiInscriber extends AEBaseGui -{ - - private final ContainerInscriber cvc; - private GuiProgressBar pb; - - public GuiInscriber( final InventoryPlayer inventoryPlayer, final TileInscriber te ) - { - super( new ContainerInscriber( inventoryPlayer, te ) ); - this.cvc = (ContainerInscriber) this.inventorySlots; - this.ySize = 176; - this.xSize = this.hasToolbox() ? 246 : 211; - } - - private boolean hasToolbox() - { - return ( (ContainerUpgradeable) this.inventorySlots ).hasToolbox(); - } - - @Override - public void initGui() - { - super.initGui(); - - this.pb = new GuiProgressBar( this.cvc, "guis/inscriber.png", 135, 39, 135, 177, 6, 18, Direction.VERTICAL ); - this.buttonList.add( this.pb ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.pb.setFullMsg( this.cvc.getCurrentProgress() * 100 / this.cvc.getMaxProgress() + "%" ); - - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.Inscriber.getLocal() ), 8, 6, GuiColors.InscriberTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.InscriberInventory.getColor() ); - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/inscriber.png" ); - this.pb.xPosition = 135 + this.guiLeft; - this.pb.yPosition = 39 + this.guiTop; - - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, 211 - 34, this.ySize ); - - if( this.drawUpgrades() ) - { - this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 14 + this.cvc.availableUpgrades() * 18 ); - } - if( this.hasToolbox() ) - { - this.drawTexturedModalRect( offsetX + 178, offsetY + this.ySize - 90, 178, this.ySize - 90, 68, 68 ); - } - } - - private boolean drawUpgrades() - { - return true; - } +public class GuiInscriber extends AEBaseGui { + + private final ContainerInscriber cvc; + private GuiProgressBar pb; + + public GuiInscriber(final InventoryPlayer inventoryPlayer, final TileInscriber te) { + super(new ContainerInscriber(inventoryPlayer, te)); + this.cvc = (ContainerInscriber) this.inventorySlots; + this.ySize = 176; + this.xSize = this.hasToolbox() ? 246 : 211; + } + + private boolean hasToolbox() { + return ((ContainerUpgradeable) this.inventorySlots).hasToolbox(); + } + + @Override + public void initGui() { + super.initGui(); + + this.pb = new GuiProgressBar(this.cvc, "guis/inscriber.png", 135, 39, 135, 177, 6, 18, Direction.VERTICAL); + this.buttonList.add(this.pb); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.pb.setFullMsg(this.cvc.getCurrentProgress() * 100 / this.cvc.getMaxProgress() + "%"); + + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.Inscriber.getLocal()), 8, 6, GuiColors.InscriberTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.InscriberInventory.getColor()); + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/inscriber.png"); + this.pb.xPosition = 135 + this.guiLeft; + this.pb.yPosition = 39 + this.guiTop; + + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, 211 - 34, this.ySize); + + if (this.drawUpgrades()) { + this.drawTexturedModalRect(offsetX + 177, offsetY, 177, 0, 35, 14 + this.cvc.availableUpgrades() * 18); + } + if (this.hasToolbox()) { + this.drawTexturedModalRect(offsetX + 178, offsetY + this.ySize - 90, 178, this.ySize - 90, 68, 68); + } + } + + private boolean drawUpgrades() { + return true; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiInterface.java b/src/main/java/appeng/client/gui/implementations/GuiInterface.java index de09d37a15b..4d69c2476f9 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiInterface.java +++ b/src/main/java/appeng/client/gui/implementations/GuiInterface.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.config.InsertionMode; import appeng.api.config.Settings; import appeng.api.config.YesNo; @@ -26,8 +25,8 @@ import appeng.client.gui.widgets.GuiTabButton; import appeng.client.gui.widgets.GuiToggleButton; import appeng.container.implementations.ContainerInterface; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.GuiBridge; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketConfigButton; @@ -37,98 +36,92 @@ import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Mouse; - -public class GuiInterface extends GuiUpgradeable -{ - - private GuiTabButton priority; - private GuiImgButton BlockMode; - private GuiToggleButton interfaceMode; - private GuiImgButton insertionMode; - - public GuiInterface( final InventoryPlayer inventoryPlayer, final IInterfaceHost te ) - { - super( new ContainerInterface( inventoryPlayer, te ) ); - this.ySize = 211; - } - - @Override - protected void addButtons() - { - this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender ); - this.buttonList.add( this.priority ); - - this.BlockMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.BLOCK, YesNo.NO ); - this.buttonList.add( this.BlockMode ); - - this.interfaceMode = new GuiToggleButton( this.guiLeft - 18, this.guiTop + 26, 84, 85, GuiText.InterfaceTerminal.getLocal(), GuiText.InterfaceTerminalHint.getLocal() ); - this.buttonList.add( this.interfaceMode ); - - this.insertionMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 44, Settings.INSERTION_MODE, InsertionMode.DEFAULT ); - this.buttonList.add( this.insertionMode ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - if( this.BlockMode != null ) - { - this.BlockMode.set( ( (ContainerInterface) this.cvb ).getBlockingMode() ); - } - - if( this.interfaceMode != null ) - { - this.interfaceMode.setState( ( (ContainerInterface) this.cvb ).getInterfaceTerminalMode() == YesNo.YES ); - } - - if( this.insertionMode != null ) - { - this.insertionMode.set( ( (ContainerInterface) this.cvb ).getInsertionMode()); - } - - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.Interface.getLocal() ), 8, 6, GuiColors.InterfaceTitle.getColor() ); - } - - @Override - protected String getBackground() - { - switch (((ContainerInterface) this.cvb).getPatternCapacityCardsInstalled()) - { - case 1: - return "guis/interface2.png"; - case 2: - return "guis/interface3.png"; - case 3: - return "guis/interface4.png"; - } - return "guis/interface.png"; - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - final boolean backwards = Mouse.isButtonDown( 1 ); - - if( btn == this.priority ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - - if( btn == this.interfaceMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( Settings.INTERFACE_TERMINAL, backwards ) ); - } - - if( btn == this.BlockMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.BlockMode.getSetting(), backwards ) ); - } - - if( btn == this.insertionMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.insertionMode.getSetting(), backwards ) ); - } - } +public class GuiInterface extends GuiUpgradeable { + + private GuiTabButton priority; + private GuiImgButton BlockMode; + private GuiToggleButton interfaceMode; + private GuiImgButton insertionMode; + + public GuiInterface(final InventoryPlayer inventoryPlayer, final IInterfaceHost te) { + super(new ContainerInterface(inventoryPlayer, te)); + this.ySize = 211; + } + + @Override + protected void addButtons() { + this.priority = + new GuiTabButton(this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender); + this.buttonList.add(this.priority); + + this.BlockMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.BLOCK, YesNo.NO); + this.buttonList.add(this.BlockMode); + + this.interfaceMode = new GuiToggleButton( + this.guiLeft - 18, + this.guiTop + 26, + 84, + 85, + GuiText.InterfaceTerminal.getLocal(), + GuiText.InterfaceTerminalHint.getLocal()); + this.buttonList.add(this.interfaceMode); + + this.insertionMode = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 44, Settings.INSERTION_MODE, InsertionMode.DEFAULT); + this.buttonList.add(this.insertionMode); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + if (this.BlockMode != null) { + this.BlockMode.set(((ContainerInterface) this.cvb).getBlockingMode()); + } + + if (this.interfaceMode != null) { + this.interfaceMode.setState(((ContainerInterface) this.cvb).getInterfaceTerminalMode() == YesNo.YES); + } + + if (this.insertionMode != null) { + this.insertionMode.set(((ContainerInterface) this.cvb).getInsertionMode()); + } + + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.Interface.getLocal()), 8, 6, GuiColors.InterfaceTitle.getColor()); + } + + @Override + protected String getBackground() { + switch (((ContainerInterface) this.cvb).getPatternCapacityCardsInstalled()) { + case 1: + return "guis/interface2.png"; + case 2: + return "guis/interface3.png"; + case 3: + return "guis/interface4.png"; + } + return "guis/interface.png"; + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + final boolean backwards = Mouse.isButtonDown(1); + + if (btn == this.priority) { + NetworkHandler.instance.sendToServer(new PacketSwitchGuis(GuiBridge.GUI_PRIORITY)); + } + + if (btn == this.interfaceMode) { + NetworkHandler.instance.sendToServer(new PacketConfigButton(Settings.INTERFACE_TERMINAL, backwards)); + } + + if (btn == this.BlockMode) { + NetworkHandler.instance.sendToServer(new PacketConfigButton(this.BlockMode.getSetting(), backwards)); + } + + if (btn == this.insertionMode) { + NetworkHandler.instance.sendToServer(new PacketConfigButton(this.insertionMode.getSetting(), backwards)); + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiInterfaceTerminal.java b/src/main/java/appeng/client/gui/implementations/GuiInterfaceTerminal.java index 3a6c71f53e3..4611e8d3b0e 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiInterfaceTerminal.java +++ b/src/main/java/appeng/client/gui/implementations/GuiInterfaceTerminal.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.AEApi; import appeng.api.config.ActionItems; import appeng.api.config.Settings; @@ -38,8 +37,8 @@ import appeng.core.AEConfig; import appeng.core.CommonHelper; import appeng.core.localization.ButtonToolTips; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.localization.PlayerMessages; import appeng.helpers.PatternHelper; import appeng.integration.IntegrationRegistry; @@ -47,6 +46,7 @@ import appeng.parts.reporting.PartInterfaceTerminal; import appeng.util.Platform; import com.google.common.collect.HashMultimap; +import java.util.*; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; @@ -57,24 +57,20 @@ import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; -import java.util.*; +public class GuiInterfaceTerminal extends AEBaseGui implements IDropToFillTextField { + private static final int MAGIC_HEIGHT_NUMBER = 52 + 99; + private static final int offsetX = 21; -public class GuiInterfaceTerminal extends AEBaseGui implements IDropToFillTextField -{ + private final HashMap byId = new HashMap<>(); + private final HashMultimap byName = HashMultimap.create(); + private final HashMap blockPosHashMap = new HashMap<>(); + private final HashMap guiButtonHashMap = new HashMap<>(); + private final ArrayList names = new ArrayList<>(); + private final ArrayList lines = new ArrayList<>(); + private final Set matchedStacks = new HashSet<>(); - private static final int MAGIC_HEIGHT_NUMBER = 52 + 99; - private static final int offsetX = 21; - - private final HashMap byId = new HashMap<>(); - private final HashMultimap byName = HashMultimap.create(); - private final HashMap blockPosHashMap = new HashMap<>(); - private final HashMap guiButtonHashMap = new HashMap<>(); - private final ArrayList names = new ArrayList<>(); - private final ArrayList lines = new ArrayList<>(); - private final Set matchedStacks = new HashSet<>(); - - private final Map> cachedSearches = new WeakHashMap<>(); + private final Map> cachedSearches = new WeakHashMap<>(); private final MEGuiTextField searchFieldOutputs; private final MEGuiTextField searchFieldInputs; @@ -83,658 +79,582 @@ public class GuiInterfaceTerminal extends AEBaseGui implements IDropToFillTextFi private final GuiImgButton guiButtonAssemblersOnly; private final GuiImgButton guiButtonBrokenRecipes; private final GuiImgButton terminalStyleBox; - private boolean refreshList = false; - private boolean onlyMolecularAssemblers = false; - private boolean onlyBrokenRecipes = false; - - // private final IConfigManager configSrc; - private int rows = 3; - - private static final String MOLECULAR_ASSEMBLER = "tile.appliedenergistics2.BlockMolecularAssembler"; - - public GuiInterfaceTerminal( final InventoryPlayer inventoryPlayer, final PartInterfaceTerminal te ) - { - super( new ContainerInterfaceTerminal( inventoryPlayer, te ) ); - - this.setScrollBar( new GuiScrollbar() ); - this.xSize = 208; - this.ySize = 255; - - - searchFieldInputs = new MEGuiTextField( 86, 12, ButtonToolTips.SearchFieldInputs.getLocal() ) - { - @Override - public void onTextChange(final String oldText) - { - refreshList(); - } - }; - - searchFieldOutputs = new MEGuiTextField( 86, 12, ButtonToolTips.SearchFieldOutputs.getLocal() ) - { - @Override - public void onTextChange(final String oldText) - { - refreshList(); - } - }; - - searchFieldNames = new MEGuiTextField( 71, 12, ButtonToolTips.SearchFieldNames.getLocal() ) - { - @Override - public void onTextChange(final String oldText) - { - refreshList(); - } - }; - searchFieldNames.setFocused(true); - - guiButtonAssemblersOnly = new GuiImgButton(0, 0, Settings.ACTIONS, null ); - guiButtonHideFull = new GuiImgButton( 0, 0, Settings.ACTIONS, null ); - guiButtonBrokenRecipes = new GuiImgButton( 0, 0, Settings.ACTIONS, null ); - - terminalStyleBox = new GuiImgButton( 0, 0, Settings.TERMINAL_STYLE, null ); - } - - private void setScrollBar() - { - this.getScrollBar().setTop( 52 ).setLeft( 189 ).setHeight( this.rows * 18 - 2 ); - this.getScrollBar().setRange( 0, this.lines.size() - this.rows, 2 ); - } - - @Override - public void initGui() - { - this.rows = calculateRowsCount(); - - super.initGui(); - - this.ySize = MAGIC_HEIGHT_NUMBER + this.rows * 18; - final int unusedSpace = this.height - this.ySize; - this.guiTop = (int) Math.floor( unusedSpace / ( unusedSpace < 0 ? 3.8f : 2.0f ) ); - - searchFieldInputs.x = guiLeft + Math.max( 32, offsetX ); - searchFieldInputs.y = guiTop + 25; - - searchFieldOutputs.x = guiLeft + Math.max( 32, offsetX ); - searchFieldOutputs.y = guiTop + 38; - - searchFieldNames.x = guiLeft + Math.max( 32, offsetX ) + 99; - searchFieldNames.y = guiTop + 38; - - guiButtonAssemblersOnly.xPosition = guiLeft + Math.max( 32, offsetX ) + 99; - guiButtonAssemblersOnly.yPosition = guiTop + 20; - - guiButtonHideFull.xPosition = guiButtonAssemblersOnly.xPosition + 18; - guiButtonHideFull.yPosition = guiTop + 20; - - guiButtonBrokenRecipes.xPosition = guiButtonHideFull.xPosition + 18; - guiButtonBrokenRecipes.yPosition = guiTop + 20; - - terminalStyleBox.xPosition = guiLeft - 18; - terminalStyleBox.yPosition = guiTop + 8; - - this.setScrollBar(); - this.repositionSlots(); - } - - protected void repositionSlots() - { - for (final Object obj : this.inventorySlots.inventorySlots) { - if (obj instanceof AppEngSlot) { - final AppEngSlot slot = (AppEngSlot) obj; - slot.yDisplayPosition = this.ySize + slot.getY() - 78 - 7; - } - } - - } - - protected int calculateRowsCount() - { - final int maxRows = this.getMaxRows(); - final boolean hasNEI = IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.NEI ); - final int NEIPadding = hasNEI? 22 /* input */ + 18 /* top panel */: 0; - final int extraSpace = this.height - MAGIC_HEIGHT_NUMBER - NEIPadding; - - return Math.max(3, Math.min(maxRows, extraSpace / 18)); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - fontRendererObj.drawString( getGuiDisplayName( GuiText.InterfaceTerminal.getLocal() ), 8, 6, GuiColors.InterfaceTerminalTitle.getColor() ); - fontRendererObj.drawString( GuiText.inventory.getLocal(), GuiInterfaceTerminal.offsetX + 2, this.ySize - 96, GuiColors.InterfaceTerminalInventory.getColor() ); - - int offset = 51; - final int ex = getScrollBar().getCurrentScroll(); - for( int x = 0; x < this.rows && ex + x < this.lines.size(); x++ ) - { - final Object lineObj = this.lines.get( ex + x ); - if( lineObj instanceof ClientDCInternalInv ) - { - final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; - for( int z = 0; z < inv.getInventory().getSizeInventory(); z++ ) - { - if (this.matchedStacks.contains(inv.getInventory().getStackInSlot(z))) - drawRect( z * 18 + 22, 1 + offset, z * 18 + 22 + 16, 1 + offset + 16, GuiColors.InterfaceTerminalMatch.getColor() ); - } - } - else if( lineObj instanceof String ) - { - String name = (String) lineObj; - final int rows = this.byName.get( name ).size(); - String postfix = ""; - - if( rows > 1 ) - { - postfix = " (" + rows + ')'; - } - - while( name.length() > 2 && this.fontRendererObj.getStringWidth( name + postfix ) > 158 ) - { - name = name.substring( 0, name.length() - 1 ); - } - - this.fontRendererObj.drawString( name + postfix, GuiInterfaceTerminal.offsetX + 3, 6 + offset, GuiColors.InterfaceTerminalName.getColor() ); - } - - offset += 18; - } - - } - - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { - - buttonList.clear(); - inventorySlots.inventorySlots.removeIf( slot -> slot instanceof SlotDisconnected ); - - guiButtonAssemblersOnly.set( onlyMolecularAssemblers ? ActionItems.MOLECULAR_ASSEMBLEERS_ON : ActionItems.MOLECULAR_ASSEMBLEERS_OFF ); - guiButtonHideFull.set( AEConfig.instance.showOnlyInterfacesWithFreeSlotsInInterfaceTerminal ? ActionItems.TOGGLE_SHOW_FULL_INTERFACES_OFF : ActionItems.TOGGLE_SHOW_FULL_INTERFACES_ON ); - guiButtonBrokenRecipes.set( onlyBrokenRecipes? ActionItems.TOGGLE_SHOW_ONLY_INVALID_PATTERN_OFF : ActionItems.TOGGLE_SHOW_ONLY_INVALID_PATTERN_ON ); - - terminalStyleBox.set( AEConfig.instance.settings.getSetting(Settings.TERMINAL_STYLE) ); - - buttonList.add(guiButtonAssemblersOnly); - buttonList.add(guiButtonHideFull); - buttonList.add(guiButtonBrokenRecipes); - - buttonList.add(terminalStyleBox); - - int offset = 51; - final int ex = this.getScrollBar().getCurrentScroll(); - for( int x = 0; x < this.rows && ex + x < this.lines.size(); x++ ) - { - final Object lineObj = this.lines.get( ex + x ); - if( lineObj instanceof ClientDCInternalInv ) - { - final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; - for( int z = 0; z < inv.getInventory().getSizeInventory(); z++ ) - { - inventorySlots.inventorySlots.add( new SlotDisconnected( inv, z, z * 18 + 22, 1 + offset ) ); - } - - GuiButton guiButton = new GuiImgButton(guiLeft + 4, guiTop + offset + 1, Settings.ACTIONS, ActionItems.HIGHLIGHT_INTERFACE); - guiButtonHashMap.put( guiButton , inv); - buttonList.add( guiButton ); - } - - offset += 18; - } - - super.drawScreen(mouseX, mouseY, btn); - - handleTooltip(mouseX, mouseY, searchFieldInputs); - handleTooltip(mouseX, mouseY, searchFieldOutputs); - handleTooltip(mouseX, mouseY, searchFieldNames); - } - - @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) - { - searchFieldInputs.mouseClicked( xCoord, yCoord, btn ); - searchFieldOutputs.mouseClicked( xCoord, yCoord, btn ); - searchFieldNames.mouseClicked( xCoord, yCoord, btn ); - - super.mouseClicked( xCoord, yCoord, btn ); - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - if( guiButtonHashMap.containsKey( btn ) ) - { - DimensionalCoord blockPos = blockPosHashMap.get( guiButtonHashMap.get( btn ) ); - WorldCoord blockPos2 = new WorldCoord((int)mc.thePlayer.posX, (int)mc.thePlayer.posY, (int)mc.thePlayer.posZ); - if( mc.theWorld.provider.dimensionId != blockPos.getDimension() ) - { - mc.thePlayer.addChatMessage(new ChatComponentTranslation( PlayerMessages.InterfaceInOtherDim.getName(), blockPos.getDimension())); - } - else - { - BlockPosHighlighter.highlightBlock(blockPos, System.currentTimeMillis() + 500 * WorldCoord.getTaxicabDistance(blockPos, blockPos2)); - mc.thePlayer.addChatMessage(new ChatComponentTranslation( PlayerMessages.InterfaceHighlighted.getName(), blockPos.x, blockPos.y, blockPos.z)); - } - mc.thePlayer.closeScreen(); - } - else if (btn == guiButtonHideFull) - { - AEConfig.instance.showOnlyInterfacesWithFreeSlotsInInterfaceTerminal = !AEConfig.instance.showOnlyInterfacesWithFreeSlotsInInterfaceTerminal; - this.refreshList(); - } - else if (btn == guiButtonAssemblersOnly) - { - onlyMolecularAssemblers = !onlyMolecularAssemblers; - this.refreshList(); - } - else if (btn == guiButtonBrokenRecipes) - { - onlyBrokenRecipes = !onlyBrokenRecipes; - this.refreshList(); - } - else if ( btn instanceof GuiImgButton ) - { - final GuiImgButton iBtn = (GuiImgButton) btn; - if( iBtn.getSetting() != Settings.ACTIONS ) - { - final Enum cv = iBtn.getCurrentValue(); - final boolean backwards = Mouse.isButtonDown( 1 ); - final Enum next = Platform.rotateEnum( cv, backwards, iBtn.getSetting().getPossibleValues() ); - - if( btn == this.terminalStyleBox ) - { - AEConfig.instance.settings.putSetting( iBtn.getSetting(), next ); - - this.reinitialize(); - } - - iBtn.set( next ); - } - } - - } - - private void reinitialize() - { - this.buttonList.clear(); - this.initGui(); - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/newinterfaceterminal.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, 53 ); - - int offset = 51; - final int ex = this.getScrollBar().getCurrentScroll(); - - for (int x = 0; x < this.rows; x++) { - this.drawTexturedModalRect( offsetX, offsetY + 53 + x * 18, 0, 52, this.xSize, 18); - } - - for (int x = 0; x < this.rows && ex + x < this.lines.size(); x++) { - - final Object lineObj = this.lines.get( ex + x ); - if (lineObj instanceof ClientDCInternalInv) { - final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; - - GL11.glColor4f( 1, 1, 1, 1 ); - final int width = inv.getInventory().getSizeInventory() * 18; - this.drawTexturedModalRect( offsetX + 20, offsetY + offset, 20, 173, width, 18 ); - } - - offset += 18; - } - - this.drawTexturedModalRect( offsetX, offsetY + 50 + this.rows * 18, 0, 158, this.xSize, 99); - - searchFieldInputs.drawTextBox(); - searchFieldOutputs.drawTextBox(); - searchFieldNames.drawTextBox(); - } - - @Override - protected void keyTyped( final char character, final int key ) - { - if( !checkHotbarKeys( key ) ) - { - if( character == ' ' ) - { - if( ( searchFieldInputs.getText().isEmpty() && searchFieldInputs.isFocused() ) || - ( searchFieldOutputs.getText().isEmpty() && searchFieldOutputs.isFocused() ) || - ( searchFieldNames.getText().isEmpty() && searchFieldNames.isFocused() ) ) - return; - } else if( character == '\t' ) - { - if( handleTab() ) - return; + private boolean refreshList = false; + private boolean onlyMolecularAssemblers = false; + private boolean onlyBrokenRecipes = false; + + // private final IConfigManager configSrc; + private int rows = 3; + + private static final String MOLECULAR_ASSEMBLER = "tile.appliedenergistics2.BlockMolecularAssembler"; + + public GuiInterfaceTerminal(final InventoryPlayer inventoryPlayer, final PartInterfaceTerminal te) { + super(new ContainerInterfaceTerminal(inventoryPlayer, te)); + + this.setScrollBar(new GuiScrollbar()); + this.xSize = 208; + this.ySize = 255; + + searchFieldInputs = new MEGuiTextField(86, 12, ButtonToolTips.SearchFieldInputs.getLocal()) { + @Override + public void onTextChange(final String oldText) { + refreshList(); } - if( searchFieldInputs.textboxKeyTyped( character, key ) || - searchFieldOutputs.textboxKeyTyped( character, key ) || - searchFieldNames.textboxKeyTyped( character, key ) ) - { + }; + + searchFieldOutputs = new MEGuiTextField(86, 12, ButtonToolTips.SearchFieldOutputs.getLocal()) { + @Override + public void onTextChange(final String oldText) { refreshList(); - } else - { - super.keyTyped( character, key ); + } + }; + + searchFieldNames = new MEGuiTextField(71, 12, ButtonToolTips.SearchFieldNames.getLocal()) { + @Override + public void onTextChange(final String oldText) { + refreshList(); + } + }; + searchFieldNames.setFocused(true); + + guiButtonAssemblersOnly = new GuiImgButton(0, 0, Settings.ACTIONS, null); + guiButtonHideFull = new GuiImgButton(0, 0, Settings.ACTIONS, null); + guiButtonBrokenRecipes = new GuiImgButton(0, 0, Settings.ACTIONS, null); + + terminalStyleBox = new GuiImgButton(0, 0, Settings.TERMINAL_STYLE, null); + } + + private void setScrollBar() { + this.getScrollBar().setTop(52).setLeft(189).setHeight(this.rows * 18 - 2); + this.getScrollBar().setRange(0, this.lines.size() - this.rows, 2); + } + + @Override + public void initGui() { + this.rows = calculateRowsCount(); + + super.initGui(); + + this.ySize = MAGIC_HEIGHT_NUMBER + this.rows * 18; + final int unusedSpace = this.height - this.ySize; + this.guiTop = (int) Math.floor(unusedSpace / (unusedSpace < 0 ? 3.8f : 2.0f)); + + searchFieldInputs.x = guiLeft + Math.max(32, offsetX); + searchFieldInputs.y = guiTop + 25; + + searchFieldOutputs.x = guiLeft + Math.max(32, offsetX); + searchFieldOutputs.y = guiTop + 38; + + searchFieldNames.x = guiLeft + Math.max(32, offsetX) + 99; + searchFieldNames.y = guiTop + 38; + + guiButtonAssemblersOnly.xPosition = guiLeft + Math.max(32, offsetX) + 99; + guiButtonAssemblersOnly.yPosition = guiTop + 20; + + guiButtonHideFull.xPosition = guiButtonAssemblersOnly.xPosition + 18; + guiButtonHideFull.yPosition = guiTop + 20; + + guiButtonBrokenRecipes.xPosition = guiButtonHideFull.xPosition + 18; + guiButtonBrokenRecipes.yPosition = guiTop + 20; + + terminalStyleBox.xPosition = guiLeft - 18; + terminalStyleBox.yPosition = guiTop + 8; + + this.setScrollBar(); + this.repositionSlots(); + } + + protected void repositionSlots() { + for (final Object obj : this.inventorySlots.inventorySlots) { + if (obj instanceof AppEngSlot) { + final AppEngSlot slot = (AppEngSlot) obj; + slot.yDisplayPosition = this.ySize + slot.getY() - 78 - 7; } } } - private boolean handleTab() - { - if( searchFieldInputs.isFocused() ) - { - searchFieldInputs.setFocused( false ); - if (isShiftKeyDown()) - searchFieldNames.setFocused( true ); - else - searchFieldOutputs.setFocused( true ); + protected int calculateRowsCount() { + final int maxRows = this.getMaxRows(); + final boolean hasNEI = IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.NEI); + final int NEIPadding = hasNEI ? 22 /* input */ + 18 /* top panel */ : 0; + final int extraSpace = this.height - MAGIC_HEIGHT_NUMBER - NEIPadding; + + return Math.max(3, Math.min(maxRows, extraSpace / 18)); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + fontRendererObj.drawString( + getGuiDisplayName(GuiText.InterfaceTerminal.getLocal()), + 8, + 6, + GuiColors.InterfaceTerminalTitle.getColor()); + fontRendererObj.drawString( + GuiText.inventory.getLocal(), + GuiInterfaceTerminal.offsetX + 2, + this.ySize - 96, + GuiColors.InterfaceTerminalInventory.getColor()); + + int offset = 51; + final int ex = getScrollBar().getCurrentScroll(); + for (int x = 0; x < this.rows && ex + x < this.lines.size(); x++) { + final Object lineObj = this.lines.get(ex + x); + if (lineObj instanceof ClientDCInternalInv) { + final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; + for (int z = 0; z < inv.getInventory().getSizeInventory(); z++) { + if (this.matchedStacks.contains(inv.getInventory().getStackInSlot(z))) + drawRect( + z * 18 + 22, + 1 + offset, + z * 18 + 22 + 16, + 1 + offset + 16, + GuiColors.InterfaceTerminalMatch.getColor()); + } + } else if (lineObj instanceof String) { + String name = (String) lineObj; + final int rows = this.byName.get(name).size(); + String postfix = ""; + + if (rows > 1) { + postfix = " (" + rows + ')'; + } + + while (name.length() > 2 && this.fontRendererObj.getStringWidth(name + postfix) > 158) { + name = name.substring(0, name.length() - 1); + } + + this.fontRendererObj.drawString( + name + postfix, + GuiInterfaceTerminal.offsetX + 3, + 6 + offset, + GuiColors.InterfaceTerminalName.getColor()); + } + + offset += 18; + } + } + + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { + + buttonList.clear(); + inventorySlots.inventorySlots.removeIf(slot -> slot instanceof SlotDisconnected); + + guiButtonAssemblersOnly.set( + onlyMolecularAssemblers ? ActionItems.MOLECULAR_ASSEMBLEERS_ON : ActionItems.MOLECULAR_ASSEMBLEERS_OFF); + guiButtonHideFull.set( + AEConfig.instance.showOnlyInterfacesWithFreeSlotsInInterfaceTerminal + ? ActionItems.TOGGLE_SHOW_FULL_INTERFACES_OFF + : ActionItems.TOGGLE_SHOW_FULL_INTERFACES_ON); + guiButtonBrokenRecipes.set( + onlyBrokenRecipes + ? ActionItems.TOGGLE_SHOW_ONLY_INVALID_PATTERN_OFF + : ActionItems.TOGGLE_SHOW_ONLY_INVALID_PATTERN_ON); + + terminalStyleBox.set(AEConfig.instance.settings.getSetting(Settings.TERMINAL_STYLE)); + + buttonList.add(guiButtonAssemblersOnly); + buttonList.add(guiButtonHideFull); + buttonList.add(guiButtonBrokenRecipes); + + buttonList.add(terminalStyleBox); + + int offset = 51; + final int ex = this.getScrollBar().getCurrentScroll(); + for (int x = 0; x < this.rows && ex + x < this.lines.size(); x++) { + final Object lineObj = this.lines.get(ex + x); + if (lineObj instanceof ClientDCInternalInv) { + final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; + for (int z = 0; z < inv.getInventory().getSizeInventory(); z++) { + inventorySlots.inventorySlots.add(new SlotDisconnected(inv, z, z * 18 + 22, 1 + offset)); + } + + GuiButton guiButton = new GuiImgButton( + guiLeft + 4, guiTop + offset + 1, Settings.ACTIONS, ActionItems.HIGHLIGHT_INTERFACE); + guiButtonHashMap.put(guiButton, inv); + buttonList.add(guiButton); + } + + offset += 18; + } + + super.drawScreen(mouseX, mouseY, btn); + + handleTooltip(mouseX, mouseY, searchFieldInputs); + handleTooltip(mouseX, mouseY, searchFieldOutputs); + handleTooltip(mouseX, mouseY, searchFieldNames); + } + + @Override + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) { + searchFieldInputs.mouseClicked(xCoord, yCoord, btn); + searchFieldOutputs.mouseClicked(xCoord, yCoord, btn); + searchFieldNames.mouseClicked(xCoord, yCoord, btn); + + super.mouseClicked(xCoord, yCoord, btn); + } + + @Override + protected void actionPerformed(final GuiButton btn) { + if (guiButtonHashMap.containsKey(btn)) { + DimensionalCoord blockPos = blockPosHashMap.get(guiButtonHashMap.get(btn)); + WorldCoord blockPos2 = + new WorldCoord((int) mc.thePlayer.posX, (int) mc.thePlayer.posY, (int) mc.thePlayer.posZ); + if (mc.theWorld.provider.dimensionId != blockPos.getDimension()) { + mc.thePlayer.addChatMessage(new ChatComponentTranslation( + PlayerMessages.InterfaceInOtherDim.getName(), blockPos.getDimension())); + } else { + BlockPosHighlighter.highlightBlock( + blockPos, + System.currentTimeMillis() + 500 * WorldCoord.getTaxicabDistance(blockPos, blockPos2)); + mc.thePlayer.addChatMessage(new ChatComponentTranslation( + PlayerMessages.InterfaceHighlighted.getName(), blockPos.x, blockPos.y, blockPos.z)); + } + mc.thePlayer.closeScreen(); + } else if (btn == guiButtonHideFull) { + AEConfig.instance.showOnlyInterfacesWithFreeSlotsInInterfaceTerminal = + !AEConfig.instance.showOnlyInterfacesWithFreeSlotsInInterfaceTerminal; + this.refreshList(); + } else if (btn == guiButtonAssemblersOnly) { + onlyMolecularAssemblers = !onlyMolecularAssemblers; + this.refreshList(); + } else if (btn == guiButtonBrokenRecipes) { + onlyBrokenRecipes = !onlyBrokenRecipes; + this.refreshList(); + } else if (btn instanceof GuiImgButton) { + final GuiImgButton iBtn = (GuiImgButton) btn; + if (iBtn.getSetting() != Settings.ACTIONS) { + final Enum cv = iBtn.getCurrentValue(); + final boolean backwards = Mouse.isButtonDown(1); + final Enum next = + Platform.rotateEnum(cv, backwards, iBtn.getSetting().getPossibleValues()); + + if (btn == this.terminalStyleBox) { + AEConfig.instance.settings.putSetting(iBtn.getSetting(), next); + + this.reinitialize(); + } + + iBtn.set(next); + } + } + } + + private void reinitialize() { + this.buttonList.clear(); + this.initGui(); + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/newinterfaceterminal.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, 53); + + int offset = 51; + final int ex = this.getScrollBar().getCurrentScroll(); + + for (int x = 0; x < this.rows; x++) { + this.drawTexturedModalRect(offsetX, offsetY + 53 + x * 18, 0, 52, this.xSize, 18); + } + + for (int x = 0; x < this.rows && ex + x < this.lines.size(); x++) { + + final Object lineObj = this.lines.get(ex + x); + if (lineObj instanceof ClientDCInternalInv) { + final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; + + GL11.glColor4f(1, 1, 1, 1); + final int width = inv.getInventory().getSizeInventory() * 18; + this.drawTexturedModalRect(offsetX + 20, offsetY + offset, 20, 173, width, 18); + } + + offset += 18; + } + + this.drawTexturedModalRect(offsetX, offsetY + 50 + this.rows * 18, 0, 158, this.xSize, 99); + + searchFieldInputs.drawTextBox(); + searchFieldOutputs.drawTextBox(); + searchFieldNames.drawTextBox(); + } + + @Override + protected void keyTyped(final char character, final int key) { + if (!checkHotbarKeys(key)) { + if (character == ' ') { + if ((searchFieldInputs.getText().isEmpty() && searchFieldInputs.isFocused()) + || (searchFieldOutputs.getText().isEmpty() && searchFieldOutputs.isFocused()) + || (searchFieldNames.getText().isEmpty() && searchFieldNames.isFocused())) return; + } else if (character == '\t') { + if (handleTab()) return; + } + if (searchFieldInputs.textboxKeyTyped(character, key) + || searchFieldOutputs.textboxKeyTyped(character, key) + || searchFieldNames.textboxKeyTyped(character, key)) { + refreshList(); + } else { + super.keyTyped(character, key); + } + } + } + + private boolean handleTab() { + if (searchFieldInputs.isFocused()) { + searchFieldInputs.setFocused(false); + if (isShiftKeyDown()) searchFieldNames.setFocused(true); + else searchFieldOutputs.setFocused(true); return true; - } else if( searchFieldOutputs.isFocused() ) - { - searchFieldOutputs.setFocused( false ); - if (isShiftKeyDown()) - searchFieldInputs.setFocused( true ); - else - searchFieldNames.setFocused( true ); + } else if (searchFieldOutputs.isFocused()) { + searchFieldOutputs.setFocused(false); + if (isShiftKeyDown()) searchFieldInputs.setFocused(true); + else searchFieldNames.setFocused(true); return true; - } else if( searchFieldNames.isFocused() ) - { - searchFieldNames.setFocused( false ); - if (isShiftKeyDown()) - searchFieldOutputs.setFocused( true ); - else - searchFieldInputs.setFocused( true ); + } else if (searchFieldNames.isFocused()) { + searchFieldNames.setFocused(false); + if (isShiftKeyDown()) searchFieldOutputs.setFocused(true); + else searchFieldInputs.setFocused(true); return true; } return false; } - public void postUpdate( final NBTTagCompound in ) - { - if( in.getBoolean( "clear" ) ) - { - this.byId.clear(); - this.refreshList = true; - } - - for( final Object oKey : in.func_150296_c() ) - { - final String key = (String) oKey; - if( key.startsWith( "=" ) ) - { - try - { - final long id = Long.parseLong( key.substring( 1 ), Character.MAX_RADIX ); - final NBTTagCompound invData = in.getCompoundTag( key ); - final ClientDCInternalInv current = this.getById( id, invData.getLong( "sortBy" ), invData.getString( "un" ) ); - int X = invData.getInteger( "x" ); - int Y = invData.getInteger( "y" ); - int Z = invData.getInteger( "z" ); - int dim = invData.getInteger( "dim" ); - blockPosHashMap.put( current, new DimensionalCoord( X, Y, Z, dim ) ); - - for( int x = 0; x < current.getInventory().getSizeInventory(); x++ ) - { - final String which = Integer.toString( x ); - if( invData.hasKey( which ) ) - { - current.getInventory().setInventorySlotContents( x, ItemStack.loadItemStackFromNBT( invData.getCompoundTag( which ) ) ); - } - } - } - catch( final NumberFormatException ignored ) - { - } - } - } - - if( this.refreshList ) - { - this.refreshList = false; - // invalid caches on refresh - this.cachedSearches.clear(); - this.refreshList(); - } - } - - /** - * Rebuilds the list of interfaces. - *

- * Respects a search term if present (ignores case) and adding only matching patterns. - */ - private void refreshList() - { - this.byName.clear(); - this.buttonList.clear(); - this.matchedStacks.clear(); - - final String searchFieldInputs = this.searchFieldInputs.getText().toLowerCase(); - final String searchFieldOutputs = this.searchFieldOutputs.getText().toLowerCase(); - final String searchFieldNames = this.searchFieldNames.getText().toLowerCase(); - - final Set cachedSearch = this.getCacheForSearchTerm( - "IN:" + searchFieldInputs + - "OUT:" + searchFieldOutputs + - "NAME:" + searchFieldNames + - AEConfig.instance.showOnlyInterfacesWithFreeSlotsInInterfaceTerminal + - onlyMolecularAssemblers + - onlyBrokenRecipes - ); - final boolean rebuild = cachedSearch.isEmpty(); - - for( final ClientDCInternalInv entry : this.byId.values() ) - { - // ignore inventory if not doing a full rebuild and cache already marks it as miss. - if( !rebuild && !cachedSearch.contains( entry ) ) - { - continue; - } - - // Shortcut to skip any filter if search term is ""/empty - boolean found = searchFieldInputs.isEmpty() && searchFieldOutputs.isEmpty(); - boolean interfaceHasFreeSlots = false; - boolean interfaceHasBrokenRecipes = false; - - // Search if the current inventory holds a pattern containing the search term. - if( !found || AEConfig.instance.showOnlyInterfacesWithFreeSlotsInInterfaceTerminal || onlyBrokenRecipes) - { - for( final ItemStack itemStack : entry.getInventory() ) - { - // If only Interfaces with empty slots should be shown, check that here - if( itemStack == null ) - { - interfaceHasFreeSlots = true; - continue; - } - - if (onlyBrokenRecipes && recipeIsBroken(itemStack)) - { - interfaceHasBrokenRecipes = true; - } - - if ( - (!searchFieldInputs.isEmpty() && itemStackMatchesSearchTerm(itemStack, searchFieldInputs, 0)) || - (!searchFieldOutputs.isEmpty() && itemStackMatchesSearchTerm(itemStack, searchFieldOutputs, 1)) - ) - { - found = true; - matchedStacks.add( itemStack ); - } - - } - } - - if ( - (found && entry.getName().toLowerCase().contains( searchFieldNames )) && - (!onlyMolecularAssemblers || entry.getUnlocalizedName().contains(MOLECULAR_ASSEMBLER)) && - (!AEConfig.instance.showOnlyInterfacesWithFreeSlotsInInterfaceTerminal || interfaceHasFreeSlots) && - (!onlyBrokenRecipes || interfaceHasBrokenRecipes) - ) - { - this.byName.put( entry.getName(), entry ); - cachedSearch.add( entry ); - } - else - { - cachedSearch.remove( entry ); - } - - } - - this.names.clear(); - this.names.addAll( this.byName.keySet() ); - - Collections.sort( this.names ); - - this.lines.clear(); - this.lines.ensureCapacity( this.names.size() + this.byId.size() ); - - for( final String n : this.names ) - { - this.lines.add( n ); - final ArrayList clientInventories = new ArrayList<>( this.byName.get( n ) ); - Collections.sort( clientInventories ); - this.lines.addAll( clientInventories ); - } - - this.setScrollBar(); - } - - private boolean itemStackMatchesSearchTerm( final ItemStack itemStack, final String searchTerm, int pass ) - { - if( itemStack == null ) - { - return false; - } - - final NBTTagCompound encodedValue = itemStack.getTagCompound(); - - if( encodedValue == null ) - { - return false; - } - - final NBTTagList tags = encodedValue.getTagList( pass == 0 ? "in" : "out", 10 ); - final boolean containsInvalidDisplayName = GuiText.UnknownItem.getLocal().toLowerCase().contains(searchTerm); - - for( int i = 0; i < tags.tagCount(); i++ ) - { - final NBTTagCompound tag = tags.getCompoundTagAt( i ); - final ItemStack parsedItemStack = ItemStack.loadItemStackFromNBT( tag ); - - if( parsedItemStack != null ) - { - final String displayName = Platform.getItemDisplayName( AEApi.instance().storage().createItemStack( parsedItemStack ) ).toLowerCase(); - if( displayName.contains( searchTerm ) ) - { - return true; - } - } - else if (containsInvalidDisplayName && !tag.hasNoTags()) - { - return true; - } - } - - return false; - } - - private boolean recipeIsBroken( final ItemStack itemStack ) - { - - if( itemStack == null ) - { - return false; - } - - final NBTTagCompound encodedValue = itemStack.getTagCompound(); - if( encodedValue == null ) - { - return true; - } - - final World w = CommonHelper.proxy.getWorld(); - if( w == null ) - { - return false; - } - - try - { - new PatternHelper(itemStack, w); - return false; - } - catch( final Throwable t ) - { - return true; - } - } - - /** - * Tries to retrieve a cache for a with search term as keyword. - *

- * If this cache should be empty, it will populate it with an earlier cache if available or at least the cache for - * the empty string. - * - * @param searchTerm the corresponding search - * @return a Set matching a superset of the search term - */ - private Set getCacheForSearchTerm( final String searchTerm ) - { - if( !this.cachedSearches.containsKey( searchTerm ) ) - { - this.cachedSearches.put( searchTerm, new HashSet<>() ); - } - - final Set cache = this.cachedSearches.get( searchTerm ); - - if( cache.isEmpty() && searchTerm.length() > 1 ) - { - cache.addAll( this.getCacheForSearchTerm( searchTerm.substring( 0, searchTerm.length() - 1 ) ) ); - return cache; - } - - return cache; - } - - private int getMaxRows() - { - return AEConfig.instance.getConfigManager().getSetting( Settings.TERMINAL_STYLE ) == TerminalStyle.SMALL ? AEConfig.instance.InterfaceTerminalSmallSize : Integer.MAX_VALUE; - } - - private ClientDCInternalInv getById( final long id, final long sortBy, final String unlocalizedName ) - { - ClientDCInternalInv o = this.byId.get( id ); - - if( o == null ) - { - this.byId.put( id, o = new ClientDCInternalInv( 9, id, sortBy, unlocalizedName ) ); - this.refreshList = true; - } - - return o; - } - - public boolean isOverTextField(final int mousex, final int mousey) - { - return searchFieldInputs.isMouseIn(mousex, mousey) || searchFieldOutputs.isMouseIn(mousex, mousey) || searchFieldNames.isMouseIn(mousex, mousey); - } - - public void setTextFieldValue(final String displayName, final int mousex, final int mousey, final ItemStack stack) - { - - if (searchFieldInputs.isMouseIn(mousex, mousey)) { - searchFieldInputs.setText(displayName); - } else if (searchFieldOutputs.isMouseIn(mousex, mousey)) { - searchFieldOutputs.setText(displayName); - } else if (searchFieldNames.isMouseIn(mousex, mousey)) { - searchFieldNames.setText(displayName); - } - - } + public void postUpdate(final NBTTagCompound in) { + if (in.getBoolean("clear")) { + this.byId.clear(); + this.refreshList = true; + } + + for (final Object oKey : in.func_150296_c()) { + final String key = (String) oKey; + if (key.startsWith("=")) { + try { + final long id = Long.parseLong(key.substring(1), Character.MAX_RADIX); + final NBTTagCompound invData = in.getCompoundTag(key); + final ClientDCInternalInv current = + this.getById(id, invData.getLong("sortBy"), invData.getString("un")); + int X = invData.getInteger("x"); + int Y = invData.getInteger("y"); + int Z = invData.getInteger("z"); + int dim = invData.getInteger("dim"); + blockPosHashMap.put(current, new DimensionalCoord(X, Y, Z, dim)); + + for (int x = 0; x < current.getInventory().getSizeInventory(); x++) { + final String which = Integer.toString(x); + if (invData.hasKey(which)) { + current.getInventory() + .setInventorySlotContents( + x, ItemStack.loadItemStackFromNBT(invData.getCompoundTag(which))); + } + } + } catch (final NumberFormatException ignored) { + } + } + } + + if (this.refreshList) { + this.refreshList = false; + // invalid caches on refresh + this.cachedSearches.clear(); + this.refreshList(); + } + } + + /** + * Rebuilds the list of interfaces. + *

+ * Respects a search term if present (ignores case) and adding only matching patterns. + */ + private void refreshList() { + this.byName.clear(); + this.buttonList.clear(); + this.matchedStacks.clear(); + + final String searchFieldInputs = this.searchFieldInputs.getText().toLowerCase(); + final String searchFieldOutputs = this.searchFieldOutputs.getText().toLowerCase(); + final String searchFieldNames = this.searchFieldNames.getText().toLowerCase(); + + final Set cachedSearch = this.getCacheForSearchTerm("IN:" + searchFieldInputs + "OUT:" + + searchFieldOutputs + "NAME:" + + searchFieldNames + AEConfig.instance.showOnlyInterfacesWithFreeSlotsInInterfaceTerminal + + onlyMolecularAssemblers + + onlyBrokenRecipes); + final boolean rebuild = cachedSearch.isEmpty(); + + for (final ClientDCInternalInv entry : this.byId.values()) { + // ignore inventory if not doing a full rebuild and cache already marks it as miss. + if (!rebuild && !cachedSearch.contains(entry)) { + continue; + } + + // Shortcut to skip any filter if search term is ""/empty + boolean found = searchFieldInputs.isEmpty() && searchFieldOutputs.isEmpty(); + boolean interfaceHasFreeSlots = false; + boolean interfaceHasBrokenRecipes = false; + + // Search if the current inventory holds a pattern containing the search term. + if (!found || AEConfig.instance.showOnlyInterfacesWithFreeSlotsInInterfaceTerminal || onlyBrokenRecipes) { + for (final ItemStack itemStack : entry.getInventory()) { + // If only Interfaces with empty slots should be shown, check that here + if (itemStack == null) { + interfaceHasFreeSlots = true; + continue; + } + + if (onlyBrokenRecipes && recipeIsBroken(itemStack)) { + interfaceHasBrokenRecipes = true; + } + + if ((!searchFieldInputs.isEmpty() && itemStackMatchesSearchTerm(itemStack, searchFieldInputs, 0)) + || (!searchFieldOutputs.isEmpty() + && itemStackMatchesSearchTerm(itemStack, searchFieldOutputs, 1))) { + found = true; + matchedStacks.add(itemStack); + } + } + } + + if ((found && entry.getName().toLowerCase().contains(searchFieldNames)) + && (!onlyMolecularAssemblers || entry.getUnlocalizedName().contains(MOLECULAR_ASSEMBLER)) + && (!AEConfig.instance.showOnlyInterfacesWithFreeSlotsInInterfaceTerminal || interfaceHasFreeSlots) + && (!onlyBrokenRecipes || interfaceHasBrokenRecipes)) { + this.byName.put(entry.getName(), entry); + cachedSearch.add(entry); + } else { + cachedSearch.remove(entry); + } + } + + this.names.clear(); + this.names.addAll(this.byName.keySet()); + + Collections.sort(this.names); + + this.lines.clear(); + this.lines.ensureCapacity(this.names.size() + this.byId.size()); + + for (final String n : this.names) { + this.lines.add(n); + final ArrayList clientInventories = new ArrayList<>(this.byName.get(n)); + Collections.sort(clientInventories); + this.lines.addAll(clientInventories); + } + + this.setScrollBar(); + } + + private boolean itemStackMatchesSearchTerm(final ItemStack itemStack, final String searchTerm, int pass) { + if (itemStack == null) { + return false; + } + + final NBTTagCompound encodedValue = itemStack.getTagCompound(); + if (encodedValue == null) { + return false; + } + + final NBTTagList tags = encodedValue.getTagList(pass == 0 ? "in" : "out", 10); + final boolean containsInvalidDisplayName = + GuiText.UnknownItem.getLocal().toLowerCase().contains(searchTerm); + + for (int i = 0; i < tags.tagCount(); i++) { + final NBTTagCompound tag = tags.getCompoundTagAt(i); + final ItemStack parsedItemStack = ItemStack.loadItemStackFromNBT(tag); + + if (parsedItemStack != null) { + final String displayName = Platform.getItemDisplayName( + AEApi.instance().storage().createItemStack(parsedItemStack)) + .toLowerCase(); + if (displayName.contains(searchTerm)) { + return true; + } + } else if (containsInvalidDisplayName && !tag.hasNoTags()) { + return true; + } + } + + return false; + } + + private boolean recipeIsBroken(final ItemStack itemStack) { + + if (itemStack == null) { + return false; + } + + final NBTTagCompound encodedValue = itemStack.getTagCompound(); + if (encodedValue == null) { + return true; + } + + final World w = CommonHelper.proxy.getWorld(); + if (w == null) { + return false; + } + + try { + new PatternHelper(itemStack, w); + return false; + } catch (final Throwable t) { + return true; + } + } + + /** + * Tries to retrieve a cache for a with search term as keyword. + *

+ * If this cache should be empty, it will populate it with an earlier cache if available or at least the cache for + * the empty string. + * + * @param searchTerm the corresponding search + * @return a Set matching a superset of the search term + */ + private Set getCacheForSearchTerm(final String searchTerm) { + if (!this.cachedSearches.containsKey(searchTerm)) { + this.cachedSearches.put(searchTerm, new HashSet<>()); + } + + final Set cache = this.cachedSearches.get(searchTerm); + + if (cache.isEmpty() && searchTerm.length() > 1) { + cache.addAll(this.getCacheForSearchTerm(searchTerm.substring(0, searchTerm.length() - 1))); + return cache; + } + + return cache; + } + + private int getMaxRows() { + return AEConfig.instance.getConfigManager().getSetting(Settings.TERMINAL_STYLE) == TerminalStyle.SMALL + ? AEConfig.instance.InterfaceTerminalSmallSize + : Integer.MAX_VALUE; + } + + private ClientDCInternalInv getById(final long id, final long sortBy, final String unlocalizedName) { + ClientDCInternalInv o = this.byId.get(id); + + if (o == null) { + this.byId.put(id, o = new ClientDCInternalInv(9, id, sortBy, unlocalizedName)); + this.refreshList = true; + } + + return o; + } + + public boolean isOverTextField(final int mousex, final int mousey) { + return searchFieldInputs.isMouseIn(mousex, mousey) + || searchFieldOutputs.isMouseIn(mousex, mousey) + || searchFieldNames.isMouseIn(mousex, mousey); + } + + public void setTextFieldValue(final String displayName, final int mousex, final int mousey, final ItemStack stack) { + + if (searchFieldInputs.isMouseIn(mousex, mousey)) { + searchFieldInputs.setText(displayName); + } else if (searchFieldOutputs.isMouseIn(mousex, mousey)) { + searchFieldOutputs.setText(displayName); + } else if (searchFieldNames.isMouseIn(mousex, mousey)) { + searchFieldNames.setText(displayName); + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiLevelEmitter.java b/src/main/java/appeng/client/gui/implementations/GuiLevelEmitter.java index 894a1a15b25..538f09d2e23 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiLevelEmitter.java +++ b/src/main/java/appeng/client/gui/implementations/GuiLevelEmitter.java @@ -18,258 +18,231 @@ package appeng.client.gui.implementations; - import appeng.api.config.*; import appeng.client.gui.widgets.GuiImgButton; import appeng.client.gui.widgets.GuiNumberBox; import appeng.container.implementations.ContainerLevelEmitter; import appeng.core.AEConfig; import appeng.core.AELog; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketConfigButton; import appeng.core.sync.packets.PacketValueConfig; import appeng.parts.automation.PartLevelEmitter; +import java.io.IOException; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Mouse; -import java.io.IOException; - - -public class GuiLevelEmitter extends GuiUpgradeable -{ - - private GuiNumberBox level; - - private GuiButton plus1; - private GuiButton plus10; - private GuiButton plus100; - private GuiButton plus1000; - private GuiButton minus1; - private GuiButton minus10; - private GuiButton minus100; - private GuiButton minus1000; - - private GuiImgButton levelMode; - private GuiImgButton craftingMode; - - public GuiLevelEmitter( final InventoryPlayer inventoryPlayer, final PartLevelEmitter te ) - { - super( new ContainerLevelEmitter( inventoryPlayer, te ) ); - } - - @Override - public void initGui() - { - super.initGui(); - - this.level = new GuiNumberBox( this.fontRendererObj, this.guiLeft + 24, this.guiTop + 43, 79, this.fontRendererObj.FONT_HEIGHT, Long.class ); - this.level.setEnableBackgroundDrawing( false ); - this.level.setMaxStringLength( 16 ); - this.level.setTextColor( GuiColors.LevelEmitterValue.getColor() ); - this.level.setVisible( true ); - this.level.setFocused( true ); - ( (ContainerLevelEmitter) this.inventorySlots ).setTextField( this.level ); - } - - @Override - protected void addButtons() - { - this.levelMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL ); - this.redstoneMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.REDSTONE_EMITTER, RedstoneMode.LOW_SIGNAL ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.craftingMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.CRAFT_VIA_REDSTONE, YesNo.NO ); - - final int a = AEConfig.instance.levelByStackAmounts( 0 ); - final int b = AEConfig.instance.levelByStackAmounts( 1 ); - final int c = AEConfig.instance.levelByStackAmounts( 2 ); - final int d = AEConfig.instance.levelByStackAmounts( 3 ); - - this.buttonList.add( this.plus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 17, 22, 20, "+" + a ) ); - this.buttonList.add( this.plus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 17, 28, 20, "+" + b ) ); - this.buttonList.add( this.plus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 17, 32, 20, "+" + c ) ); - this.buttonList.add( this.plus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 17, 38, 20, "+" + d ) ); - - this.buttonList.add( this.minus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 59, 22, 20, "-" + a ) ); - this.buttonList.add( this.minus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 59, 28, 20, "-" + b ) ); - this.buttonList.add( this.minus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 59, 32, 20, "-" + c ) ); - this.buttonList.add( this.minus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 59, 38, 20, "-" + d ) ); - - this.buttonList.add( this.levelMode ); - this.buttonList.add( this.redstoneMode ); - this.buttonList.add( this.fuzzyMode ); - this.buttonList.add( this.craftingMode ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - final boolean notCraftingMode = this.bc.getInstalledUpgrades( Upgrades.CRAFTING ) == 0; - - // configure enabled status... - this.level.setEnabled( notCraftingMode ); - this.plus1.enabled = notCraftingMode; - this.plus10.enabled = notCraftingMode; - this.plus100.enabled = notCraftingMode; - this.plus1000.enabled = notCraftingMode; - this.minus1.enabled = notCraftingMode; - this.minus10.enabled = notCraftingMode; - this.minus100.enabled = notCraftingMode; - this.minus1000.enabled = notCraftingMode; - this.levelMode.enabled = notCraftingMode; - this.redstoneMode.enabled = notCraftingMode; - - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - - if( this.craftingMode != null ) - { - this.craftingMode.set( this.cvb.getCraftingMode() ); - } - - if( this.levelMode != null ) - { - this.levelMode.set( ( (ContainerLevelEmitter) this.cvb ).getLevelMode() ); - } - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - super.drawBG( offsetX, offsetY, mouseX, mouseY ); - this.level.drawTextBox(); - } - - @Override - protected void handleButtonVisibility() - { - this.craftingMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ); - this.fuzzyMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ); - } - - @Override - protected String getBackground() - { - return "guis/lvlemitter.png"; - } - - @Override - protected GuiText getName() - { - return GuiText.LevelEmitter; - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - final boolean backwards = Mouse.isButtonDown( 1 ); - - if( btn == this.craftingMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.craftingMode.getSetting(), backwards ) ); - } - - if( btn == this.levelMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.levelMode.getSetting(), backwards ) ); - } - - final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; - final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; - - if( isPlus || isMinus ) - { - this.addQty( this.getQty( btn ) ); - } - } - - private void addQty( final long i ) - { - try - { - String Out = this.level.getText(); - - boolean Fixed = false; - while( Out.startsWith( "0" ) && Out.length() > 1 ) - { - Out = Out.substring( 1 ); - Fixed = true; - } - - if( Fixed ) - { - this.level.setText( Out ); - } - - if( Out.isEmpty() ) - { - Out = "0"; - } - - long result = Long.parseLong( Out ); - result += i; - if( result < 0 ) - { - result = 0; - } - - this.level.setText( Out = Long.toString( result ) ); - - NetworkHandler.instance.sendToServer( new PacketValueConfig( "LevelEmitter.Value", Out ) ); - } - catch( final NumberFormatException e ) - { - // nope.. - this.level.setText( "0" ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - - @Override - protected void keyTyped( final char character, final int key ) - { - if( !this.checkHotbarKeys( key ) ) - { - if( ( key == 211 || key == 205 || key == 203 || key == 14 || Character.isDigit( character ) ) && this.level.textboxKeyTyped( character, key ) ) - { - try - { - String Out = this.level.getText(); - - boolean Fixed = false; - while( Out.startsWith( "0" ) && Out.length() > 1 ) - { - Out = Out.substring( 1 ); - Fixed = true; - } - - if( Fixed ) - { - this.level.setText( Out ); - } - - if( Out.isEmpty() ) - { - Out = "0"; - } - - NetworkHandler.instance.sendToServer( new PacketValueConfig( "LevelEmitter.Value", Out ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - else - { - super.keyTyped( character, key ); - } - } - } +public class GuiLevelEmitter extends GuiUpgradeable { + + private GuiNumberBox level; + + private GuiButton plus1; + private GuiButton plus10; + private GuiButton plus100; + private GuiButton plus1000; + private GuiButton minus1; + private GuiButton minus10; + private GuiButton minus100; + private GuiButton minus1000; + + private GuiImgButton levelMode; + private GuiImgButton craftingMode; + + public GuiLevelEmitter(final InventoryPlayer inventoryPlayer, final PartLevelEmitter te) { + super(new ContainerLevelEmitter(inventoryPlayer, te)); + } + + @Override + public void initGui() { + super.initGui(); + + this.level = new GuiNumberBox( + this.fontRendererObj, + this.guiLeft + 24, + this.guiTop + 43, + 79, + this.fontRendererObj.FONT_HEIGHT, + Long.class); + this.level.setEnableBackgroundDrawing(false); + this.level.setMaxStringLength(16); + this.level.setTextColor(GuiColors.LevelEmitterValue.getColor()); + this.level.setVisible(true); + this.level.setFocused(true); + ((ContainerLevelEmitter) this.inventorySlots).setTextField(this.level); + } + + @Override + protected void addButtons() { + this.levelMode = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL); + this.redstoneMode = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 28, Settings.REDSTONE_EMITTER, RedstoneMode.LOW_SIGNAL); + this.fuzzyMode = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 48, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.craftingMode = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 48, Settings.CRAFT_VIA_REDSTONE, YesNo.NO); + + final int a = AEConfig.instance.levelByStackAmounts(0); + final int b = AEConfig.instance.levelByStackAmounts(1); + final int c = AEConfig.instance.levelByStackAmounts(2); + final int d = AEConfig.instance.levelByStackAmounts(3); + + this.buttonList.add(this.plus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 17, 22, 20, "+" + a)); + this.buttonList.add(this.plus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 17, 28, 20, "+" + b)); + this.buttonList.add(this.plus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 17, 32, 20, "+" + c)); + this.buttonList.add(this.plus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 17, 38, 20, "+" + d)); + + this.buttonList.add(this.minus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 59, 22, 20, "-" + a)); + this.buttonList.add(this.minus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 59, 28, 20, "-" + b)); + this.buttonList.add(this.minus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 59, 32, 20, "-" + c)); + this.buttonList.add(this.minus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 59, 38, 20, "-" + d)); + + this.buttonList.add(this.levelMode); + this.buttonList.add(this.redstoneMode); + this.buttonList.add(this.fuzzyMode); + this.buttonList.add(this.craftingMode); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + final boolean notCraftingMode = this.bc.getInstalledUpgrades(Upgrades.CRAFTING) == 0; + + // configure enabled status... + this.level.setEnabled(notCraftingMode); + this.plus1.enabled = notCraftingMode; + this.plus10.enabled = notCraftingMode; + this.plus100.enabled = notCraftingMode; + this.plus1000.enabled = notCraftingMode; + this.minus1.enabled = notCraftingMode; + this.minus10.enabled = notCraftingMode; + this.minus100.enabled = notCraftingMode; + this.minus1000.enabled = notCraftingMode; + this.levelMode.enabled = notCraftingMode; + this.redstoneMode.enabled = notCraftingMode; + + super.drawFG(offsetX, offsetY, mouseX, mouseY); + + if (this.craftingMode != null) { + this.craftingMode.set(this.cvb.getCraftingMode()); + } + + if (this.levelMode != null) { + this.levelMode.set(((ContainerLevelEmitter) this.cvb).getLevelMode()); + } + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + super.drawBG(offsetX, offsetY, mouseX, mouseY); + this.level.drawTextBox(); + } + + @Override + protected void handleButtonVisibility() { + this.craftingMode.setVisibility(this.bc.getInstalledUpgrades(Upgrades.CRAFTING) > 0); + this.fuzzyMode.setVisibility(this.bc.getInstalledUpgrades(Upgrades.FUZZY) > 0); + } + + @Override + protected String getBackground() { + return "guis/lvlemitter.png"; + } + + @Override + protected GuiText getName() { + return GuiText.LevelEmitter; + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + final boolean backwards = Mouse.isButtonDown(1); + + if (btn == this.craftingMode) { + NetworkHandler.instance.sendToServer(new PacketConfigButton(this.craftingMode.getSetting(), backwards)); + } + + if (btn == this.levelMode) { + NetworkHandler.instance.sendToServer(new PacketConfigButton(this.levelMode.getSetting(), backwards)); + } + + final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; + final boolean isMinus = + btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; + + if (isPlus || isMinus) { + this.addQty(this.getQty(btn)); + } + } + + private void addQty(final long i) { + try { + String Out = this.level.getText(); + + boolean Fixed = false; + while (Out.startsWith("0") && Out.length() > 1) { + Out = Out.substring(1); + Fixed = true; + } + + if (Fixed) { + this.level.setText(Out); + } + + if (Out.isEmpty()) { + Out = "0"; + } + + long result = Long.parseLong(Out); + result += i; + if (result < 0) { + result = 0; + } + + this.level.setText(Out = Long.toString(result)); + + NetworkHandler.instance.sendToServer(new PacketValueConfig("LevelEmitter.Value", Out)); + } catch (final NumberFormatException e) { + // nope.. + this.level.setText("0"); + } catch (final IOException e) { + AELog.debug(e); + } + } + + @Override + protected void keyTyped(final char character, final int key) { + if (!this.checkHotbarKeys(key)) { + if ((key == 211 || key == 205 || key == 203 || key == 14 || Character.isDigit(character)) + && this.level.textboxKeyTyped(character, key)) { + try { + String Out = this.level.getText(); + + boolean Fixed = false; + while (Out.startsWith("0") && Out.length() > 1) { + Out = Out.substring(1); + Fixed = true; + } + + if (Fixed) { + this.level.setText(Out); + } + + if (Out.isEmpty()) { + Out = "0"; + } + + NetworkHandler.instance.sendToServer(new PacketValueConfig("LevelEmitter.Value", Out)); + } catch (final IOException e) { + AELog.debug(e); + } + } else { + super.keyTyped(character, key); + } + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiMAC.java b/src/main/java/appeng/client/gui/implementations/GuiMAC.java index 2175a4c2399..b90f6718e43 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiMAC.java +++ b/src/main/java/appeng/client/gui/implementations/GuiMAC.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.config.RedstoneMode; import appeng.api.config.Settings; import appeng.client.gui.widgets.GuiImgButton; @@ -29,60 +28,52 @@ import appeng.tile.crafting.TileMolecularAssembler; import net.minecraft.entity.player.InventoryPlayer; +public class GuiMAC extends GuiUpgradeable { -public class GuiMAC extends GuiUpgradeable -{ - - private final ContainerMAC container; - private GuiProgressBar pb; + private final ContainerMAC container; + private GuiProgressBar pb; - public GuiMAC( final InventoryPlayer inventoryPlayer, final TileMolecularAssembler te ) - { - super( new ContainerMAC( inventoryPlayer, te ) ); - this.ySize = 197; - this.container = (ContainerMAC) this.inventorySlots; - } + public GuiMAC(final InventoryPlayer inventoryPlayer, final TileMolecularAssembler te) { + super(new ContainerMAC(inventoryPlayer, te)); + this.ySize = 197; + this.container = (ContainerMAC) this.inventorySlots; + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.pb = new GuiProgressBar( this.container, "guis/mac.png", 139, 36, 148, 201, 6, 18, Direction.VERTICAL ); - this.buttonList.add( this.pb ); - } + this.pb = new GuiProgressBar(this.container, "guis/mac.png", 139, 36, 148, 201, 6, 18, Direction.VERTICAL); + this.buttonList.add(this.pb); + } - @Override - protected void addButtons() - { - this.redstoneMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.buttonList.add( this.redstoneMode ); - } + @Override + protected void addButtons() { + this.redstoneMode = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.buttonList.add(this.redstoneMode); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.pb.setFullMsg( this.container.getCurrentProgress() + "%" ); - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - } + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.pb.setFullMsg(this.container.getCurrentProgress() + "%"); + super.drawFG(offsetX, offsetY, mouseX, mouseY); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.pb.xPosition = 148 + this.guiLeft; - this.pb.yPosition = 48 + this.guiTop; - super.drawBG( offsetX, offsetY, mouseX, mouseY ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.pb.xPosition = 148 + this.guiLeft; + this.pb.yPosition = 48 + this.guiTop; + super.drawBG(offsetX, offsetY, mouseX, mouseY); + } - @Override - protected String getBackground() - { - return "guis/mac.png"; - } + @Override + protected String getBackground() { + return "guis/mac.png"; + } - @Override - protected GuiText getName() - { - return GuiText.MolecularAssembler; - } + @Override + protected GuiText getName() { + return GuiText.MolecularAssembler; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java b/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java index 22624926ce4..9f717d559f8 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java +++ b/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.config.*; import appeng.api.implementations.guiobjects.IPortableCell; import appeng.api.implementations.tiles.IMEChest; @@ -40,8 +39,8 @@ import appeng.core.AELog; import appeng.core.CommonHelper; import appeng.core.localization.ButtonToolTips; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.GuiBridge; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketSwitchGuis; @@ -56,6 +55,9 @@ import codechicken.nei.TextField; import cpw.mods.fml.common.Loader; import cpw.mods.fml.relauncher.ReflectionHelper; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.List; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; @@ -63,561 +65,535 @@ import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.List; +public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfigManagerHost, IDropToFillTextField { + + public static int craftingGridOffsetX; + public static int craftingGridOffsetY; + + private static String memoryText = ""; + private final ItemRepo repo; + private final int offsetX = 9; + private final int MAGIC_HEIGHT_NUMBER = 114 + 1; + private final int lowerTextureOffset = 0; + private final IConfigManager configSrc; + private final boolean viewCell; + private final ItemStack[] myCurrentViewCells = new ItemStack[5]; + private final ContainerMEMonitorable monitorableContainer; + private GuiTabButton craftingStatusBtn; + private GuiImgButton craftingStatusImgBtn; + private final MEGuiTextField searchField; + private TextField NEISearchField; + private GuiText myName; + private int perRow = 9; + private int reservedSpace = 0; + private boolean customSortOrder = true; + private int rows = 0; + private int standardSize; + private GuiImgButton ViewBox; + private GuiImgButton SortByBox; + private GuiImgButton SortDirBox; + private GuiImgButton searchBoxSettings; + private GuiImgButton terminalStyleBox; + private GuiImgButton searchStringSave; + private boolean isAutoFocus = false; + private int currentMouseX = 0; + private int currentMouseY = 0; + + public GuiMEMonitorable(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + this(inventoryPlayer, te, new ContainerMEMonitorable(inventoryPlayer, te)); + } + + public GuiMEMonitorable( + final InventoryPlayer inventoryPlayer, final ITerminalHost te, final ContainerMEMonitorable c) { + + super(c); + + final GuiScrollbar scrollbar = new GuiScrollbar(); + this.setScrollBar(scrollbar); + this.repo = new ItemRepo(scrollbar, this); + + this.xSize = 195; + this.ySize = 204; + + this.standardSize = this.xSize; + + this.configSrc = ((IConfigurableObject) this.inventorySlots).getConfigManager(); + (this.monitorableContainer = (ContainerMEMonitorable) this.inventorySlots).setGui(this); + + this.viewCell = te instanceof IViewCellStorage; + + if (te instanceof TileSecurity) { + this.myName = GuiText.Security; + } else if (te instanceof WirelessTerminalGuiObject) { + this.myName = GuiText.WirelessTerminal; + } else if (te instanceof IPortableCell) { + this.myName = GuiText.PortableCell; + } else if (te instanceof IMEChest) { + this.myName = GuiText.Chest; + } else if (te instanceof AbstractPartTerminal) { + this.myName = GuiText.Terminal; + } + + this.searchField = new MEGuiTextField(90, 12, ButtonToolTips.SearchStringTooltip.getLocal()) { + @Override + public void onTextChange(final String oldText) { + final String text = getText(); + repo.setSearchString(text); + repo.updateView(); + setScrollBar(); + } + }; + + if (Loader.isModLoaded("NotEnoughItems")) { + + try { + final Class clazz = + ReflectionHelper.getClass(this.getClass().getClassLoader(), "codechicken.nei.LayoutManager"); + final Field fldSearchField = clazz.getField("searchField"); + this.NEISearchField = (TextField) fldSearchField.get(clazz); + } catch (NoSuchFieldException | IllegalAccessException e) { + e.printStackTrace(); + } + } + } + + public void postUpdate(final List list) { + for (final IAEItemStack is : list) { + this.repo.postUpdate(is); + } + + this.repo.updateView(); + this.setScrollBar(); + } + + private void setScrollBar() { + this.getScrollBar().setTop(18).setLeft(175).setHeight(this.rows * 18 - 2); + this.getScrollBar() + .setRange( + 0, (this.repo.size() + this.perRow - 1) / this.perRow - this.rows, Math.max(1, this.rows / 6)); + } + + @Override + protected void actionPerformed(final GuiButton btn) { + + if (btn == this.craftingStatusBtn || btn == this.craftingStatusImgBtn) { + NetworkHandler.instance.sendToServer(new PacketSwitchGuis(GuiBridge.GUI_CRAFTING_STATUS)); + } + + if (btn instanceof GuiImgButton) { + final GuiImgButton iBtn = (GuiImgButton) btn; + if (iBtn.getSetting() != Settings.ACTIONS) { + final Enum cv = iBtn.getCurrentValue(); + final boolean backwards = Mouse.isButtonDown(1); + final Enum next = + Platform.rotateEnum(cv, backwards, iBtn.getSetting().getPossibleValues()); + + if (btn == this.terminalStyleBox) { + AEConfig.instance.settings.putSetting(iBtn.getSetting(), next); + } else if (btn == this.searchBoxSettings) { + AEConfig.instance.settings.putSetting(iBtn.getSetting(), next); + } else if (btn == this.searchStringSave) { + AEConfig.instance.preserveSearchBar = next == YesNo.YES; + } else { + try { + NetworkHandler.instance.sendToServer( + new PacketValueConfig(iBtn.getSetting().name(), next.name())); + } catch (final IOException e) { + AELog.debug(e); + } + } + + iBtn.set(next); + + if (next.getClass() == SearchBoxMode.class || next.getClass() == TerminalStyle.class) { + this.reinitalize(); + } + } + } + } + + private void reinitalize() { + this.buttonList.clear(); + this.initGui(); + } + + @Override + public void initGui() { + Keyboard.enableRepeatEvents(true); + + this.perRow = AEConfig.instance.getConfigManager().getSetting(Settings.TERMINAL_STYLE) != TerminalStyle.FULL + ? 9 + : 9 + ((this.width - this.standardSize) / 18); + this.rows = calculateRowsCount(); + + this.getMeSlots().clear(); + for (int y = 0; y < this.rows; y++) { + for (int x = 0; x < this.perRow; x++) { + this.getMeSlots() + .add(new InternalSlotME(this.repo, x + y * this.perRow, this.offsetX + x * 18, 18 + y * 18)); + } + } + + if (AEConfig.instance.getConfigManager().getSetting(Settings.TERMINAL_STYLE) != TerminalStyle.FULL) { + this.xSize = this.standardSize + ((this.perRow - 9) * 18); + } else { + this.xSize = this.standardSize; + } + + super.initGui(); + // full size : 204 + // extra slots : 72 + // slot 18 + + this.ySize = MAGIC_HEIGHT_NUMBER + this.rows * 18 + this.reservedSpace; + final int unusedSpace = this.height - this.ySize; + this.guiTop = (int) Math.floor(unusedSpace / (unusedSpace < 0 ? 3.8f : 2.0f)); + + int offset = this.guiTop + 8; + + if (this.customSortOrder) { + this.buttonList.add( + this.SortByBox = new GuiImgButton( + this.guiLeft - 18, offset, Settings.SORT_BY, this.configSrc.getSetting(Settings.SORT_BY))); + offset += 20; + } + + if (this.viewCell || this instanceof GuiWirelessTerm) { + this.buttonList.add( + this.ViewBox = new GuiImgButton( + this.guiLeft - 18, + offset, + Settings.VIEW_MODE, + this.configSrc.getSetting(Settings.VIEW_MODE))); + offset += 20; + } + + this.buttonList.add( + this.SortDirBox = new GuiImgButton( + this.guiLeft - 18, + offset, + Settings.SORT_DIRECTION, + this.configSrc.getSetting(Settings.SORT_DIRECTION))); + offset += 20; + + this.buttonList.add( + this.searchBoxSettings = new GuiImgButton( + this.guiLeft - 18, + offset, + Settings.SEARCH_MODE, + AEConfig.instance.settings.getSetting(Settings.SEARCH_MODE))); + offset += 20; + + this.buttonList.add( + this.searchStringSave = new GuiImgButton( + this.guiLeft - 18, + offset, + Settings.SAVE_SEARCH, + AEConfig.instance.preserveSearchBar ? YesNo.YES : YesNo.NO)); + offset += 20; + + if (!(this instanceof GuiMEPortableCell) || this instanceof GuiWirelessTerm) { + this.buttonList.add( + this.terminalStyleBox = new GuiImgButton( + this.guiLeft - 18, + offset, + Settings.TERMINAL_STYLE, + AEConfig.instance.settings.getSetting(Settings.TERMINAL_STYLE))); + offset += 20; + } + + if (this.viewCell || this instanceof GuiWirelessTerm) { + if (AEConfig.instance + .getConfigManager() + .getSetting(Settings.CRAFTING_STATUS) + .equals(CraftingStatus.BUTTON)) { + this.buttonList.add( + this.craftingStatusImgBtn = new GuiImgButton( + this.guiLeft - 18, + offset, + Settings.CRAFTING_STATUS, + AEConfig.instance.settings.getSetting(Settings.CRAFTING_STATUS))); + } else { + this.buttonList.add( + this.craftingStatusBtn = new GuiTabButton( + this.guiLeft + 170, + this.guiTop - 4, + 2 + 11 * 16, + GuiText.CraftingStatus.getLocal(), + itemRender)); + this.craftingStatusBtn.setHideEdge(13); // GuiTabButton implementation // + } + } + + // Enum setting = AEConfig.INSTANCE.getSetting( "Terminal", SearchBoxMode.class, SearchBoxMode.AUTOSEARCH ); + final Enum searchMode = AEConfig.instance.settings.getSetting(Settings.SEARCH_MODE); + this.isAutoFocus = SearchBoxMode.AUTOSEARCH == searchMode || SearchBoxMode.NEI_AUTOSEARCH == searchMode; + + this.searchField.x = this.guiLeft + Math.max(80, this.offsetX); + this.searchField.y = this.guiTop + 4; + this.searchField.setFocused(this.isAutoFocus); + + if (this.isSubGui()) { + this.searchField.setText(memoryText); + } else if (AEConfig.instance.preserveSearchBar) { + this.searchField.setText(memoryText, true); + repo.setSearchString(memoryText); + } + + this.setScrollBar(); + + craftingGridOffsetX = Integer.MAX_VALUE; + craftingGridOffsetY = Integer.MAX_VALUE; + + for (final Object s : this.inventorySlots.inventorySlots) { + if (s instanceof AppEngSlot) { + if (((Slot) s).xDisplayPosition < 197) { + this.repositionSlot((AppEngSlot) s); + } + } + + if (s instanceof SlotCraftingMatrix || s instanceof SlotFakeCraftingMatrix) { + final Slot g = (Slot) s; + if (g.xDisplayPosition > 0 && g.yDisplayPosition > 0) { + craftingGridOffsetX = Math.min(craftingGridOffsetX, g.xDisplayPosition); + craftingGridOffsetY = Math.min(craftingGridOffsetY, g.yDisplayPosition); + } + } + } + + craftingGridOffsetX -= 25; + craftingGridOffsetY -= 6; + } + + protected int calculateRowsCount() { + final boolean hasNEI = IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.NEI); + final int NEIPadding = hasNEI + ? 22 + /** input */ + + 20 + /** top panel */ + : 0; + final int extraSpace = this.height - MAGIC_HEIGHT_NUMBER - NEIPadding - this.reservedSpace; + + return Math.max(3, Math.min(this.getMaxRows(), (int) Math.floor(extraSpace / 18))); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + this.getGuiDisplayName(this.myName.getLocal()), 8, 6, GuiColors.MEMonitorableTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.MEMonitorableInventory.getColor()); + + this.currentMouseX = mouseX; + this.currentMouseY = mouseY; + } + + @Override + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) { + searchField.mouseClicked(xCoord, yCoord, btn); + super.mouseClicked(xCoord, yCoord, btn); + } + + @Override + public void onGuiClosed() { + super.onGuiClosed(); + Keyboard.enableRepeatEvents(false); + memoryText = this.searchField.getText(); + } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + + this.bindTexture(this.getBackground()); + final int x_width = 195; + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, x_width, 18); + + if (this.viewCell || (this instanceof GuiSecurity)) { + this.drawTexturedModalRect(offsetX + x_width, offsetY, x_width, 0, 46, 128); + } + + for (int x = 0; x < this.rows; x++) { + this.drawTexturedModalRect(offsetX, offsetY + 18 + x * 18, 0, 18, x_width, 18); + } + + this.drawTexturedModalRect( + offsetX, + offsetY + 16 + this.rows * 18 + this.lowerTextureOffset, + 0, + 106 - 18 - 18, + x_width, + 99 + this.reservedSpace - this.lowerTextureOffset); + + if (this.viewCell) { + boolean update = false; + + for (int i = 0; i < 5; i++) { + if (this.myCurrentViewCells[i] + != this.monitorableContainer.getCellViewSlot(i).getStack()) { + update = true; + this.myCurrentViewCells[i] = + this.monitorableContainer.getCellViewSlot(i).getStack(); + } + } + + if (update) { + this.repo.setViewCell(this.myCurrentViewCells); + } + } + + searchField.drawTextBox(); + } + + protected String getBackground() { + return "guis/terminal.png"; + } + + @Override + protected boolean isPowered() { + return this.repo.hasPower(); + } + + int getMaxRows() { + return AEConfig.instance.getConfigManager().getSetting(Settings.TERMINAL_STYLE) == TerminalStyle.SMALL + ? AEConfig.instance.MEMonitorableSmallSize + : Integer.MAX_VALUE; + } + + protected void repositionSlot(final AppEngSlot s) { + s.yDisplayPosition = s.getY() + this.ySize - 78 - 5; + } + + @Override + protected void keyTyped(final char character, final int key) { + if (!this.checkHotbarKeys(key)) { + + if (NEISearchField != null + && (NEISearchField.focused() || searchField.isFocused()) + && CommonHelper.proxy.isActionKey(ActionKey.TOGGLE_FOCUS, key)) { + final boolean focused = searchField.isFocused(); + searchField.setFocused(!focused); + NEISearchField.setFocus(focused); + return; + } + + if (NEISearchField != null && NEISearchField.focused()) { + return; + } + + if (searchField.isFocused() && key == Keyboard.KEY_RETURN) { + searchField.setFocused(false); + return; + } + + if (character == ' ' && searchField.getText().isEmpty()) { + return; + } + + final boolean mouseInGui = + this.isPointInRegion(0, 0, this.xSize, this.ySize, this.currentMouseX, this.currentMouseY); + + if (this.isAutoFocus && !searchField.isFocused() && mouseInGui) { + searchField.setFocused(true); + } + + if (!searchField.textboxKeyTyped(character, key)) { + super.keyTyped(character, key); + } + } + } + + @Override + public void updateScreen() { + this.repo.setPower(this.monitorableContainer.isPowered()); + super.updateScreen(); + } + + @Override + public Enum getSortBy() { + return this.configSrc.getSetting(Settings.SORT_BY); + } + + @Override + public Enum getSortDir() { + return this.configSrc.getSetting(Settings.SORT_DIRECTION); + } + + @Override + public Enum getSortDisplay() { + return this.configSrc.getSetting(Settings.VIEW_MODE); + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + if (this.SortByBox != null) { + this.SortByBox.set(this.configSrc.getSetting(Settings.SORT_BY)); + } + + if (this.SortDirBox != null) { + this.SortDirBox.set(this.configSrc.getSetting(Settings.SORT_DIRECTION)); + } + + if (this.ViewBox != null) { + this.ViewBox.set(this.configSrc.getSetting(Settings.VIEW_MODE)); + } + + this.repo.updateView(); + } + + @SuppressWarnings("SameParameterValue") + protected boolean isPointInRegion(int rectX, int rectY, int rectWidth, int rectHeight, int pointX, int pointY) { + pointX -= this.guiLeft; + pointY -= this.guiTop; + return pointX >= rectX - 1 + && pointX < rectX + rectWidth + 1 + && pointY >= rectY - 1 + && pointY < rectY + rectHeight + 1; + } + + int getReservedSpace() { + return this.reservedSpace; + } + + void setReservedSpace(final int reservedSpace) { + this.reservedSpace = reservedSpace; + } + + public boolean isCustomSortOrder() { + return this.customSortOrder; + } + + void setCustomSortOrder(final boolean customSortOrder) { + this.customSortOrder = customSortOrder; + } -public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfigManagerHost, IDropToFillTextField -{ - - public static int craftingGridOffsetX; - public static int craftingGridOffsetY; - - private static String memoryText = ""; - private final ItemRepo repo; - private final int offsetX = 9; - private final int MAGIC_HEIGHT_NUMBER = 114 + 1; - private final int lowerTextureOffset = 0; - private final IConfigManager configSrc; - private final boolean viewCell; - private final ItemStack[] myCurrentViewCells = new ItemStack[5]; - private final ContainerMEMonitorable monitorableContainer; - private GuiTabButton craftingStatusBtn; - private GuiImgButton craftingStatusImgBtn; - private final MEGuiTextField searchField; - private TextField NEISearchField; - private GuiText myName; - private int perRow = 9; - private int reservedSpace = 0; - private boolean customSortOrder = true; - private int rows = 0; - private int standardSize; - private GuiImgButton ViewBox; - private GuiImgButton SortByBox; - private GuiImgButton SortDirBox; - private GuiImgButton searchBoxSettings; - private GuiImgButton terminalStyleBox; - private GuiImgButton searchStringSave; - private boolean isAutoFocus = false; - private int currentMouseX = 0; - private int currentMouseY = 0; - - public GuiMEMonitorable( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - this( inventoryPlayer, te, new ContainerMEMonitorable( inventoryPlayer, te ) ); - } - - public GuiMEMonitorable( final InventoryPlayer inventoryPlayer, final ITerminalHost te, final ContainerMEMonitorable c ) - { - - super( c ); - - final GuiScrollbar scrollbar = new GuiScrollbar(); - this.setScrollBar( scrollbar ); - this.repo = new ItemRepo( scrollbar, this ); - - this.xSize = 195; - this.ySize = 204; - - this.standardSize = this.xSize; - - this.configSrc = ( (IConfigurableObject) this.inventorySlots ).getConfigManager(); - ( this.monitorableContainer = (ContainerMEMonitorable) this.inventorySlots ).setGui( this ); - - this.viewCell = te instanceof IViewCellStorage; - - if( te instanceof TileSecurity ) - { - this.myName = GuiText.Security; - } - else if( te instanceof WirelessTerminalGuiObject ) - { - this.myName = GuiText.WirelessTerminal; - } - else if( te instanceof IPortableCell ) - { - this.myName = GuiText.PortableCell; - } - else if( te instanceof IMEChest ) - { - this.myName = GuiText.Chest; - } - else if( te instanceof AbstractPartTerminal ) - { - this.myName = GuiText.Terminal; - } - - this.searchField = new MEGuiTextField( 90, 12, ButtonToolTips.SearchStringTooltip.getLocal()) - { - @Override - public void onTextChange(final String oldText) - { - final String text = getText(); - repo.setSearchString(text); - repo.updateView(); - setScrollBar(); - } - }; - - if (Loader.isModLoaded("NotEnoughItems")) { - - try { - final Class clazz = ReflectionHelper.getClass(this.getClass().getClassLoader(), "codechicken.nei.LayoutManager"); - final Field fldSearchField = clazz.getField("searchField"); - this.NEISearchField = (TextField) fldSearchField.get(clazz); - } catch (NoSuchFieldException | IllegalAccessException e) { - e.printStackTrace(); - } - - } - - } - - public void postUpdate( final List list ) - { - for( final IAEItemStack is : list ) - { - this.repo.postUpdate( is ); - } - - this.repo.updateView(); - this.setScrollBar(); - } - - private void setScrollBar() - { - this.getScrollBar().setTop( 18 ).setLeft( 175 ).setHeight( this.rows * 18 - 2 ); - this.getScrollBar().setRange( 0, ( this.repo.size() + this.perRow - 1 ) / this.perRow - this.rows, Math.max( 1, this.rows / 6 ) ); - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - - if( btn == this.craftingStatusBtn || btn == this.craftingStatusImgBtn ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_CRAFTING_STATUS ) ); - } - - if( btn instanceof GuiImgButton ) - { - final GuiImgButton iBtn = (GuiImgButton) btn; - if( iBtn.getSetting() != Settings.ACTIONS ) - { - final Enum cv = iBtn.getCurrentValue(); - final boolean backwards = Mouse.isButtonDown( 1 ); - final Enum next = Platform.rotateEnum( cv, backwards, iBtn.getSetting().getPossibleValues() ); - - if( btn == this.terminalStyleBox ) - { - AEConfig.instance.settings.putSetting( iBtn.getSetting(), next ); - } - else if( btn == this.searchBoxSettings ) - { - AEConfig.instance.settings.putSetting( iBtn.getSetting(), next ); - } - else if( btn == this.searchStringSave ) - { - AEConfig.instance.preserveSearchBar = next == YesNo.YES; - } - else - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( iBtn.getSetting().name(), next.name() ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - - iBtn.set( next ); - - if( next.getClass() == SearchBoxMode.class || next.getClass() == TerminalStyle.class ) - { - this.reinitalize(); - } - } - } - } - - private void reinitalize() - { - this.buttonList.clear(); - this.initGui(); - } - - @Override - public void initGui() - { - Keyboard.enableRepeatEvents( true ); - - this.perRow = AEConfig.instance.getConfigManager().getSetting( Settings.TERMINAL_STYLE ) != TerminalStyle.FULL ? 9 : 9 + ( ( this.width - this.standardSize ) / 18 ); - this.rows = calculateRowsCount(); - - this.getMeSlots().clear(); - for( int y = 0; y < this.rows; y++ ) - { - for( int x = 0; x < this.perRow; x++ ) - { - this.getMeSlots().add( new InternalSlotME( this.repo, x + y * this.perRow, this.offsetX + x * 18, 18 + y * 18 ) ); - } - } - - if( AEConfig.instance.getConfigManager().getSetting( Settings.TERMINAL_STYLE ) != TerminalStyle.FULL ) - { - this.xSize = this.standardSize + ( ( this.perRow - 9 ) * 18 ); - } - else - { - this.xSize = this.standardSize; - } - - super.initGui(); - // full size : 204 - // extra slots : 72 - // slot 18 - - this.ySize = MAGIC_HEIGHT_NUMBER + this.rows * 18 + this.reservedSpace; - final int unusedSpace = this.height - this.ySize; - this.guiTop = (int) Math.floor( unusedSpace / ( unusedSpace < 0 ? 3.8f : 2.0f ) ); - - int offset = this.guiTop + 8; - - if( this.customSortOrder ) - { - this.buttonList.add( this.SortByBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.SORT_BY, this.configSrc.getSetting( Settings.SORT_BY ) ) ); - offset += 20; - } - - if( this.viewCell || this instanceof GuiWirelessTerm ) - { - this.buttonList.add( this.ViewBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.VIEW_MODE, this.configSrc.getSetting( Settings.VIEW_MODE ) ) ); - offset += 20; - } - - this.buttonList.add( this.SortDirBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.SORT_DIRECTION, this.configSrc.getSetting( Settings.SORT_DIRECTION ) ) ); - offset += 20; - - this.buttonList.add( this.searchBoxSettings = new GuiImgButton( this.guiLeft - 18, offset, Settings.SEARCH_MODE, AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ) ) ); - offset += 20; - - this.buttonList.add( this.searchStringSave = new GuiImgButton( this.guiLeft - 18, offset, Settings.SAVE_SEARCH, AEConfig.instance.preserveSearchBar ? YesNo.YES : YesNo.NO ) ); - offset += 20; - - if( !( this instanceof GuiMEPortableCell ) || this instanceof GuiWirelessTerm ) - { - this.buttonList.add( this.terminalStyleBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.TERMINAL_STYLE, AEConfig.instance.settings.getSetting( Settings.TERMINAL_STYLE ) ) ); - offset += 20; - } - - if( this.viewCell || this instanceof GuiWirelessTerm ) - { - if (AEConfig.instance.getConfigManager().getSetting(Settings.CRAFTING_STATUS).equals(CraftingStatus.BUTTON)) { - this.buttonList.add(this.craftingStatusImgBtn = new GuiImgButton(this.guiLeft - 18, offset, Settings.CRAFTING_STATUS, AEConfig.instance.settings.getSetting(Settings.CRAFTING_STATUS))); - } else { - this.buttonList.add(this.craftingStatusBtn = new GuiTabButton(this.guiLeft + 170, this.guiTop - 4, 2 + 11 * 16, GuiText.CraftingStatus.getLocal(), itemRender)); - this.craftingStatusBtn.setHideEdge( 13 ); // GuiTabButton implementation // - } - } - - // Enum setting = AEConfig.INSTANCE.getSetting( "Terminal", SearchBoxMode.class, SearchBoxMode.AUTOSEARCH ); - final Enum searchMode = AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ); - this.isAutoFocus = SearchBoxMode.AUTOSEARCH == searchMode || SearchBoxMode.NEI_AUTOSEARCH == searchMode; - - this.searchField.x = this.guiLeft + Math.max( 80, this.offsetX ); - this.searchField.y = this.guiTop + 4; - this.searchField.setFocused( this.isAutoFocus ); - - if (this.isSubGui()) { - this.searchField.setText(memoryText); - } else if (AEConfig.instance.preserveSearchBar) { - this.searchField.setText(memoryText, true); - repo.setSearchString(memoryText); - } - - this.setScrollBar(); - - craftingGridOffsetX = Integer.MAX_VALUE; - craftingGridOffsetY = Integer.MAX_VALUE; - - for( final Object s : this.inventorySlots.inventorySlots ) - { - if( s instanceof AppEngSlot ) - { - if( ( (Slot) s ).xDisplayPosition < 197 ) - { - this.repositionSlot( (AppEngSlot) s ); - } - } - - if( s instanceof SlotCraftingMatrix || s instanceof SlotFakeCraftingMatrix ) - { - final Slot g = (Slot) s; - if( g.xDisplayPosition > 0 && g.yDisplayPosition > 0 ) - { - craftingGridOffsetX = Math.min( craftingGridOffsetX, g.xDisplayPosition ); - craftingGridOffsetY = Math.min( craftingGridOffsetY, g.yDisplayPosition ); - } - } - } - - craftingGridOffsetX -= 25; - craftingGridOffsetY -= 6; - } - - protected int calculateRowsCount() - { - final boolean hasNEI = IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.NEI ); - final int NEIPadding = hasNEI? 22 /** input */ + 20 /** top panel */: 0; - final int extraSpace = this.height - MAGIC_HEIGHT_NUMBER - NEIPadding - this.reservedSpace; - - return Math.max(3, Math.min(this.getMaxRows(), (int) Math.floor( extraSpace / 18 ))); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( this.myName.getLocal() ), 8, 6, GuiColors.MEMonitorableTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.MEMonitorableInventory.getColor() ); - - this.currentMouseX = mouseX; - this.currentMouseY = mouseY; - } - - @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) - { - searchField.mouseClicked( xCoord, yCoord, btn ); - super.mouseClicked( xCoord, yCoord, btn ); - } - - @Override - public void onGuiClosed() - { - super.onGuiClosed(); - Keyboard.enableRepeatEvents( false ); - memoryText = this.searchField.getText(); - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - - this.bindTexture( this.getBackground() ); - final int x_width = 195; - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, x_width, 18 ); - - if( this.viewCell || ( this instanceof GuiSecurity ) ) - { - this.drawTexturedModalRect( offsetX + x_width, offsetY, x_width, 0, 46, 128 ); - } - - for( int x = 0; x < this.rows; x++ ) - { - this.drawTexturedModalRect( offsetX, offsetY + 18 + x * 18, 0, 18, x_width, 18 ); - } - - this.drawTexturedModalRect( offsetX, offsetY + 16 + this.rows * 18 + this.lowerTextureOffset, 0, 106 - 18 - 18, x_width, 99 + this.reservedSpace - this.lowerTextureOffset ); - - if( this.viewCell ) - { - boolean update = false; - - for( int i = 0; i < 5; i++ ) - { - if( this.myCurrentViewCells[i] != this.monitorableContainer.getCellViewSlot( i ).getStack() ) - { - update = true; - this.myCurrentViewCells[i] = this.monitorableContainer.getCellViewSlot( i ).getStack(); - } - } - - if( update ) - { - this.repo.setViewCell( this.myCurrentViewCells ); - } - } - - searchField.drawTextBox(); - } - - protected String getBackground() - { - return "guis/terminal.png"; - } - - @Override - protected boolean isPowered() - { - return this.repo.hasPower(); - } - - int getMaxRows() - { - return AEConfig.instance.getConfigManager().getSetting( Settings.TERMINAL_STYLE ) == TerminalStyle.SMALL ? AEConfig.instance.MEMonitorableSmallSize : Integer.MAX_VALUE; - } - - protected void repositionSlot( final AppEngSlot s ) - { - s.yDisplayPosition = s.getY() + this.ySize - 78 - 5; - } - - @Override - protected void keyTyped( final char character, final int key ) - { - if( !this.checkHotbarKeys( key ) ) - { - - if (NEISearchField != null && (NEISearchField.focused() || searchField.isFocused()) && CommonHelper.proxy.isActionKey(ActionKey.TOGGLE_FOCUS, key)) - { - final boolean focused = searchField.isFocused(); - searchField.setFocused(!focused); - NEISearchField.setFocus(focused); - return; - } - - if (NEISearchField != null && NEISearchField.focused()) - { - return; - } - - if (searchField.isFocused() && key == Keyboard.KEY_RETURN) - { - searchField.setFocused( false ); - return; - } - - - if (character == ' ' && searchField.getText().isEmpty()) - { - return; - } - - final boolean mouseInGui = this.isPointInRegion( 0, 0, this.xSize, this.ySize, this.currentMouseX, this.currentMouseY ); - - if (this.isAutoFocus && !searchField.isFocused() && mouseInGui) - { - searchField.setFocused( true ); - } - - if (!searchField.textboxKeyTyped(character, key)) - { - super.keyTyped( character, key ); - } - - } - } - - @Override - public void updateScreen() - { - this.repo.setPower( this.monitorableContainer.isPowered() ); - super.updateScreen(); - } - - @Override - public Enum getSortBy() - { - return this.configSrc.getSetting( Settings.SORT_BY ); - } - - @Override - public Enum getSortDir() - { - return this.configSrc.getSetting( Settings.SORT_DIRECTION ); - } - - @Override - public Enum getSortDisplay() - { - return this.configSrc.getSetting( Settings.VIEW_MODE ); - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - if( this.SortByBox != null ) - { - this.SortByBox.set( this.configSrc.getSetting( Settings.SORT_BY ) ); - } - - if( this.SortDirBox != null ) - { - this.SortDirBox.set( this.configSrc.getSetting( Settings.SORT_DIRECTION ) ); - } - - if( this.ViewBox != null ) - { - this.ViewBox.set( this.configSrc.getSetting( Settings.VIEW_MODE ) ); - } - - this.repo.updateView(); - } - - @SuppressWarnings("SameParameterValue") - protected boolean isPointInRegion(int rectX, int rectY, int rectWidth, int rectHeight, int pointX, int pointY) - { - pointX -= this.guiLeft; - pointY -= this.guiTop; - return pointX >= rectX - 1 && pointX < rectX + rectWidth + 1 && pointY >= rectY - 1 && pointY < rectY + rectHeight + 1; - } - - int getReservedSpace() - { - return this.reservedSpace; - } - - void setReservedSpace( final int reservedSpace ) - { - this.reservedSpace = reservedSpace; - } - - public boolean isCustomSortOrder() - { - return this.customSortOrder; - } - - void setCustomSortOrder( final boolean customSortOrder ) - { - this.customSortOrder = customSortOrder; - } - - public int getStandardSize() - { - return this.standardSize; - } - - void setStandardSize( final int standardSize ) - { - this.standardSize = standardSize; - } - - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { - super.drawScreen(mouseX, mouseY, btn); - - handleTooltip(mouseX, mouseY, searchField); - } - - public boolean isOverTextField(final int mousex, final int mousey) - { - return searchField.isMouseIn(mousex, mousey); - } - - public void setTextFieldValue(final String displayName, final int mousex, final int mousey, final ItemStack stack) - { - searchField.setText(displayName); - } + public int getStandardSize() { + return this.standardSize; + } + + void setStandardSize(final int standardSize) { + this.standardSize = standardSize; + } + + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { + super.drawScreen(mouseX, mouseY, btn); + + handleTooltip(mouseX, mouseY, searchField); + } + + public boolean isOverTextField(final int mousex, final int mousey) { + return searchField.isMouseIn(mousex, mousey); + } + + public void setTextFieldValue(final String displayName, final int mousex, final int mousey, final ItemStack stack) { + searchField.setText(displayName); + } @Override - protected void handleMouseClick(Slot p_146984_1_, int p_146984_2_, int p_146984_3_, int p_146984_4_) - { + protected void handleMouseClick(Slot p_146984_1_, int p_146984_2_, int p_146984_3_, int p_146984_4_) { - //Hack for view cells, because they are outside the container + // Hack for view cells, because they are outside the container if (p_146984_1_ != null && p_146984_4_ == 4 && p_146984_1_.xDisplayPosition > this.xSize) { p_146984_4_ = 0; } @@ -625,30 +601,28 @@ protected void handleMouseClick(Slot p_146984_1_, int p_146984_2_, int p_146984_ super.handleMouseClick(p_146984_1_, p_146984_2_, p_146984_3_, p_146984_4_); } - public boolean hideItemPanelSlot(int tx, int ty, int tw, int th) - { - - if (this.viewCell) { - int rw = 33; - int rh = 14 + myCurrentViewCells.length * 18; - - if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) { - return false; - } - - int rx = this.guiLeft + this.xSize; - int ry = this.guiTop + 0; - - rw += rx; - rh += ry; - tw += tx; - th += ty; - - // overflow || intersect - return (rw < rx || rw > tx) && (rh < ry || rh > ty) && (tw < tx || tw > rx) && (th < ty || th > ry); - } + public boolean hideItemPanelSlot(int tx, int ty, int tw, int th) { + + if (this.viewCell) { + int rw = 33; + int rh = 14 + myCurrentViewCells.length * 18; + + if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) { + return false; + } + + int rx = this.guiLeft + this.xSize; + int ry = this.guiTop + 0; + + rw += rx; + rh += ry; + tw += tx; + th += ty; + + // overflow || intersect + return (rw < rx || rw > tx) && (rh < ry || rh > ty) && (tw < tx || tw > rx) && (th < ty || th > ry); + } return false; } - } diff --git a/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java b/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java index def2d1514c0..94743ea5b1f 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java +++ b/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java @@ -18,28 +18,22 @@ package appeng.client.gui.implementations; - import appeng.api.implementations.guiobjects.IPortableCell; import appeng.container.implementations.ContainerMEPortableCell; import net.minecraft.entity.player.InventoryPlayer; +public class GuiMEPortableCell extends GuiMEMonitorable { -public class GuiMEPortableCell extends GuiMEMonitorable -{ - - public GuiMEPortableCell( final InventoryPlayer inventoryPlayer, final IPortableCell te ) - { - super( inventoryPlayer, te, new ContainerMEPortableCell( inventoryPlayer, te ) ); - } + public GuiMEPortableCell(final InventoryPlayer inventoryPlayer, final IPortableCell te) { + super(inventoryPlayer, te, new ContainerMEPortableCell(inventoryPlayer, te)); + } - int defaultGetMaxRows() - { - return super.getMaxRows(); - } + int defaultGetMaxRows() { + return super.getMaxRows(); + } - @Override - int getMaxRows() - { - return 3; - } + @Override + int getMaxRows() { + return 3; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java b/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java index 56389771218..6322e38d5f8 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java +++ b/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.config.Settings; import appeng.api.config.SortDir; import appeng.api.config.SortOrder; @@ -33,9 +32,10 @@ import appeng.client.me.SlotME; import appeng.container.implementations.ContainerNetworkStatus; import appeng.core.AEConfig; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.util.Platform; +import java.util.List; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; @@ -43,276 +43,259 @@ import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; -import java.util.List; - - -public class GuiNetworkStatus extends AEBaseGui implements ISortSource -{ - - private final ItemRepo repo; - private final int rows = 4; - private GuiImgButton units; - private int tooltip = -1; - - public GuiNetworkStatus( final InventoryPlayer inventoryPlayer, final INetworkTool te ) - { - super( new ContainerNetworkStatus( inventoryPlayer, te ) ); - final GuiScrollbar scrollbar = new GuiScrollbar(); - - this.setScrollBar( scrollbar ); - this.repo = new ItemRepo( scrollbar, this ); - this.ySize = 153; - this.xSize = 195; - this.repo.setRowSize( 5 ); - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - final boolean backwards = Mouse.isButtonDown( 1 ); - - if( btn == this.units ) - { - AEConfig.instance.nextPowerUnit( backwards ); - this.units.set( AEConfig.instance.selectedPowerUnit() ); - } - } - - @Override - public void initGui() - { - super.initGui(); - - this.units = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.POWER_UNITS, AEConfig.instance.selectedPowerUnit() ); - this.buttonList.add( this.units ); - } - - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { - - final int gx = ( this.width - this.xSize ) / 2; - final int gy = ( this.height - this.ySize ) / 2; - - this.tooltip = -1; - - int y = 0; - int x = 0; - for( int z = 0; z <= 4 * 5; z++ ) - { - final int minX = gx + 14 + x * 31; - final int minY = gy + 41 + y * 18; - - if( minX < mouseX && minX + 28 > mouseX ) - { - if( minY < mouseY && minY + 20 > mouseY ) - { - this.tooltip = z; - break; - } - } - - x++; - - if( x > 4 ) - { - y++; - x = 0; - } - } - - super.drawScreen( mouseX, mouseY, btn ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - final ContainerNetworkStatus ns = (ContainerNetworkStatus) this.inventorySlots; - - this.fontRendererObj.drawString( GuiText.NetworkDetails.getLocal(), 8, 6, GuiColors.NetworkStatusDetails.getColor() ); - - this.fontRendererObj.drawString( GuiText.StoredPower.getLocal() + ": " + Platform.formatPowerLong( ns.getCurrentPower(), false ), 13, 16, GuiColors.NetworkStatusStoredPower.getColor() ); - this.fontRendererObj.drawString( GuiText.MaxPower.getLocal() + ": " + Platform.formatPowerLong( ns.getMaxPower(), false ), 13, 26, GuiColors.NetworkStatusMaxPower.getColor() ); - - this.fontRendererObj.drawString( GuiText.PowerInputRate.getLocal() + ": " + Platform.formatPowerLong( ns.getAverageAddition(), true ), 13, 143 - 10, GuiColors.NetworkStatusPowerInputRate.getColor() ); - this.fontRendererObj.drawString( GuiText.PowerUsageRate.getLocal() + ": " + Platform.formatPowerLong( ns.getPowerUsage(), true ), 13, 143 - 20, GuiColors.NetworkStatusPowerUsageRate.getColor() ); - - final int sectionLength = 30; - - int x = 0; - int y = 0; - final int xo = 12; - final int yo = 42; - final int viewStart = 0;// myScrollBar.getCurrentScroll() * 5; - final int viewEnd = viewStart + 5 * 4; - - String toolTip = ""; - int toolPosX = 0; - int toolPosY = 0; - - for( int z = viewStart; z < Math.min( viewEnd, this.repo.size() ); z++ ) - { - final IAEItemStack refStack = this.repo.getReferenceItem( z ); - if( refStack != null ) - { - GL11.glPushMatrix(); - GL11.glScaled( 0.5, 0.5, 0.5 ); - - String str = Long.toString( refStack.getStackSize() ); - if( refStack.getStackSize() >= 10000 ) - { - str = Long.toString( refStack.getStackSize() / 1000 ) + 'k'; - } - - final int w = this.fontRendererObj.getStringWidth( str ); - this.fontRendererObj.drawString( str, (int) ( ( x * sectionLength + xo + sectionLength - 19 - ( w * 0.5 ) ) * 2 ), ( y * 18 + yo + 6 ) * 2, GuiColors.NetworkStatusItemCount.getColor() ); - - GL11.glPopMatrix(); - final int posX = x * sectionLength + xo + sectionLength - 18; - final int posY = y * 18 + yo; - - if( this.tooltip == z - viewStart ) - { - toolTip = Platform.getItemDisplayName( this.repo.getItem( z ) ); - - toolTip += ( '\n' + GuiText.Installed.getLocal() + ": " + ( refStack.getStackSize() ) ); - if( refStack.getCountRequestable() > 0 ) - { - toolTip += ( '\n' + GuiText.EnergyDrain.getLocal() + ": " + Platform.formatPowerLong( refStack.getCountRequestable(), true ) ); - } - - toolPosX = x * sectionLength + xo + sectionLength - 8; - toolPosY = y * 18 + yo; - } - - this.drawItem( posX, posY, this.repo.getItem( z ) ); - - x++; - - if( x > 4 ) - { - y++; - x = 0; - } - } - } - - if( this.tooltip >= 0 && toolTip.length() > 0 ) - { - this.drawTooltip( toolPosX, toolPosY + 10, 0, toolTip ); - } - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/networkstatus.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - public void postUpdate( final List list ) - { - this.repo.clear(); - - for( final IAEItemStack is : list ) - { - this.repo.postUpdate( is ); - } - - this.repo.updateView(); - this.setScrollBar(); - } - - private void setScrollBar() - { - final int size = this.repo.size(); - this.getScrollBar().setTop( 39 ).setLeft( 175 ).setHeight( 78 ); - this.getScrollBar().setRange( 0, ( size + 4 ) / 5 - this.rows, 1 ); - } - - // @Override - NEI - public List handleItemTooltip( final ItemStack stack, final int mouseX, final int mouseY, final List currentToolTip ) - { - if( stack != null ) - { - final Slot s = this.getSlot( mouseX, mouseY ); - if( s instanceof SlotME ) - { - IAEItemStack myStack = null; - - try - { - final SlotME theSlotField = (SlotME) s; - myStack = theSlotField.getAEStack(); - } - catch( final Throwable ignore ) - { - } - - if( myStack != null ) - { - while( currentToolTip.size() > 1 ) - { - currentToolTip.remove( 1 ); - } - } - } - } - return currentToolTip; - } - - // Vanilla version... - protected void drawItemStackTooltip( final ItemStack stack, final int x, final int y ) - { - final Slot s = this.getSlot( x, y ); - if( s instanceof SlotME && stack != null ) - { - IAEItemStack myStack = null; - - try - { - final SlotME theSlotField = (SlotME) s; - myStack = theSlotField.getAEStack(); - } - catch( final Throwable ignore ) - { - } - - if( myStack != null ) - { - final List currentToolTip = stack.getTooltip( this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips ); - - while( currentToolTip.size() > 1 ) - { - currentToolTip.remove( 1 ); - } - - currentToolTip.add( GuiText.Installed.getLocal() + ": " + ( myStack.getStackSize() ) ); - currentToolTip.add( GuiText.EnergyDrain.getLocal() + ": " + Platform.formatPowerLong( myStack.getCountRequestable(), true ) ); - - this.drawTooltip( x, y, 0, join( currentToolTip, "\n" ) ); - } - } - // super.drawItemStackTooltip( stack, x, y ); - } - - @Override - public Enum getSortBy() - { - return SortOrder.NAME; - } - - @Override - public Enum getSortDir() - { - return SortDir.ASCENDING; - } - - @Override - public Enum getSortDisplay() - { - return ViewItems.ALL; - } +public class GuiNetworkStatus extends AEBaseGui implements ISortSource { + + private final ItemRepo repo; + private final int rows = 4; + private GuiImgButton units; + private int tooltip = -1; + + public GuiNetworkStatus(final InventoryPlayer inventoryPlayer, final INetworkTool te) { + super(new ContainerNetworkStatus(inventoryPlayer, te)); + final GuiScrollbar scrollbar = new GuiScrollbar(); + + this.setScrollBar(scrollbar); + this.repo = new ItemRepo(scrollbar, this); + this.ySize = 153; + this.xSize = 195; + this.repo.setRowSize(5); + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + final boolean backwards = Mouse.isButtonDown(1); + + if (btn == this.units) { + AEConfig.instance.nextPowerUnit(backwards); + this.units.set(AEConfig.instance.selectedPowerUnit()); + } + } + + @Override + public void initGui() { + super.initGui(); + + this.units = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 8, Settings.POWER_UNITS, AEConfig.instance.selectedPowerUnit()); + this.buttonList.add(this.units); + } + + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { + + final int gx = (this.width - this.xSize) / 2; + final int gy = (this.height - this.ySize) / 2; + + this.tooltip = -1; + + int y = 0; + int x = 0; + for (int z = 0; z <= 4 * 5; z++) { + final int minX = gx + 14 + x * 31; + final int minY = gy + 41 + y * 18; + + if (minX < mouseX && minX + 28 > mouseX) { + if (minY < mouseY && minY + 20 > mouseY) { + this.tooltip = z; + break; + } + } + + x++; + + if (x > 4) { + y++; + x = 0; + } + } + + super.drawScreen(mouseX, mouseY, btn); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + final ContainerNetworkStatus ns = (ContainerNetworkStatus) this.inventorySlots; + + this.fontRendererObj.drawString( + GuiText.NetworkDetails.getLocal(), 8, 6, GuiColors.NetworkStatusDetails.getColor()); + + this.fontRendererObj.drawString( + GuiText.StoredPower.getLocal() + ": " + Platform.formatPowerLong(ns.getCurrentPower(), false), + 13, + 16, + GuiColors.NetworkStatusStoredPower.getColor()); + this.fontRendererObj.drawString( + GuiText.MaxPower.getLocal() + ": " + Platform.formatPowerLong(ns.getMaxPower(), false), + 13, + 26, + GuiColors.NetworkStatusMaxPower.getColor()); + + this.fontRendererObj.drawString( + GuiText.PowerInputRate.getLocal() + ": " + Platform.formatPowerLong(ns.getAverageAddition(), true), + 13, + 143 - 10, + GuiColors.NetworkStatusPowerInputRate.getColor()); + this.fontRendererObj.drawString( + GuiText.PowerUsageRate.getLocal() + ": " + Platform.formatPowerLong(ns.getPowerUsage(), true), + 13, + 143 - 20, + GuiColors.NetworkStatusPowerUsageRate.getColor()); + + final int sectionLength = 30; + + int x = 0; + int y = 0; + final int xo = 12; + final int yo = 42; + final int viewStart = 0; // myScrollBar.getCurrentScroll() * 5; + final int viewEnd = viewStart + 5 * 4; + + String toolTip = ""; + int toolPosX = 0; + int toolPosY = 0; + + for (int z = viewStart; z < Math.min(viewEnd, this.repo.size()); z++) { + final IAEItemStack refStack = this.repo.getReferenceItem(z); + if (refStack != null) { + GL11.glPushMatrix(); + GL11.glScaled(0.5, 0.5, 0.5); + + String str = Long.toString(refStack.getStackSize()); + if (refStack.getStackSize() >= 10000) { + str = Long.toString(refStack.getStackSize() / 1000) + 'k'; + } + + final int w = this.fontRendererObj.getStringWidth(str); + this.fontRendererObj.drawString( + str, + (int) ((x * sectionLength + xo + sectionLength - 19 - (w * 0.5)) * 2), + (y * 18 + yo + 6) * 2, + GuiColors.NetworkStatusItemCount.getColor()); + + GL11.glPopMatrix(); + final int posX = x * sectionLength + xo + sectionLength - 18; + final int posY = y * 18 + yo; + + if (this.tooltip == z - viewStart) { + toolTip = Platform.getItemDisplayName(this.repo.getItem(z)); + + toolTip += ('\n' + GuiText.Installed.getLocal() + ": " + (refStack.getStackSize())); + if (refStack.getCountRequestable() > 0) { + toolTip += ('\n' + GuiText.EnergyDrain.getLocal() + ": " + + Platform.formatPowerLong(refStack.getCountRequestable(), true)); + } + + toolPosX = x * sectionLength + xo + sectionLength - 8; + toolPosY = y * 18 + yo; + } + + this.drawItem(posX, posY, this.repo.getItem(z)); + + x++; + + if (x > 4) { + y++; + x = 0; + } + } + } + + if (this.tooltip >= 0 && toolTip.length() > 0) { + this.drawTooltip(toolPosX, toolPosY + 10, 0, toolTip); + } + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/networkstatus.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } + + public void postUpdate(final List list) { + this.repo.clear(); + + for (final IAEItemStack is : list) { + this.repo.postUpdate(is); + } + + this.repo.updateView(); + this.setScrollBar(); + } + + private void setScrollBar() { + final int size = this.repo.size(); + this.getScrollBar().setTop(39).setLeft(175).setHeight(78); + this.getScrollBar().setRange(0, (size + 4) / 5 - this.rows, 1); + } + + // @Override - NEI + public List handleItemTooltip( + final ItemStack stack, final int mouseX, final int mouseY, final List currentToolTip) { + if (stack != null) { + final Slot s = this.getSlot(mouseX, mouseY); + if (s instanceof SlotME) { + IAEItemStack myStack = null; + + try { + final SlotME theSlotField = (SlotME) s; + myStack = theSlotField.getAEStack(); + } catch (final Throwable ignore) { + } + + if (myStack != null) { + while (currentToolTip.size() > 1) { + currentToolTip.remove(1); + } + } + } + } + return currentToolTip; + } + + // Vanilla version... + protected void drawItemStackTooltip(final ItemStack stack, final int x, final int y) { + final Slot s = this.getSlot(x, y); + if (s instanceof SlotME && stack != null) { + IAEItemStack myStack = null; + + try { + final SlotME theSlotField = (SlotME) s; + myStack = theSlotField.getAEStack(); + } catch (final Throwable ignore) { + } + + if (myStack != null) { + final List currentToolTip = + stack.getTooltip(this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips); + + while (currentToolTip.size() > 1) { + currentToolTip.remove(1); + } + + currentToolTip.add(GuiText.Installed.getLocal() + ": " + (myStack.getStackSize())); + currentToolTip.add(GuiText.EnergyDrain.getLocal() + ": " + + Platform.formatPowerLong(myStack.getCountRequestable(), true)); + + this.drawTooltip(x, y, 0, join(currentToolTip, "\n")); + } + } + // super.drawItemStackTooltip( stack, x, y ); + } + + @Override + public Enum getSortBy() { + return SortOrder.NAME; + } + + @Override + public Enum getSortDir() { + return SortDir.ASCENDING; + } + + @Override + public Enum getSortDisplay() { + return ViewItems.ALL; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiNetworkTool.java b/src/main/java/appeng/client/gui/implementations/GuiNetworkTool.java index 4df7bba0dba..98d6e65a8a1 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiNetworkTool.java +++ b/src/main/java/appeng/client/gui/implementations/GuiNetworkTool.java @@ -18,77 +18,71 @@ package appeng.client.gui.implementations; - import appeng.api.implementations.guiobjects.INetworkTool; import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiToggleButton; import appeng.container.implementations.ContainerNetworkTool; import appeng.core.AELog; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; +import java.io.IOException; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; -import java.io.IOException; - - -public class GuiNetworkTool extends AEBaseGui -{ - - private GuiToggleButton tFacades; - - public GuiNetworkTool( final InventoryPlayer inventoryPlayer, final INetworkTool te ) - { - super( new ContainerNetworkTool( inventoryPlayer, te ) ); - this.ySize = 166; - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - try - { - if( btn == this.tFacades ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "NetworkTool", "Toggle" ) ); - } - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - - @Override - public void initGui() - { - super.initGui(); - - this.tFacades = new GuiToggleButton( this.guiLeft - 18, this.guiTop + 8, 23, 22, GuiText.TransparentFacades.getLocal(), GuiText.TransparentFacadesHint.getLocal() ); - - this.buttonList.add( this.tFacades ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - if( this.tFacades != null ) - { - this.tFacades.setState( ( (ContainerNetworkTool) this.inventorySlots ).isFacadeMode() ); - } - - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.NetworkTool.getLocal() ), 8, 6, GuiColors.NetworkToolTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.NetworkToolInventory.getColor() ); - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/toolbox.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } +public class GuiNetworkTool extends AEBaseGui { + + private GuiToggleButton tFacades; + + public GuiNetworkTool(final InventoryPlayer inventoryPlayer, final INetworkTool te) { + super(new ContainerNetworkTool(inventoryPlayer, te)); + this.ySize = 166; + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + try { + if (btn == this.tFacades) { + NetworkHandler.instance.sendToServer(new PacketValueConfig("NetworkTool", "Toggle")); + } + } catch (final IOException e) { + AELog.debug(e); + } + } + + @Override + public void initGui() { + super.initGui(); + + this.tFacades = new GuiToggleButton( + this.guiLeft - 18, + this.guiTop + 8, + 23, + 22, + GuiText.TransparentFacades.getLocal(), + GuiText.TransparentFacadesHint.getLocal()); + + this.buttonList.add(this.tFacades); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + if (this.tFacades != null) { + this.tFacades.setState(((ContainerNetworkTool) this.inventorySlots).isFacadeMode()); + } + + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.NetworkTool.getLocal()), 8, 6, GuiColors.NetworkToolTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.NetworkToolInventory.getColor()); + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/toolbox.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiOreFilter.java b/src/main/java/appeng/client/gui/implementations/GuiOreFilter.java index 06bddc50f65..a6d978c6257 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiOreFilter.java +++ b/src/main/java/appeng/client/gui/implementations/GuiOreFilter.java @@ -6,8 +6,8 @@ import appeng.container.AEBaseContainer; import appeng.container.implementations.ContainerOreFilter; import appeng.core.AELog; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.GuiBridge; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketSwitchGuis; @@ -16,42 +16,35 @@ import appeng.parts.automation.PartSharedItemBus; import appeng.parts.misc.PartStorageBus; import appeng.tile.misc.TileCellWorkbench; +import java.io.IOException; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; -import java.io.IOException; - -public class GuiOreFilter extends AEBaseGui implements IDropToFillTextField -{ +public class GuiOreFilter extends AEBaseGui implements IDropToFillTextField { private MEGuiTextField textField; - public GuiOreFilter(InventoryPlayer ip, IOreFilterable obj) - { + public GuiOreFilter(InventoryPlayer ip, IOreFilterable obj) { super(new ContainerOreFilter(ip, obj)); this.xSize = 256; - this.textField = new MEGuiTextField(231, 12) - { + this.textField = new MEGuiTextField(231, 12) { - @Override - public void onTextChange(final String oldText) - { + @Override + public void onTextChange(final String oldText) { final String text = getText(); if (!text.equals(oldText)) { ((ContainerOreFilter) inventorySlots).setFilter(text); } - } - - }; + } + }; this.textField.setMaxStringLength(120); } @Override - public void initGui() - { + public void initGui() { super.initGui(); this.textField.x = this.guiLeft + 12; @@ -62,62 +55,50 @@ public void initGui() } @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.fontRendererObj.drawString( GuiText.OreFilterLabel.getLocal(), 12, 8, GuiColors.OreFilterLabel.getColor() ); + public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) { + this.fontRendererObj.drawString(GuiText.OreFilterLabel.getLocal(), 12, 8, GuiColors.OreFilterLabel.getColor()); } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.bindTexture( "guis/renamer.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) { + this.bindTexture("guis/renamer.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); this.textField.drawTextBox(); } @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) - { - this.textField.mouseClicked( xCoord, yCoord, btn ); - super.mouseClicked( xCoord, yCoord, btn ); - } + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) { + this.textField.mouseClicked(xCoord, yCoord, btn); + super.mouseClicked(xCoord, yCoord, btn); + } @Override - protected void keyTyped(final char character, final int key) - { - if (key == 28) {// Enter + protected void keyTyped(final char character, final int key) { + if (key == 28) { // Enter try { NetworkHandler.instance.sendToServer(new PacketValueConfig("OreFilter", this.textField.getText())); } catch (IOException e) { AELog.debug(e); } - final Object target = ( (AEBaseContainer) this.inventorySlots ).getTarget(); + final Object target = ((AEBaseContainer) this.inventorySlots).getTarget(); GuiBridge OriginalGui = null; - if (target instanceof PartStorageBus) - OriginalGui = GuiBridge.GUI_STORAGEBUS; - else if (target instanceof PartSharedItemBus) - OriginalGui = GuiBridge.GUI_BUS; - else if (target instanceof TileCellWorkbench) - OriginalGui = GuiBridge.GUI_CELL_WORKBENCH; - - if (OriginalGui != null) - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( OriginalGui ) ); - else - this.mc.thePlayer.closeScreen(); + if (target instanceof PartStorageBus) OriginalGui = GuiBridge.GUI_STORAGEBUS; + else if (target instanceof PartSharedItemBus) OriginalGui = GuiBridge.GUI_BUS; + else if (target instanceof TileCellWorkbench) OriginalGui = GuiBridge.GUI_CELL_WORKBENCH; + + if (OriginalGui != null) NetworkHandler.instance.sendToServer(new PacketSwitchGuis(OriginalGui)); + else this.mc.thePlayer.closeScreen(); } else if (!this.textField.textboxKeyTyped(character, key)) { super.keyTyped(character, key); } - } - public boolean isOverTextField(final int mousex, final int mousey) - { - return textField.isMouseIn(mousex, mousey); - } + public boolean isOverTextField(final int mousex, final int mousey) { + return textField.isMouseIn(mousex, mousey); + } - public void setTextFieldValue(final String displayName, final int mousex, final int mousey, final ItemStack stack) - { + public void setTextFieldValue(final String displayName, final int mousex, final int mousey, final ItemStack stack) { final int[] ores = OreDictionary.getOreIDs(stack); if (ores.length > 0) { @@ -125,7 +106,5 @@ public void setTextFieldValue(final String displayName, final int mousex, final } else { textField.setText(displayName); } - - } - + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiPatternTerm.java b/src/main/java/appeng/client/gui/implementations/GuiPatternTerm.java index 063e391c81c..335557212d7 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiPatternTerm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiPatternTerm.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.config.ActionItems; import appeng.api.config.ItemSubstitution; import appeng.api.config.Settings; @@ -27,162 +26,156 @@ import appeng.client.gui.widgets.GuiTabButton; import appeng.container.implementations.ContainerPatternTerm; import appeng.container.slot.AppEngSlot; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; +import java.io.IOException; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import org.lwjgl.input.Keyboard; -import java.io.IOException; - - -public class GuiPatternTerm extends GuiMEMonitorable -{ - - private static final String SUBSITUTION_DISABLE = "0"; - private static final String SUBSITUTION_ENABLE = "1"; - - private static final String CRAFTMODE_CRFTING = "1"; - private static final String CRAFTMODE_PROCESSING = "0"; - - private final ContainerPatternTerm container; - - private GuiTabButton tabCraftButton; - private GuiTabButton tabProcessButton; - private GuiImgButton substitutionsEnabledBtn; - private GuiImgButton substitutionsDisabledBtn; - private GuiImgButton encodeBtn; - private GuiImgButton clearBtn; - private GuiImgButton doubleBtn; - - public GuiPatternTerm( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( inventoryPlayer, te, new ContainerPatternTerm( inventoryPlayer, te ) ); - this.container = (ContainerPatternTerm) this.inventorySlots; - this.setReservedSpace( 81 ); - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - try - { - if( this.tabCraftButton == btn || this.tabProcessButton == btn ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminal.CraftMode", this.tabProcessButton == btn ? CRAFTMODE_CRFTING : CRAFTMODE_PROCESSING ) ); - } - else if( this.encodeBtn == btn ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminal.Encode", - isCtrlKeyDown() ? (isShiftKeyDown() ? "6" : "1") : (isShiftKeyDown() ? "2" : "1") ) ); - } - else if( this.clearBtn == btn ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminal.Clear", "1" ) ); - } - else if( this.substitutionsEnabledBtn == btn || this.substitutionsDisabledBtn == btn ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminal.Substitute", this.substitutionsEnabledBtn == btn ? SUBSITUTION_DISABLE : SUBSITUTION_ENABLE ) ); - } - else if (doubleBtn == btn) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminal.Double", Keyboard.isKeyDown( Keyboard.KEY_LSHIFT ) ? "1": "0") ); - } - } - catch( final IOException e ) - { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Override - public void initGui() - { - super.initGui(); - this.tabCraftButton = new GuiTabButton( this.guiLeft + 173, this.guiTop + this.ySize - 177, new ItemStack( Blocks.crafting_table ), GuiText.CraftingPattern.getLocal(), itemRender ); - this.buttonList.add( this.tabCraftButton ); - - this.tabProcessButton = new GuiTabButton( this.guiLeft + 173, this.guiTop + this.ySize - 177, new ItemStack( Blocks.furnace ), GuiText.ProcessingPattern.getLocal(), itemRender ); - this.buttonList.add( this.tabProcessButton ); - - this.substitutionsEnabledBtn = new GuiImgButton( this.guiLeft + 84, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.ENABLED ); - this.substitutionsEnabledBtn.setHalfSize( true ); - this.buttonList.add( this.substitutionsEnabledBtn ); - - this.substitutionsDisabledBtn = new GuiImgButton( this.guiLeft + 84, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.DISABLED ); - this.substitutionsDisabledBtn.setHalfSize( true ); - this.buttonList.add( this.substitutionsDisabledBtn ); - - this.clearBtn = new GuiImgButton( this.guiLeft + 74, this.guiTop + this.ySize - 163, Settings.ACTIONS, ActionItems.CLOSE ); - this.clearBtn.setHalfSize( true ); - this.buttonList.add( this.clearBtn ); - - this.encodeBtn = new GuiImgButton( this.guiLeft + 147, this.guiTop + this.ySize - 142, Settings.ACTIONS, ActionItems.ENCODE ); - this.buttonList.add( this.encodeBtn ); - - this.doubleBtn = new GuiImgButton( this.guiLeft + 74, this.guiTop + this.ySize - 153, Settings.ACTIONS, ActionItems.DOUBLE ); - this.doubleBtn.setHalfSize( true ); - this.buttonList.add( this.doubleBtn ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - if( !this.container.isCraftingMode() ) - { - this.tabCraftButton.visible = false; - this.tabProcessButton.visible = true; - this.doubleBtn.visible = true; - } - else - { - this.tabCraftButton.visible = true; - this.tabProcessButton.visible = false; - this.doubleBtn.visible = false; - } - - if( this.container.substitute ) - { - this.substitutionsEnabledBtn.visible = true; - this.substitutionsDisabledBtn.visible = false; - } - else - { - this.substitutionsEnabledBtn.visible = false; - this.substitutionsDisabledBtn.visible = true; - } - - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - this.fontRendererObj.drawString( GuiText.PatternTerminal.getLocal(), 8, this.ySize - 96 + 2 - this.getReservedSpace(), GuiColors.PatternTerminalTitle.getColor() ); - } - - @Override - protected String getBackground() - { - if( this.container.isCraftingMode() ) - { - return "guis/pattern.png"; - } - return "guis/pattern2.png"; - } - - @Override - protected void repositionSlot( final AppEngSlot s ) - { - if( s.isPlayerSide() ) - { - s.yDisplayPosition = s.getY() + this.ySize - 78 - 5; - } - else - { - s.yDisplayPosition = s.getY() + this.ySize - 78 - 3; - } - } +public class GuiPatternTerm extends GuiMEMonitorable { + + private static final String SUBSITUTION_DISABLE = "0"; + private static final String SUBSITUTION_ENABLE = "1"; + + private static final String CRAFTMODE_CRFTING = "1"; + private static final String CRAFTMODE_PROCESSING = "0"; + + private final ContainerPatternTerm container; + + private GuiTabButton tabCraftButton; + private GuiTabButton tabProcessButton; + private GuiImgButton substitutionsEnabledBtn; + private GuiImgButton substitutionsDisabledBtn; + private GuiImgButton encodeBtn; + private GuiImgButton clearBtn; + private GuiImgButton doubleBtn; + + public GuiPatternTerm(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(inventoryPlayer, te, new ContainerPatternTerm(inventoryPlayer, te)); + this.container = (ContainerPatternTerm) this.inventorySlots; + this.setReservedSpace(81); + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + try { + if (this.tabCraftButton == btn || this.tabProcessButton == btn) { + NetworkHandler.instance.sendToServer(new PacketValueConfig( + "PatternTerminal.CraftMode", + this.tabProcessButton == btn ? CRAFTMODE_CRFTING : CRAFTMODE_PROCESSING)); + } else if (this.encodeBtn == btn) { + NetworkHandler.instance.sendToServer(new PacketValueConfig( + "PatternTerminal.Encode", + isCtrlKeyDown() ? (isShiftKeyDown() ? "6" : "1") : (isShiftKeyDown() ? "2" : "1"))); + } else if (this.clearBtn == btn) { + NetworkHandler.instance.sendToServer(new PacketValueConfig("PatternTerminal.Clear", "1")); + } else if (this.substitutionsEnabledBtn == btn || this.substitutionsDisabledBtn == btn) { + NetworkHandler.instance.sendToServer(new PacketValueConfig( + "PatternTerminal.Substitute", + this.substitutionsEnabledBtn == btn ? SUBSITUTION_DISABLE : SUBSITUTION_ENABLE)); + } else if (doubleBtn == btn) { + NetworkHandler.instance.sendToServer(new PacketValueConfig( + "PatternTerminal.Double", Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) ? "1" : "0")); + } + } catch (final IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Override + public void initGui() { + super.initGui(); + this.tabCraftButton = new GuiTabButton( + this.guiLeft + 173, + this.guiTop + this.ySize - 177, + new ItemStack(Blocks.crafting_table), + GuiText.CraftingPattern.getLocal(), + itemRender); + this.buttonList.add(this.tabCraftButton); + + this.tabProcessButton = new GuiTabButton( + this.guiLeft + 173, + this.guiTop + this.ySize - 177, + new ItemStack(Blocks.furnace), + GuiText.ProcessingPattern.getLocal(), + itemRender); + this.buttonList.add(this.tabProcessButton); + + this.substitutionsEnabledBtn = new GuiImgButton( + this.guiLeft + 84, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.ENABLED); + this.substitutionsEnabledBtn.setHalfSize(true); + this.buttonList.add(this.substitutionsEnabledBtn); + + this.substitutionsDisabledBtn = new GuiImgButton( + this.guiLeft + 84, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.DISABLED); + this.substitutionsDisabledBtn.setHalfSize(true); + this.buttonList.add(this.substitutionsDisabledBtn); + + this.clearBtn = new GuiImgButton( + this.guiLeft + 74, this.guiTop + this.ySize - 163, Settings.ACTIONS, ActionItems.CLOSE); + this.clearBtn.setHalfSize(true); + this.buttonList.add(this.clearBtn); + + this.encodeBtn = new GuiImgButton( + this.guiLeft + 147, this.guiTop + this.ySize - 142, Settings.ACTIONS, ActionItems.ENCODE); + this.buttonList.add(this.encodeBtn); + + this.doubleBtn = new GuiImgButton( + this.guiLeft + 74, this.guiTop + this.ySize - 153, Settings.ACTIONS, ActionItems.DOUBLE); + this.doubleBtn.setHalfSize(true); + this.buttonList.add(this.doubleBtn); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + if (!this.container.isCraftingMode()) { + this.tabCraftButton.visible = false; + this.tabProcessButton.visible = true; + this.doubleBtn.visible = true; + } else { + this.tabCraftButton.visible = true; + this.tabProcessButton.visible = false; + this.doubleBtn.visible = false; + } + + if (this.container.substitute) { + this.substitutionsEnabledBtn.visible = true; + this.substitutionsDisabledBtn.visible = false; + } else { + this.substitutionsEnabledBtn.visible = false; + this.substitutionsDisabledBtn.visible = true; + } + + super.drawFG(offsetX, offsetY, mouseX, mouseY); + this.fontRendererObj.drawString( + GuiText.PatternTerminal.getLocal(), + 8, + this.ySize - 96 + 2 - this.getReservedSpace(), + GuiColors.PatternTerminalTitle.getColor()); + } + + @Override + protected String getBackground() { + if (this.container.isCraftingMode()) { + return "guis/pattern.png"; + } + return "guis/pattern2.png"; + } + + @Override + protected void repositionSlot(final AppEngSlot s) { + if (s.isPlayerSide()) { + s.yDisplayPosition = s.getY() + this.ySize - 78 - 5; + } else { + s.yDisplayPosition = s.getY() + this.ySize - 78 - 3; + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiPatternTermEx.java b/src/main/java/appeng/client/gui/implementations/GuiPatternTermEx.java index 99f8dfce26c..2a1e4c8492d 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiPatternTermEx.java +++ b/src/main/java/appeng/client/gui/implementations/GuiPatternTermEx.java @@ -10,19 +10,17 @@ import appeng.container.implementations.ContainerPatternTermEx; import appeng.container.slot.AppEngSlot; import appeng.core.AppEng; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; +import java.io.IOException; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; -import java.io.IOException; - -public class GuiPatternTermEx extends GuiMEMonitorable -{ +public class GuiPatternTermEx extends GuiMEMonitorable { private static final String SUBSITUTION_DISABLE = "0"; private static final String SUBSITUTION_ENABLE = "1"; @@ -36,112 +34,109 @@ public class GuiPatternTermEx extends GuiMEMonitorable private GuiImgButton doubleBtn; private final GuiScrollbar processingScrollBar = new GuiScrollbar(); - public GuiPatternTermEx(final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( inventoryPlayer, te, new ContainerPatternTermEx( inventoryPlayer, te ) ); + public GuiPatternTermEx(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(inventoryPlayer, te, new ContainerPatternTermEx(inventoryPlayer, te)); this.container = (ContainerPatternTermEx) this.inventorySlots; - this.setReservedSpace( 81 ); + this.setReservedSpace(81); processingScrollBar.setHeight(70).setWidth(7).setLeft(6).setRange(0, 1, 1); processingScrollBar.setTexture(AppEng.MOD_ID, "guis/pattern3.png", 242, 0); } @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - try - { - if( this.encodeBtn == btn ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminalEx.Encode", isCtrlKeyDown() ? (isShiftKeyDown() ? "6" : "1") : (isShiftKeyDown() ? "2" : "1") ) ); - } - else if( this.clearBtn == btn ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminalEx.Clear", "1" ) ); - } - else if( this.invertBtn == btn ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminalEx.Invert", container.inverted ? "0" : "1") ); - } - else if( this.substitutionsEnabledBtn == btn || this.substitutionsDisabledBtn == btn ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminalEx.Substitute", this.substitutionsEnabledBtn == btn ? SUBSITUTION_DISABLE : SUBSITUTION_ENABLE ) ); - } - else if (doubleBtn == btn) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminalEx.Double", Keyboard.isKeyDown( Keyboard.KEY_LSHIFT ) ? "1": "0") ); + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + try { + if (this.encodeBtn == btn) { + NetworkHandler.instance.sendToServer(new PacketValueConfig( + "PatternTerminalEx.Encode", + isCtrlKeyDown() ? (isShiftKeyDown() ? "6" : "1") : (isShiftKeyDown() ? "2" : "1"))); + } else if (this.clearBtn == btn) { + NetworkHandler.instance.sendToServer(new PacketValueConfig("PatternTerminalEx.Clear", "1")); + } else if (this.invertBtn == btn) { + NetworkHandler.instance.sendToServer( + new PacketValueConfig("PatternTerminalEx.Invert", container.inverted ? "0" : "1")); + } else if (this.substitutionsEnabledBtn == btn || this.substitutionsDisabledBtn == btn) { + NetworkHandler.instance.sendToServer(new PacketValueConfig( + "PatternTerminalEx.Substitute", + this.substitutionsEnabledBtn == btn ? SUBSITUTION_DISABLE : SUBSITUTION_ENABLE)); + } else if (doubleBtn == btn) { + NetworkHandler.instance.sendToServer(new PacketValueConfig( + "PatternTerminalEx.Double", Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) ? "1" : "0")); } - } - catch( final IOException e ) - { + } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override - public void initGui() - { + public void initGui() { super.initGui(); - this.substitutionsEnabledBtn = new GuiImgButton( this.guiLeft + 97, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.ENABLED ); - this.substitutionsEnabledBtn.setHalfSize( true ); - this.buttonList.add( this.substitutionsEnabledBtn ); - - this.substitutionsDisabledBtn = new GuiImgButton( this.guiLeft + 97, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.DISABLED ); - this.substitutionsDisabledBtn.setHalfSize( true ); - this.buttonList.add( this.substitutionsDisabledBtn ); - - this.clearBtn = new GuiImgButton( this.guiLeft + 87, this.guiTop + this.ySize - 163, Settings.ACTIONS, ActionItems.CLOSE ); - this.clearBtn.setHalfSize( true ); - this.buttonList.add( this.clearBtn ); - - this.encodeBtn = new GuiImgButton( this.guiLeft + 147, this.guiTop + this.ySize - 142, Settings.ACTIONS, ActionItems.ENCODE ); - this.buttonList.add( this.encodeBtn ); - - invertBtn = new GuiImgButton( this.guiLeft + 87, this.guiTop + this.ySize - 153, Settings.ACTIONS, container.inverted ? PatternSlotConfig.C_4_16 : PatternSlotConfig.C_16_4); - invertBtn.setHalfSize( true ); - this.buttonList.add( this.invertBtn ); - - this.doubleBtn = new GuiImgButton( this.guiLeft + 97, this.guiTop + this.ySize - 153, Settings.ACTIONS, ActionItems.DOUBLE ); - this.doubleBtn.setHalfSize( true ); - this.buttonList.add( this.doubleBtn ); + this.substitutionsEnabledBtn = new GuiImgButton( + this.guiLeft + 97, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.ENABLED); + this.substitutionsEnabledBtn.setHalfSize(true); + this.buttonList.add(this.substitutionsEnabledBtn); + + this.substitutionsDisabledBtn = new GuiImgButton( + this.guiLeft + 97, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.DISABLED); + this.substitutionsDisabledBtn.setHalfSize(true); + this.buttonList.add(this.substitutionsDisabledBtn); + + this.clearBtn = new GuiImgButton( + this.guiLeft + 87, this.guiTop + this.ySize - 163, Settings.ACTIONS, ActionItems.CLOSE); + this.clearBtn.setHalfSize(true); + this.buttonList.add(this.clearBtn); + + this.encodeBtn = new GuiImgButton( + this.guiLeft + 147, this.guiTop + this.ySize - 142, Settings.ACTIONS, ActionItems.ENCODE); + this.buttonList.add(this.encodeBtn); + + invertBtn = new GuiImgButton( + this.guiLeft + 87, + this.guiTop + this.ySize - 153, + Settings.ACTIONS, + container.inverted ? PatternSlotConfig.C_4_16 : PatternSlotConfig.C_16_4); + invertBtn.setHalfSize(true); + this.buttonList.add(this.invertBtn); + + this.doubleBtn = new GuiImgButton( + this.guiLeft + 97, this.guiTop + this.ySize - 153, Settings.ACTIONS, ActionItems.DOUBLE); + this.doubleBtn.setHalfSize(true); + this.buttonList.add(this.doubleBtn); processingScrollBar.setTop(this.ySize - 164); } @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - this.fontRendererObj.drawString( GuiText.PatternTerminalEx.getLocal(), 8, this.ySize - 96 + 2 - this.getReservedSpace(), GuiColors.PatternTerminalEx.getColor() ); + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + super.drawFG(offsetX, offsetY, mouseX, mouseY); + this.fontRendererObj.drawString( + GuiText.PatternTerminalEx.getLocal(), + 8, + this.ySize - 96 + 2 - this.getReservedSpace(), + GuiColors.PatternTerminalEx.getColor()); this.processingScrollBar.draw(this); } @Override - protected String getBackground() - { + protected String getBackground() { return container.inverted ? "guis/pattern4.png" : "guis/pattern3.png"; } @Override - protected void repositionSlot( final AppEngSlot s ) - { - if( s.isPlayerSide() ) - { + protected void repositionSlot(final AppEngSlot s) { + if (s.isPlayerSide()) { s.yDisplayPosition = s.getY() + this.ySize - 78 - 5; - } - else - { + } else { s.yDisplayPosition = s.getY() + this.ySize - 78 - 3; } } @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { + public void drawScreen(final int mouseX, final int mouseY, final float btn) { if (container.substitute) { substitutionsEnabledBtn.visible = true; @@ -151,12 +146,12 @@ public void drawScreen( final int mouseX, final int mouseY, final float btn ) substitutionsDisabledBtn.visible = true; } - final int offset = container.inverted? 18 * -3: 0; - - substitutionsEnabledBtn.xPosition = this.guiLeft + 97 + offset; + final int offset = container.inverted ? 18 * -3 : 0; + + substitutionsEnabledBtn.xPosition = this.guiLeft + 97 + offset; substitutionsDisabledBtn.xPosition = this.guiLeft + 97 + offset; doubleBtn.xPosition = this.guiLeft + 97 + offset; - clearBtn.xPosition = this.guiLeft + 87 + offset; + clearBtn.xPosition = this.guiLeft + 87 + offset; invertBtn.xPosition = this.guiLeft + 87 + offset; processingScrollBar.setCurrentScroll(container.activePage); @@ -164,33 +159,30 @@ public void drawScreen( final int mouseX, final int mouseY, final float btn ) super.drawScreen(mouseX, mouseY, btn); } - @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) - { + @Override + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) { final int currentScroll = this.processingScrollBar.getCurrentScroll(); this.processingScrollBar.click(this, xCoord - this.guiLeft, yCoord - this.guiTop); - super.mouseClicked(xCoord, yCoord, btn); + super.mouseClicked(xCoord, yCoord, btn); if (currentScroll != this.processingScrollBar.getCurrentScroll()) { changeActivePage(); } - } + } - @Override - protected void mouseClickMove( final int x, final int y, final int c, final long d ) - { + @Override + protected void mouseClickMove(final int x, final int y, final int c, final long d) { final int currentScroll = this.processingScrollBar.getCurrentScroll(); - this.processingScrollBar.click(this, x - this.guiLeft, y - this.guiTop ); + this.processingScrollBar.click(this, x - this.guiLeft, y - this.guiTop); super.mouseClickMove(x, y, c, d); if (currentScroll != this.processingScrollBar.getCurrentScroll()) { changeActivePage(); } - } + } @Override - public void handleMouseInput() - { + public void handleMouseInput() { super.handleMouseInput(); final int wheel = Mouse.getEventDWheel(); @@ -198,7 +190,7 @@ public void handleMouseInput() if (wheel != 0) { final int x = Mouse.getEventX() * this.width / this.mc.displayWidth; final int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight; - + if (this.processingScrollBar.contains(x - this.guiLeft, y - this.guiTop)) { final int currentScroll = this.processingScrollBar.getCurrentScroll(); this.processingScrollBar.wheel(wheel); @@ -206,21 +198,17 @@ public void handleMouseInput() if (currentScroll != this.processingScrollBar.getCurrentScroll()) { changeActivePage(); } - } } + } - } - - private void changeActivePage() - { + private void changeActivePage() { try { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminalEx.ActivePage", String.valueOf(this.processingScrollBar.getCurrentScroll())) ); - } catch( final IOException e ) { + NetworkHandler.instance.sendToServer(new PacketValueConfig( + "PatternTerminalEx.ActivePage", String.valueOf(this.processingScrollBar.getCurrentScroll()))); + } catch (final IOException e) { e.printStackTrace(); } - } - } diff --git a/src/main/java/appeng/client/gui/implementations/GuiPatternValueAmount.java b/src/main/java/appeng/client/gui/implementations/GuiPatternValueAmount.java index fdbce75da38..76868fc9ce8 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiPatternValueAmount.java +++ b/src/main/java/appeng/client/gui/implementations/GuiPatternValueAmount.java @@ -16,7 +16,6 @@ import appeng.core.sync.packets.PacketPatternValueSet; import appeng.core.sync.packets.PacketSwitchGuis; import appeng.helpers.Reflected; -import appeng.helpers.WirelessTerminalGuiObject; import appeng.parts.reporting.PartPatternTerminal; import appeng.parts.reporting.PartPatternTerminalEx; import appeng.util.calculators.ArithHelper; @@ -29,8 +28,7 @@ import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; -public class GuiPatternValueAmount extends AEBaseGui -{ +public class GuiPatternValueAmount extends AEBaseGui { private GuiTextField amountToSet; private GuiTabButton originalGuiBtn; @@ -51,118 +49,105 @@ public class GuiPatternValueAmount extends AEBaseGui private final int originalAmount; @Reflected - public GuiPatternValueAmount( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( new ContainerPatternValueAmount( inventoryPlayer, te ) ); + public GuiPatternValueAmount(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(new ContainerPatternValueAmount(inventoryPlayer, te)); GuiContainer gui = (GuiContainer) Minecraft.getMinecraft().currentScreen; - if( gui != null && gui.theSlot != null && gui.theSlot.getHasStack() ) - { + if (gui != null && gui.theSlot != null && gui.theSlot.getHasStack()) { Slot slot = gui.theSlot; originalAmount = slot.getStack().stackSize; valueIndex = slot.slotNumber; - } else - { + } else { valueIndex = -1; originalAmount = 0; } } @Override - public void initGui() - { + public void initGui() { super.initGui(); - final int a = AEConfig.instance.craftItemsByStackAmounts( 0 ); - final int b = AEConfig.instance.craftItemsByStackAmounts( 1 ); - final int c = AEConfig.instance.craftItemsByStackAmounts( 2 ); - final int d = AEConfig.instance.craftItemsByStackAmounts( 3 ); + final int a = AEConfig.instance.craftItemsByStackAmounts(0); + final int b = AEConfig.instance.craftItemsByStackAmounts(1); + final int c = AEConfig.instance.craftItemsByStackAmounts(2); + final int d = AEConfig.instance.craftItemsByStackAmounts(3); - this.buttonList.add( this.plus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 26, 22, 20, "+" + a ) ); - this.buttonList.add( this.plus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 26, 28, 20, "+" + b ) ); - this.buttonList.add( this.plus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 26, 32, 20, "+" + c ) ); - this.buttonList.add( this.plus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 26, 38, 20, "+" + d ) ); + this.buttonList.add(this.plus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 26, 22, 20, "+" + a)); + this.buttonList.add(this.plus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 26, 28, 20, "+" + b)); + this.buttonList.add(this.plus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 26, 32, 20, "+" + c)); + this.buttonList.add(this.plus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 26, 38, 20, "+" + d)); - this.buttonList.add( this.minus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 75, 22, 20, "-" + a ) ); - this.buttonList.add( this.minus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 75, 28, 20, "-" + b ) ); - this.buttonList.add( this.minus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 75, 32, 20, "-" + c ) ); - this.buttonList.add( this.minus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 75, 38, 20, "-" + d ) ); - - this.buttonList.add( this.set = new GuiButton( 0, this.guiLeft + 128, this.guiTop + 51, 38, 20, GuiText.Next.getLocal() ) ); + this.buttonList.add(this.minus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 75, 22, 20, "-" + a)); + this.buttonList.add(this.minus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 75, 28, 20, "-" + b)); + this.buttonList.add(this.minus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 75, 32, 20, "-" + c)); + this.buttonList.add(this.minus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 75, 38, 20, "-" + d)); + this.buttonList.add( + this.set = new GuiButton(0, this.guiLeft + 128, this.guiTop + 51, 38, 20, GuiText.Next.getLocal())); ItemStack myIcon = null; - final Object target = ( (AEBaseContainer) this.inventorySlots ).getTarget(); + final Object target = ((AEBaseContainer) this.inventorySlots).getTarget(); final IDefinitions definitions = AEApi.instance().definitions(); final IParts parts = definitions.parts(); - if( target instanceof PartPatternTerminal ) - { - for( final ItemStack stack : parts.patternTerminal().maybeStack( 1 ).asSet() ) - { + if (target instanceof PartPatternTerminal) { + for (final ItemStack stack : parts.patternTerminal().maybeStack(1).asSet()) { myIcon = stack; } this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL; } - if( target instanceof PartPatternTerminalEx ) - { - for( final ItemStack stack : parts.patternTerminalEx().maybeStack( 1 ).asSet() ) - { + if (target instanceof PartPatternTerminalEx) { + for (final ItemStack stack : parts.patternTerminalEx().maybeStack(1).asSet()) { myIcon = stack; } this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL_EX; } - if( this.originalGui != null && myIcon != null ) - { - this.buttonList.add( this.originalGuiBtn = new GuiTabButton( this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), itemRender ) ); + if (this.originalGui != null && myIcon != null) { + this.buttonList.add( + this.originalGuiBtn = new GuiTabButton( + this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), itemRender)); } - this.amountToSet = new GuiTextField( this.fontRendererObj, this.guiLeft + 62, this.guiTop + 57, 59, this.fontRendererObj.FONT_HEIGHT ); - this.amountToSet.setEnableBackgroundDrawing( false ); - this.amountToSet.setMaxStringLength( 16 ); - this.amountToSet.setTextColor( GuiColors.CraftAmountToCraft.getColor() ); - this.amountToSet.setVisible( true ); - this.amountToSet.setFocused( true ); - this.amountToSet.setText( String.valueOf( originalAmount ) ); - this.amountToSet.setSelectionPos( 0 ); - + this.amountToSet = new GuiTextField( + this.fontRendererObj, this.guiLeft + 62, this.guiTop + 57, 59, this.fontRendererObj.FONT_HEIGHT); + this.amountToSet.setEnableBackgroundDrawing(false); + this.amountToSet.setMaxStringLength(16); + this.amountToSet.setTextColor(GuiColors.CraftAmountToCraft.getColor()); + this.amountToSet.setVisible(true); + this.amountToSet.setFocused(true); + this.amountToSet.setText(String.valueOf(originalAmount)); + this.amountToSet.setSelectionPos(0); } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( GuiText.SelectAmount.getLocal(), 8, 6, GuiColors.CraftAmountSelectAmount.getColor() ); + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + GuiText.SelectAmount.getLocal(), 8, 6, GuiColors.CraftAmountSelectAmount.getColor()); } @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { this.set.displayString = GuiText.Set.getLocal(); this.set.enabled = valueIndex >= 0; - this.bindTexture( "guis/craftAmt.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + this.bindTexture("guis/craftAmt.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); - try - { + try { String out = this.amountToSet.getText(); - double resultD = Calculator.conversion( out ); + double resultD = Calculator.conversion(out); int resultI; - if( resultD <= 0 || Double.isNaN( resultD ) ) - { + if (resultD <= 0 || Double.isNaN(resultD)) { resultI = 0; - } else - { - resultI = (int) ArithHelper.round( resultD, 0 ); + } else { + resultI = (int) ArithHelper.round(resultD, 0); } this.set.enabled = resultI > 0; - } catch( final NumberFormatException e ) - { + } catch (final NumberFormatException e) { this.set.enabled = false; } @@ -170,102 +155,84 @@ public void drawBG( final int offsetX, final int offsetY, final int mouseX, fina } @Override - protected void keyTyped( final char character, final int key ) - { - if( !this.checkHotbarKeys( key ) ) - { - if( key == 28 ) - { - this.actionPerformed( this.set ); + protected void keyTyped(final char character, final int key) { + if (!this.checkHotbarKeys(key)) { + if (key == 28) { + this.actionPerformed(this.set); } - this.amountToSet.textboxKeyTyped( character, key ); - super.keyTyped( character, key ); + this.amountToSet.textboxKeyTyped(character, key); + super.keyTyped(character, key); } } @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - try - { + try { - if( btn == this.originalGuiBtn ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.originalGui ) ); + if (btn == this.originalGuiBtn) { + NetworkHandler.instance.sendToServer(new PacketSwitchGuis(this.originalGui)); } - if( btn == this.set && btn.enabled ) - { - double resultD = Calculator.conversion( this.amountToSet.getText() ); + if (btn == this.set && btn.enabled) { + double resultD = Calculator.conversion(this.amountToSet.getText()); int resultI; - if( resultD <= 0 || Double.isNaN( resultD ) ) - { + if (resultD <= 0 || Double.isNaN(resultD)) { resultI = 1; - } else - { - resultI = (int) ArithHelper.round( resultD, 0 ); + } else { + resultI = (int) ArithHelper.round(resultD, 0); } - NetworkHandler.instance.sendToServer( new PacketPatternValueSet( originalGui.ordinal(), resultI, valueIndex ) ); + NetworkHandler.instance.sendToServer( + new PacketPatternValueSet(originalGui.ordinal(), resultI, valueIndex)); } - } catch( final NumberFormatException e ) - { + } catch (final NumberFormatException e) { // nope.. - this.amountToSet.setText( "1" ); + this.amountToSet.setText("1"); } final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; - final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; + final boolean isMinus = + btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; - if( isPlus || isMinus ) - { - this.addQty( this.getQty( btn ) ); + if (isPlus || isMinus) { + this.addQty(this.getQty(btn)); } } - private void addQty( final int i ) - { - try - { + private void addQty(final int i) { + try { String out = this.amountToSet.getText(); - double resultD = Calculator.conversion( out ); + double resultD = Calculator.conversion(out); int resultI; - if( resultD <= 0 || Double.isNaN( resultD ) ) - { + if (resultD <= 0 || Double.isNaN(resultD)) { resultI = 0; - } else - { - resultI = (int) ArithHelper.round( resultD, 0 ); + } else { + resultI = (int) ArithHelper.round(resultD, 0); } - if( resultI == 1 && i > 1 ) - { + if (resultI == 1 && i > 1) { resultI = 0; } resultI += i; - if( resultI < 1 ) - { + if (resultI < 1) { resultI = 1; } - out = Integer.toString( resultI ); + out = Integer.toString(resultI); - this.amountToSet.setText( out ); - } catch( final NumberFormatException e ) - { + this.amountToSet.setText(out); + } catch (final NumberFormatException e) { // :P } } - protected String getBackground() - { + protected String getBackground() { return "guis/craftAmt.png"; } - } diff --git a/src/main/java/appeng/client/gui/implementations/GuiPriority.java b/src/main/java/appeng/client/gui/implementations/GuiPriority.java index 911962136a5..d4e3d2f4f16 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiPriority.java +++ b/src/main/java/appeng/client/gui/implementations/GuiPriority.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.AEApi; import appeng.api.definitions.IBlocks; import appeng.api.definitions.IDefinitions; @@ -30,8 +29,8 @@ import appeng.container.implementations.ContainerPriority; import appeng.core.AEConfig; import appeng.core.AELog; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.GuiBridge; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketSwitchGuis; @@ -43,251 +42,224 @@ import appeng.tile.misc.TileInterface; import appeng.tile.storage.TileChest; import appeng.tile.storage.TileDrive; +import java.io.IOException; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; -import java.io.IOException; - - -public class GuiPriority extends AEBaseGui -{ - - private GuiNumberBox priority; - private GuiTabButton originalGuiBtn; - - private GuiButton plus1; - private GuiButton plus10; - private GuiButton plus100; - private GuiButton plus1000; - private GuiButton minus1; - private GuiButton minus10; - private GuiButton minus100; - private GuiButton minus1000; - - private GuiBridge OriginalGui; - - public GuiPriority( final InventoryPlayer inventoryPlayer, final IPriorityHost te ) - { - super( new ContainerPriority( inventoryPlayer, te ) ); - } - - @Override - public void initGui() - { - super.initGui(); - - final int a = AEConfig.instance.priorityByStacksAmounts( 0 ); - final int b = AEConfig.instance.priorityByStacksAmounts( 1 ); - final int c = AEConfig.instance.priorityByStacksAmounts( 2 ); - final int d = AEConfig.instance.priorityByStacksAmounts( 3 ); - - this.buttonList.add( this.plus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 32, 22, 20, "+" + a ) ); - this.buttonList.add( this.plus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 32, 28, 20, "+" + b ) ); - this.buttonList.add( this.plus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 32, 32, 20, "+" + c ) ); - this.buttonList.add( this.plus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 32, 38, 20, "+" + d ) ); - - this.buttonList.add( this.minus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 69, 22, 20, "-" + a ) ); - this.buttonList.add( this.minus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 69, 28, 20, "-" + b ) ); - this.buttonList.add( this.minus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 69, 32, 20, "-" + c ) ); - this.buttonList.add( this.minus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 69, 38, 20, "-" + d ) ); - - ItemStack myIcon = null; - final Object target = ( (AEBaseContainer) this.inventorySlots ).getTarget(); - final IDefinitions definitions = AEApi.instance().definitions(); - final IParts parts = definitions.parts(); - final IBlocks blocks = definitions.blocks(); - - if( target instanceof PartStorageBus ) - { - for( final ItemStack storageBusStack : parts.storageBus().maybeStack( 1 ).asSet() ) - { - myIcon = storageBusStack; - } - this.OriginalGui = GuiBridge.GUI_STORAGEBUS; - } - - if( target instanceof PartFormationPlane ) - { - for( final ItemStack formationPlaneStack : parts.formationPlane().maybeStack( 1 ).asSet() ) - { - myIcon = formationPlaneStack; - } - this.OriginalGui = GuiBridge.GUI_FORMATION_PLANE; - } - - if( target instanceof TileDrive ) - { - for( final ItemStack driveStack : blocks.drive().maybeStack( 1 ).asSet() ) - { - myIcon = driveStack; - } - - this.OriginalGui = GuiBridge.GUI_DRIVE; - } - - if( target instanceof TileChest ) - { - for( final ItemStack chestStack : blocks.chest().maybeStack( 1 ).asSet() ) - { - myIcon = chestStack; - } - - this.OriginalGui = GuiBridge.GUI_CHEST; - } - - if( target instanceof TileInterface ) - { - for( final ItemStack interfaceStack : blocks.iface().maybeStack( 1 ).asSet() ) - { - myIcon = interfaceStack; - } - - this.OriginalGui = GuiBridge.GUI_INTERFACE; - } - - if( target instanceof PartInterface ) - { - for( final ItemStack interfaceStack : parts.iface().maybeStack( 1 ).asSet() ) - { - myIcon = interfaceStack; - } - this.OriginalGui = GuiBridge.GUI_INTERFACE; - } - - if( this.OriginalGui != null && myIcon != null ) - { - this.buttonList.add( this.originalGuiBtn = new GuiTabButton( this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), itemRender ) ); - } - - this.priority = new GuiNumberBox( this.fontRendererObj, this.guiLeft + 62, this.guiTop + 57, 59, this.fontRendererObj.FONT_HEIGHT, Long.class ); - this.priority.setEnableBackgroundDrawing( false ); - this.priority.setMaxStringLength( 16 ); - this.priority.setTextColor( GuiColors.PriorityValue.getColor() ); - this.priority.setVisible( true ); - this.priority.setFocused( true ); - ( (ContainerPriority) this.inventorySlots ).setTextField( this.priority ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( GuiText.Priority.getLocal(), 8, 6, GuiColors.PriorityTitle.getColor() ); - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/priority.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - - this.priority.drawTextBox(); - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - if( btn == this.originalGuiBtn ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.OriginalGui ) ); - } - - final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; - final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; - - if( isPlus || isMinus ) - { - this.addQty( this.getQty( btn ) ); - } - } - - private void addQty( final int i ) - { - try - { - String out = this.priority.getText(); - - boolean fixed = false; - while( out.startsWith( "0" ) && out.length() > 1 ) - { - out = out.substring( 1 ); - fixed = true; - } - - if( fixed ) - { - this.priority.setText( out ); - } - - if( out.isEmpty() ) - { - out = "0"; - } - - long result = Long.parseLong( out ); - result += i; - - this.priority.setText( out = Long.toString( result ) ); - - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PriorityHost.Priority", out ) ); - } - catch( final NumberFormatException e ) - { - // nope.. - this.priority.setText( "0" ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - - @Override - protected void keyTyped( final char character, final int key ) - { - if( !this.checkHotbarKeys( key ) ) - { - if( ( key == 211 || key == 205 || key == 203 || key == 14 || character == '-' || Character.isDigit( character ) ) && this.priority.textboxKeyTyped( character, key ) ) - { - try - { - String out = this.priority.getText(); - - boolean fixed = false; - while( out.startsWith( "0" ) && out.length() > 1 ) - { - out = out.substring( 1 ); - fixed = true; - } - - if( fixed ) - { - this.priority.setText( out ); - } - - if( out.isEmpty() ) - { - out = "0"; - } - - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PriorityHost.Priority", out ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - else - { - super.keyTyped( character, key ); - } - } - } - - protected String getBackground() - { - return "guis/priority.png"; - } +public class GuiPriority extends AEBaseGui { + + private GuiNumberBox priority; + private GuiTabButton originalGuiBtn; + + private GuiButton plus1; + private GuiButton plus10; + private GuiButton plus100; + private GuiButton plus1000; + private GuiButton minus1; + private GuiButton minus10; + private GuiButton minus100; + private GuiButton minus1000; + + private GuiBridge OriginalGui; + + public GuiPriority(final InventoryPlayer inventoryPlayer, final IPriorityHost te) { + super(new ContainerPriority(inventoryPlayer, te)); + } + + @Override + public void initGui() { + super.initGui(); + + final int a = AEConfig.instance.priorityByStacksAmounts(0); + final int b = AEConfig.instance.priorityByStacksAmounts(1); + final int c = AEConfig.instance.priorityByStacksAmounts(2); + final int d = AEConfig.instance.priorityByStacksAmounts(3); + + this.buttonList.add(this.plus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 32, 22, 20, "+" + a)); + this.buttonList.add(this.plus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 32, 28, 20, "+" + b)); + this.buttonList.add(this.plus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 32, 32, 20, "+" + c)); + this.buttonList.add(this.plus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 32, 38, 20, "+" + d)); + + this.buttonList.add(this.minus1 = new GuiButton(0, this.guiLeft + 20, this.guiTop + 69, 22, 20, "-" + a)); + this.buttonList.add(this.minus10 = new GuiButton(0, this.guiLeft + 48, this.guiTop + 69, 28, 20, "-" + b)); + this.buttonList.add(this.minus100 = new GuiButton(0, this.guiLeft + 82, this.guiTop + 69, 32, 20, "-" + c)); + this.buttonList.add(this.minus1000 = new GuiButton(0, this.guiLeft + 120, this.guiTop + 69, 38, 20, "-" + d)); + + ItemStack myIcon = null; + final Object target = ((AEBaseContainer) this.inventorySlots).getTarget(); + final IDefinitions definitions = AEApi.instance().definitions(); + final IParts parts = definitions.parts(); + final IBlocks blocks = definitions.blocks(); + + if (target instanceof PartStorageBus) { + for (final ItemStack storageBusStack : + parts.storageBus().maybeStack(1).asSet()) { + myIcon = storageBusStack; + } + this.OriginalGui = GuiBridge.GUI_STORAGEBUS; + } + + if (target instanceof PartFormationPlane) { + for (final ItemStack formationPlaneStack : + parts.formationPlane().maybeStack(1).asSet()) { + myIcon = formationPlaneStack; + } + this.OriginalGui = GuiBridge.GUI_FORMATION_PLANE; + } + + if (target instanceof TileDrive) { + for (final ItemStack driveStack : blocks.drive().maybeStack(1).asSet()) { + myIcon = driveStack; + } + + this.OriginalGui = GuiBridge.GUI_DRIVE; + } + + if (target instanceof TileChest) { + for (final ItemStack chestStack : blocks.chest().maybeStack(1).asSet()) { + myIcon = chestStack; + } + + this.OriginalGui = GuiBridge.GUI_CHEST; + } + + if (target instanceof TileInterface) { + for (final ItemStack interfaceStack : blocks.iface().maybeStack(1).asSet()) { + myIcon = interfaceStack; + } + + this.OriginalGui = GuiBridge.GUI_INTERFACE; + } + + if (target instanceof PartInterface) { + for (final ItemStack interfaceStack : parts.iface().maybeStack(1).asSet()) { + myIcon = interfaceStack; + } + this.OriginalGui = GuiBridge.GUI_INTERFACE; + } + + if (this.OriginalGui != null && myIcon != null) { + this.buttonList.add( + this.originalGuiBtn = new GuiTabButton( + this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), itemRender)); + } + + this.priority = new GuiNumberBox( + this.fontRendererObj, + this.guiLeft + 62, + this.guiTop + 57, + 59, + this.fontRendererObj.FONT_HEIGHT, + Long.class); + this.priority.setEnableBackgroundDrawing(false); + this.priority.setMaxStringLength(16); + this.priority.setTextColor(GuiColors.PriorityValue.getColor()); + this.priority.setVisible(true); + this.priority.setFocused(true); + ((ContainerPriority) this.inventorySlots).setTextField(this.priority); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString(GuiText.Priority.getLocal(), 8, 6, GuiColors.PriorityTitle.getColor()); + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/priority.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + + this.priority.drawTextBox(); + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + if (btn == this.originalGuiBtn) { + NetworkHandler.instance.sendToServer(new PacketSwitchGuis(this.OriginalGui)); + } + + final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; + final boolean isMinus = + btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; + + if (isPlus || isMinus) { + this.addQty(this.getQty(btn)); + } + } + + private void addQty(final int i) { + try { + String out = this.priority.getText(); + + boolean fixed = false; + while (out.startsWith("0") && out.length() > 1) { + out = out.substring(1); + fixed = true; + } + + if (fixed) { + this.priority.setText(out); + } + + if (out.isEmpty()) { + out = "0"; + } + + long result = Long.parseLong(out); + result += i; + + this.priority.setText(out = Long.toString(result)); + + NetworkHandler.instance.sendToServer(new PacketValueConfig("PriorityHost.Priority", out)); + } catch (final NumberFormatException e) { + // nope.. + this.priority.setText("0"); + } catch (final IOException e) { + AELog.debug(e); + } + } + + @Override + protected void keyTyped(final char character, final int key) { + if (!this.checkHotbarKeys(key)) { + if ((key == 211 + || key == 205 + || key == 203 + || key == 14 + || character == '-' + || Character.isDigit(character)) + && this.priority.textboxKeyTyped(character, key)) { + try { + String out = this.priority.getText(); + + boolean fixed = false; + while (out.startsWith("0") && out.length() > 1) { + out = out.substring(1); + fixed = true; + } + + if (fixed) { + this.priority.setText(out); + } + + if (out.isEmpty()) { + out = "0"; + } + + NetworkHandler.instance.sendToServer(new PacketValueConfig("PriorityHost.Priority", out)); + } catch (final IOException e) { + AELog.debug(e); + } + } else { + super.keyTyped(character, key); + } + } + } + + protected String getBackground() { + return "guis/priority.png"; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiQNB.java b/src/main/java/appeng/client/gui/implementations/GuiQNB.java index e21f352832d..716b9c7aac6 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiQNB.java +++ b/src/main/java/appeng/client/gui/implementations/GuiQNB.java @@ -18,35 +18,34 @@ package appeng.client.gui.implementations; - import appeng.client.gui.AEBaseGui; import appeng.container.implementations.ContainerQNB; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.tile.qnb.TileQuantumBridge; import net.minecraft.entity.player.InventoryPlayer; - -public class GuiQNB extends AEBaseGui -{ - - public GuiQNB( final InventoryPlayer inventoryPlayer, final TileQuantumBridge te ) - { - super( new ContainerQNB( inventoryPlayer, te ) ); - this.ySize = 166; - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.QuantumLinkChamber.getLocal() ), 8, 6, GuiColors.QuantumLinkChamberTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.QuantumLinkChamberInventory.getColor() ); - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/chest.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } +public class GuiQNB extends AEBaseGui { + + public GuiQNB(final InventoryPlayer inventoryPlayer, final TileQuantumBridge te) { + super(new ContainerQNB(inventoryPlayer, te)); + this.ySize = 166; + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.QuantumLinkChamber.getLocal()), + 8, + 6, + GuiColors.QuantumLinkChamberTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.QuantumLinkChamberInventory.getColor()); + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/chest.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiQuartzKnife.java b/src/main/java/appeng/client/gui/implementations/GuiQuartzKnife.java index b7d0cb724e9..eccef79a4e8 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiQuartzKnife.java +++ b/src/main/java/appeng/client/gui/implementations/GuiQuartzKnife.java @@ -18,100 +18,89 @@ package appeng.client.gui.implementations; - import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.IDropToFillTextField; import appeng.client.gui.widgets.MEGuiTextField; import appeng.container.implementations.ContainerQuartzKnife; import appeng.core.AELog; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; import appeng.items.contents.QuartzKnifeObj; +import java.io.IOException; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; -import java.io.IOException; - - -public class GuiQuartzKnife extends AEBaseGui implements IDropToFillTextField -{ - - private MEGuiTextField textField; +public class GuiQuartzKnife extends AEBaseGui implements IDropToFillTextField { - public GuiQuartzKnife( final InventoryPlayer inventoryPlayer, final QuartzKnifeObj te ) - { - super( new ContainerQuartzKnife( inventoryPlayer, te ) ); - this.ySize = 184; + private MEGuiTextField textField; - this.textField = new MEGuiTextField(90, 12) - { + public GuiQuartzKnife(final InventoryPlayer inventoryPlayer, final QuartzKnifeObj te) { + super(new ContainerQuartzKnife(inventoryPlayer, te)); + this.ySize = 184; - @Override - public void onTextChange(final String oldText) - { - try { - final String Out = getText(); - ( (ContainerQuartzKnife) inventorySlots ).setName( Out ); - NetworkHandler.instance.sendToServer( new PacketValueConfig( "QuartzKnife.Name", Out ) ); - } catch (final IOException e) { - AELog.debug( e ); - } - } + this.textField = new MEGuiTextField(90, 12) { - }; + @Override + public void onTextChange(final String oldText) { + try { + final String Out = getText(); + ((ContainerQuartzKnife) inventorySlots).setName(Out); + NetworkHandler.instance.sendToServer(new PacketValueConfig("QuartzKnife.Name", Out)); + } catch (final IOException e) { + AELog.debug(e); + } + } + }; this.textField.setMaxStringLength(32); - } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.textField.x = this.guiLeft + 21; + this.textField.x = this.guiLeft + 21; this.textField.y = this.guiTop + 30; - this.textField.setFocused( true ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.QuartzCuttingKnife.getLocal() ), 8, 6, GuiColors.QuartzCuttingKnifeTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.QuartzCuttingKnifeInventory.getColor() ); - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/quartzknife.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - this.textField.drawTextBox(); - } - - @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) - { - this.textField.mouseClicked( xCoord, yCoord, btn ); - super.mouseClicked( xCoord, yCoord, btn ); - } - - @Override - protected void keyTyped( final char character, final int key ) - { - if (!this.textField.textboxKeyTyped(character, key)) { - super.keyTyped(character, key); - } - } - - public boolean isOverTextField(final int mousex, final int mousey) - { - return textField.isMouseIn(mousex, mousey); - } - - public void setTextFieldValue(final String displayName, final int mousex, final int mousey, final ItemStack stack) - { - textField.setText(displayName); - } - + this.textField.setFocused(true); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.QuartzCuttingKnife.getLocal()), + 8, + 6, + GuiColors.QuartzCuttingKnifeTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.QuartzCuttingKnifeInventory.getColor()); + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/quartzknife.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + this.textField.drawTextBox(); + } + + @Override + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) { + this.textField.mouseClicked(xCoord, yCoord, btn); + super.mouseClicked(xCoord, yCoord, btn); + } + + @Override + protected void keyTyped(final char character, final int key) { + if (!this.textField.textboxKeyTyped(character, key)) { + super.keyTyped(character, key); + } + } + + public boolean isOverTextField(final int mousex, final int mousey) { + return textField.isMouseIn(mousex, mousey); + } + + public void setTextFieldValue(final String displayName, final int mousex, final int mousey, final ItemStack stack) { + textField.setText(displayName); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiRenamer.java b/src/main/java/appeng/client/gui/implementations/GuiRenamer.java index 0ff90a83cda..f592aafd1d1 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiRenamer.java +++ b/src/main/java/appeng/client/gui/implementations/GuiRenamer.java @@ -5,45 +5,38 @@ import appeng.client.gui.widgets.MEGuiTextField; import appeng.container.implementations.ContainerRenamer; import appeng.core.AELog; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; import appeng.helpers.ICustomNameObject; +import java.io.IOException; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; -import java.io.IOException; - -public class GuiRenamer extends AEBaseGui implements IDropToFillTextField -{ +public class GuiRenamer extends AEBaseGui implements IDropToFillTextField { private MEGuiTextField textField; - public GuiRenamer(InventoryPlayer ip, ICustomNameObject obj) - { + public GuiRenamer(InventoryPlayer ip, ICustomNameObject obj) { super(new ContainerRenamer(ip, obj)); this.xSize = 256; - this.textField = new MEGuiTextField(230, 12) - { + this.textField = new MEGuiTextField(230, 12) { - @Override - public void onTextChange(final String oldText) - { + @Override + public void onTextChange(final String oldText) { final String text = getText(); if (!text.equals(oldText)) { ((ContainerRenamer) inventorySlots).setCustomName(text); } - } - - }; + } + }; this.textField.setMaxStringLength(32); } @Override - public void initGui() - { + public void initGui() { super.initGui(); this.textField.x = this.guiLeft + 12; @@ -54,32 +47,29 @@ public void initGui() } @Override - public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.fontRendererObj.drawString( GuiText.Renamer.getLocal(), 12, 8, GuiColors.RenamerTitle.getColor() ); + public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY) { + this.fontRendererObj.drawString(GuiText.Renamer.getLocal(), 12, 8, GuiColors.RenamerTitle.getColor()); } @Override - public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) - { - this.bindTexture( "guis/renamer.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + public void drawBG(int offsetX, int offsetY, int mouseX, int mouseY) { + this.bindTexture("guis/renamer.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); this.textField.drawTextBox(); } @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) - { - this.textField.mouseClicked( xCoord, yCoord, btn ); - super.mouseClicked( xCoord, yCoord, btn ); - } + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) { + this.textField.mouseClicked(xCoord, yCoord, btn); + super.mouseClicked(xCoord, yCoord, btn); + } @Override - protected void keyTyped(final char character, final int key) - { + protected void keyTyped(final char character, final int key) { if (key == 28) { // Enter try { - NetworkHandler.instance.sendToServer(new PacketValueConfig("QuartzKnife.ReName", this.textField.getText())); + NetworkHandler.instance.sendToServer( + new PacketValueConfig("QuartzKnife.ReName", this.textField.getText())); } catch (IOException e) { AELog.debug(e); } @@ -87,17 +77,13 @@ protected void keyTyped(final char character, final int key) } else if (!this.textField.textboxKeyTyped(character, key)) { super.keyTyped(character, key); } - } - public boolean isOverTextField(final int mousex, final int mousey) - { - return textField.isMouseIn(mousex, mousey); - } - - public void setTextFieldValue(final String displayName, final int mousex, final int mousey, final ItemStack stack) - { - textField.setText(displayName); - } + public boolean isOverTextField(final int mousex, final int mousey) { + return textField.isMouseIn(mousex, mousey); + } + public void setTextFieldValue(final String displayName, final int mousex, final int mousey, final ItemStack stack) { + textField.setText(displayName); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiSecurity.java b/src/main/java/appeng/client/gui/implementations/GuiSecurity.java index afec6f79d8a..8398825bde2 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiSecurity.java +++ b/src/main/java/appeng/client/gui/implementations/GuiSecurity.java @@ -18,124 +18,145 @@ package appeng.client.gui.implementations; - import appeng.api.config.SecurityPermissions; import appeng.api.config.SortOrder; import appeng.api.storage.ITerminalHost; import appeng.client.gui.widgets.GuiToggleButton; import appeng.container.implementations.ContainerSecurity; import appeng.core.AELog; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; -import net.minecraft.entity.player.InventoryPlayer; - import java.io.IOException; +import net.minecraft.entity.player.InventoryPlayer; - -public class GuiSecurity extends GuiMEMonitorable -{ - - private GuiToggleButton inject; - private GuiToggleButton extract; - private GuiToggleButton craft; - private GuiToggleButton build; - private GuiToggleButton security; - - public GuiSecurity( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( inventoryPlayer, te, new ContainerSecurity( inventoryPlayer, te ) ); - this.setCustomSortOrder( false ); - this.setReservedSpace( 33 ); - - // increase size so that the slot is over the gui. - this.xSize += 56; - this.setStandardSize( this.xSize ); - } - - @Override - protected void actionPerformed( final net.minecraft.client.gui.GuiButton btn ) - { - super.actionPerformed( btn ); - - SecurityPermissions toggleSetting = null; - - if( btn == this.inject ) - { - toggleSetting = SecurityPermissions.INJECT; - } - if( btn == this.extract ) - { - toggleSetting = SecurityPermissions.EXTRACT; - } - if( btn == this.craft ) - { - toggleSetting = SecurityPermissions.CRAFT; - } - if( btn == this.build ) - { - toggleSetting = SecurityPermissions.BUILD; - } - if( btn == this.security ) - { - toggleSetting = SecurityPermissions.SECURITY; - } - - if( toggleSetting != null ) - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "TileSecurity.ToggleOption", toggleSetting.name() ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - - @Override - public void initGui() - { - super.initGui(); - - final int top = this.guiTop + this.ySize - 116; - this.buttonList.add( this.inject = new GuiToggleButton( this.guiLeft + 56, top, 11 * 16, 12 * 16, SecurityPermissions.INJECT.getUnlocalizedName(), SecurityPermissions.INJECT.getUnlocalizedTip() ) ); - - this.buttonList.add( this.extract = new GuiToggleButton( this.guiLeft + 56 + 18, top, 11 * 16 + 1, 12 * 16 + 1, SecurityPermissions.EXTRACT.getUnlocalizedName(), SecurityPermissions.EXTRACT.getUnlocalizedTip() ) ); - - this.buttonList.add( this.craft = new GuiToggleButton( this.guiLeft + 56 + 18 * 2, top, 11 * 16 + 2, 12 * 16 + 2, SecurityPermissions.CRAFT.getUnlocalizedName(), SecurityPermissions.CRAFT.getUnlocalizedTip() ) ); - - this.buttonList.add( this.build = new GuiToggleButton( this.guiLeft + 56 + 18 * 3, top, 11 * 16 + 3, 12 * 16 + 3, SecurityPermissions.BUILD.getUnlocalizedName(), SecurityPermissions.BUILD.getUnlocalizedTip() ) ); - - this.buttonList.add( this.security = new GuiToggleButton( this.guiLeft + 56 + 18 * 4, top, 11 * 16 + 4, 12 * 16 + 4, SecurityPermissions.SECURITY.getUnlocalizedName(), SecurityPermissions.SECURITY.getUnlocalizedTip() ) ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - this.fontRendererObj.drawString( GuiText.SecurityCardEditor.getLocal(), 8, this.ySize - 96 + 1 - this.getReservedSpace(), GuiColors.SecurityCardEditorTitle.getColor() ); - } - - @Override - protected String getBackground() - { - final ContainerSecurity cs = (ContainerSecurity) this.inventorySlots; - - this.inject.setState( ( cs.getPermissionMode() & ( 1 << SecurityPermissions.INJECT.ordinal() ) ) > 0 ); - this.extract.setState( ( cs.getPermissionMode() & ( 1 << SecurityPermissions.EXTRACT.ordinal() ) ) > 0 ); - this.craft.setState( ( cs.getPermissionMode() & ( 1 << SecurityPermissions.CRAFT.ordinal() ) ) > 0 ); - this.build.setState( ( cs.getPermissionMode() & ( 1 << SecurityPermissions.BUILD.ordinal() ) ) > 0 ); - this.security.setState( ( cs.getPermissionMode() & ( 1 << SecurityPermissions.SECURITY.ordinal() ) ) > 0 ); - - return "guis/security.png"; - } - - @Override - public Enum getSortBy() - { - return SortOrder.NAME; - } +public class GuiSecurity extends GuiMEMonitorable { + + private GuiToggleButton inject; + private GuiToggleButton extract; + private GuiToggleButton craft; + private GuiToggleButton build; + private GuiToggleButton security; + + public GuiSecurity(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(inventoryPlayer, te, new ContainerSecurity(inventoryPlayer, te)); + this.setCustomSortOrder(false); + this.setReservedSpace(33); + + // increase size so that the slot is over the gui. + this.xSize += 56; + this.setStandardSize(this.xSize); + } + + @Override + protected void actionPerformed(final net.minecraft.client.gui.GuiButton btn) { + super.actionPerformed(btn); + + SecurityPermissions toggleSetting = null; + + if (btn == this.inject) { + toggleSetting = SecurityPermissions.INJECT; + } + if (btn == this.extract) { + toggleSetting = SecurityPermissions.EXTRACT; + } + if (btn == this.craft) { + toggleSetting = SecurityPermissions.CRAFT; + } + if (btn == this.build) { + toggleSetting = SecurityPermissions.BUILD; + } + if (btn == this.security) { + toggleSetting = SecurityPermissions.SECURITY; + } + + if (toggleSetting != null) { + try { + NetworkHandler.instance.sendToServer( + new PacketValueConfig("TileSecurity.ToggleOption", toggleSetting.name())); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + + @Override + public void initGui() { + super.initGui(); + + final int top = this.guiTop + this.ySize - 116; + this.buttonList.add( + this.inject = new GuiToggleButton( + this.guiLeft + 56, + top, + 11 * 16, + 12 * 16, + SecurityPermissions.INJECT.getUnlocalizedName(), + SecurityPermissions.INJECT.getUnlocalizedTip())); + + this.buttonList.add( + this.extract = new GuiToggleButton( + this.guiLeft + 56 + 18, + top, + 11 * 16 + 1, + 12 * 16 + 1, + SecurityPermissions.EXTRACT.getUnlocalizedName(), + SecurityPermissions.EXTRACT.getUnlocalizedTip())); + + this.buttonList.add( + this.craft = new GuiToggleButton( + this.guiLeft + 56 + 18 * 2, + top, + 11 * 16 + 2, + 12 * 16 + 2, + SecurityPermissions.CRAFT.getUnlocalizedName(), + SecurityPermissions.CRAFT.getUnlocalizedTip())); + + this.buttonList.add( + this.build = new GuiToggleButton( + this.guiLeft + 56 + 18 * 3, + top, + 11 * 16 + 3, + 12 * 16 + 3, + SecurityPermissions.BUILD.getUnlocalizedName(), + SecurityPermissions.BUILD.getUnlocalizedTip())); + + this.buttonList.add( + this.security = new GuiToggleButton( + this.guiLeft + 56 + 18 * 4, + top, + 11 * 16 + 4, + 12 * 16 + 4, + SecurityPermissions.SECURITY.getUnlocalizedName(), + SecurityPermissions.SECURITY.getUnlocalizedTip())); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + super.drawFG(offsetX, offsetY, mouseX, mouseY); + this.fontRendererObj.drawString( + GuiText.SecurityCardEditor.getLocal(), + 8, + this.ySize - 96 + 1 - this.getReservedSpace(), + GuiColors.SecurityCardEditorTitle.getColor()); + } + + @Override + protected String getBackground() { + final ContainerSecurity cs = (ContainerSecurity) this.inventorySlots; + + this.inject.setState((cs.getPermissionMode() & (1 << SecurityPermissions.INJECT.ordinal())) > 0); + this.extract.setState((cs.getPermissionMode() & (1 << SecurityPermissions.EXTRACT.ordinal())) > 0); + this.craft.setState((cs.getPermissionMode() & (1 << SecurityPermissions.CRAFT.ordinal())) > 0); + this.build.setState((cs.getPermissionMode() & (1 << SecurityPermissions.BUILD.ordinal())) > 0); + this.security.setState((cs.getPermissionMode() & (1 << SecurityPermissions.SECURITY.ordinal())) > 0); + + return "guis/security.png"; + } + + @Override + public Enum getSortBy() { + return SortOrder.NAME; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiSkyChest.java b/src/main/java/appeng/client/gui/implementations/GuiSkyChest.java index a358dc38d0d..75e7a006d04 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiSkyChest.java +++ b/src/main/java/appeng/client/gui/implementations/GuiSkyChest.java @@ -18,43 +18,38 @@ package appeng.client.gui.implementations; - import appeng.client.gui.AEBaseGui; import appeng.container.implementations.ContainerSkyChest; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.integration.IntegrationRegistry; import appeng.integration.IntegrationType; import appeng.tile.storage.TileSkyChest; import net.minecraft.entity.player.InventoryPlayer; - -public class GuiSkyChest extends AEBaseGui -{ - - public GuiSkyChest( final InventoryPlayer inventoryPlayer, final TileSkyChest te ) - { - super( new ContainerSkyChest( inventoryPlayer, te ) ); - this.ySize = 195; - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.SkyChest.getLocal() ), 8, 8, GuiColors.SkyChestTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 2, GuiColors.SkyChestInventory.getColor() ); - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/skychest.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - @Override - protected boolean enableSpaceClicking() - { - return !IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.InvTweaks ); - } +public class GuiSkyChest extends AEBaseGui { + + public GuiSkyChest(final InventoryPlayer inventoryPlayer, final TileSkyChest te) { + super(new ContainerSkyChest(inventoryPlayer, te)); + this.ySize = 195; + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.SkyChest.getLocal()), 8, 8, GuiColors.SkyChestTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 2, GuiColors.SkyChestInventory.getColor()); + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/skychest.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } + + @Override + protected boolean enableSpaceClicking() { + return !IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.InvTweaks); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiSpatialIOPort.java b/src/main/java/appeng/client/gui/implementations/GuiSpatialIOPort.java index 9c2521da136..b04ba69b678 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiSpatialIOPort.java +++ b/src/main/java/appeng/client/gui/implementations/GuiSpatialIOPort.java @@ -18,73 +18,85 @@ package appeng.client.gui.implementations; - import appeng.api.config.Settings; import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiImgButton; import appeng.container.implementations.ContainerSpatialIOPort; import appeng.core.AEConfig; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.tile.spatial.TileSpatialIOPort; import appeng.util.Platform; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Mouse; +public class GuiSpatialIOPort extends AEBaseGui { -public class GuiSpatialIOPort extends AEBaseGui -{ - - private final ContainerSpatialIOPort container; - private GuiImgButton units; + private final ContainerSpatialIOPort container; + private GuiImgButton units; - public GuiSpatialIOPort( final InventoryPlayer inventoryPlayer, final TileSpatialIOPort te ) - { - super( new ContainerSpatialIOPort( inventoryPlayer, te ) ); - this.ySize = 199; - this.container = (ContainerSpatialIOPort) this.inventorySlots; - } + public GuiSpatialIOPort(final InventoryPlayer inventoryPlayer, final TileSpatialIOPort te) { + super(new ContainerSpatialIOPort(inventoryPlayer, te)); + this.ySize = 199; + this.container = (ContainerSpatialIOPort) this.inventorySlots; + } - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean backwards = Mouse.isButtonDown(1); - if( btn == this.units ) - { - AEConfig.instance.nextPowerUnit( backwards ); - this.units.set( AEConfig.instance.selectedPowerUnit() ); - } - } + if (btn == this.units) { + AEConfig.instance.nextPowerUnit(backwards); + this.units.set(AEConfig.instance.selectedPowerUnit()); + } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.units = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.POWER_UNITS, AEConfig.instance.selectedPowerUnit() ); - this.buttonList.add( this.units ); - } + this.units = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 8, Settings.POWER_UNITS, AEConfig.instance.selectedPowerUnit()); + this.buttonList.add(this.units); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( GuiText.StoredPower.getLocal() + ": " + Platform.formatPowerLong( this.container.getCurrentPower(), false ), 13, 21, GuiColors.SpatialIOStoredPower.getColor() ); - this.fontRendererObj.drawString( GuiText.MaxPower.getLocal() + ": " + Platform.formatPowerLong( this.container.getMaxPower(), false ), 13, 31, GuiColors.SpatialIOMaxPower.getColor() ); - this.fontRendererObj.drawString( GuiText.RequiredPower.getLocal() + ": " + Platform.formatPowerLong( this.container.getRequiredPower(), false ), 13, 78, GuiColors.SpatialIORequiredPower.getColor() ); - this.fontRendererObj.drawString( GuiText.Efficiency.getLocal() + ": " + ( ( (float) this.container.getEfficency() ) / 100 ) + '%', 13, 88, GuiColors.SpatialIOEfficiency.getColor() ); + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + GuiText.StoredPower.getLocal() + ": " + + Platform.formatPowerLong(this.container.getCurrentPower(), false), + 13, + 21, + GuiColors.SpatialIOStoredPower.getColor()); + this.fontRendererObj.drawString( + GuiText.MaxPower.getLocal() + ": " + Platform.formatPowerLong(this.container.getMaxPower(), false), + 13, + 31, + GuiColors.SpatialIOMaxPower.getColor()); + this.fontRendererObj.drawString( + GuiText.RequiredPower.getLocal() + ": " + + Platform.formatPowerLong(this.container.getRequiredPower(), false), + 13, + 78, + GuiColors.SpatialIORequiredPower.getColor()); + this.fontRendererObj.drawString( + GuiText.Efficiency.getLocal() + ": " + (((float) this.container.getEfficency()) / 100) + '%', + 13, + 88, + GuiColors.SpatialIOEfficiency.getColor()); - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.SpatialIOPort.getLocal() ), 8, 6, GuiColors.SpatialIOTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96, GuiColors.SpatialIOInventory.getColor() ); - } + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.SpatialIOPort.getLocal()), 8, 6, GuiColors.SpatialIOTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96, GuiColors.SpatialIOInventory.getColor()); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/spatialio.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/spatialio.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiStorageBus.java b/src/main/java/appeng/client/gui/implementations/GuiStorageBus.java index 2980c3b049b..08ade767b3c 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiStorageBus.java +++ b/src/main/java/appeng/client/gui/implementations/GuiStorageBus.java @@ -18,124 +18,109 @@ package appeng.client.gui.implementations; - import appeng.api.config.*; import appeng.client.gui.widgets.GuiImgButton; import appeng.client.gui.widgets.GuiTabButton; import appeng.container.implementations.ContainerStorageBus; import appeng.core.AELog; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.GuiBridge; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketConfigButton; import appeng.core.sync.packets.PacketSwitchGuis; import appeng.core.sync.packets.PacketValueConfig; import appeng.parts.misc.PartStorageBus; +import java.io.IOException; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Mouse; -import java.io.IOException; - - -public class GuiStorageBus extends GuiUpgradeable -{ - - private GuiImgButton rwMode; - private GuiImgButton storageFilter; - private GuiTabButton priority; - private GuiImgButton partition; - private GuiImgButton clear; - - public GuiStorageBus( final InventoryPlayer inventoryPlayer, final PartStorageBus te ) - { - super( new ContainerStorageBus( inventoryPlayer, te ) ); - this.ySize = 251; - } - - @Override - @SuppressWarnings( "unchecked" ) - protected void addButtons() - { - this.clear = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.ACTIONS, ActionItems.CLOSE ); - this.partition = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH ); - this.rwMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.ACCESS, AccessRestriction.READ_WRITE ); - this.storageFilter = new GuiImgButton( this.guiLeft - 18, this.guiTop + 68, Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 88, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.oreFilter = new GuiImgButton( this.guiLeft - 18, this.guiTop + 88, Settings.ACTIONS, ActionItems.ORE_FILTER); - - this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender ) ); - - this.buttonList.add( this.storageFilter ); - this.buttonList.add( this.fuzzyMode ); - this.buttonList.add( this.rwMode ); - this.buttonList.add( this.partition ); - this.buttonList.add( this.clear ); - this.buttonList.add( this.oreFilter ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.StorageBus.getLocal() ), 8, 6, GuiColors.StorageBusTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.StorageBusInventory.getColor() ); - - if( this.fuzzyMode != null ) - { - this.fuzzyMode.set( this.cvb.getFuzzyMode() ); - } - - if( this.storageFilter != null ) - { - this.storageFilter.set( ( (ContainerStorageBus) this.cvb ).getStorageFilter() ); - } - - if( this.rwMode != null ) - { - this.rwMode.set( ( (ContainerStorageBus) this.cvb ).getReadWriteMode() ); - } - } - - @Override - protected String getBackground() - { - return "guis/storagebus.png"; - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - final boolean backwards = Mouse.isButtonDown( 1 ); - - try - { - if( btn == this.partition ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "StorageBus.Action", "Partition" ) ); - } - else if( btn == this.clear ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "StorageBus.Action", "Clear" ) ); - } - else if( btn == this.priority ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - else if( btn == this.rwMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.rwMode.getSetting(), backwards ) ); - } - else if( btn == this.storageFilter ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.storageFilter.getSetting(), backwards ) ); - } - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } +public class GuiStorageBus extends GuiUpgradeable { + + private GuiImgButton rwMode; + private GuiImgButton storageFilter; + private GuiTabButton priority; + private GuiImgButton partition; + private GuiImgButton clear; + + public GuiStorageBus(final InventoryPlayer inventoryPlayer, final PartStorageBus te) { + super(new ContainerStorageBus(inventoryPlayer, te)); + this.ySize = 251; + } + + @Override + @SuppressWarnings("unchecked") + protected void addButtons() { + this.clear = new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.ACTIONS, ActionItems.CLOSE); + this.partition = new GuiImgButton(this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH); + this.rwMode = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 48, Settings.ACCESS, AccessRestriction.READ_WRITE); + this.storageFilter = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 68, Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY); + this.fuzzyMode = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 88, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.oreFilter = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 88, Settings.ACTIONS, ActionItems.ORE_FILTER); + + this.buttonList.add( + this.priority = new GuiTabButton( + this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender)); + + this.buttonList.add(this.storageFilter); + this.buttonList.add(this.fuzzyMode); + this.buttonList.add(this.rwMode); + this.buttonList.add(this.partition); + this.buttonList.add(this.clear); + this.buttonList.add(this.oreFilter); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.StorageBus.getLocal()), 8, 6, GuiColors.StorageBusTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.StorageBusInventory.getColor()); + + if (this.fuzzyMode != null) { + this.fuzzyMode.set(this.cvb.getFuzzyMode()); + } + + if (this.storageFilter != null) { + this.storageFilter.set(((ContainerStorageBus) this.cvb).getStorageFilter()); + } + + if (this.rwMode != null) { + this.rwMode.set(((ContainerStorageBus) this.cvb).getReadWriteMode()); + } + } + + @Override + protected String getBackground() { + return "guis/storagebus.png"; + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + final boolean backwards = Mouse.isButtonDown(1); + + try { + if (btn == this.partition) { + NetworkHandler.instance.sendToServer(new PacketValueConfig("StorageBus.Action", "Partition")); + } else if (btn == this.clear) { + NetworkHandler.instance.sendToServer(new PacketValueConfig("StorageBus.Action", "Clear")); + } else if (btn == this.priority) { + NetworkHandler.instance.sendToServer(new PacketSwitchGuis(GuiBridge.GUI_PRIORITY)); + } else if (btn == this.rwMode) { + NetworkHandler.instance.sendToServer(new PacketConfigButton(this.rwMode.getSetting(), backwards)); + } else if (btn == this.storageFilter) { + NetworkHandler.instance.sendToServer( + new PacketConfigButton(this.storageFilter.getSetting(), backwards)); + } + } catch (final IOException e) { + AELog.debug(e); + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java b/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java index 64730204c70..439452a6d34 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java +++ b/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java @@ -18,15 +18,15 @@ package appeng.client.gui.implementations; - +import akka.japi.Pair; import appeng.api.config.*; import appeng.api.implementations.IUpgradeableHost; import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiImgButton; import appeng.container.implementations.ContainerUpgradeable; import appeng.container.slot.SlotFake; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.core.sync.GuiBridge; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketConfigButton; @@ -34,258 +34,221 @@ import appeng.core.sync.packets.PacketSwitchGuis; import appeng.parts.automation.PartExportBus; import appeng.parts.automation.PartImportBus; -import akka.japi.Pair; import codechicken.nei.VisiblityData; import codechicken.nei.api.INEIGuiHandler; import codechicken.nei.api.TaggedInventoryArea; import cpw.mods.fml.common.Optional; +import java.awt.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import org.lwjgl.input.Mouse; -import java.awt.*; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +@Optional.Interface(modid = "NotEnoughItems", iface = "codechicken.nei.api.INEIGuiHandler") +public class GuiUpgradeable extends AEBaseGui implements INEIGuiHandler { + protected final ContainerUpgradeable cvb; + protected final IUpgradeableHost bc; -@Optional.Interface(modid = "NotEnoughItems", iface = "codechicken.nei.api.INEIGuiHandler") -public class GuiUpgradeable extends AEBaseGui implements INEIGuiHandler -{ - - protected final ContainerUpgradeable cvb; - protected final IUpgradeableHost bc; - - protected GuiImgButton redstoneMode; - protected GuiImgButton fuzzyMode; - protected GuiImgButton craftMode; - protected GuiImgButton schedulingMode; - protected GuiImgButton oreFilter; - - public GuiUpgradeable( final InventoryPlayer inventoryPlayer, final IUpgradeableHost te ) - { - this( new ContainerUpgradeable( inventoryPlayer, te ) ); - } - - public GuiUpgradeable( final ContainerUpgradeable te ) - { - super( te ); - this.cvb = te; - - this.bc = (IUpgradeableHost) te.getTarget(); - this.xSize = this.hasToolbox() ? 246 : 211; - this.ySize = 184; - } - - protected boolean hasToolbox() - { - return ( (ContainerUpgradeable) this.inventorySlots ).hasToolbox(); - } - - @Override - public void initGui() - { - super.initGui(); - this.addButtons(); - } - - @SuppressWarnings( "unchecked" ) - protected void addButtons() - { - this.redstoneMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.craftMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.CRAFT_ONLY, YesNo.NO ); - this.schedulingMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 68, Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT ); - this.oreFilter = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.ORE_FILTER); - - this.buttonList.add( this.craftMode ); - this.buttonList.add( this.redstoneMode ); - this.buttonList.add( this.fuzzyMode ); - this.buttonList.add( this.schedulingMode ); - this.buttonList.add( this.oreFilter ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( this.getName().getLocal() ), 8, 6, GuiColors.UpgradableTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.UpgradableInventory.getColor() ); - - if( this.redstoneMode != null ) - { - this.redstoneMode.set( this.cvb.getRedStoneMode() ); - } - - if( this.fuzzyMode != null ) - { - this.fuzzyMode.set( this.cvb.getFuzzyMode() ); - } - - if( this.craftMode != null ) - { - this.craftMode.set( this.cvb.getCraftingMode() ); - } - - if( this.schedulingMode != null ) - { - this.schedulingMode.set( this.cvb.getSchedulingMode() ); - } - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.handleButtonVisibility(); - - this.bindTexture( this.getBackground() ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, 211 - 34, this.ySize ); - if( this.drawUpgrades() ) - { - this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 14 + this.cvb.availableUpgrades() * 18 ); - } - if( this.hasToolbox() ) - { - this.drawTexturedModalRect( offsetX + 178, offsetY + this.ySize - 90, 178, this.ySize - 90, 68, 68 ); - } - } - - protected void handleButtonVisibility() - { - if( this.redstoneMode != null ) - { - this.redstoneMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.REDSTONE ) > 0 ); - } - if( this.fuzzyMode != null ) - { - this.fuzzyMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.FUZZY ) > 0 && this.bc.getInstalledUpgrades( Upgrades.ORE_FILTER ) == 0); - } - if( this.craftMode != null ) - { - this.craftMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ); - } - if( this.schedulingMode != null ) - { - this.schedulingMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.CAPACITY ) > 0 && this.bc instanceof PartExportBus ); - } - if( this.oreFilter != null ) - { - this.oreFilter.setVisibility( this.bc.getInstalledUpgrades( Upgrades.ORE_FILTER ) > 0); - } - } - - protected String getBackground() - { - return "guis/bus.png"; - } - - protected boolean drawUpgrades() - { - return true; - } - - protected GuiText getName() - { - return this.bc instanceof PartImportBus ? GuiText.ImportBus : GuiText.ExportBus; - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - final boolean backwards = Mouse.isButtonDown( 1 ); - - if( btn == this.redstoneMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.redstoneMode.getSetting(), backwards ) ); - } - - if( btn == this.craftMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.craftMode.getSetting(), backwards ) ); - } - - if( btn == this.fuzzyMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.fuzzyMode.getSetting(), backwards ) ); - } - - if( btn == this.schedulingMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.schedulingMode.getSetting(), backwards ) ); - } - - if( btn == this.oreFilter ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_ORE_FILTER ) ); - } - } + protected GuiImgButton redstoneMode; + protected GuiImgButton fuzzyMode; + protected GuiImgButton craftMode; + protected GuiImgButton schedulingMode; + protected GuiImgButton oreFilter; + + public GuiUpgradeable(final InventoryPlayer inventoryPlayer, final IUpgradeableHost te) { + this(new ContainerUpgradeable(inventoryPlayer, te)); + } + + public GuiUpgradeable(final ContainerUpgradeable te) { + super(te); + this.cvb = te; + + this.bc = (IUpgradeableHost) te.getTarget(); + this.xSize = this.hasToolbox() ? 246 : 211; + this.ySize = 184; + } + + protected boolean hasToolbox() { + return ((ContainerUpgradeable) this.inventorySlots).hasToolbox(); + } + + @Override + public void initGui() { + super.initGui(); + this.addButtons(); + } + + @SuppressWarnings("unchecked") + protected void addButtons() { + this.redstoneMode = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 8, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.fuzzyMode = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 28, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.craftMode = new GuiImgButton(this.guiLeft - 18, this.guiTop + 48, Settings.CRAFT_ONLY, YesNo.NO); + this.schedulingMode = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 68, Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT); + this.oreFilter = + new GuiImgButton(this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.ORE_FILTER); + + this.buttonList.add(this.craftMode); + this.buttonList.add(this.redstoneMode); + this.buttonList.add(this.fuzzyMode); + this.buttonList.add(this.schedulingMode); + this.buttonList.add(this.oreFilter); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + this.getGuiDisplayName(this.getName().getLocal()), 8, 6, GuiColors.UpgradableTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.UpgradableInventory.getColor()); + + if (this.redstoneMode != null) { + this.redstoneMode.set(this.cvb.getRedStoneMode()); + } + + if (this.fuzzyMode != null) { + this.fuzzyMode.set(this.cvb.getFuzzyMode()); + } + + if (this.craftMode != null) { + this.craftMode.set(this.cvb.getCraftingMode()); + } + + if (this.schedulingMode != null) { + this.schedulingMode.set(this.cvb.getSchedulingMode()); + } + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.handleButtonVisibility(); + + this.bindTexture(this.getBackground()); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, 211 - 34, this.ySize); + if (this.drawUpgrades()) { + this.drawTexturedModalRect(offsetX + 177, offsetY, 177, 0, 35, 14 + this.cvb.availableUpgrades() * 18); + } + if (this.hasToolbox()) { + this.drawTexturedModalRect(offsetX + 178, offsetY + this.ySize - 90, 178, this.ySize - 90, 68, 68); + } + } + + protected void handleButtonVisibility() { + if (this.redstoneMode != null) { + this.redstoneMode.setVisibility(this.bc.getInstalledUpgrades(Upgrades.REDSTONE) > 0); + } + if (this.fuzzyMode != null) { + this.fuzzyMode.setVisibility(this.bc.getInstalledUpgrades(Upgrades.FUZZY) > 0 + && this.bc.getInstalledUpgrades(Upgrades.ORE_FILTER) == 0); + } + if (this.craftMode != null) { + this.craftMode.setVisibility(this.bc.getInstalledUpgrades(Upgrades.CRAFTING) > 0); + } + if (this.schedulingMode != null) { + this.schedulingMode.setVisibility( + this.bc.getInstalledUpgrades(Upgrades.CAPACITY) > 0 && this.bc instanceof PartExportBus); + } + if (this.oreFilter != null) { + this.oreFilter.setVisibility(this.bc.getInstalledUpgrades(Upgrades.ORE_FILTER) > 0); + } + } + + protected String getBackground() { + return "guis/bus.png"; + } + + protected boolean drawUpgrades() { + return true; + } + + protected GuiText getName() { + return this.bc instanceof PartImportBus ? GuiText.ImportBus : GuiText.ExportBus; + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + final boolean backwards = Mouse.isButtonDown(1); + + if (btn == this.redstoneMode) { + NetworkHandler.instance.sendToServer(new PacketConfigButton(this.redstoneMode.getSetting(), backwards)); + } + + if (btn == this.craftMode) { + NetworkHandler.instance.sendToServer(new PacketConfigButton(this.craftMode.getSetting(), backwards)); + } + + if (btn == this.fuzzyMode) { + NetworkHandler.instance.sendToServer(new PacketConfigButton(this.fuzzyMode.getSetting(), backwards)); + } + + if (btn == this.schedulingMode) { + NetworkHandler.instance.sendToServer(new PacketConfigButton(this.schedulingMode.getSetting(), backwards)); + } + + if (btn == this.oreFilter) { + NetworkHandler.instance.sendToServer(new PacketSwitchGuis(GuiBridge.GUI_ORE_FILTER)); + } + } @Override - public VisiblityData modifyVisiblity( GuiContainer gui, VisiblityData currentVisibility ) - { + public VisiblityData modifyVisiblity(GuiContainer gui, VisiblityData currentVisibility) { return currentVisibility; } @Override - public Iterable getItemSpawnSlots( GuiContainer gui, ItemStack item ) - { + public Iterable getItemSpawnSlots(GuiContainer gui, ItemStack item) { return Collections.emptyList(); } @Override - public List getInventoryAreas( GuiContainer gui ) - { + public List getInventoryAreas(GuiContainer gui) { return null; } @Override - public boolean handleDragNDrop( GuiContainer gui, int mouseX, int mouseY, ItemStack draggedStack, int button ) - { + public boolean handleDragNDrop(GuiContainer gui, int mouseX, int mouseY, ItemStack draggedStack, int button) { List> slots = new ArrayList<>(); - if( this.inventorySlots.inventorySlots.size() > 0 ) - { - for( int i = 0; i < this.inventorySlots.inventorySlots.size(); i ++ ) - { - Object slot = this.inventorySlots.inventorySlots.get( i ); - if( slot instanceof SlotFake ) - { - slots.add( new Pair<> ( (SlotFake) slot, i ) ); + if (this.inventorySlots.inventorySlots.size() > 0) { + for (int i = 0; i < this.inventorySlots.inventorySlots.size(); i++) { + Object slot = this.inventorySlots.inventorySlots.get(i); + if (slot instanceof SlotFake) { + slots.add(new Pair<>((SlotFake) slot, i)); } } } - for( Pair fakeSlotPair : slots ) - { + for (Pair fakeSlotPair : slots) { SlotFake fakeSlot = fakeSlotPair.first(); - if( fakeSlot.isEnabled() && getSlotArea( fakeSlot ).contains( mouseX, mouseY ) ) - { - fakeSlot.putStack( draggedStack ); - NetworkHandler.instance.sendToServer( new PacketNEIDragClick( draggedStack, fakeSlotPair.second() ) ); - if( draggedStack != null ) - { + if (fakeSlot.isEnabled() && getSlotArea(fakeSlot).contains(mouseX, mouseY)) { + fakeSlot.putStack(draggedStack); + NetworkHandler.instance.sendToServer(new PacketNEIDragClick(draggedStack, fakeSlotPair.second())); + if (draggedStack != null) { draggedStack.stackSize = 0; } return true; } } - if( draggedStack != null ) - { + if (draggedStack != null) { draggedStack.stackSize = 0; } return false; } @Override - public boolean hideItemPanelSlot( GuiContainer gui, int x, int y, int w, int h ) - { + public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h) { return false; } - private Rectangle getSlotArea( SlotFake slot ) - { - return new Rectangle( guiLeft + slot.getX(), guiTop + slot.getY(), 16, 16); + private Rectangle getSlotArea(SlotFake slot) { + return new Rectangle(guiLeft + slot.getX(), guiTop + slot.getY(), 16, 16); } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiVibrationChamber.java b/src/main/java/appeng/client/gui/implementations/GuiVibrationChamber.java index b752065e2cf..9f1e982458a 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiVibrationChamber.java +++ b/src/main/java/appeng/client/gui/implementations/GuiVibrationChamber.java @@ -18,65 +18,62 @@ package appeng.client.gui.implementations; - import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiProgressBar; import appeng.client.gui.widgets.GuiProgressBar.Direction; import appeng.container.implementations.ContainerVibrationChamber; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.tile.misc.TileVibrationChamber; import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.opengl.GL11; +public class GuiVibrationChamber extends AEBaseGui { -public class GuiVibrationChamber extends AEBaseGui -{ - - private final ContainerVibrationChamber cvc; - private GuiProgressBar pb; + private final ContainerVibrationChamber cvc; + private GuiProgressBar pb; - public GuiVibrationChamber( final InventoryPlayer inventoryPlayer, final TileVibrationChamber te ) - { - super( new ContainerVibrationChamber( inventoryPlayer, te ) ); - this.cvc = (ContainerVibrationChamber) this.inventorySlots; - this.ySize = 166; - } + public GuiVibrationChamber(final InventoryPlayer inventoryPlayer, final TileVibrationChamber te) { + super(new ContainerVibrationChamber(inventoryPlayer, te)); + this.cvc = (ContainerVibrationChamber) this.inventorySlots; + this.ySize = 166; + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.pb = new GuiProgressBar( this.cvc, "guis/vibchamber.png", 99, 36, 176, 14, 6, 18, Direction.VERTICAL ); - this.buttonList.add( this.pb ); - } + this.pb = new GuiProgressBar(this.cvc, "guis/vibchamber.png", 99, 36, 176, 14, 6, 18, Direction.VERTICAL); + this.buttonList.add(this.pb); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.VibrationChamber.getLocal() ), 8, 6, GuiColors.VibrationChamberTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.VibrationChamberInventory.getColor() ); + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.VibrationChamber.getLocal()), + 8, + 6, + GuiColors.VibrationChamberTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.VibrationChamberInventory.getColor()); - this.pb.setFullMsg( this.cvc.getAePerTick() * this.cvc.getCurrentProgress() / 100 + " AE/t" ); + this.pb.setFullMsg(this.cvc.getAePerTick() * this.cvc.getCurrentProgress() / 100 + " AE/t"); - if( this.cvc.getCurrentProgress() > 0 ) - { - final int i1 = this.cvc.getCurrentProgress(); - this.bindTexture( "guis/vibchamber.png" ); - GL11.glColor3f( 1, 1, 1 ); - final int l = -15; - final int k = 25; - this.drawTexturedModalRect( k + 56, l + 36 + 12 - i1, 176, 12 - i1, 14, i1 + 2 ); - } - } + if (this.cvc.getCurrentProgress() > 0) { + final int i1 = this.cvc.getCurrentProgress(); + this.bindTexture("guis/vibchamber.png"); + GL11.glColor3f(1, 1, 1); + final int l = -15; + final int k = 25; + this.drawTexturedModalRect(k + 56, l + 36 + 12 - i1, 176, 12 - i1, 14, i1 + 2); + } + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/vibchamber.png" ); - this.pb.xPosition = 99 + this.guiLeft; - this.pb.yPosition = 36 + this.guiTop; - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/vibchamber.png"); + this.pb.xPosition = 99 + this.guiLeft; + this.pb.yPosition = 36 + this.guiTop; + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiWireless.java b/src/main/java/appeng/client/gui/implementations/GuiWireless.java index a0da54b4eba..6995e495ca2 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiWireless.java +++ b/src/main/java/appeng/client/gui/implementations/GuiWireless.java @@ -18,79 +18,76 @@ package appeng.client.gui.implementations; - import appeng.api.config.Settings; import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiImgButton; import appeng.container.implementations.ContainerWireless; import appeng.core.AEConfig; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import appeng.tile.networking.TileWireless; import appeng.util.Platform; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Mouse; - -public class GuiWireless extends AEBaseGui -{ - - private GuiImgButton units; - - public GuiWireless( final InventoryPlayer inventoryPlayer, final TileWireless te ) - { - super( new ContainerWireless( inventoryPlayer, te ) ); - this.ySize = 166; - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - final boolean backwards = Mouse.isButtonDown( 1 ); - - if( btn == this.units ) - { - AEConfig.instance.nextPowerUnit( backwards ); - this.units.set( AEConfig.instance.selectedPowerUnit() ); - } - } - - @Override - public void initGui() - { - super.initGui(); - - this.units = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.POWER_UNITS, AEConfig.instance.selectedPowerUnit() ); - this.buttonList.add( this.units ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.Wireless.getLocal() ), 8, 6, GuiColors.WirelessTitle.getColor() ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.WirelessInventory.getColor() ); - - final ContainerWireless cw = (ContainerWireless) this.inventorySlots; - - if( cw.getRange() > 0 ) - { - final String firstMessage = GuiText.Range.getLocal() + ": " + ( cw.getRange() / 10.0 ) + " m"; - final String secondMessage = GuiText.PowerUsageRate.getLocal() + ": " + Platform.formatPowerLong( cw.getDrain(), true ); - - final int strWidth = Math.max( this.fontRendererObj.getStringWidth( firstMessage ), this.fontRendererObj.getStringWidth( secondMessage ) ); - final int cOffset = ( this.xSize / 2 ) - ( strWidth / 2 ); - this.fontRendererObj.drawString( firstMessage, cOffset, 20, GuiColors.WirelessRange.getColor() ); - this.fontRendererObj.drawString( secondMessage, cOffset, 20 + 12, GuiColors.WirelessPowerUsageRate.getColor() ); - } - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/wireless.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } +public class GuiWireless extends AEBaseGui { + + private GuiImgButton units; + + public GuiWireless(final InventoryPlayer inventoryPlayer, final TileWireless te) { + super(new ContainerWireless(inventoryPlayer, te)); + this.ySize = 166; + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + final boolean backwards = Mouse.isButtonDown(1); + + if (btn == this.units) { + AEConfig.instance.nextPowerUnit(backwards); + this.units.set(AEConfig.instance.selectedPowerUnit()); + } + } + + @Override + public void initGui() { + super.initGui(); + + this.units = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 8, Settings.POWER_UNITS, AEConfig.instance.selectedPowerUnit()); + this.buttonList.add(this.units); + } + + @Override + public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.Wireless.getLocal()), 8, 6, GuiColors.WirelessTitle.getColor()); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, GuiColors.WirelessInventory.getColor()); + + final ContainerWireless cw = (ContainerWireless) this.inventorySlots; + + if (cw.getRange() > 0) { + final String firstMessage = GuiText.Range.getLocal() + ": " + (cw.getRange() / 10.0) + " m"; + final String secondMessage = + GuiText.PowerUsageRate.getLocal() + ": " + Platform.formatPowerLong(cw.getDrain(), true); + + final int strWidth = Math.max( + this.fontRendererObj.getStringWidth(firstMessage), + this.fontRendererObj.getStringWidth(secondMessage)); + final int cOffset = (this.xSize / 2) - (strWidth / 2); + this.fontRendererObj.drawString(firstMessage, cOffset, 20, GuiColors.WirelessRange.getColor()); + this.fontRendererObj.drawString( + secondMessage, cOffset, 20 + 12, GuiColors.WirelessPowerUsageRate.getColor()); + } + } + + @Override + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/wireless.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiWirelessTerm.java b/src/main/java/appeng/client/gui/implementations/GuiWirelessTerm.java index 7eb18a9e27c..5a9c23fec57 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiWirelessTerm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiWirelessTerm.java @@ -18,22 +18,17 @@ package appeng.client.gui.implementations; - import appeng.api.implementations.guiobjects.IPortableCell; import net.minecraft.entity.player.InventoryPlayer; +public class GuiWirelessTerm extends GuiMEPortableCell { -public class GuiWirelessTerm extends GuiMEPortableCell -{ - - public GuiWirelessTerm( final InventoryPlayer inventoryPlayer, final IPortableCell te ) - { - super( inventoryPlayer, te ); - } + public GuiWirelessTerm(final InventoryPlayer inventoryPlayer, final IPortableCell te) { + super(inventoryPlayer, te); + } - @Override - int getMaxRows() - { - return this.defaultGetMaxRows(); - } + @Override + int getMaxRows() { + return this.defaultGetMaxRows(); + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiCraftingCPUTable.java b/src/main/java/appeng/client/gui/widgets/GuiCraftingCPUTable.java index 62640cbac37..69b8e58877d 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiCraftingCPUTable.java +++ b/src/main/java/appeng/client/gui/widgets/GuiCraftingCPUTable.java @@ -9,16 +9,14 @@ import appeng.core.localization.GuiText; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; +import java.io.IOException; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; -import java.io.IOException; -import java.util.List; - -public class GuiCraftingCPUTable -{ +public class GuiCraftingCPUTable { private final AEBaseGui parent; private final ContainerCPUTable container; @@ -34,331 +32,277 @@ public class GuiCraftingCPUTable private String selectedCPUName = ""; - public GuiCraftingCPUTable( AEBaseGui parent, ContainerCPUTable container ) - { + public GuiCraftingCPUTable(AEBaseGui parent, ContainerCPUTable container) { this.parent = parent; this.container = container; this.cpuScrollbar = new GuiScrollbar(); - this.cpuScrollbar.setLeft( -16 ); - this.cpuScrollbar.setTop( 19 ); - this.cpuScrollbar.setWidth( 12 ); - this.cpuScrollbar.setHeight( 137 ); + this.cpuScrollbar.setLeft(-16); + this.cpuScrollbar.setTop(19); + this.cpuScrollbar.setWidth(12); + this.cpuScrollbar.setHeight(137); } - public ContainerCPUTable getContainer() - { + public ContainerCPUTable getContainer() { return container; } - public String getSelectedCPUName() - { + public String getSelectedCPUName() { return selectedCPUName; } - public void drawScreen( ) - { + public void drawScreen() { final List cpus = container.getCPUs(); final int selectedCpuSerial = container.selectedCpuSerial; this.selectedCPUName = null; - this.cpuScrollbar.setRange( 0, Integer.max( 0, cpus.size() - CPU_TABLE_SLOTS ), 1 ); - for( CraftingCPUStatus cpu : cpus ) - { - if( cpu.getSerial() == selectedCpuSerial ) - { + this.cpuScrollbar.setRange(0, Integer.max(0, cpus.size() - CPU_TABLE_SLOTS), 1); + for (CraftingCPUStatus cpu : cpus) { + if (cpu.getSerial() == selectedCpuSerial) { this.selectedCPUName = cpu.getName(); } } } - public void drawFG( int offsetX, int offsetY, int mouseX, int mouseY, int guiLeft, int guiTop ) - { - if( this.cpuScrollbar != null ) - { - this.cpuScrollbar.draw( parent ); + public void drawFG(int offsetX, int offsetY, int mouseX, int mouseY, int guiLeft, int guiTop) { + if (this.cpuScrollbar != null) { + this.cpuScrollbar.draw(parent); } final List cpus = container.getCPUs(); final int selectedCpuSerial = container.selectedCpuSerial; final int firstCpu = this.cpuScrollbar.getCurrentScroll(); - CraftingCPUStatus hoveredCpu = hitCpu( mouseX - guiLeft, mouseY - guiTop ); + CraftingCPUStatus hoveredCpu = hitCpu(mouseX - guiLeft, mouseY - guiTop); { FontRenderer font = Minecraft.getMinecraft().fontRenderer; - for( int i = firstCpu; i < firstCpu + CPU_TABLE_SLOTS; i++ ) - { - if( i < 0 || i >= cpus.size() ) - { + for (int i = firstCpu; i < firstCpu + CPU_TABLE_SLOTS; i++) { + if (i < 0 || i >= cpus.size()) { continue; } - CraftingCPUStatus cpu = cpus.get( i ); - if( cpu == null ) - { + CraftingCPUStatus cpu = cpus.get(i); + if (cpu == null) { continue; } int x = -CPU_TABLE_WIDTH + 9; - int y = 19 + ( i - firstCpu ) * CPU_TABLE_SLOT_HEIGHT; - if( cpu.getSerial() == selectedCpuSerial ) - { - if( !container.getCpuFilter().test( cpu ) ) - { - GL11.glColor4f( 1.0F, 0.25F, 0.25F, 1.0F ); - } else - { - GL11.glColor4f( 0.0F, 0.8352F, 1.0F, 1.0F ); + int y = 19 + (i - firstCpu) * CPU_TABLE_SLOT_HEIGHT; + if (cpu.getSerial() == selectedCpuSerial) { + if (!container.getCpuFilter().test(cpu)) { + GL11.glColor4f(1.0F, 0.25F, 0.25F, 1.0F); + } else { + GL11.glColor4f(0.0F, 0.8352F, 1.0F, 1.0F); } - } else if( hoveredCpu != null && hoveredCpu.getSerial() == cpu.getSerial() ) - { - GL11.glColor4f( 0.65F, 0.9F, 1.0F, 1.0F ); - } else if( !container.getCpuFilter().test( cpu ) ) - { - GL11.glColor4f( 0.9F, 0.65F, 0.65F, 1.0F ); - } else - { - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + } else if (hoveredCpu != null && hoveredCpu.getSerial() == cpu.getSerial()) { + GL11.glColor4f(0.65F, 0.9F, 1.0F, 1.0F); + } else if (!container.getCpuFilter().test(cpu)) { + GL11.glColor4f(0.9F, 0.65F, 0.65F, 1.0F); + } else { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } - parent.bindTexture( "guis/cpu_selector.png" ); - parent.drawTexturedModalRect( x, y, CPU_TABLE_SLOT_XOFF, CPU_TABLE_SLOT_YOFF, CPU_TABLE_SLOT_WIDTH, CPU_TABLE_SLOT_HEIGHT ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + parent.bindTexture("guis/cpu_selector.png"); + parent.drawTexturedModalRect( + x, y, CPU_TABLE_SLOT_XOFF, CPU_TABLE_SLOT_YOFF, CPU_TABLE_SLOT_WIDTH, CPU_TABLE_SLOT_HEIGHT); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); String name = cpu.getName(); - if( name == null || name.isEmpty() ) - { + if (name == null || name.isEmpty()) { name = GuiText.CPUs.getLocal() + " #" + cpu.getSerial(); } - if( name.length() > 12 ) - { - name = name.substring( 0, 11 ) + ".."; + if (name.length() > 12) { + name = name.substring(0, 11) + ".."; } GL11.glPushMatrix(); - GL11.glTranslatef( x + 3, y + 3, 0 ); - GL11.glScalef( 0.8f, 0.8f, 1.0f ); - font.drawString( name, 0, 0, GuiColors.CraftingStatusCPUName.getColor() ); + GL11.glTranslatef(x + 3, y + 3, 0); + GL11.glScalef(0.8f, 0.8f, 1.0f); + font.drawString(name, 0, 0, GuiColors.CraftingStatusCPUName.getColor()); GL11.glPopMatrix(); GL11.glPushMatrix(); - GL11.glTranslatef( x + 3, y + 11, 0 ); + GL11.glTranslatef(x + 3, y + 11, 0); final IAEItemStack craftingStack = cpu.getCrafting(); - if( craftingStack != null ) - { + if (craftingStack != null) { final int iconIndex = 16 * 11 + 2; - parent.bindTexture( "guis/states.png" ); + parent.bindTexture("guis/states.png"); final int uv_y = iconIndex / 16; final int uv_x = iconIndex - uv_y * 16; - GL11.glScalef( 0.5f, 0.5f, 1.0f ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - parent.drawTexturedModalRect( 0, 0, uv_x * 16, uv_y * 16, 16, 16 ); - GL11.glTranslatef( 18.0f, 2.0f, 0.0f ); - String amount = Long.toString( craftingStack.getStackSize() ); - if( amount.length() > 5 ) - { - amount = amount.substring( 0, 5 ) + ".."; + GL11.glScalef(0.5f, 0.5f, 1.0f); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + parent.drawTexturedModalRect(0, 0, uv_x * 16, uv_y * 16, 16, 16); + GL11.glTranslatef(18.0f, 2.0f, 0.0f); + String amount = Long.toString(craftingStack.getStackSize()); + if (amount.length() > 5) { + amount = amount.substring(0, 5) + ".."; } - GL11.glScalef( 1.5f, 1.5f, 1.0f ); - font.drawString( amount, 0, 0, GuiColors.CraftingStatusCPUAmount.getColor() ); + GL11.glScalef(1.5f, 1.5f, 1.0f); + font.drawString(amount, 0, 0, GuiColors.CraftingStatusCPUAmount.getColor()); GL11.glPopMatrix(); GL11.glPushMatrix(); - GL11.glTranslatef( x + CPU_TABLE_SLOT_WIDTH - 19, y + 3, 0 ); - parent.drawItem( 0, 0, craftingStack.getItemStack() ); - } else - { + GL11.glTranslatef(x + CPU_TABLE_SLOT_WIDTH - 19, y + 3, 0); + parent.drawItem(0, 0, craftingStack.getItemStack()); + } else { final int iconIndex = 16 * 4 + 3; - parent.bindTexture( "guis/states.png" ); + parent.bindTexture("guis/states.png"); final int uv_y = iconIndex / 16; final int uv_x = iconIndex - uv_y * 16; - GL11.glScalef( 0.5f, 0.5f, 1.0f ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - parent.drawTexturedModalRect( 0, 0, uv_x * 16, uv_y * 16, 16, 16 ); - GL11.glTranslatef( 18.0f, 2.0f, 0.0f ); - GL11.glScalef( 1.5f, 1.5f, 1.0f ); - font.drawString( cpu.formatStorage(), 0, 0, GuiColors.CraftingStatusCPUStorage.getColor() ); + GL11.glScalef(0.5f, 0.5f, 1.0f); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + parent.drawTexturedModalRect(0, 0, uv_x * 16, uv_y * 16, 16, 16); + GL11.glTranslatef(18.0f, 2.0f, 0.0f); + GL11.glScalef(1.5f, 1.5f, 1.0f); + font.drawString(cpu.formatStorage(), 0, 0, GuiColors.CraftingStatusCPUStorage.getColor()); } GL11.glPopMatrix(); } - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } - if( hoveredCpu != null ) - { + if (hoveredCpu != null) { StringBuilder tooltip = new StringBuilder(); String name = hoveredCpu.getName(); - if( name != null && !name.isEmpty() ) - { - tooltip.append( name ); - tooltip.append( '\n' ); - } else - { - tooltip.append( GuiText.CPUs.getLocal() ); - tooltip.append( " #" ); - tooltip.append( hoveredCpu.getSerial() ); - tooltip.append( '\n' ); + if (name != null && !name.isEmpty()) { + tooltip.append(name); + tooltip.append('\n'); + } else { + tooltip.append(GuiText.CPUs.getLocal()); + tooltip.append(" #"); + tooltip.append(hoveredCpu.getSerial()); + tooltip.append('\n'); } IAEItemStack crafting = hoveredCpu.getCrafting(); - if( crafting != null && crafting.getStackSize() > 0 ) - { - tooltip.append( GuiText.Crafting.getLocal() ); - tooltip.append( ": " ); - tooltip.append( crafting.getStackSize() ); - tooltip.append( ' ' ); - tooltip.append( crafting.getItemStack().getDisplayName() ); - tooltip.append( '\n' ); - tooltip.append( hoveredCpu.getRemainingItems() ); - tooltip.append( " / " ); - tooltip.append( hoveredCpu.getTotalItems() ); - tooltip.append( '\n' ); + if (crafting != null && crafting.getStackSize() > 0) { + tooltip.append(GuiText.Crafting.getLocal()); + tooltip.append(": "); + tooltip.append(crafting.getStackSize()); + tooltip.append(' '); + tooltip.append(crafting.getItemStack().getDisplayName()); + tooltip.append('\n'); + tooltip.append(hoveredCpu.getRemainingItems()); + tooltip.append(" / "); + tooltip.append(hoveredCpu.getTotalItems()); + tooltip.append('\n'); } - if( hoveredCpu.getStorage() > 0 ) - { - tooltip.append( GuiText.Bytes.getLocal() ); - tooltip.append( ": " ); - tooltip.append( hoveredCpu.formatStorage() ); - tooltip.append( '\n' ); + if (hoveredCpu.getStorage() > 0) { + tooltip.append(GuiText.Bytes.getLocal()); + tooltip.append(": "); + tooltip.append(hoveredCpu.formatStorage()); + tooltip.append('\n'); } - if( hoveredCpu.getCoprocessors() > 0 ) - { - tooltip.append( GuiText.CoProcessors.getLocal() ); - tooltip.append( ": " ); - tooltip.append( hoveredCpu.getCoprocessors() ); - tooltip.append( '\n' ); + if (hoveredCpu.getCoprocessors() > 0) { + tooltip.append(GuiText.CoProcessors.getLocal()); + tooltip.append(": "); + tooltip.append(hoveredCpu.getCoprocessors()); + tooltip.append('\n'); } - if( tooltip.length() > 0 ) - { - parent.drawTooltip( mouseX - offsetX, mouseY - offsetY, 0, tooltip.toString() ); + if (tooltip.length() > 0) { + parent.drawTooltip(mouseX - offsetX, mouseY - offsetY, 0, tooltip.toString()); } } } - public void drawBG( int offsetX, int offsetY ) - { - parent.bindTexture( "guis/cpu_selector.png" ); - parent.drawTexturedModalRect( offsetX - CPU_TABLE_WIDTH, offsetY, 0, 0, CPU_TABLE_WIDTH, CPU_TABLE_HEIGHT ); + public void drawBG(int offsetX, int offsetY) { + parent.bindTexture("guis/cpu_selector.png"); + parent.drawTexturedModalRect(offsetX - CPU_TABLE_WIDTH, offsetY, 0, 0, CPU_TABLE_WIDTH, CPU_TABLE_HEIGHT); } /** * Tests if a cpu button is under the cursor. Subtract guiLeft, guiTop from x, y before calling */ - public CraftingCPUStatus hitCpu( int x, int y ) - { + public CraftingCPUStatus hitCpu(int x, int y) { x -= -CPU_TABLE_WIDTH; - if( !( x >= 9 && x < CPU_TABLE_SLOT_WIDTH + 9 && y >= 19 && y < 19 + CPU_TABLE_SLOTS * CPU_TABLE_SLOT_HEIGHT ) ) - { + if (!(x >= 9 && x < CPU_TABLE_SLOT_WIDTH + 9 && y >= 19 && y < 19 + CPU_TABLE_SLOTS * CPU_TABLE_SLOT_HEIGHT)) { return null; } int scrollOffset = this.cpuScrollbar != null ? this.cpuScrollbar.getCurrentScroll() : 0; - int cpuId = scrollOffset + ( y - 19 ) / CPU_TABLE_SLOT_HEIGHT; + int cpuId = scrollOffset + (y - 19) / CPU_TABLE_SLOT_HEIGHT; List cpus = container.getCPUs(); - return ( cpuId >= 0 && cpuId < cpus.size() ) ? cpus.get( cpuId ) : null; + return (cpuId >= 0 && cpuId < cpus.size()) ? cpus.get(cpuId) : null; } /** * Subtract guiLeft, guiTop from x, y before calling */ - public void mouseClicked( int xCoord, int yCoord, int btn ) - { - if( cpuScrollbar != null ) - { - cpuScrollbar.click( parent, xCoord, yCoord ); + public void mouseClicked(int xCoord, int yCoord, int btn) { + if (cpuScrollbar != null) { + cpuScrollbar.click(parent, xCoord, yCoord); } - CraftingCPUStatus hit = hitCpu( xCoord, yCoord ); - if( hit != null ) - { - sendCPUSwitch( hit.getSerial() ); + CraftingCPUStatus hit = hitCpu(xCoord, yCoord); + if (hit != null) { + sendCPUSwitch(hit.getSerial()); } } - public void sendCPUSwitch( int serial ) - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "CPUTable.Cpu.Set", Integer.toString( serial ) ) ); - } catch( final IOException e ) - { - AELog.warn( e ); + public void sendCPUSwitch(int serial) { + try { + NetworkHandler.instance.sendToServer(new PacketValueConfig("CPUTable.Cpu.Set", Integer.toString(serial))); + } catch (final IOException e) { + AELog.warn(e); } } /** * Subtract guiLeft, guiTop from x, y before calling */ - public void mouseClickMove( int xCoord, int yCoord ) - { - if( cpuScrollbar != null ) - { - cpuScrollbar.click( parent, xCoord, yCoord ); + public void mouseClickMove(int xCoord, int yCoord) { + if (cpuScrollbar != null) { + cpuScrollbar.click(parent, xCoord, yCoord); } } /** * @return True if event was handled */ - public boolean handleMouseInput( int guiLeft, int guiTop ) - { + public boolean handleMouseInput(int guiLeft, int guiTop) { int x = Mouse.getEventX() * parent.width / parent.mc.displayWidth; int y = parent.height - Mouse.getEventY() * parent.height / parent.mc.displayHeight - 1; x -= guiLeft - CPU_TABLE_WIDTH; y -= guiTop; int dwheel = Mouse.getEventDWheel(); - if( x >= 9 && x < CPU_TABLE_SLOT_WIDTH + 9 && y >= 19 && y < 19 + CPU_TABLE_SLOTS * CPU_TABLE_SLOT_HEIGHT ) - { - if( this.cpuScrollbar != null && dwheel != 0 ) - { - this.cpuScrollbar.wheel( dwheel ); + if (x >= 9 && x < CPU_TABLE_SLOT_WIDTH + 9 && y >= 19 && y < 19 + CPU_TABLE_SLOTS * CPU_TABLE_SLOT_HEIGHT) { + if (this.cpuScrollbar != null && dwheel != 0) { + this.cpuScrollbar.wheel(dwheel); return true; } } return false; } - public boolean hideItemPanelSlot( int x, int y, int w, int h ) - { + public boolean hideItemPanelSlot(int x, int y, int w, int h) { x += CPU_TABLE_WIDTH; - boolean xInside = - ( x >= 0 && x < CPU_TABLE_SLOT_WIDTH + 9 ) - || ( x + w >= 0 && x + w < CPU_TABLE_SLOT_WIDTH + 9 ) - || ( x <= 0 && x + w >= CPU_TABLE_SLOT_WIDTH + 9 ); - boolean yInside = - ( y >= 0 && y < 19 + CPU_TABLE_SLOTS * CPU_TABLE_SLOT_HEIGHT ) - || ( y + h >= 0 && y + h < 19 + CPU_TABLE_SLOTS * CPU_TABLE_SLOT_HEIGHT ) - || ( y < 0 && y + h >= 19 + CPU_TABLE_SLOTS * CPU_TABLE_SLOT_HEIGHT ); + boolean xInside = (x >= 0 && x < CPU_TABLE_SLOT_WIDTH + 9) + || (x + w >= 0 && x + w < CPU_TABLE_SLOT_WIDTH + 9) + || (x <= 0 && x + w >= CPU_TABLE_SLOT_WIDTH + 9); + boolean yInside = (y >= 0 && y < 19 + CPU_TABLE_SLOTS * CPU_TABLE_SLOT_HEIGHT) + || (y + h >= 0 && y + h < 19 + CPU_TABLE_SLOTS * CPU_TABLE_SLOT_HEIGHT) + || (y < 0 && y + h >= 19 + CPU_TABLE_SLOTS * CPU_TABLE_SLOT_HEIGHT); return xInside && yInside; } - public void cycleCPU(boolean backwards) - { + public void cycleCPU(boolean backwards) { int current = container.selectedCpuSerial; List cpus = container.getCPUs(); final int next_increment = backwards ? (cpus.size() - 1) : 1; - if( cpus.isEmpty() ) - { + if (cpus.isEmpty()) { return; } int next = 0; - for( int i = 0; i < cpus.size(); i++ ) - { - if( cpus.get( i ).getSerial() == current ) - { + for (int i = 0; i < cpus.size(); i++) { + if (cpus.get(i).getSerial() == current) { next = i + next_increment; break; } } final boolean preferBusy = container.isBusyCPUsPreferred(); - for (int i = 0; i < cpus.size(); i++) - { + for (int i = 0; i < cpus.size(); i++) { next = next % cpus.size(); CraftingCPUStatus cpu = cpus.get(next); - if (cpu.isBusy() == preferBusy && container.getCpuFilter().test(cpu)) - { + if (cpu.isBusy() == preferBusy && container.getCpuFilter().test(cpu)) { break; - } - else - { + } else { next += next_increment; } } next = next % cpus.size(); - sendCPUSwitch( cpus.get( next ).getSerial() ); - if( next < cpuScrollbar.getCurrentScroll() || next >= cpuScrollbar.getCurrentScroll() + CPU_TABLE_SLOTS ) - { - cpuScrollbar.setCurrentScroll( next ); + sendCPUSwitch(cpus.get(next).getSerial()); + if (next < cpuScrollbar.getCurrentScroll() || next >= cpuScrollbar.getCurrentScroll() + CPU_TABLE_SLOTS) { + cpuScrollbar.setCurrentScroll(next); } } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiImgButton.java b/src/main/java/appeng/client/gui/widgets/GuiImgButton.java index d0c0fa005e4..ed2dfedcebc 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiImgButton.java +++ b/src/main/java/appeng/client/gui/widgets/GuiImgButton.java @@ -18,411 +18,716 @@ package appeng.client.gui.widgets; - import appeng.api.config.*; import appeng.client.texture.ExtraBlockTextures; import appeng.core.localization.ButtonToolTips; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.util.StatCollector; import org.lwjgl.opengl.GL11; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Pattern; - - -public class GuiImgButton extends GuiButton implements ITooltip -{ - private static final Pattern COMPILE = Pattern.compile( "%s" ); - private static final Pattern PATTERN_NEW_LINE = Pattern.compile( "\\n", Pattern.LITERAL ); - private static Map appearances; - private final Enum buttonSetting; - private boolean halfSize = false; - private String fillVar; - private Enum currentValue; - - public GuiImgButton( final int x, final int y, final Enum idx, final Enum val ) - { - super( 0, 0, 16, "" ); - - this.buttonSetting = idx; - this.currentValue = val; - this.xPosition = x; - this.yPosition = y; - this.width = 16; - this.height = 16; - - if( appearances == null ) - { - appearances = new HashMap(); - this.registerApp( 16 * 7, Settings.CONDENSER_OUTPUT, CondenserOutput.TRASH, ButtonToolTips.CondenserOutput, ButtonToolTips.Trash ); - this.registerApp( 16 * 7 + 1, Settings.CONDENSER_OUTPUT, CondenserOutput.MATTER_BALLS, ButtonToolTips.CondenserOutput, ButtonToolTips.MatterBalls ); - this.registerApp( 16 * 7 + 2, Settings.CONDENSER_OUTPUT, CondenserOutput.SINGULARITY, ButtonToolTips.CondenserOutput, ButtonToolTips.Singularity ); - - this.registerApp( 16 * 9 + 1, Settings.ACCESS, AccessRestriction.READ, ButtonToolTips.IOMode, ButtonToolTips.Read ); - this.registerApp( 16 * 9, Settings.ACCESS, AccessRestriction.WRITE, ButtonToolTips.IOMode, ButtonToolTips.Write ); - this.registerApp( 16 * 9 + 2, Settings.ACCESS, AccessRestriction.READ_WRITE, ButtonToolTips.IOMode, ButtonToolTips.ReadWrite ); - - this.registerApp( 16 * 10, Settings.POWER_UNITS, PowerUnits.AE, ButtonToolTips.PowerUnits, PowerUnits.AE.unlocalizedName ); - this.registerApp( 16 * 10 + 1, Settings.POWER_UNITS, PowerUnits.EU, ButtonToolTips.PowerUnits, PowerUnits.EU.unlocalizedName ); - this.registerApp( 16 * 10 + 2, Settings.POWER_UNITS, PowerUnits.MK, ButtonToolTips.PowerUnits, PowerUnits.MK.unlocalizedName ); - this.registerApp( 16 * 10 + 3, Settings.POWER_UNITS, PowerUnits.WA, ButtonToolTips.PowerUnits, PowerUnits.WA.unlocalizedName ); - this.registerApp( 16 * 10 + 4, Settings.POWER_UNITS, PowerUnits.RF, ButtonToolTips.PowerUnits, PowerUnits.RF.unlocalizedName ); - - this.registerApp( 3, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE, ButtonToolTips.RedstoneMode, ButtonToolTips.AlwaysActive ); - this.registerApp( 0, Settings.REDSTONE_CONTROLLED, RedstoneMode.LOW_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.ActiveWithoutSignal ); - this.registerApp( 1, Settings.REDSTONE_CONTROLLED, RedstoneMode.HIGH_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.ActiveWithSignal ); - this.registerApp( 2, Settings.REDSTONE_CONTROLLED, RedstoneMode.SIGNAL_PULSE, ButtonToolTips.RedstoneMode, ButtonToolTips.ActiveOnPulse ); - - this.registerApp( 0, Settings.REDSTONE_EMITTER, RedstoneMode.LOW_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.EmitLevelsBelow ); - this.registerApp( 1, Settings.REDSTONE_EMITTER, RedstoneMode.HIGH_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.EmitLevelAbove ); - - this.registerApp( 51, Settings.OPERATION_MODE, OperationMode.FILL, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToStorageCell ); - this.registerApp( 50, Settings.OPERATION_MODE, OperationMode.EMPTY, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToNetwork ); - - this.registerApp( 51, Settings.IO_DIRECTION, RelativeDirection.LEFT, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToStorageCell ); - this.registerApp( 50, Settings.IO_DIRECTION, RelativeDirection.RIGHT, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToNetwork ); - - this.registerApp( 48, Settings.SORT_DIRECTION, SortDir.ASCENDING, ButtonToolTips.SortOrder, ButtonToolTips.ToggleSortDirection ); - this.registerApp( 49, Settings.SORT_DIRECTION, SortDir.DESCENDING, ButtonToolTips.SortOrder, ButtonToolTips.ToggleSortDirection ); - - this.registerApp( 16 * 2 + 3, Settings.SEARCH_MODE, SearchBoxMode.AUTOSEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_Auto ); - this.registerApp( 16 * 2 + 4, Settings.SEARCH_MODE, SearchBoxMode.MANUAL_SEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_Standard ); - this.registerApp( 16 * 2 + 5, Settings.SEARCH_MODE, SearchBoxMode.NEI_AUTOSEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_NEIAuto ); - this.registerApp( 16 * 2 + 6, Settings.SEARCH_MODE, SearchBoxMode.NEI_MANUAL_SEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_NEIStandard ); - - this.registerApp( 16 * 2 + 7, Settings.SAVE_SEARCH, YesNo.YES, ButtonToolTips.SaveSearchString, ButtonToolTips.SaveSearchStringYes ); - this.registerApp( 16 * 2 + 8, Settings.SAVE_SEARCH, YesNo.NO, ButtonToolTips.SaveSearchString, ButtonToolTips.SaveSearchStringNo ); - - this.registerApp( 16 * 5 + 3, Settings.LEVEL_TYPE, LevelType.ENERGY_LEVEL, ButtonToolTips.LevelType, ButtonToolTips.LevelType_Energy ); - this.registerApp( 16 * 4 + 3, Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL, ButtonToolTips.LevelType, ButtonToolTips.LevelType_Item ); - - this.registerApp( 16 * 13, Settings.TERMINAL_STYLE, TerminalStyle.TALL, ButtonToolTips.TerminalStyle, ButtonToolTips.TerminalStyle_Tall ); - this.registerApp( 16 * 13 + 1, Settings.TERMINAL_STYLE, TerminalStyle.SMALL, ButtonToolTips.TerminalStyle, ButtonToolTips.TerminalStyle_Small ); - this.registerApp( 16 * 13 + 2, Settings.TERMINAL_STYLE, TerminalStyle.FULL, ButtonToolTips.TerminalStyle, ButtonToolTips.TerminalStyle_Full ); - - this.registerApp( 64, Settings.SORT_BY, SortOrder.NAME, ButtonToolTips.SortBy, ButtonToolTips.ItemName ); - this.registerApp( 65, Settings.SORT_BY, SortOrder.AMOUNT, ButtonToolTips.SortBy, ButtonToolTips.NumberOfItems ); - this.registerApp( 68, Settings.SORT_BY, SortOrder.INVTWEAKS, ButtonToolTips.SortBy, ButtonToolTips.InventoryTweaks ); - this.registerApp( 69, Settings.SORT_BY, SortOrder.MOD, ButtonToolTips.SortBy, ButtonToolTips.Mod ); - - this.registerApp( 66, Settings.ACTIONS, ActionItems.WRENCH, ButtonToolTips.PartitionStorage, ButtonToolTips.PartitionStorageHint ); - this.registerApp( 6, Settings.ACTIONS, ActionItems.CLOSE, ButtonToolTips.Clear, ButtonToolTips.ClearSettings ); - this.registerApp( 6, Settings.ACTIONS, ActionItems.STASH, ButtonToolTips.Stash, ButtonToolTips.StashDesc ); - - this.registerApp( 8, Settings.ACTIONS, ActionItems.ENCODE, ButtonToolTips.Encode, ButtonToolTips.EncodeDescription ); - this.registerApp( 4 + 3 * 16, Settings.ACTIONS, ItemSubstitution.ENABLED, ButtonToolTips.Substitutions, ButtonToolTips.SubstitutionsDescEnabled ); - this.registerApp( 7 + 3 * 16, Settings.ACTIONS, ItemSubstitution.DISABLED, ButtonToolTips.Substitutions, ButtonToolTips.SubstitutionsDescDisabled ); - - this.registerApp( 8 + 16, Settings.ACTIONS, PatternSlotConfig.C_16_4, ButtonToolTips.PatternSlotConfigTitle, ButtonToolTips.PatternSlotConfigInfo ); - this.registerApp( 8 + 16, Settings.ACTIONS, PatternSlotConfig.C_4_16, ButtonToolTips.PatternSlotConfigTitle, ButtonToolTips.PatternSlotConfigInfo ); - - this.registerApp( 16, Settings.VIEW_MODE, ViewItems.STORED, ButtonToolTips.View, ButtonToolTips.StoredItems ); - this.registerApp( 18, Settings.VIEW_MODE, ViewItems.ALL, ButtonToolTips.View, ButtonToolTips.StoredCraftable ); - this.registerApp( 19, Settings.VIEW_MODE, ViewItems.CRAFTABLE, ButtonToolTips.View, ButtonToolTips.Craftable ); - - this.registerApp( 16 * 6, Settings.FUZZY_MODE, FuzzyMode.PERCENT_25, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_25 ); - this.registerApp( 16 * 6 + 1, Settings.FUZZY_MODE, FuzzyMode.PERCENT_50, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_50 ); - this.registerApp( 16 * 6 + 2, Settings.FUZZY_MODE, FuzzyMode.PERCENT_75, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_75 ); - this.registerApp( 16 * 6 + 3, Settings.FUZZY_MODE, FuzzyMode.PERCENT_99, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_99 ); - this.registerApp( 16 * 6 + 4, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL, ButtonToolTips.FuzzyMode, ButtonToolTips.FZIgnoreAll ); - - this.registerApp( 80, Settings.FULLNESS_MODE, FullnessMode.EMPTY, ButtonToolTips.OperationMode, ButtonToolTips.MoveWhenEmpty ); - this.registerApp( 81, Settings.FULLNESS_MODE, FullnessMode.HALF, ButtonToolTips.OperationMode, ButtonToolTips.MoveWhenWorkIsDone ); - this.registerApp( 82, Settings.FULLNESS_MODE, FullnessMode.FULL, ButtonToolTips.OperationMode, ButtonToolTips.MoveWhenFull ); - - this.registerApp( 16 + 5, Settings.BLOCK, YesNo.YES, ButtonToolTips.InterfaceBlockingMode, ButtonToolTips.Blocking ); - this.registerApp( 16 + 4, Settings.BLOCK, YesNo.NO, ButtonToolTips.InterfaceBlockingMode, ButtonToolTips.NonBlocking ); - - this.registerApp( 16 + 3, Settings.CRAFT_ONLY, YesNo.YES, ButtonToolTips.Craft, ButtonToolTips.CraftOnly ); - this.registerApp( 16 + 2, Settings.CRAFT_ONLY, YesNo.NO, ButtonToolTips.Craft, ButtonToolTips.CraftEither ); - - this.registerApp( 16 * 11 + 2, Settings.CRAFT_VIA_REDSTONE, YesNo.YES, ButtonToolTips.EmitterMode, ButtonToolTips.CraftViaRedstone ); - this.registerApp( 16 * 11 + 1, Settings.CRAFT_VIA_REDSTONE, YesNo.NO, ButtonToolTips.EmitterMode, ButtonToolTips.EmitWhenCrafting ); - - this.registerApp( 16 * 3 + 5, Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY, ButtonToolTips.ReportInaccessibleItems, ButtonToolTips.ReportInaccessibleItemsNo ); - this.registerApp( 16 * 3 + 6, Settings.STORAGE_FILTER, StorageFilter.NONE, ButtonToolTips.ReportInaccessibleItems, ButtonToolTips.ReportInaccessibleItemsYes ); - - this.registerApp( 16 * 14, Settings.PLACE_BLOCK, YesNo.YES, ButtonToolTips.BlockPlacement, ButtonToolTips.BlockPlacementYes ); - this.registerApp( 16 * 14 + 1, Settings.PLACE_BLOCK, YesNo.NO, ButtonToolTips.BlockPlacement, ButtonToolTips.BlockPlacementNo ); - - this.registerApp( 16 * 15, Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT, ButtonToolTips.SchedulingMode, ButtonToolTips.SchedulingModeDefault ); - this.registerApp( 16 * 15 + 1, Settings.SCHEDULING_MODE, SchedulingMode.ROUNDROBIN, ButtonToolTips.SchedulingMode, ButtonToolTips.SchedulingModeRoundRobin ); - this.registerApp( 16 * 15 + 2, Settings.SCHEDULING_MODE, SchedulingMode.RANDOM, ButtonToolTips.SchedulingMode, ButtonToolTips.SchedulingModeRandom ); - - this.registerApp( 70, Settings.ACTIONS, ActionItems.ORE_FILTER, ButtonToolTips.OreFilter, ButtonToolTips.OreFilterHint ); - this.registerApp( 71, Settings.ACTIONS, ActionItems.DOUBLE, ButtonToolTips.DoublePattern, ButtonToolTips.DoublePatternHint ); - this.registerApp( 16 * 14 + 2, Settings.CRAFTING_STATUS, CraftingStatus.BUTTON, ButtonToolTips.CraftingStatus, ButtonToolTips.CraftingStatusDesc ); - - this.registerApp( 4 + 5 * 16, Settings.ACTIONS, ActionItems.TOGGLE_SHOW_ONLY_INVALID_PATTERN_ON, ButtonToolTips.ToggleShowOnlyInvalidInterface, ButtonToolTips.ToggleShowOnlyInvalidInterfaceOnDesc ); - this.registerApp( 5 + 5 * 16, Settings.ACTIONS, ActionItems.TOGGLE_SHOW_ONLY_INVALID_PATTERN_OFF, ButtonToolTips.ToggleShowOnlyInvalidInterface, ButtonToolTips.ToggleShowOnlyInvalidInterfaceOffDesc ); - - this.registerApp( 6 + 5 * 16, Settings.ACTIONS, ActionItems.MOLECULAR_ASSEMBLEERS_ON, ButtonToolTips.ToggleMolecularAssemblers, ButtonToolTips.ToggleMolecularAssemblersDescOn ); - this.registerApp( 7 + 5 * 16, Settings.ACTIONS, ActionItems.TOGGLE_SHOW_FULL_INTERFACES_ON, ButtonToolTips.ToggleShowFullInterfaces, ButtonToolTips.ToggleShowFullInterfacesOnDesc ); - this.registerApp( 8 + 5 * 16, Settings.ACTIONS, ActionItems.TOGGLE_SHOW_FULL_INTERFACES_OFF, ButtonToolTips.ToggleShowFullInterfaces, ButtonToolTips.ToggleShowFullInterfacesOffDesc ); - this.registerApp( 9 + 5 * 16, Settings.ACTIONS, ActionItems.MOLECULAR_ASSEMBLEERS_OFF, ButtonToolTips.ToggleMolecularAssemblers, ButtonToolTips.ToggleMolecularAssemblersDescOff ); - this.registerApp( 6 + 6 * 16, Settings.ACTIONS, ActionItems.HIGHLIGHT_INTERFACE, ButtonToolTips.HighlightInterface, "" ); - - this.registerApp( 16 * 9 + 3, Settings.INSERTION_MODE, InsertionMode.DEFAULT, ButtonToolTips.InsertionModeDefault, ButtonToolTips.InsertionModeDefaultDesc ); - this.registerApp( 16 * 9 + 4, Settings.INSERTION_MODE, InsertionMode.PREFER_EMPTY, ButtonToolTips.InsertionModePreferEmpty, ButtonToolTips.InsertionModePreferEmptyDesc ); - this.registerApp( 16 * 9 + 5, Settings.INSERTION_MODE, InsertionMode.ONLY_EMPTY, ButtonToolTips.InsertionModeOnlyEmpty, ButtonToolTips.InsertionModeOnlyEmptyDesc ); - } - } - - private void registerApp( final int iconIndex, final Settings setting, final Enum val, final ButtonToolTips title, final Object hint ) - { - final ButtonAppearance a = new ButtonAppearance(); - a.displayName = title.getUnlocalized(); - a.displayValue = (String) ( hint instanceof String ? hint : ( (ButtonToolTips) hint ).getUnlocalized() ); - a.index = iconIndex; - appearances.put( new EnumPair( setting, val ), a ); - } - - public void setVisibility( final boolean vis ) - { - this.visible = vis; - this.enabled = vis; - } - - @Override - public void drawButton( final Minecraft par1Minecraft, final int par2, final int par3 ) - { - if( this.visible ) - { - final int iconIndex = this.getIconIndex(); - - if( this.halfSize ) - { - this.width = 8; - this.height = 8; - - GL11.glPushMatrix(); - GL11.glTranslatef( this.xPosition, this.yPosition, 0.0F ); - GL11.glScalef( 0.5f, 0.5f, 0.5f ); - - if( this.enabled ) - { - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - } - else - { - GL11.glColor4f( 0.5f, 0.5f, 0.5f, 1.0f ); - } - - par1Minecraft.renderEngine.bindTexture( ExtraBlockTextures.GuiTexture( "guis/states.png" ) ); - this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + this.width && par3 < this.yPosition + this.height; - - final int uv_y = (int) Math.floor( iconIndex / 16 ); - final int uv_x = iconIndex - uv_y * 16; - - this.drawTexturedModalRect( 0, 0, 256 - 16, 256 - 16, 16, 16 ); - this.drawTexturedModalRect( 0, 0, uv_x * 16, uv_y * 16, 16, 16 ); - this.mouseDragged( par1Minecraft, par2, par3 ); - - GL11.glPopMatrix(); - } - else - { - if( this.enabled ) - { - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - } - else - { - GL11.glColor4f( 0.5f, 0.5f, 0.5f, 1.0f ); - } - - par1Minecraft.renderEngine.bindTexture( ExtraBlockTextures.GuiTexture( "guis/states.png" ) ); - this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + this.width && par3 < this.yPosition + this.height; - - final int uv_y = (int) Math.floor( iconIndex / 16 ); - final int uv_x = iconIndex - uv_y * 16; - - this.drawTexturedModalRect( this.xPosition, this.yPosition, 256 - 16, 256 - 16, 16, 16 ); - this.drawTexturedModalRect( this.xPosition, this.yPosition, uv_x * 16, uv_y * 16, 16, 16 ); - this.mouseDragged( par1Minecraft, par2, par3 ); - } - } - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - } - - private int getIconIndex() - { - if( this.buttonSetting != null && this.currentValue != null ) - { - final ButtonAppearance app = appearances.get( new EnumPair( this.buttonSetting, this.currentValue ) ); - if( app == null ) - { - return 256 - 1; - } - return app.index; - } - return 256 - 1; - } - - public Settings getSetting() - { - return (Settings) this.buttonSetting; - } - - public Enum getCurrentValue() - { - return this.currentValue; - } - - @Override - public String getMessage() - { - String displayName = null; - String displayValue = null; - - if( this.buttonSetting != null && this.currentValue != null ) - { - final ButtonAppearance buttonAppearance = appearances.get( new EnumPair( this.buttonSetting, this.currentValue ) ); - if( buttonAppearance == null ) - { - return "No Such Message"; - } - - displayName = buttonAppearance.displayName; - displayValue = buttonAppearance.displayValue; - } - - if( displayName != null ) - { - String name = StatCollector.translateToLocal( displayName ); - String value = StatCollector.translateToLocal( displayValue ); - - if( name == null || name.isEmpty() ) - { - name = displayName; - } - if( value == null || value.isEmpty() ) - { - value = displayValue; - } - - if( this.fillVar != null ) - { - value = COMPILE.matcher( value ).replaceFirst( this.fillVar ); - } - - value = PATTERN_NEW_LINE.matcher( value ).replaceAll( "\n" ); - final StringBuilder sb = new StringBuilder( value ); - - int i = sb.lastIndexOf( "\n" ); - if( i <= 0 ) - { - i = 0; - } - while( i + 30 < sb.length() && ( i = sb.lastIndexOf( " ", i + 30 ) ) != -1 ) - { - sb.replace( i, i + 1, "\n" ); - } - - return name + '\n' + sb; - } - return null; - } - - @Override - public int xPos() - { - return this.xPosition; - } - - @Override - public int yPos() - { - return this.yPosition; - } - - @Override - public int getWidth() - { - return this.halfSize ? 8 : 16; - } - - @Override - public int getHeight() - { - return this.halfSize ? 8 : 16; - } - - @Override - public boolean isVisible() - { - return this.visible; - } - - public void set( final Enum e ) - { - if( this.currentValue != e ) - { - this.currentValue = e; - } - } - - public boolean isHalfSize() - { - return this.halfSize; - } - - public void setHalfSize( final boolean halfSize ) - { - this.halfSize = halfSize; - } - - public String getFillVar() - { - return this.fillVar; - } - - public void setFillVar( final String fillVar ) - { - this.fillVar = fillVar; - } - - private static final class EnumPair - { - - final Enum setting; - final Enum value; - - EnumPair( final Enum a, final Enum b ) - { - this.setting = a; - this.value = b; - } - - @Override - public int hashCode() - { - return this.setting.hashCode() ^ this.value.hashCode(); - } - - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - final EnumPair other = (EnumPair) obj; - return other.setting == this.setting && other.value == this.value; - } - } - - - private static class ButtonAppearance - { - public int index; - public String displayName; - public String displayValue; - } +public class GuiImgButton extends GuiButton implements ITooltip { + private static final Pattern COMPILE = Pattern.compile("%s"); + private static final Pattern PATTERN_NEW_LINE = Pattern.compile("\\n", Pattern.LITERAL); + private static Map appearances; + private final Enum buttonSetting; + private boolean halfSize = false; + private String fillVar; + private Enum currentValue; + + public GuiImgButton(final int x, final int y, final Enum idx, final Enum val) { + super(0, 0, 16, ""); + + this.buttonSetting = idx; + this.currentValue = val; + this.xPosition = x; + this.yPosition = y; + this.width = 16; + this.height = 16; + + if (appearances == null) { + appearances = new HashMap(); + this.registerApp( + 16 * 7, + Settings.CONDENSER_OUTPUT, + CondenserOutput.TRASH, + ButtonToolTips.CondenserOutput, + ButtonToolTips.Trash); + this.registerApp( + 16 * 7 + 1, + Settings.CONDENSER_OUTPUT, + CondenserOutput.MATTER_BALLS, + ButtonToolTips.CondenserOutput, + ButtonToolTips.MatterBalls); + this.registerApp( + 16 * 7 + 2, + Settings.CONDENSER_OUTPUT, + CondenserOutput.SINGULARITY, + ButtonToolTips.CondenserOutput, + ButtonToolTips.Singularity); + + this.registerApp( + 16 * 9 + 1, Settings.ACCESS, AccessRestriction.READ, ButtonToolTips.IOMode, ButtonToolTips.Read); + this.registerApp( + 16 * 9, Settings.ACCESS, AccessRestriction.WRITE, ButtonToolTips.IOMode, ButtonToolTips.Write); + this.registerApp( + 16 * 9 + 2, + Settings.ACCESS, + AccessRestriction.READ_WRITE, + ButtonToolTips.IOMode, + ButtonToolTips.ReadWrite); + + this.registerApp( + 16 * 10, + Settings.POWER_UNITS, + PowerUnits.AE, + ButtonToolTips.PowerUnits, + PowerUnits.AE.unlocalizedName); + this.registerApp( + 16 * 10 + 1, + Settings.POWER_UNITS, + PowerUnits.EU, + ButtonToolTips.PowerUnits, + PowerUnits.EU.unlocalizedName); + this.registerApp( + 16 * 10 + 2, + Settings.POWER_UNITS, + PowerUnits.MK, + ButtonToolTips.PowerUnits, + PowerUnits.MK.unlocalizedName); + this.registerApp( + 16 * 10 + 3, + Settings.POWER_UNITS, + PowerUnits.WA, + ButtonToolTips.PowerUnits, + PowerUnits.WA.unlocalizedName); + this.registerApp( + 16 * 10 + 4, + Settings.POWER_UNITS, + PowerUnits.RF, + ButtonToolTips.PowerUnits, + PowerUnits.RF.unlocalizedName); + + this.registerApp( + 3, + Settings.REDSTONE_CONTROLLED, + RedstoneMode.IGNORE, + ButtonToolTips.RedstoneMode, + ButtonToolTips.AlwaysActive); + this.registerApp( + 0, + Settings.REDSTONE_CONTROLLED, + RedstoneMode.LOW_SIGNAL, + ButtonToolTips.RedstoneMode, + ButtonToolTips.ActiveWithoutSignal); + this.registerApp( + 1, + Settings.REDSTONE_CONTROLLED, + RedstoneMode.HIGH_SIGNAL, + ButtonToolTips.RedstoneMode, + ButtonToolTips.ActiveWithSignal); + this.registerApp( + 2, + Settings.REDSTONE_CONTROLLED, + RedstoneMode.SIGNAL_PULSE, + ButtonToolTips.RedstoneMode, + ButtonToolTips.ActiveOnPulse); + + this.registerApp( + 0, + Settings.REDSTONE_EMITTER, + RedstoneMode.LOW_SIGNAL, + ButtonToolTips.RedstoneMode, + ButtonToolTips.EmitLevelsBelow); + this.registerApp( + 1, + Settings.REDSTONE_EMITTER, + RedstoneMode.HIGH_SIGNAL, + ButtonToolTips.RedstoneMode, + ButtonToolTips.EmitLevelAbove); + + this.registerApp( + 51, + Settings.OPERATION_MODE, + OperationMode.FILL, + ButtonToolTips.TransferDirection, + ButtonToolTips.TransferToStorageCell); + this.registerApp( + 50, + Settings.OPERATION_MODE, + OperationMode.EMPTY, + ButtonToolTips.TransferDirection, + ButtonToolTips.TransferToNetwork); + + this.registerApp( + 51, + Settings.IO_DIRECTION, + RelativeDirection.LEFT, + ButtonToolTips.TransferDirection, + ButtonToolTips.TransferToStorageCell); + this.registerApp( + 50, + Settings.IO_DIRECTION, + RelativeDirection.RIGHT, + ButtonToolTips.TransferDirection, + ButtonToolTips.TransferToNetwork); + + this.registerApp( + 48, + Settings.SORT_DIRECTION, + SortDir.ASCENDING, + ButtonToolTips.SortOrder, + ButtonToolTips.ToggleSortDirection); + this.registerApp( + 49, + Settings.SORT_DIRECTION, + SortDir.DESCENDING, + ButtonToolTips.SortOrder, + ButtonToolTips.ToggleSortDirection); + + this.registerApp( + 16 * 2 + 3, + Settings.SEARCH_MODE, + SearchBoxMode.AUTOSEARCH, + ButtonToolTips.SearchMode, + ButtonToolTips.SearchMode_Auto); + this.registerApp( + 16 * 2 + 4, + Settings.SEARCH_MODE, + SearchBoxMode.MANUAL_SEARCH, + ButtonToolTips.SearchMode, + ButtonToolTips.SearchMode_Standard); + this.registerApp( + 16 * 2 + 5, + Settings.SEARCH_MODE, + SearchBoxMode.NEI_AUTOSEARCH, + ButtonToolTips.SearchMode, + ButtonToolTips.SearchMode_NEIAuto); + this.registerApp( + 16 * 2 + 6, + Settings.SEARCH_MODE, + SearchBoxMode.NEI_MANUAL_SEARCH, + ButtonToolTips.SearchMode, + ButtonToolTips.SearchMode_NEIStandard); + + this.registerApp( + 16 * 2 + 7, + Settings.SAVE_SEARCH, + YesNo.YES, + ButtonToolTips.SaveSearchString, + ButtonToolTips.SaveSearchStringYes); + this.registerApp( + 16 * 2 + 8, + Settings.SAVE_SEARCH, + YesNo.NO, + ButtonToolTips.SaveSearchString, + ButtonToolTips.SaveSearchStringNo); + + this.registerApp( + 16 * 5 + 3, + Settings.LEVEL_TYPE, + LevelType.ENERGY_LEVEL, + ButtonToolTips.LevelType, + ButtonToolTips.LevelType_Energy); + this.registerApp( + 16 * 4 + 3, + Settings.LEVEL_TYPE, + LevelType.ITEM_LEVEL, + ButtonToolTips.LevelType, + ButtonToolTips.LevelType_Item); + + this.registerApp( + 16 * 13, + Settings.TERMINAL_STYLE, + TerminalStyle.TALL, + ButtonToolTips.TerminalStyle, + ButtonToolTips.TerminalStyle_Tall); + this.registerApp( + 16 * 13 + 1, + Settings.TERMINAL_STYLE, + TerminalStyle.SMALL, + ButtonToolTips.TerminalStyle, + ButtonToolTips.TerminalStyle_Small); + this.registerApp( + 16 * 13 + 2, + Settings.TERMINAL_STYLE, + TerminalStyle.FULL, + ButtonToolTips.TerminalStyle, + ButtonToolTips.TerminalStyle_Full); + + this.registerApp(64, Settings.SORT_BY, SortOrder.NAME, ButtonToolTips.SortBy, ButtonToolTips.ItemName); + this.registerApp( + 65, Settings.SORT_BY, SortOrder.AMOUNT, ButtonToolTips.SortBy, ButtonToolTips.NumberOfItems); + this.registerApp( + 68, Settings.SORT_BY, SortOrder.INVTWEAKS, ButtonToolTips.SortBy, ButtonToolTips.InventoryTweaks); + this.registerApp(69, Settings.SORT_BY, SortOrder.MOD, ButtonToolTips.SortBy, ButtonToolTips.Mod); + + this.registerApp( + 66, + Settings.ACTIONS, + ActionItems.WRENCH, + ButtonToolTips.PartitionStorage, + ButtonToolTips.PartitionStorageHint); + this.registerApp( + 6, Settings.ACTIONS, ActionItems.CLOSE, ButtonToolTips.Clear, ButtonToolTips.ClearSettings); + this.registerApp(6, Settings.ACTIONS, ActionItems.STASH, ButtonToolTips.Stash, ButtonToolTips.StashDesc); + + this.registerApp( + 8, Settings.ACTIONS, ActionItems.ENCODE, ButtonToolTips.Encode, ButtonToolTips.EncodeDescription); + this.registerApp( + 4 + 3 * 16, + Settings.ACTIONS, + ItemSubstitution.ENABLED, + ButtonToolTips.Substitutions, + ButtonToolTips.SubstitutionsDescEnabled); + this.registerApp( + 7 + 3 * 16, + Settings.ACTIONS, + ItemSubstitution.DISABLED, + ButtonToolTips.Substitutions, + ButtonToolTips.SubstitutionsDescDisabled); + + this.registerApp( + 8 + 16, + Settings.ACTIONS, + PatternSlotConfig.C_16_4, + ButtonToolTips.PatternSlotConfigTitle, + ButtonToolTips.PatternSlotConfigInfo); + this.registerApp( + 8 + 16, + Settings.ACTIONS, + PatternSlotConfig.C_4_16, + ButtonToolTips.PatternSlotConfigTitle, + ButtonToolTips.PatternSlotConfigInfo); + + this.registerApp(16, Settings.VIEW_MODE, ViewItems.STORED, ButtonToolTips.View, ButtonToolTips.StoredItems); + this.registerApp( + 18, Settings.VIEW_MODE, ViewItems.ALL, ButtonToolTips.View, ButtonToolTips.StoredCraftable); + this.registerApp( + 19, Settings.VIEW_MODE, ViewItems.CRAFTABLE, ButtonToolTips.View, ButtonToolTips.Craftable); + + this.registerApp( + 16 * 6, + Settings.FUZZY_MODE, + FuzzyMode.PERCENT_25, + ButtonToolTips.FuzzyMode, + ButtonToolTips.FZPercent_25); + this.registerApp( + 16 * 6 + 1, + Settings.FUZZY_MODE, + FuzzyMode.PERCENT_50, + ButtonToolTips.FuzzyMode, + ButtonToolTips.FZPercent_50); + this.registerApp( + 16 * 6 + 2, + Settings.FUZZY_MODE, + FuzzyMode.PERCENT_75, + ButtonToolTips.FuzzyMode, + ButtonToolTips.FZPercent_75); + this.registerApp( + 16 * 6 + 3, + Settings.FUZZY_MODE, + FuzzyMode.PERCENT_99, + ButtonToolTips.FuzzyMode, + ButtonToolTips.FZPercent_99); + this.registerApp( + 16 * 6 + 4, + Settings.FUZZY_MODE, + FuzzyMode.IGNORE_ALL, + ButtonToolTips.FuzzyMode, + ButtonToolTips.FZIgnoreAll); + + this.registerApp( + 80, + Settings.FULLNESS_MODE, + FullnessMode.EMPTY, + ButtonToolTips.OperationMode, + ButtonToolTips.MoveWhenEmpty); + this.registerApp( + 81, + Settings.FULLNESS_MODE, + FullnessMode.HALF, + ButtonToolTips.OperationMode, + ButtonToolTips.MoveWhenWorkIsDone); + this.registerApp( + 82, + Settings.FULLNESS_MODE, + FullnessMode.FULL, + ButtonToolTips.OperationMode, + ButtonToolTips.MoveWhenFull); + + this.registerApp( + 16 + 5, Settings.BLOCK, YesNo.YES, ButtonToolTips.InterfaceBlockingMode, ButtonToolTips.Blocking); + this.registerApp( + 16 + 4, Settings.BLOCK, YesNo.NO, ButtonToolTips.InterfaceBlockingMode, ButtonToolTips.NonBlocking); + + this.registerApp(16 + 3, Settings.CRAFT_ONLY, YesNo.YES, ButtonToolTips.Craft, ButtonToolTips.CraftOnly); + this.registerApp(16 + 2, Settings.CRAFT_ONLY, YesNo.NO, ButtonToolTips.Craft, ButtonToolTips.CraftEither); + + this.registerApp( + 16 * 11 + 2, + Settings.CRAFT_VIA_REDSTONE, + YesNo.YES, + ButtonToolTips.EmitterMode, + ButtonToolTips.CraftViaRedstone); + this.registerApp( + 16 * 11 + 1, + Settings.CRAFT_VIA_REDSTONE, + YesNo.NO, + ButtonToolTips.EmitterMode, + ButtonToolTips.EmitWhenCrafting); + + this.registerApp( + 16 * 3 + 5, + Settings.STORAGE_FILTER, + StorageFilter.EXTRACTABLE_ONLY, + ButtonToolTips.ReportInaccessibleItems, + ButtonToolTips.ReportInaccessibleItemsNo); + this.registerApp( + 16 * 3 + 6, + Settings.STORAGE_FILTER, + StorageFilter.NONE, + ButtonToolTips.ReportInaccessibleItems, + ButtonToolTips.ReportInaccessibleItemsYes); + + this.registerApp( + 16 * 14, + Settings.PLACE_BLOCK, + YesNo.YES, + ButtonToolTips.BlockPlacement, + ButtonToolTips.BlockPlacementYes); + this.registerApp( + 16 * 14 + 1, + Settings.PLACE_BLOCK, + YesNo.NO, + ButtonToolTips.BlockPlacement, + ButtonToolTips.BlockPlacementNo); + + this.registerApp( + 16 * 15, + Settings.SCHEDULING_MODE, + SchedulingMode.DEFAULT, + ButtonToolTips.SchedulingMode, + ButtonToolTips.SchedulingModeDefault); + this.registerApp( + 16 * 15 + 1, + Settings.SCHEDULING_MODE, + SchedulingMode.ROUNDROBIN, + ButtonToolTips.SchedulingMode, + ButtonToolTips.SchedulingModeRoundRobin); + this.registerApp( + 16 * 15 + 2, + Settings.SCHEDULING_MODE, + SchedulingMode.RANDOM, + ButtonToolTips.SchedulingMode, + ButtonToolTips.SchedulingModeRandom); + + this.registerApp( + 70, + Settings.ACTIONS, + ActionItems.ORE_FILTER, + ButtonToolTips.OreFilter, + ButtonToolTips.OreFilterHint); + this.registerApp( + 71, + Settings.ACTIONS, + ActionItems.DOUBLE, + ButtonToolTips.DoublePattern, + ButtonToolTips.DoublePatternHint); + this.registerApp( + 16 * 14 + 2, + Settings.CRAFTING_STATUS, + CraftingStatus.BUTTON, + ButtonToolTips.CraftingStatus, + ButtonToolTips.CraftingStatusDesc); + + this.registerApp( + 4 + 5 * 16, + Settings.ACTIONS, + ActionItems.TOGGLE_SHOW_ONLY_INVALID_PATTERN_ON, + ButtonToolTips.ToggleShowOnlyInvalidInterface, + ButtonToolTips.ToggleShowOnlyInvalidInterfaceOnDesc); + this.registerApp( + 5 + 5 * 16, + Settings.ACTIONS, + ActionItems.TOGGLE_SHOW_ONLY_INVALID_PATTERN_OFF, + ButtonToolTips.ToggleShowOnlyInvalidInterface, + ButtonToolTips.ToggleShowOnlyInvalidInterfaceOffDesc); + + this.registerApp( + 6 + 5 * 16, + Settings.ACTIONS, + ActionItems.MOLECULAR_ASSEMBLEERS_ON, + ButtonToolTips.ToggleMolecularAssemblers, + ButtonToolTips.ToggleMolecularAssemblersDescOn); + this.registerApp( + 7 + 5 * 16, + Settings.ACTIONS, + ActionItems.TOGGLE_SHOW_FULL_INTERFACES_ON, + ButtonToolTips.ToggleShowFullInterfaces, + ButtonToolTips.ToggleShowFullInterfacesOnDesc); + this.registerApp( + 8 + 5 * 16, + Settings.ACTIONS, + ActionItems.TOGGLE_SHOW_FULL_INTERFACES_OFF, + ButtonToolTips.ToggleShowFullInterfaces, + ButtonToolTips.ToggleShowFullInterfacesOffDesc); + this.registerApp( + 9 + 5 * 16, + Settings.ACTIONS, + ActionItems.MOLECULAR_ASSEMBLEERS_OFF, + ButtonToolTips.ToggleMolecularAssemblers, + ButtonToolTips.ToggleMolecularAssemblersDescOff); + this.registerApp( + 6 + 6 * 16, + Settings.ACTIONS, + ActionItems.HIGHLIGHT_INTERFACE, + ButtonToolTips.HighlightInterface, + ""); + + this.registerApp( + 16 * 9 + 3, + Settings.INSERTION_MODE, + InsertionMode.DEFAULT, + ButtonToolTips.InsertionModeDefault, + ButtonToolTips.InsertionModeDefaultDesc); + this.registerApp( + 16 * 9 + 4, + Settings.INSERTION_MODE, + InsertionMode.PREFER_EMPTY, + ButtonToolTips.InsertionModePreferEmpty, + ButtonToolTips.InsertionModePreferEmptyDesc); + this.registerApp( + 16 * 9 + 5, + Settings.INSERTION_MODE, + InsertionMode.ONLY_EMPTY, + ButtonToolTips.InsertionModeOnlyEmpty, + ButtonToolTips.InsertionModeOnlyEmptyDesc); + } + } + + private void registerApp( + final int iconIndex, + final Settings setting, + final Enum val, + final ButtonToolTips title, + final Object hint) { + final ButtonAppearance a = new ButtonAppearance(); + a.displayName = title.getUnlocalized(); + a.displayValue = (String) (hint instanceof String ? hint : ((ButtonToolTips) hint).getUnlocalized()); + a.index = iconIndex; + appearances.put(new EnumPair(setting, val), a); + } + + public void setVisibility(final boolean vis) { + this.visible = vis; + this.enabled = vis; + } + + @Override + public void drawButton(final Minecraft par1Minecraft, final int par2, final int par3) { + if (this.visible) { + final int iconIndex = this.getIconIndex(); + + if (this.halfSize) { + this.width = 8; + this.height = 8; + + GL11.glPushMatrix(); + GL11.glTranslatef(this.xPosition, this.yPosition, 0.0F); + GL11.glScalef(0.5f, 0.5f, 0.5f); + + if (this.enabled) { + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } else { + GL11.glColor4f(0.5f, 0.5f, 0.5f, 1.0f); + } + + par1Minecraft.renderEngine.bindTexture(ExtraBlockTextures.GuiTexture("guis/states.png")); + this.field_146123_n = par2 >= this.xPosition + && par3 >= this.yPosition + && par2 < this.xPosition + this.width + && par3 < this.yPosition + this.height; + + final int uv_y = (int) Math.floor(iconIndex / 16); + final int uv_x = iconIndex - uv_y * 16; + + this.drawTexturedModalRect(0, 0, 256 - 16, 256 - 16, 16, 16); + this.drawTexturedModalRect(0, 0, uv_x * 16, uv_y * 16, 16, 16); + this.mouseDragged(par1Minecraft, par2, par3); + + GL11.glPopMatrix(); + } else { + if (this.enabled) { + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } else { + GL11.glColor4f(0.5f, 0.5f, 0.5f, 1.0f); + } + + par1Minecraft.renderEngine.bindTexture(ExtraBlockTextures.GuiTexture("guis/states.png")); + this.field_146123_n = par2 >= this.xPosition + && par3 >= this.yPosition + && par2 < this.xPosition + this.width + && par3 < this.yPosition + this.height; + + final int uv_y = (int) Math.floor(iconIndex / 16); + final int uv_x = iconIndex - uv_y * 16; + + this.drawTexturedModalRect(this.xPosition, this.yPosition, 256 - 16, 256 - 16, 16, 16); + this.drawTexturedModalRect(this.xPosition, this.yPosition, uv_x * 16, uv_y * 16, 16, 16); + this.mouseDragged(par1Minecraft, par2, par3); + } + } + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } + + private int getIconIndex() { + if (this.buttonSetting != null && this.currentValue != null) { + final ButtonAppearance app = appearances.get(new EnumPair(this.buttonSetting, this.currentValue)); + if (app == null) { + return 256 - 1; + } + return app.index; + } + return 256 - 1; + } + + public Settings getSetting() { + return (Settings) this.buttonSetting; + } + + public Enum getCurrentValue() { + return this.currentValue; + } + + @Override + public String getMessage() { + String displayName = null; + String displayValue = null; + + if (this.buttonSetting != null && this.currentValue != null) { + final ButtonAppearance buttonAppearance = + appearances.get(new EnumPair(this.buttonSetting, this.currentValue)); + if (buttonAppearance == null) { + return "No Such Message"; + } + + displayName = buttonAppearance.displayName; + displayValue = buttonAppearance.displayValue; + } + + if (displayName != null) { + String name = StatCollector.translateToLocal(displayName); + String value = StatCollector.translateToLocal(displayValue); + + if (name == null || name.isEmpty()) { + name = displayName; + } + if (value == null || value.isEmpty()) { + value = displayValue; + } + + if (this.fillVar != null) { + value = COMPILE.matcher(value).replaceFirst(this.fillVar); + } + + value = PATTERN_NEW_LINE.matcher(value).replaceAll("\n"); + final StringBuilder sb = new StringBuilder(value); + + int i = sb.lastIndexOf("\n"); + if (i <= 0) { + i = 0; + } + while (i + 30 < sb.length() && (i = sb.lastIndexOf(" ", i + 30)) != -1) { + sb.replace(i, i + 1, "\n"); + } + + return name + '\n' + sb; + } + return null; + } + + @Override + public int xPos() { + return this.xPosition; + } + + @Override + public int yPos() { + return this.yPosition; + } + + @Override + public int getWidth() { + return this.halfSize ? 8 : 16; + } + + @Override + public int getHeight() { + return this.halfSize ? 8 : 16; + } + + @Override + public boolean isVisible() { + return this.visible; + } + + public void set(final Enum e) { + if (this.currentValue != e) { + this.currentValue = e; + } + } + + public boolean isHalfSize() { + return this.halfSize; + } + + public void setHalfSize(final boolean halfSize) { + this.halfSize = halfSize; + } + + public String getFillVar() { + return this.fillVar; + } + + public void setFillVar(final String fillVar) { + this.fillVar = fillVar; + } + + private static final class EnumPair { + + final Enum setting; + final Enum value; + + EnumPair(final Enum a, final Enum b) { + this.setting = a; + this.value = b; + } + + @Override + public int hashCode() { + return this.setting.hashCode() ^ this.value.hashCode(); + } + + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final EnumPair other = (EnumPair) obj; + return other.setting == this.setting && other.value == this.value; + } + } + + private static class ButtonAppearance { + public int index; + public String displayName; + public String displayValue; + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java b/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java index 539023666ad..35e069c5cfe 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java +++ b/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java @@ -18,46 +18,39 @@ package appeng.client.gui.widgets; - import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiTextField; - -public class GuiNumberBox extends GuiTextField -{ - - private final Class type; - - public GuiNumberBox( final FontRenderer fontRenderer, final int x, final int y, final int width, final int height, final Class type ) - { - super( fontRenderer, x, y, width, height ); - this.type = type; - } - - @Override - public void writeText( final String selectedText ) - { - final String original = this.getText(); - super.writeText( selectedText ); - - try - { - if( this.type == int.class || this.type == Integer.class ) - { - Integer.parseInt( this.getText() ); - } - else if( this.type == long.class || this.type == Long.class ) - { - Long.parseLong( this.getText() ); - } - else if( this.type == double.class || this.type == Double.class ) - { - Double.parseDouble( this.getText() ); - } - } - catch( final NumberFormatException e ) - { - this.setText( original ); - } - } +public class GuiNumberBox extends GuiTextField { + + private final Class type; + + public GuiNumberBox( + final FontRenderer fontRenderer, + final int x, + final int y, + final int width, + final int height, + final Class type) { + super(fontRenderer, x, y, width, height); + this.type = type; + } + + @Override + public void writeText(final String selectedText) { + final String original = this.getText(); + super.writeText(selectedText); + + try { + if (this.type == int.class || this.type == Integer.class) { + Integer.parseInt(this.getText()); + } else if (this.type == long.class || this.type == Long.class) { + Long.parseLong(this.getText()); + } else if (this.type == double.class || this.type == Double.class) { + Double.parseDouble(this.getText()); + } + } catch (final NumberFormatException e) { + this.setText(original); + } + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiProgressBar.java b/src/main/java/appeng/client/gui/widgets/GuiProgressBar.java index 90bc58cf93d..3d1f491af2d 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiProgressBar.java +++ b/src/main/java/appeng/client/gui/widgets/GuiProgressBar.java @@ -18,117 +18,136 @@ package appeng.client.gui.widgets; - import appeng.container.interfaces.IProgressProvider; import appeng.core.localization.GuiText; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.util.ResourceLocation; - -public class GuiProgressBar extends GuiButton implements ITooltip -{ - - private final IProgressProvider source; - private final ResourceLocation texture; - private final int fill_u; - private final int fill_v; - private final Direction layout; - private final String titleName; - private String fullMsg; - - public GuiProgressBar( final IProgressProvider source, final String texture, final int posX, final int posY, final int u, final int y, final int width, final int height, final Direction dir ) - { - this( source, texture, posX, posY, u, y, width, height, dir, null ); - } - - public GuiProgressBar( final IProgressProvider source, final String texture, final int posX, final int posY, final int u, final int y, final int width, final int height, final Direction dir, final String title ) - { - super( posX, posY, width, "" ); - this.source = source; - this.xPosition = posX; - this.yPosition = posY; - this.texture = new ResourceLocation( "appliedenergistics2", "textures/" + texture ); - this.width = width; - this.height = height; - this.fill_u = u; - this.fill_v = y; - this.layout = dir; - this.titleName = title; - } - - @Override - public void drawButton( final Minecraft par1Minecraft, final int par2, final int par3 ) - { - if( this.visible ) - { - par1Minecraft.getTextureManager().bindTexture( this.texture ); - final int max = this.source.getMaxProgress(); - final int current = this.source.getCurrentProgress(); - - if( this.layout == Direction.VERTICAL ) - { - final int diff = this.height - ( max > 0 ? ( this.height * current ) / max : 0 ); - this.drawTexturedModalRect( this.xPosition, this.yPosition + diff, this.fill_u, this.fill_v + diff, this.width, this.height - diff ); - } - else - { - final int diff = this.width - ( max > 0 ? ( this.width * current ) / max : 0 ); - this.drawTexturedModalRect( this.xPosition, this.yPosition, this.fill_u + diff, this.fill_v, this.width - diff, this.height ); - } - - this.mouseDragged( par1Minecraft, par2, par3 ); - } - } - - public void setFullMsg( final String msg ) - { - this.fullMsg = msg; - } - - @Override - public String getMessage() - { - if( this.fullMsg != null ) - { - return this.fullMsg; - } - - return ( this.titleName != null ? this.titleName : "" ) + '\n' + this.source.getCurrentProgress() + ' ' + GuiText.Of.getLocal() + ' ' + this.source.getMaxProgress(); - } - - @Override - public int xPos() - { - return this.xPosition - 2; - } - - @Override - public int yPos() - { - return this.yPosition - 2; - } - - @Override - public int getWidth() - { - return this.width + 4; - } - - @Override - public int getHeight() - { - return this.height + 4; - } - - @Override - public boolean isVisible() - { - return true; - } - - public enum Direction - { - HORIZONTAL, VERTICAL - } +public class GuiProgressBar extends GuiButton implements ITooltip { + + private final IProgressProvider source; + private final ResourceLocation texture; + private final int fill_u; + private final int fill_v; + private final Direction layout; + private final String titleName; + private String fullMsg; + + public GuiProgressBar( + final IProgressProvider source, + final String texture, + final int posX, + final int posY, + final int u, + final int y, + final int width, + final int height, + final Direction dir) { + this(source, texture, posX, posY, u, y, width, height, dir, null); + } + + public GuiProgressBar( + final IProgressProvider source, + final String texture, + final int posX, + final int posY, + final int u, + final int y, + final int width, + final int height, + final Direction dir, + final String title) { + super(posX, posY, width, ""); + this.source = source; + this.xPosition = posX; + this.yPosition = posY; + this.texture = new ResourceLocation("appliedenergistics2", "textures/" + texture); + this.width = width; + this.height = height; + this.fill_u = u; + this.fill_v = y; + this.layout = dir; + this.titleName = title; + } + + @Override + public void drawButton(final Minecraft par1Minecraft, final int par2, final int par3) { + if (this.visible) { + par1Minecraft.getTextureManager().bindTexture(this.texture); + final int max = this.source.getMaxProgress(); + final int current = this.source.getCurrentProgress(); + + if (this.layout == Direction.VERTICAL) { + final int diff = this.height - (max > 0 ? (this.height * current) / max : 0); + this.drawTexturedModalRect( + this.xPosition, + this.yPosition + diff, + this.fill_u, + this.fill_v + diff, + this.width, + this.height - diff); + } else { + final int diff = this.width - (max > 0 ? (this.width * current) / max : 0); + this.drawTexturedModalRect( + this.xPosition, + this.yPosition, + this.fill_u + diff, + this.fill_v, + this.width - diff, + this.height); + } + + this.mouseDragged(par1Minecraft, par2, par3); + } + } + + public void setFullMsg(final String msg) { + this.fullMsg = msg; + } + + @Override + public String getMessage() { + if (this.fullMsg != null) { + return this.fullMsg; + } + + return (this.titleName != null ? this.titleName : "") + + '\n' + + this.source.getCurrentProgress() + + ' ' + + GuiText.Of.getLocal() + + ' ' + + this.source.getMaxProgress(); + } + + @Override + public int xPos() { + return this.xPosition - 2; + } + + @Override + public int yPos() { + return this.yPosition - 2; + } + + @Override + public int getWidth() { + return this.width + 4; + } + + @Override + public int getHeight() { + return this.height + 4; + } + + @Override + public boolean isVisible() { + return true; + } + + public enum Direction { + HORIZONTAL, + VERTICAL + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiScrollbar.java b/src/main/java/appeng/client/gui/widgets/GuiScrollbar.java index a6c7b755426..871d12b0ab0 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiScrollbar.java +++ b/src/main/java/appeng/client/gui/widgets/GuiScrollbar.java @@ -18,151 +18,132 @@ package appeng.client.gui.widgets; - import appeng.client.gui.AEBaseGui; import org.lwjgl.opengl.GL11; - -public class GuiScrollbar implements IScrollSource -{ - private String txtBase = "minecraft"; - private String txtFile = "gui/container/creative_inventory/tabs.png"; - private int txtShiftX = 232; - private int txtShiftY = 0; - - private int displayX = 0; - private int displayY = 0; - private int width = 12; - private int height = 16; - private int pageSize = 1; - - private int maxScroll = 0; - private int minScroll = 0; - private int currentScroll = 0; - - public void setTexture(final String base, final String file, final int shiftX, final int shiftY) - { - txtBase = base; - txtFile = file; - txtShiftX = shiftX; - txtShiftY = shiftY; - } - - public void draw( final AEBaseGui g ) - { - g.bindTexture( txtBase, txtFile ); - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - - if (this.getRange() == 0) { - g.drawTexturedModalRect( this.displayX, this.displayY, txtShiftX + this.width, txtShiftY, this.width, 15 ); - } else { - final int offset = ( this.currentScroll - this.minScroll ) * ( this.height - 15 ) / this.getRange(); - g.drawTexturedModalRect( this.displayX, offset + this.displayY, txtShiftX, txtShiftY, this.width, 15 ); - } - - } - - private int getRange() - { - return this.maxScroll - this.minScroll; - } - - public int getLeft() - { - return this.displayX; - } - - public GuiScrollbar setLeft( final int v ) - { - this.displayX = v; - return this; - } - - public int getTop() - { - return this.displayY; - } - - public GuiScrollbar setTop( final int v ) - { - this.displayY = v; - return this; - } - - public int getWidth() - { - return this.width; - } - - public GuiScrollbar setWidth( final int v ) - { - this.width = v; - return this; - } - - public int getHeight() - { - return this.height; - } - - public GuiScrollbar setHeight( final int v ) - { - this.height = v; - return this; - } - - public void setRange( final int min, final int max, final int pageSize ) - { - this.minScroll = min; - this.maxScroll = max; - this.pageSize = pageSize; - - if (this.minScroll > this.maxScroll) { - this.maxScroll = this.minScroll; - } - - this.applyRange(); - } - - private void applyRange() - { - this.currentScroll = Math.max( Math.min( this.currentScroll, this.maxScroll ), this.minScroll ); - } - - @Override - public int getCurrentScroll() - { - return this.currentScroll; - } - - public void setCurrentScroll(final int currentScroll) - { - this.currentScroll = Math.max( Math.min( currentScroll, this.maxScroll ), this.minScroll ); - } - - public boolean contains(final int x, final int y) - { - return x >= this.displayX && y >= this.displayY && x <= this.displayX + this.width && y <= this.displayY + this.height; - } - - public void click(final AEBaseGui aeBaseGui, final int x, final int y) - { - if (this.getRange() == 0) { - return; - } - - if (this.contains(x, y)) { - this.currentScroll = ( y - this.displayY ); - this.currentScroll = this.minScroll + ( ( this.currentScroll * 2 * this.getRange() / this.height ) ); - this.currentScroll = ( this.currentScroll + 1 ) >> 1; - this.applyRange(); - } - } - - public void wheel( int delta ) - { - delta = Math.max( Math.min( -delta, 1 ), -1 ); - this.currentScroll += delta * this.pageSize; - this.applyRange(); - } +public class GuiScrollbar implements IScrollSource { + private String txtBase = "minecraft"; + private String txtFile = "gui/container/creative_inventory/tabs.png"; + private int txtShiftX = 232; + private int txtShiftY = 0; + + private int displayX = 0; + private int displayY = 0; + private int width = 12; + private int height = 16; + private int pageSize = 1; + + private int maxScroll = 0; + private int minScroll = 0; + private int currentScroll = 0; + + public void setTexture(final String base, final String file, final int shiftX, final int shiftY) { + txtBase = base; + txtFile = file; + txtShiftX = shiftX; + txtShiftY = shiftY; + } + + public void draw(final AEBaseGui g) { + g.bindTexture(txtBase, txtFile); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + + if (this.getRange() == 0) { + g.drawTexturedModalRect(this.displayX, this.displayY, txtShiftX + this.width, txtShiftY, this.width, 15); + } else { + final int offset = (this.currentScroll - this.minScroll) * (this.height - 15) / this.getRange(); + g.drawTexturedModalRect(this.displayX, offset + this.displayY, txtShiftX, txtShiftY, this.width, 15); + } + } + + private int getRange() { + return this.maxScroll - this.minScroll; + } + + public int getLeft() { + return this.displayX; + } + + public GuiScrollbar setLeft(final int v) { + this.displayX = v; + return this; + } + + public int getTop() { + return this.displayY; + } + + public GuiScrollbar setTop(final int v) { + this.displayY = v; + return this; + } + + public int getWidth() { + return this.width; + } + + public GuiScrollbar setWidth(final int v) { + this.width = v; + return this; + } + + public int getHeight() { + return this.height; + } + + public GuiScrollbar setHeight(final int v) { + this.height = v; + return this; + } + + public void setRange(final int min, final int max, final int pageSize) { + this.minScroll = min; + this.maxScroll = max; + this.pageSize = pageSize; + + if (this.minScroll > this.maxScroll) { + this.maxScroll = this.minScroll; + } + + this.applyRange(); + } + + private void applyRange() { + this.currentScroll = Math.max(Math.min(this.currentScroll, this.maxScroll), this.minScroll); + } + + @Override + public int getCurrentScroll() { + return this.currentScroll; + } + + public void setCurrentScroll(final int currentScroll) { + this.currentScroll = Math.max(Math.min(currentScroll, this.maxScroll), this.minScroll); + } + + public boolean contains(final int x, final int y) { + return x >= this.displayX + && y >= this.displayY + && x <= this.displayX + this.width + && y <= this.displayY + this.height; + } + + public void click(final AEBaseGui aeBaseGui, final int x, final int y) { + if (this.getRange() == 0) { + return; + } + + if (this.contains(x, y)) { + this.currentScroll = (y - this.displayY); + this.currentScroll = this.minScroll + ((this.currentScroll * 2 * this.getRange() / this.height)); + this.currentScroll = (this.currentScroll + 1) >> 1; + this.applyRange(); + } + } + + public void wheel(int delta) { + delta = Math.max(Math.min(-delta, 1), -1); + this.currentScroll += delta * this.pageSize; + this.applyRange(); + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiTabButton.java b/src/main/java/appeng/client/gui/widgets/GuiTabButton.java index 54c0f7ac17f..241b2d166dc 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiTabButton.java +++ b/src/main/java/appeng/client/gui/widgets/GuiTabButton.java @@ -18,7 +18,6 @@ package appeng.client.gui.widgets; - import appeng.client.texture.ExtraBlockTextures; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; @@ -29,135 +28,128 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; - -public class GuiTabButton extends GuiButton implements ITooltip -{ - private final RenderItem itemRenderer; - private final String message; - private int hideEdge = 0; - private int myIcon = -1; - private ItemStack myItem; - - public GuiTabButton( final int x, final int y, final int ico, final String message, final RenderItem ir ) - { - super( 0, 0, 16, "" ); - - this.xPosition = x; - this.yPosition = y; - this.width = 22; - this.height = 22; - this.myIcon = ico; - this.message = message; - this.itemRenderer = ir; - } - - /** - * Using itemstack as an icon - * - * @param x x pos of button - * @param y y pos of button - * @param ico used icon - * @param message mouse over message - * @param ir renderer - */ - public GuiTabButton( final int x, final int y, final ItemStack ico, final String message, final RenderItem ir ) - { - super( 0, 0, 16, "" ); - this.xPosition = x; - this.yPosition = y; - this.width = 22; - this.height = 22; - this.myItem = ico; - this.message = message; - this.itemRenderer = ir; - } - - @Override - public void drawButton( final Minecraft minecraft, final int x, final int y ) - { - if( this.visible ) - { - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - minecraft.renderEngine.bindTexture( ExtraBlockTextures.GuiTexture( "guis/states.png" ) ); - this.field_146123_n = x >= this.xPosition && y >= this.yPosition && x < this.xPosition + this.width && y < this.yPosition + this.height; - - int uv_x = ( this.hideEdge > 0 ? 11 : 13 ); - - final int offsetX = this.hideEdge > 0 ? 1 : 0; - - this.drawTexturedModalRect( this.xPosition, this.yPosition, uv_x * 16, 0, 25, 22 ); - - if( this.myIcon >= 0 ) - { - final int uv_y = (int) Math.floor( this.myIcon / 16 ); - uv_x = this.myIcon - uv_y * 16; - - this.drawTexturedModalRect( offsetX + this.xPosition + 3, this.yPosition + 3, uv_x * 16, uv_y * 16, 16, 16 ); - } - - this.mouseDragged( minecraft, x, y ); - - if( this.myItem != null ) - { - this.zLevel = 100.0F; - this.itemRenderer.zLevel = 100.0F; - - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - RenderHelper.enableGUIStandardItemLighting(); - final FontRenderer fontrenderer = minecraft.fontRenderer; - this.itemRenderer.renderItemAndEffectIntoGUI( fontrenderer, minecraft.renderEngine, this.myItem, offsetX + this.xPosition + 3, this.yPosition + 3 ); - GL11.glDisable( GL11.GL_LIGHTING ); - - this.itemRenderer.zLevel = 0.0F; - this.zLevel = 0.0F; - } - } - } - - @Override - public String getMessage() - { - return this.message; - } - - @Override - public int xPos() - { - return this.xPosition; - } - - @Override - public int yPos() - { - return this.yPosition; - } - - @Override - public int getWidth() - { - return 22; - } - - @Override - public int getHeight() - { - return 22; - } - - @Override - public boolean isVisible() - { - return this.visible; - } - - public int getHideEdge() - { - return this.hideEdge; - } - - public void setHideEdge( final int hideEdge ) - { - this.hideEdge = hideEdge; - } +public class GuiTabButton extends GuiButton implements ITooltip { + private final RenderItem itemRenderer; + private final String message; + private int hideEdge = 0; + private int myIcon = -1; + private ItemStack myItem; + + public GuiTabButton(final int x, final int y, final int ico, final String message, final RenderItem ir) { + super(0, 0, 16, ""); + + this.xPosition = x; + this.yPosition = y; + this.width = 22; + this.height = 22; + this.myIcon = ico; + this.message = message; + this.itemRenderer = ir; + } + + /** + * Using itemstack as an icon + * + * @param x x pos of button + * @param y y pos of button + * @param ico used icon + * @param message mouse over message + * @param ir renderer + */ + public GuiTabButton(final int x, final int y, final ItemStack ico, final String message, final RenderItem ir) { + super(0, 0, 16, ""); + this.xPosition = x; + this.yPosition = y; + this.width = 22; + this.height = 22; + this.myItem = ico; + this.message = message; + this.itemRenderer = ir; + } + + @Override + public void drawButton(final Minecraft minecraft, final int x, final int y) { + if (this.visible) { + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + minecraft.renderEngine.bindTexture(ExtraBlockTextures.GuiTexture("guis/states.png")); + this.field_146123_n = x >= this.xPosition + && y >= this.yPosition + && x < this.xPosition + this.width + && y < this.yPosition + this.height; + + int uv_x = (this.hideEdge > 0 ? 11 : 13); + + final int offsetX = this.hideEdge > 0 ? 1 : 0; + + this.drawTexturedModalRect(this.xPosition, this.yPosition, uv_x * 16, 0, 25, 22); + + if (this.myIcon >= 0) { + final int uv_y = (int) Math.floor(this.myIcon / 16); + uv_x = this.myIcon - uv_y * 16; + + this.drawTexturedModalRect( + offsetX + this.xPosition + 3, this.yPosition + 3, uv_x * 16, uv_y * 16, 16, 16); + } + + this.mouseDragged(minecraft, x, y); + + if (this.myItem != null) { + this.zLevel = 100.0F; + this.itemRenderer.zLevel = 100.0F; + + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + RenderHelper.enableGUIStandardItemLighting(); + final FontRenderer fontrenderer = minecraft.fontRenderer; + this.itemRenderer.renderItemAndEffectIntoGUI( + fontrenderer, + minecraft.renderEngine, + this.myItem, + offsetX + this.xPosition + 3, + this.yPosition + 3); + GL11.glDisable(GL11.GL_LIGHTING); + + this.itemRenderer.zLevel = 0.0F; + this.zLevel = 0.0F; + } + } + } + + @Override + public String getMessage() { + return this.message; + } + + @Override + public int xPos() { + return this.xPosition; + } + + @Override + public int yPos() { + return this.yPosition; + } + + @Override + public int getWidth() { + return 22; + } + + @Override + public int getHeight() { + return 22; + } + + @Override + public boolean isVisible() { + return this.visible; + } + + public int getHideEdge() { + return this.hideEdge; + } + + public void setHideEdge(final int hideEdge) { + this.hideEdge = hideEdge; + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java b/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java index 6477d2b4fa9..22ca0e3576b 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java +++ b/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java @@ -18,132 +18,116 @@ package appeng.client.gui.widgets; - import appeng.client.texture.ExtraBlockTextures; +import java.util.regex.Pattern; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.util.StatCollector; import org.lwjgl.opengl.GL11; -import java.util.regex.Pattern; - - -public class GuiToggleButton extends GuiButton implements ITooltip -{ - private static final Pattern PATTERN_NEW_LINE = Pattern.compile( "\\n", Pattern.LITERAL ); - private final int iconIdxOn; - private final int iconIdxOff; - - private final String displayName; - private final String displayHint; - - private boolean isActive; - - public GuiToggleButton( final int x, final int y, final int on, final int off, final String displayName, final String displayHint ) - { - super( 0, 0, 16, "" ); - this.iconIdxOn = on; - this.iconIdxOff = off; - this.displayName = displayName; - this.displayHint = displayHint; - this.xPosition = x; - this.yPosition = y; - this.width = 16; - this.height = 16; - } - - public void setState( final boolean isOn ) - { - this.isActive = isOn; - } - - @Override - public void drawButton( final Minecraft par1Minecraft, final int par2, final int par3 ) - { - if( this.visible ) - { - final int iconIndex = this.getIconIndex(); - - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - par1Minecraft.renderEngine.bindTexture( ExtraBlockTextures.GuiTexture( "guis/states.png" ) ); - this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + this.width && par3 < this.yPosition + this.height; - - final int uv_y = (int) Math.floor( iconIndex / 16 ); - final int uv_x = iconIndex - uv_y * 16; - - this.drawTexturedModalRect( this.xPosition, this.yPosition, 256 - 16, 256 - 16, 16, 16 ); - this.drawTexturedModalRect( this.xPosition, this.yPosition, uv_x * 16, uv_y * 16, 16, 16 ); - this.mouseDragged( par1Minecraft, par2, par3 ); - } - } - - private int getIconIndex() - { - return this.isActive ? this.iconIdxOn : this.iconIdxOff; - } - - @Override - public String getMessage() - { - if( this.displayName != null ) - { - String name = StatCollector.translateToLocal( this.displayName ); - String value = StatCollector.translateToLocal( this.displayHint ); - - if( name == null || name.isEmpty() ) - { - name = this.displayName; - } - if( value == null || value.isEmpty() ) - { - value = this.displayHint; - } - - value = PATTERN_NEW_LINE.matcher( value ).replaceAll( "\n" ); - final StringBuilder sb = new StringBuilder( value ); - - int i = sb.lastIndexOf( "\n" ); - if( i <= 0 ) - { - i = 0; - } - while( i + 30 < sb.length() && ( i = sb.lastIndexOf( " ", i + 30 ) ) != -1 ) - { - sb.replace( i, i + 1, "\n" ); - } - - return name + '\n' + sb; - } - return null; - } - - @Override - public int xPos() - { - return this.xPosition; - } - - @Override - public int yPos() - { - return this.yPosition; - } - - @Override - public int getWidth() - { - return 16; - } - - @Override - public int getHeight() - { - return 16; - } - - @Override - public boolean isVisible() - { - return this.visible; - } +public class GuiToggleButton extends GuiButton implements ITooltip { + private static final Pattern PATTERN_NEW_LINE = Pattern.compile("\\n", Pattern.LITERAL); + private final int iconIdxOn; + private final int iconIdxOff; + + private final String displayName; + private final String displayHint; + + private boolean isActive; + + public GuiToggleButton( + final int x, final int y, final int on, final int off, final String displayName, final String displayHint) { + super(0, 0, 16, ""); + this.iconIdxOn = on; + this.iconIdxOff = off; + this.displayName = displayName; + this.displayHint = displayHint; + this.xPosition = x; + this.yPosition = y; + this.width = 16; + this.height = 16; + } + + public void setState(final boolean isOn) { + this.isActive = isOn; + } + + @Override + public void drawButton(final Minecraft par1Minecraft, final int par2, final int par3) { + if (this.visible) { + final int iconIndex = this.getIconIndex(); + + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + par1Minecraft.renderEngine.bindTexture(ExtraBlockTextures.GuiTexture("guis/states.png")); + this.field_146123_n = par2 >= this.xPosition + && par3 >= this.yPosition + && par2 < this.xPosition + this.width + && par3 < this.yPosition + this.height; + + final int uv_y = (int) Math.floor(iconIndex / 16); + final int uv_x = iconIndex - uv_y * 16; + + this.drawTexturedModalRect(this.xPosition, this.yPosition, 256 - 16, 256 - 16, 16, 16); + this.drawTexturedModalRect(this.xPosition, this.yPosition, uv_x * 16, uv_y * 16, 16, 16); + this.mouseDragged(par1Minecraft, par2, par3); + } + } + + private int getIconIndex() { + return this.isActive ? this.iconIdxOn : this.iconIdxOff; + } + + @Override + public String getMessage() { + if (this.displayName != null) { + String name = StatCollector.translateToLocal(this.displayName); + String value = StatCollector.translateToLocal(this.displayHint); + + if (name == null || name.isEmpty()) { + name = this.displayName; + } + if (value == null || value.isEmpty()) { + value = this.displayHint; + } + + value = PATTERN_NEW_LINE.matcher(value).replaceAll("\n"); + final StringBuilder sb = new StringBuilder(value); + + int i = sb.lastIndexOf("\n"); + if (i <= 0) { + i = 0; + } + while (i + 30 < sb.length() && (i = sb.lastIndexOf(" ", i + 30)) != -1) { + sb.replace(i, i + 1, "\n"); + } + + return name + '\n' + sb; + } + return null; + } + + @Override + public int xPos() { + return this.xPosition; + } + + @Override + public int yPos() { + return this.yPosition; + } + + @Override + public int getWidth() { + return 16; + } + + @Override + public int getHeight() { + return 16; + } + + @Override + public boolean isVisible() { + return this.visible; + } } diff --git a/src/main/java/appeng/client/gui/widgets/ICraftingCPUTableHolder.java b/src/main/java/appeng/client/gui/widgets/ICraftingCPUTableHolder.java index aaa4de377ff..c51fa501cec 100644 --- a/src/main/java/appeng/client/gui/widgets/ICraftingCPUTableHolder.java +++ b/src/main/java/appeng/client/gui/widgets/ICraftingCPUTableHolder.java @@ -1,6 +1,5 @@ package appeng.client.gui.widgets; -public interface ICraftingCPUTableHolder -{ +public interface ICraftingCPUTableHolder { GuiCraftingCPUTable getCPUTable(); } diff --git a/src/main/java/appeng/client/gui/widgets/IDropToFillTextField.java b/src/main/java/appeng/client/gui/widgets/IDropToFillTextField.java index 4dd242b805c..fa190be823b 100644 --- a/src/main/java/appeng/client/gui/widgets/IDropToFillTextField.java +++ b/src/main/java/appeng/client/gui/widgets/IDropToFillTextField.java @@ -2,11 +2,9 @@ import net.minecraft.item.ItemStack; -public interface IDropToFillTextField -{ +public interface IDropToFillTextField { public boolean isOverTextField(final int mousex, final int mousey); public void setTextFieldValue(final String displayName, final int mousex, final int mousey, final ItemStack stack); - } diff --git a/src/main/java/appeng/client/gui/widgets/IScrollSource.java b/src/main/java/appeng/client/gui/widgets/IScrollSource.java index 10829091b9a..8dc1ddf248c 100644 --- a/src/main/java/appeng/client/gui/widgets/IScrollSource.java +++ b/src/main/java/appeng/client/gui/widgets/IScrollSource.java @@ -18,9 +18,7 @@ package appeng.client.gui.widgets; +public interface IScrollSource { -public interface IScrollSource -{ - - int getCurrentScroll(); + int getCurrentScroll(); } diff --git a/src/main/java/appeng/client/gui/widgets/ISortSource.java b/src/main/java/appeng/client/gui/widgets/ISortSource.java index 534dcb0dcc2..858adafd710 100644 --- a/src/main/java/appeng/client/gui/widgets/ISortSource.java +++ b/src/main/java/appeng/client/gui/widgets/ISortSource.java @@ -18,26 +18,23 @@ package appeng.client.gui.widgets; - import appeng.api.config.SortDir; import appeng.api.config.ViewItems; +public interface ISortSource { -public interface ISortSource -{ - - /** - * @return Sor - */ - Enum getSortBy(); + /** + * @return Sor + */ + Enum getSortBy(); - /** - * @return {@link SortDir} - */ - Enum getSortDir(); + /** + * @return {@link SortDir} + */ + Enum getSortDir(); - /** - * @return {@link ViewItems} - */ - Enum getSortDisplay(); + /** + * @return {@link ViewItems} + */ + Enum getSortDisplay(); } diff --git a/src/main/java/appeng/client/gui/widgets/ITooltip.java b/src/main/java/appeng/client/gui/widgets/ITooltip.java index 232992ac661..73ef0821c0f 100644 --- a/src/main/java/appeng/client/gui/widgets/ITooltip.java +++ b/src/main/java/appeng/client/gui/widgets/ITooltip.java @@ -18,50 +18,48 @@ package appeng.client.gui.widgets; - /** * AEBaseGui controlled Tooltip Interface. */ -public interface ITooltip -{ +public interface ITooltip { - /** - * returns the tooltip message. - * - * @return tooltip message - */ - String getMessage(); + /** + * returns the tooltip message. + * + * @return tooltip message + */ + String getMessage(); - /** - * x Location for the object that triggers the tooltip. - * - * @return xPosition - */ - int xPos(); + /** + * x Location for the object that triggers the tooltip. + * + * @return xPosition + */ + int xPos(); - /** - * y Location for the object that triggers the tooltip. - * - * @return yPosition - */ - int yPos(); + /** + * y Location for the object that triggers the tooltip. + * + * @return yPosition + */ + int yPos(); - /** - * Width of the object that triggers the tooltip. - * - * @return width - */ - int getWidth(); + /** + * Width of the object that triggers the tooltip. + * + * @return width + */ + int getWidth(); - /** - * Height for the object that triggers the tooltip. - * - * @return height - */ - int getHeight(); + /** + * Height for the object that triggers the tooltip. + * + * @return height + */ + int getHeight(); - /** - * @return true if button being drawn - */ - boolean isVisible(); + /** + * @return true if button being drawn + */ + boolean isVisible(); } diff --git a/src/main/java/appeng/client/gui/widgets/MEGuiTextField.java b/src/main/java/appeng/client/gui/widgets/MEGuiTextField.java index 860cc492be7..37bb9deb62b 100644 --- a/src/main/java/appeng/client/gui/widgets/MEGuiTextField.java +++ b/src/main/java/appeng/client/gui/widgets/MEGuiTextField.java @@ -18,13 +18,11 @@ package appeng.client.gui.widgets; - -import org.lwjgl.input.Keyboard; - +import appeng.core.localization.GuiColors; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiTextField; -import appeng.core.localization.GuiColors; +import org.lwjgl.input.Keyboard; /** * A modified version of the Minecraft text field. @@ -34,236 +32,215 @@ *

* The rendering does pay attention to the size of the '_' caret. */ -public class MEGuiTextField implements ITooltip -{ - protected GuiTextField field; - - private static final int PADDING = 2; - private static final int MAX_INPUT_LENGTH = 25; - private static boolean previousKeyboardRepeatEnabled; - private static MEGuiTextField previousKeyboardRepeatEnabledField; - private String tooltip; - private int fontPad; - - public int x; - public int y; - public int w; - public int h; - - /** - * Uses the values to instantiate a padded version of a text field. - * Pays attention to the '_' caret. - * - * @param width absolute width - * @param height absolute height - * @param tooltip tooltip message - */ - public MEGuiTextField(final int width, final int height, final String tooltip) - { - final FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer; - field = new GuiTextField(fontRenderer, 0, 0, 0, 0); - - w = width; - h = height; - - field.setEnableBackgroundDrawing( false ); - field.setMaxStringLength( MAX_INPUT_LENGTH ); - field.setTextColor( GuiColors.SearchboxText.getColor() ); +public class MEGuiTextField implements ITooltip { + protected GuiTextField field; + + private static final int PADDING = 2; + private static final int MAX_INPUT_LENGTH = 25; + private static boolean previousKeyboardRepeatEnabled; + private static MEGuiTextField previousKeyboardRepeatEnabledField; + private String tooltip; + private int fontPad; + + public int x; + public int y; + public int w; + public int h; + + /** + * Uses the values to instantiate a padded version of a text field. + * Pays attention to the '_' caret. + * + * @param width absolute width + * @param height absolute height + * @param tooltip tooltip message + */ + public MEGuiTextField(final int width, final int height, final String tooltip) { + final FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer; + field = new GuiTextField(fontRenderer, 0, 0, 0, 0); + + w = width; + h = height; + + field.setEnableBackgroundDrawing(false); + field.setMaxStringLength(MAX_INPUT_LENGTH); + field.setTextColor(GuiColors.SearchboxText.getColor()); field.setCursorPositionZero(); - setMessage(tooltip); + setMessage(tooltip); - this.fontPad = fontRenderer.getCharWidth( '_' ); + this.fontPad = fontRenderer.getCharWidth('_'); - setDimensionsAndColor(); + setDimensionsAndColor(); + } - } + public MEGuiTextField(final int width, final int height) { + this(width, height, ""); + } - public MEGuiTextField(final int width, final int height) - { - this(width, height, ""); - } + public MEGuiTextField() { + this(0, 0); + } + + protected void setDimensionsAndColor() { + field.xPosition = this.x + PADDING; + field.yPosition = this.y + PADDING; + field.width = this.w - PADDING * 2 - this.fontPad; + field.height = this.h - PADDING * 2; + } - public MEGuiTextField() - { - this(0, 0); - } + public void onTextChange(final String oldText) {} - protected void setDimensionsAndColor() - { - field.xPosition = this.x + PADDING; - field.yPosition = this.y + PADDING; - field.width = this.w - PADDING * 2 - this.fontPad; - field.height = this.h - PADDING * 2; + public void mouseClicked(final int xPos, final int yPos, final int button) { + + if (!this.isMouseIn(xPos, yPos)) { + setFocused(false); + return; + } + + field.setCanLoseFocus(false); + setFocused(true); + + if (button == 1) { + setText(""); + } else { + field.mouseClicked(xPos, yPos, button); + } + + field.setCanLoseFocus(true); + } + + /** + * Checks if the mouse is within the element + * + * @param xCoord current x coord of the mouse + * @param yCoord current y coord of the mouse + * @return true if mouse position is within the getText field area + */ + public boolean isMouseIn(final int xCoord, final int yCoord) { + final boolean withinXRange = this.x <= xCoord && xCoord < this.x + this.w; + final boolean withinYRange = this.y <= yCoord && yCoord < this.y + this.h; + + return withinXRange && withinYRange; } - public void onTextChange(final String oldText) - { - } - - public void mouseClicked(final int xPos, final int yPos, final int button) - { - - if (!this.isMouseIn(xPos, yPos)) { - setFocused(false); - return; - } - - field.setCanLoseFocus(false); - setFocused(true); - - if (button == 1) { - setText(""); - } else { - field.mouseClicked(xPos, yPos, button); - } - - field.setCanLoseFocus(true); - } - - /** - * Checks if the mouse is within the element - * - * @param xCoord current x coord of the mouse - * @param yCoord current y coord of the mouse - * @return true if mouse position is within the getText field area - */ - public boolean isMouseIn(final int xCoord, final int yCoord) - { - final boolean withinXRange = this.x <= xCoord && xCoord < this.x + this.w; - final boolean withinYRange = this.y <= yCoord && yCoord < this.y + this.h; - - return withinXRange && withinYRange; - } - - public boolean textboxKeyTyped(final char keyChar, final int keyID) - { - if (!isFocused()) { - return false; - } - - final String oldText = getText(); - boolean handled = field.textboxKeyTyped(keyChar, keyID); - - if (!handled && (keyID == Keyboard.KEY_RETURN || keyID == Keyboard.KEY_NUMPADENTER || keyID == Keyboard.KEY_ESCAPE)) { - setFocused(false); - } - - if (handled) { - onTextChange(oldText); - } - - return handled; - } - - public void drawTextBox() - { - if (field.getVisible()) { - setDimensionsAndColor(); - GuiTextField.drawRect(this.x + 1, this.y + 1, this.x + this.w - 1, this.y + this.h - 1, isFocused() ? GuiColors.SearchboxFocused.getColor() : GuiColors.SearchboxUnfocused.getColor()); - field.drawTextBox(); - } - } - - public void setText(String text, boolean ignoreTrigger) - { + public boolean textboxKeyTyped(final char keyChar, final int keyID) { + if (!isFocused()) { + return false; + } + final String oldText = getText(); - - field.setText(text); - field.setCursorPositionEnd(); + boolean handled = field.textboxKeyTyped(keyChar, keyID); + + if (!handled + && (keyID == Keyboard.KEY_RETURN + || keyID == Keyboard.KEY_NUMPADENTER + || keyID == Keyboard.KEY_ESCAPE)) { + setFocused(false); + } - if (!ignoreTrigger) { - onTextChange(oldText); - } + if (handled) { + onTextChange(oldText); + } + + return handled; + } + public void drawTextBox() { + if (field.getVisible()) { + setDimensionsAndColor(); + GuiTextField.drawRect( + this.x + 1, + this.y + 1, + this.x + this.w - 1, + this.y + this.h - 1, + isFocused() ? GuiColors.SearchboxFocused.getColor() : GuiColors.SearchboxUnfocused.getColor()); + field.drawTextBox(); + } } - public void setText(String text) - { + public void setText(String text, boolean ignoreTrigger) { + final String oldText = getText(); + + field.setText(text); + field.setCursorPositionEnd(); + + if (!ignoreTrigger) { + onTextChange(oldText); + } + } + + public void setText(String text) { setText(text, false); } - public void setFocused(boolean focus) - { + public void setFocused(boolean focus) { if (field.isFocused() == focus) { - return; - } + return; + } - field.setFocused(focus); + field.setFocused(focus); - if (focus) { + if (focus) { - if (previousKeyboardRepeatEnabledField == null) { - previousKeyboardRepeatEnabled = Keyboard.areRepeatEventsEnabled(); - } + if (previousKeyboardRepeatEnabledField == null) { + previousKeyboardRepeatEnabled = Keyboard.areRepeatEventsEnabled(); + } - previousKeyboardRepeatEnabledField = this; - Keyboard.enableRepeatEvents(true); - } else { - - if (previousKeyboardRepeatEnabledField == this) { - previousKeyboardRepeatEnabledField = null; - Keyboard.enableRepeatEvents(previousKeyboardRepeatEnabled); - } - - } + previousKeyboardRepeatEnabledField = this; + Keyboard.enableRepeatEvents(true); + } else { + if (previousKeyboardRepeatEnabledField == this) { + previousKeyboardRepeatEnabledField = null; + Keyboard.enableRepeatEvents(previousKeyboardRepeatEnabled); + } + } } - public void setMaxStringLength(final int size) - { - field.setMaxStringLength(size); - } + public void setMaxStringLength(final int size) { + field.setMaxStringLength(size); + } - public boolean isFocused() - { + public boolean isFocused() { return field.isFocused(); } - public String getText() - { + public String getText() { return field.getText(); } - - public void setMessage(String t) - { - tooltip = t; - } - - @Override - public String getMessage() - { - return tooltip; - } - - @Override - public boolean isVisible() - { - return field.getVisible(); - } - - @Override - public int xPos() - { - return x; - } - - @Override - public int yPos() - { - return y; - } - - @Override - public int getWidth() - { - return w; - } - - @Override - public int getHeight() - { - return h; - } + public void setMessage(String t) { + tooltip = t; + } + + @Override + public String getMessage() { + return tooltip; + } + + @Override + public boolean isVisible() { + return field.getVisible(); + } + + @Override + public int xPos() { + return x; + } + + @Override + public int yPos() { + return y; + } + + @Override + public int getWidth() { + return w; + } + + @Override + public int getHeight() { + return h; + } } diff --git a/src/main/java/appeng/client/me/ClientDCInternalInv.java b/src/main/java/appeng/client/me/ClientDCInternalInv.java index d68edaca95e..25c74c75875 100644 --- a/src/main/java/appeng/client/me/ClientDCInternalInv.java +++ b/src/main/java/appeng/client/me/ClientDCInternalInv.java @@ -18,59 +18,48 @@ package appeng.client.me; - import appeng.tile.inventory.AppEngInternalInventory; import appeng.util.ItemSorters; -import net.minecraft.util.StatCollector; - import javax.annotation.Nonnull; +import net.minecraft.util.StatCollector; +public class ClientDCInternalInv implements Comparable { -public class ClientDCInternalInv implements Comparable -{ - - private final String unlocalizedName; - private final AppEngInternalInventory inventory; + private final String unlocalizedName; + private final AppEngInternalInventory inventory; - private final long id; - private final long sortBy; + private final long id; + private final long sortBy; - public ClientDCInternalInv( final int size, final long id, final long sortBy, final String unlocalizedName ) - { - this.inventory = new AppEngInternalInventory( null, size, 1 ); - this.unlocalizedName = unlocalizedName; - this.id = id; - this.sortBy = sortBy; - } + public ClientDCInternalInv(final int size, final long id, final long sortBy, final String unlocalizedName) { + this.inventory = new AppEngInternalInventory(null, size, 1); + this.unlocalizedName = unlocalizedName; + this.id = id; + this.sortBy = sortBy; + } - public String getName() - { - final String s = StatCollector.translateToLocal( this.unlocalizedName + ".name" ); - if( s.equals( this.unlocalizedName + ".name" ) ) - { - return StatCollector.translateToLocal( this.unlocalizedName ); - } - return s; - } + public String getName() { + final String s = StatCollector.translateToLocal(this.unlocalizedName + ".name"); + if (s.equals(this.unlocalizedName + ".name")) { + return StatCollector.translateToLocal(this.unlocalizedName); + } + return s; + } - public String getUnlocalizedName() - { - return unlocalizedName; - } + public String getUnlocalizedName() { + return unlocalizedName; + } - @Override - public int compareTo( @Nonnull final ClientDCInternalInv o ) - { - return ItemSorters.compareLong( this.sortBy, o.sortBy ); - } + @Override + public int compareTo(@Nonnull final ClientDCInternalInv o) { + return ItemSorters.compareLong(this.sortBy, o.sortBy); + } - public AppEngInternalInventory getInventory() - { - return this.inventory; - } + public AppEngInternalInventory getInventory() { + return this.inventory; + } - public long getId() - { - return this.id; - } -} \ No newline at end of file + public long getId() { + return this.id; + } +} diff --git a/src/main/java/appeng/client/me/InternalSlotME.java b/src/main/java/appeng/client/me/InternalSlotME.java index 3128932f56b..74921e399e9 100644 --- a/src/main/java/appeng/client/me/InternalSlotME.java +++ b/src/main/java/appeng/client/me/InternalSlotME.java @@ -18,49 +18,40 @@ package appeng.client.me; - import appeng.api.storage.data.IAEItemStack; import net.minecraft.item.ItemStack; +public class InternalSlotME { -public class InternalSlotME -{ - - private final int offset; - private final int xPos; - private final int yPos; - private final ItemRepo repo; + private final int offset; + private final int xPos; + private final int yPos; + private final ItemRepo repo; - public InternalSlotME( final ItemRepo def, final int offset, final int displayX, final int displayY ) - { - this.repo = def; - this.offset = offset; - this.xPos = displayX; - this.yPos = displayY; - } + public InternalSlotME(final ItemRepo def, final int offset, final int displayX, final int displayY) { + this.repo = def; + this.offset = offset; + this.xPos = displayX; + this.yPos = displayY; + } - ItemStack getStack() - { - return this.repo.getItem( this.offset ); - } + ItemStack getStack() { + return this.repo.getItem(this.offset); + } - IAEItemStack getAEStack() - { - return this.repo.getReferenceItem( this.offset ); - } + IAEItemStack getAEStack() { + return this.repo.getReferenceItem(this.offset); + } - boolean hasPower() - { - return this.repo.hasPower(); - } + boolean hasPower() { + return this.repo.hasPower(); + } - int getxPosition() - { - return this.xPos; - } + int getxPosition() { + return this.xPos; + } - int getyPosition() - { - return this.yPos; - } + int getyPosition() { + return this.yPos; + } } diff --git a/src/main/java/appeng/client/me/ItemRepo.java b/src/main/java/appeng/client/me/ItemRepo.java index 394e8ae61aa..17b370602fd 100644 --- a/src/main/java/appeng/client/me/ItemRepo.java +++ b/src/main/java/appeng/client/me/ItemRepo.java @@ -18,7 +18,6 @@ package appeng.client.me; - import appeng.api.AEApi; import appeng.api.config.*; import appeng.api.storage.data.IAEItemStack; @@ -31,275 +30,223 @@ import appeng.util.Platform; import appeng.util.prioitylist.IPartitionList; import cpw.mods.fml.relauncher.ReflectionHelper; -import net.minecraft.item.ItemStack; - -import javax.annotation.Nonnull; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.regex.Pattern; +import javax.annotation.Nonnull; +import net.minecraft.item.ItemStack; - -public class ItemRepo -{ - - private final IItemList list = AEApi.instance().storage().createItemList(); - private final ArrayList view = new ArrayList(); - private final ArrayList dsp = new ArrayList(); - private final IScrollSource src; - private final ISortSource sortSrc; - - private int rowSize = 9; - - private String searchString = ""; - private IPartitionList myPartitionList; - private String innerSearch = ""; - private String NEIWord = null; - private boolean hasPower; - - public ItemRepo( final IScrollSource src, final ISortSource sortSrc ) - { - this.src = src; - this.sortSrc = sortSrc; - } - - public IAEItemStack getReferenceItem( int idx ) - { - idx += this.src.getCurrentScroll() * this.rowSize; - - if( idx >= this.view.size() ) - { - return null; - } - return this.view.get( idx ); - } - - public ItemStack getItem( int idx ) - { - idx += this.src.getCurrentScroll() * this.rowSize; - - if( idx >= this.dsp.size() ) - { - return null; - } - return this.dsp.get( idx ); - } - - void setSearch( final String search ) - { - this.searchString = search == null ? "" : search; - } - - public void postUpdate( final IAEItemStack is ) - { - final IAEItemStack st = this.list.findPrecise( is ); - - if( st != null ) - { - st.reset(); - st.add( is ); - } - else - { - this.list.add( is ); - } - } - - public void setViewCell( final ItemStack[] list ) - { - this.myPartitionList = ItemViewCell.createFilter( list ); - this.updateView(); - } - - public void updateView() - { - this.view.clear(); - this.dsp.clear(); - - this.view.ensureCapacity( this.list.size() ); - this.dsp.ensureCapacity( this.list.size() ); - - final Enum viewMode = this.sortSrc.getSortDisplay(); - final Enum searchMode = AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ); - if( searchMode == SearchBoxMode.NEI_AUTOSEARCH || searchMode == SearchBoxMode.NEI_MANUAL_SEARCH ) - { - this.updateNEI( this.searchString ); - } - - this.innerSearch = this.searchString; - final boolean terminalSearchToolTips = AEConfig.instance.settings.getSetting( Settings.SEARCH_TOOLTIPS ) != YesNo.NO; - // boolean terminalSearchMods = Configuration.INSTANCE.settings.getSetting( Settings.SEARCH_MODS ) != YesNo.NO; - - boolean searchMod = false; - if( this.innerSearch.startsWith( "@" ) ) - { - searchMod = true; - this.innerSearch = this.innerSearch.substring( 1 ); - } - - Pattern m = null; - try - { - m = Pattern.compile( this.innerSearch.toLowerCase(), Pattern.CASE_INSENSITIVE ); - } - catch( final Throwable ignore ) - { - try - { - m = Pattern.compile( Pattern.quote( this.innerSearch.toLowerCase() ), Pattern.CASE_INSENSITIVE ); - } - catch( final Throwable __ ) - { - return; - } - } - - boolean notDone = false; - for( IAEItemStack is : this.list ) - { - if( this.myPartitionList != null ) - { - if( !this.myPartitionList.isListed( is ) ) - { - continue; - } - } - - if( viewMode == ViewItems.CRAFTABLE && !is.isCraftable() ) - { - continue; - } - - if( viewMode == ViewItems.CRAFTABLE ) - { - is = is.copy(); - is.setStackSize( 0 ); - } - - if( viewMode == ViewItems.STORED && is.getStackSize() == 0 ) - { - continue; - } - - final String dspName = searchMod ? Platform.getModId( is ) : Platform.getItemDisplayName( is ); - notDone = true; - - if( m.matcher( dspName.toLowerCase() ).find() ) - { - this.view.add( is ); - notDone = false; - } - - if( terminalSearchToolTips && notDone ) - { - for( final Object lp : Platform.getTooltip( is ) ) - { - if( lp instanceof String && m.matcher( (CharSequence) lp ).find() ) - { - this.view.add( is ); - notDone = false; - break; - } - } - } - - /* - * if ( terminalSearchMods && notDone ) { if ( m.matcher( Platform.getMod( is.getItemStack() ) ).find() ) { - * view.add( is ); notDone = false; } } - */ - } - - final Enum SortBy = this.sortSrc.getSortBy(); - final Enum SortDir = this.sortSrc.getSortDir(); - - ItemSorters.setDirection( (appeng.api.config.SortDir) SortDir ); - ItemSorters.init(); - - if( SortBy == SortOrder.MOD ) - { - Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_MOD ); - } - else if( SortBy == SortOrder.AMOUNT ) - { - Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_SIZE ); - } - else if( SortBy == SortOrder.INVTWEAKS ) - { - Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_INV_TWEAKS ); - } - else - { - Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_NAME ); - } - - for( final IAEItemStack is : this.view ) - { - this.dsp.add( is.getItemStack() ); - } - } - - private void updateNEI( final String filter ) - { - try - { - if( this.NEIWord == null || !this.NEIWord.equals( filter ) ) - { - final Class c = ReflectionHelper.getClass( this.getClass().getClassLoader(), "codechicken.nei.LayoutManager" ); - final Field fldSearchField = c.getField( "searchField" ); - final Object searchField = fldSearchField.get( c ); - - final Method a = searchField.getClass().getMethod( "setText", String.class ); - final Method b = searchField.getClass().getMethod( "onTextChange", String.class ); - - this.NEIWord = filter; - a.invoke( searchField, filter ); - b.invoke( searchField, "" ); - } - } - catch( final Throwable ignore ) - { - - } - } - - public int size() - { - return this.view.size(); - } - - public void clear() - { - this.list.resetStatus(); - } - - public boolean hasPower() - { - return this.hasPower; - } - - public void setPower( final boolean hasPower ) - { - this.hasPower = hasPower; - } - - public int getRowSize() - { - return this.rowSize; - } - - public void setRowSize( final int rowSize ) - { - this.rowSize = rowSize; - } - - public String getSearchString() - { - return this.searchString; - } - - public void setSearchString( @Nonnull final String searchString ) - { - this.searchString = searchString; - } +public class ItemRepo { + + private final IItemList list = AEApi.instance().storage().createItemList(); + private final ArrayList view = new ArrayList(); + private final ArrayList dsp = new ArrayList(); + private final IScrollSource src; + private final ISortSource sortSrc; + + private int rowSize = 9; + + private String searchString = ""; + private IPartitionList myPartitionList; + private String innerSearch = ""; + private String NEIWord = null; + private boolean hasPower; + + public ItemRepo(final IScrollSource src, final ISortSource sortSrc) { + this.src = src; + this.sortSrc = sortSrc; + } + + public IAEItemStack getReferenceItem(int idx) { + idx += this.src.getCurrentScroll() * this.rowSize; + + if (idx >= this.view.size()) { + return null; + } + return this.view.get(idx); + } + + public ItemStack getItem(int idx) { + idx += this.src.getCurrentScroll() * this.rowSize; + + if (idx >= this.dsp.size()) { + return null; + } + return this.dsp.get(idx); + } + + void setSearch(final String search) { + this.searchString = search == null ? "" : search; + } + + public void postUpdate(final IAEItemStack is) { + final IAEItemStack st = this.list.findPrecise(is); + + if (st != null) { + st.reset(); + st.add(is); + } else { + this.list.add(is); + } + } + + public void setViewCell(final ItemStack[] list) { + this.myPartitionList = ItemViewCell.createFilter(list); + this.updateView(); + } + + public void updateView() { + this.view.clear(); + this.dsp.clear(); + + this.view.ensureCapacity(this.list.size()); + this.dsp.ensureCapacity(this.list.size()); + + final Enum viewMode = this.sortSrc.getSortDisplay(); + final Enum searchMode = AEConfig.instance.settings.getSetting(Settings.SEARCH_MODE); + if (searchMode == SearchBoxMode.NEI_AUTOSEARCH || searchMode == SearchBoxMode.NEI_MANUAL_SEARCH) { + this.updateNEI(this.searchString); + } + + this.innerSearch = this.searchString; + final boolean terminalSearchToolTips = + AEConfig.instance.settings.getSetting(Settings.SEARCH_TOOLTIPS) != YesNo.NO; + // boolean terminalSearchMods = Configuration.INSTANCE.settings.getSetting( Settings.SEARCH_MODS ) != YesNo.NO; + + boolean searchMod = false; + if (this.innerSearch.startsWith("@")) { + searchMod = true; + this.innerSearch = this.innerSearch.substring(1); + } + + Pattern m = null; + try { + m = Pattern.compile(this.innerSearch.toLowerCase(), Pattern.CASE_INSENSITIVE); + } catch (final Throwable ignore) { + try { + m = Pattern.compile(Pattern.quote(this.innerSearch.toLowerCase()), Pattern.CASE_INSENSITIVE); + } catch (final Throwable __) { + return; + } + } + + boolean notDone = false; + for (IAEItemStack is : this.list) { + if (this.myPartitionList != null) { + if (!this.myPartitionList.isListed(is)) { + continue; + } + } + + if (viewMode == ViewItems.CRAFTABLE && !is.isCraftable()) { + continue; + } + + if (viewMode == ViewItems.CRAFTABLE) { + is = is.copy(); + is.setStackSize(0); + } + + if (viewMode == ViewItems.STORED && is.getStackSize() == 0) { + continue; + } + + final String dspName = searchMod ? Platform.getModId(is) : Platform.getItemDisplayName(is); + notDone = true; + + if (m.matcher(dspName.toLowerCase()).find()) { + this.view.add(is); + notDone = false; + } + + if (terminalSearchToolTips && notDone) { + for (final Object lp : Platform.getTooltip(is)) { + if (lp instanceof String && m.matcher((CharSequence) lp).find()) { + this.view.add(is); + notDone = false; + break; + } + } + } + + /* + * if ( terminalSearchMods && notDone ) { if ( m.matcher( Platform.getMod( is.getItemStack() ) ).find() ) { + * view.add( is ); notDone = false; } } + */ + } + + final Enum SortBy = this.sortSrc.getSortBy(); + final Enum SortDir = this.sortSrc.getSortDir(); + + ItemSorters.setDirection((appeng.api.config.SortDir) SortDir); + ItemSorters.init(); + + if (SortBy == SortOrder.MOD) { + Collections.sort(this.view, ItemSorters.CONFIG_BASED_SORT_BY_MOD); + } else if (SortBy == SortOrder.AMOUNT) { + Collections.sort(this.view, ItemSorters.CONFIG_BASED_SORT_BY_SIZE); + } else if (SortBy == SortOrder.INVTWEAKS) { + Collections.sort(this.view, ItemSorters.CONFIG_BASED_SORT_BY_INV_TWEAKS); + } else { + Collections.sort(this.view, ItemSorters.CONFIG_BASED_SORT_BY_NAME); + } + + for (final IAEItemStack is : this.view) { + this.dsp.add(is.getItemStack()); + } + } + + private void updateNEI(final String filter) { + try { + if (this.NEIWord == null || !this.NEIWord.equals(filter)) { + final Class c = + ReflectionHelper.getClass(this.getClass().getClassLoader(), "codechicken.nei.LayoutManager"); + final Field fldSearchField = c.getField("searchField"); + final Object searchField = fldSearchField.get(c); + + final Method a = searchField.getClass().getMethod("setText", String.class); + final Method b = searchField.getClass().getMethod("onTextChange", String.class); + + this.NEIWord = filter; + a.invoke(searchField, filter); + b.invoke(searchField, ""); + } + } catch (final Throwable ignore) { + + } + } + + public int size() { + return this.view.size(); + } + + public void clear() { + this.list.resetStatus(); + } + + public boolean hasPower() { + return this.hasPower; + } + + public void setPower(final boolean hasPower) { + this.hasPower = hasPower; + } + + public int getRowSize() { + return this.rowSize; + } + + public void setRowSize(final int rowSize) { + this.rowSize = rowSize; + } + + public String getSearchString() { + return this.searchString; + } + + public void setSearchString(@Nonnull final String searchString) { + this.searchString = searchString; + } } diff --git a/src/main/java/appeng/client/me/SlotDisconnected.java b/src/main/java/appeng/client/me/SlotDisconnected.java index e105d958a25..6dff4775f69 100644 --- a/src/main/java/appeng/client/me/SlotDisconnected.java +++ b/src/main/java/appeng/client/me/SlotDisconnected.java @@ -18,7 +18,6 @@ package appeng.client.me; - import appeng.container.slot.AppEngSlot; import appeng.items.misc.ItemEncodedPattern; import appeng.util.Platform; @@ -26,86 +25,67 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - -public class SlotDisconnected extends AppEngSlot -{ - - private final ClientDCInternalInv mySlot; - - public SlotDisconnected( final ClientDCInternalInv me, final int which, final int x, final int y ) - { - super( me.getInventory(), which, x, y ); - this.mySlot = me; - } - - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } - - @Override - public void putStack( final ItemStack par1ItemStack ) - { - - } - - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } - - @Override - public ItemStack getDisplayStack() - { - if( Platform.isClient() ) - { - final ItemStack is = super.getStack(); - if( is != null && is.getItem() instanceof ItemEncodedPattern ) - { - final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); - final ItemStack out = iep.getOutput( is ); - if( out != null ) - { - return out; - } - } - } - return super.getStack(); - } - - @Override - public void onPickupFromSlot( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) - { - } - - @Override - public boolean getHasStack() - { - return this.getStack() != null; - } - - @Override - public int getSlotStackLimit() - { - return 0; - } - - @Override - public ItemStack decrStackSize( final int par1 ) - { - return null; - } - - @Override - public boolean isSlotInInventory( final IInventory par1iInventory, final int par2 ) - { - return false; - } - - public ClientDCInternalInv getSlot() - { - return this.mySlot; - } +public class SlotDisconnected extends AppEngSlot { + + private final ClientDCInternalInv mySlot; + + public SlotDisconnected(final ClientDCInternalInv me, final int which, final int x, final int y) { + super(me.getInventory(), which, x, y); + this.mySlot = me; + } + + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } + + @Override + public void putStack(final ItemStack par1ItemStack) {} + + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } + + @Override + public ItemStack getDisplayStack() { + if (Platform.isClient()) { + final ItemStack is = super.getStack(); + if (is != null && is.getItem() instanceof ItemEncodedPattern) { + final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); + final ItemStack out = iep.getOutput(is); + if (out != null) { + return out; + } + } + } + return super.getStack(); + } + + @Override + public void onPickupFromSlot(final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack) {} + + @Override + public boolean getHasStack() { + return this.getStack() != null; + } + + @Override + public int getSlotStackLimit() { + return 0; + } + + @Override + public ItemStack decrStackSize(final int par1) { + return null; + } + + @Override + public boolean isSlotInInventory(final IInventory par1iInventory, final int par2) { + return false; + } + + public ClientDCInternalInv getSlot() { + return this.mySlot; + } } diff --git a/src/main/java/appeng/client/me/SlotME.java b/src/main/java/appeng/client/me/SlotME.java index b9640919463..0f6a3389c86 100644 --- a/src/main/java/appeng/client/me/SlotME.java +++ b/src/main/java/appeng/client/me/SlotME.java @@ -18,92 +18,72 @@ package appeng.client.me; - import appeng.api.storage.data.IAEItemStack; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; - -public class SlotME extends Slot -{ - - private final InternalSlotME mySlot; - - public SlotME( final InternalSlotME me ) - { - super( null, 0, me.getxPosition(), me.getyPosition() ); - this.mySlot = me; - } - - public IAEItemStack getAEStack() - { - if( this.mySlot.hasPower() ) - { - return this.mySlot.getAEStack(); - } - return null; - } - - @Override - public void onPickupFromSlot( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) - { - } - - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } - - @Override - public ItemStack getStack() - { - if( this.mySlot.hasPower() ) - { - return this.mySlot.getStack(); - } - return null; - } - - @Override - public boolean getHasStack() - { - if( this.mySlot.hasPower() ) - { - return this.getStack() != null; - } - return false; - } - - @Override - public void putStack( final ItemStack par1ItemStack ) - { - - } - - @Override - public int getSlotStackLimit() - { - return 0; - } - - @Override - public ItemStack decrStackSize( final int par1 ) - { - return null; - } - - @Override - public boolean isSlotInInventory( final IInventory par1iInventory, final int par2 ) - { - return false; - } - - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } +public class SlotME extends Slot { + + private final InternalSlotME mySlot; + + public SlotME(final InternalSlotME me) { + super(null, 0, me.getxPosition(), me.getyPosition()); + this.mySlot = me; + } + + public IAEItemStack getAEStack() { + if (this.mySlot.hasPower()) { + return this.mySlot.getAEStack(); + } + return null; + } + + @Override + public void onPickupFromSlot(final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack) {} + + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } + + @Override + public ItemStack getStack() { + if (this.mySlot.hasPower()) { + return this.mySlot.getStack(); + } + return null; + } + + @Override + public boolean getHasStack() { + if (this.mySlot.hasPower()) { + return this.getStack() != null; + } + return false; + } + + @Override + public void putStack(final ItemStack par1ItemStack) {} + + @Override + public int getSlotStackLimit() { + return 0; + } + + @Override + public ItemStack decrStackSize(final int par1) { + return null; + } + + @Override + public boolean isSlotInInventory(final IInventory par1iInventory, final int par2) { + return false; + } + + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } } diff --git a/src/main/java/appeng/client/render/AppEngRenderItem.java b/src/main/java/appeng/client/render/AppEngRenderItem.java index 3209fe311ad..7b15d1d5a59 100644 --- a/src/main/java/appeng/client/render/AppEngRenderItem.java +++ b/src/main/java/appeng/client/render/AppEngRenderItem.java @@ -18,13 +18,13 @@ package appeng.client.render; - import appeng.api.storage.data.IAEItemStack; import appeng.core.AEConfig; import appeng.core.localization.GuiText; import appeng.util.ISlimReadableNumberConverter; import appeng.util.IWideReadableNumberConverter; import appeng.util.ReadableNumberConverter; +import javax.annotation.Nonnull; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.RenderItem; @@ -32,133 +32,135 @@ import net.minecraft.item.ItemStack; import org.lwjgl.opengl.GL11; -import javax.annotation.Nonnull; - - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class AppEngRenderItem extends RenderItem -{ - private static final ISlimReadableNumberConverter SLIM_CONVERTER = ReadableNumberConverter.INSTANCE; - private static final IWideReadableNumberConverter WIDE_CONVERTER = ReadableNumberConverter.INSTANCE; - - private IAEItemStack aeStack = null; - - @Override - public void renderItemOverlayIntoGUI( final FontRenderer fontRenderer, final TextureManager textureManager, final ItemStack is, final int par4, final int par5, final String par6Str ) - { - if( is != null ) - { - final float scaleFactor = AEConfig.instance.useTerminalUseLargeFont() ? 0.85f : 0.5f; - final float inverseScaleFactor = 1.0f / scaleFactor; - final int offset = AEConfig.instance.useTerminalUseLargeFont() ? 0 : -1; - - final boolean unicodeFlag = fontRenderer.getUnicodeFlag(); - fontRenderer.setUnicodeFlag( false ); - - if( is.getItem().showDurabilityBar( is ) ) - { - final double health = is.getItem().getDurabilityForDisplay( is ); - final int j1 = (int) Math.round( 13.0D - health * 13.0D ); - final int k = (int) Math.round( 255.0D - health * 255.0D ); - - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL11.GL_DEPTH_TEST ); - GL11.glDisable( GL11.GL_TEXTURE_2D ); - GL11.glDisable( GL11.GL_ALPHA_TEST ); - GL11.glDisable( GL11.GL_BLEND ); - - final Tessellator tessellator = Tessellator.instance; - final int l = 255 - k << 16 | k << 8; - final int i1 = ( 255 - k ) / 4 << 16 | 16128; - - this.renderQuad( tessellator, par4 + 2, par5 + 13, 13, 2, 0 ); - this.renderQuad( tessellator, par4 + 2, par5 + 13, 12, 1, i1 ); - this.renderQuad( tessellator, par4 + 2, par5 + 13, j1, 1, l ); - - GL11.glEnable( GL11.GL_ALPHA_TEST ); - GL11.glEnable( GL11.GL_TEXTURE_2D ); - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL11.GL_DEPTH_TEST ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - } - - if( is.stackSize == 0 ) - { - final String craftLabelText = AEConfig.instance.useTerminalUseLargeFont() ? GuiText.LargeFontCraft.getLocal() : GuiText.SmallFontCraft.getLocal(); - - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL11.GL_DEPTH_TEST ); - GL11.glPushMatrix(); - GL11.glScaled( scaleFactor, scaleFactor, scaleFactor ); - - final int X = (int) ( ( (float) par4 + offset + 16.0f - fontRenderer.getStringWidth( craftLabelText ) * scaleFactor ) * inverseScaleFactor ); - final int Y = (int) ( ( (float) par5 + offset + 16.0f - 7.0f * scaleFactor ) * inverseScaleFactor ); - fontRenderer.drawStringWithShadow( craftLabelText, X, Y, 16777215 ); - - GL11.glPopMatrix(); - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL11.GL_DEPTH_TEST ); - } - - final long amount = this.aeStack != null ? this.aeStack.getStackSize() : is.stackSize; - - if( amount != 0 ) - { - final String stackSize = this.getToBeRenderedStackSize( amount ); - - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL11.GL_DEPTH_TEST ); - GL11.glPushMatrix(); - GL11.glScaled( scaleFactor, scaleFactor, scaleFactor ); - - final int X = (int) ( ( (float) par4 + offset + 16.0f - fontRenderer.getStringWidth( stackSize ) * scaleFactor ) * inverseScaleFactor ); - final int Y = (int) ( ( (float) par5 + offset + 16.0f - 7.0f * scaleFactor ) * inverseScaleFactor ); - fontRenderer.drawStringWithShadow( stackSize, X, Y, 16777215 ); - - GL11.glPopMatrix(); - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL11.GL_DEPTH_TEST ); - } - - fontRenderer.setUnicodeFlag( unicodeFlag ); - } - } - - private void renderQuad( final Tessellator par1Tessellator, final int par2, final int par3, final int par4, final int par5, final int par6 ) - { - par1Tessellator.startDrawingQuads(); - par1Tessellator.setColorOpaque_I( par6 ); - par1Tessellator.addVertex( par2, par3, 0.0D ); - par1Tessellator.addVertex( par2, par3 + par5, 0.0D ); - par1Tessellator.addVertex( par2 + par4, par3 + par5, 0.0D ); - par1Tessellator.addVertex( par2 + par4, par3, 0.0D ); - par1Tessellator.draw(); - } - - private String getToBeRenderedStackSize( final long originalSize ) - { - if( AEConfig.instance.useTerminalUseLargeFont() ) - { - return SLIM_CONVERTER.toSlimReadableForm( originalSize ); - } - else - { - return WIDE_CONVERTER.toWideReadableForm( originalSize ); - } - } - - public IAEItemStack getAeStack() - { - return this.aeStack; - } - - public void setAeStack( @Nonnull final IAEItemStack aeStack ) - { - this.aeStack = aeStack; - } +public class AppEngRenderItem extends RenderItem { + private static final ISlimReadableNumberConverter SLIM_CONVERTER = ReadableNumberConverter.INSTANCE; + private static final IWideReadableNumberConverter WIDE_CONVERTER = ReadableNumberConverter.INSTANCE; + + private IAEItemStack aeStack = null; + + @Override + public void renderItemOverlayIntoGUI( + final FontRenderer fontRenderer, + final TextureManager textureManager, + final ItemStack is, + final int par4, + final int par5, + final String par6Str) { + if (is != null) { + final float scaleFactor = AEConfig.instance.useTerminalUseLargeFont() ? 0.85f : 0.5f; + final float inverseScaleFactor = 1.0f / scaleFactor; + final int offset = AEConfig.instance.useTerminalUseLargeFont() ? 0 : -1; + + final boolean unicodeFlag = fontRenderer.getUnicodeFlag(); + fontRenderer.setUnicodeFlag(false); + + if (is.getItem().showDurabilityBar(is)) { + final double health = is.getItem().getDurabilityForDisplay(is); + final int j1 = (int) Math.round(13.0D - health * 13.0D); + final int k = (int) Math.round(255.0D - health * 255.0D); + + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glDisable(GL11.GL_BLEND); + + final Tessellator tessellator = Tessellator.instance; + final int l = 255 - k << 16 | k << 8; + final int i1 = (255 - k) / 4 << 16 | 16128; + + this.renderQuad(tessellator, par4 + 2, par5 + 13, 13, 2, 0); + this.renderQuad(tessellator, par4 + 2, par5 + 13, 12, 1, i1); + this.renderQuad(tessellator, par4 + 2, par5 + 13, j1, 1, l); + + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + } + + if (is.stackSize == 0) { + final String craftLabelText = AEConfig.instance.useTerminalUseLargeFont() + ? GuiText.LargeFontCraft.getLocal() + : GuiText.SmallFontCraft.getLocal(); + + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glPushMatrix(); + GL11.glScaled(scaleFactor, scaleFactor, scaleFactor); + + final int X = (int) + (((float) par4 + offset + 16.0f - fontRenderer.getStringWidth(craftLabelText) * scaleFactor) + * inverseScaleFactor); + final int Y = (int) (((float) par5 + offset + 16.0f - 7.0f * scaleFactor) * inverseScaleFactor); + fontRenderer.drawStringWithShadow(craftLabelText, X, Y, 16777215); + + GL11.glPopMatrix(); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + } + + final long amount = this.aeStack != null ? this.aeStack.getStackSize() : is.stackSize; + + if (amount != 0) { + final String stackSize = this.getToBeRenderedStackSize(amount); + + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glPushMatrix(); + GL11.glScaled(scaleFactor, scaleFactor, scaleFactor); + + final int X = + (int) (((float) par4 + offset + 16.0f - fontRenderer.getStringWidth(stackSize) * scaleFactor) + * inverseScaleFactor); + final int Y = (int) (((float) par5 + offset + 16.0f - 7.0f * scaleFactor) * inverseScaleFactor); + fontRenderer.drawStringWithShadow(stackSize, X, Y, 16777215); + + GL11.glPopMatrix(); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + } + + fontRenderer.setUnicodeFlag(unicodeFlag); + } + } + + private void renderQuad( + final Tessellator par1Tessellator, + final int par2, + final int par3, + final int par4, + final int par5, + final int par6) { + par1Tessellator.startDrawingQuads(); + par1Tessellator.setColorOpaque_I(par6); + par1Tessellator.addVertex(par2, par3, 0.0D); + par1Tessellator.addVertex(par2, par3 + par5, 0.0D); + par1Tessellator.addVertex(par2 + par4, par3 + par5, 0.0D); + par1Tessellator.addVertex(par2 + par4, par3, 0.0D); + par1Tessellator.draw(); + } + + private String getToBeRenderedStackSize(final long originalSize) { + if (AEConfig.instance.useTerminalUseLargeFont()) { + return SLIM_CONVERTER.toSlimReadableForm(originalSize); + } else { + return WIDE_CONVERTER.toWideReadableForm(originalSize); + } + } + + public IAEItemStack getAeStack() { + return this.aeStack; + } + + public void setAeStack(@Nonnull final IAEItemStack aeStack) { + this.aeStack = aeStack; + } } diff --git a/src/main/java/appeng/client/render/BaseBlockRender.java b/src/main/java/appeng/client/render/BaseBlockRender.java index 97990abc288..0cd82a89871 100644 --- a/src/main/java/appeng/client/render/BaseBlockRender.java +++ b/src/main/java/appeng/client/render/BaseBlockRender.java @@ -18,7 +18,6 @@ package appeng.client.render; - import appeng.api.util.IOrientable; import appeng.block.AEBaseBlock; import appeng.client.texture.ExtraBlockTextures; @@ -26,6 +25,9 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.nio.FloatBuffer; +import java.util.EnumSet; +import javax.annotation.Nullable; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.RenderHelper; @@ -43,741 +45,923 @@ import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; -import javax.annotation.Nullable; -import java.nio.FloatBuffer; -import java.util.EnumSet; - - -@SideOnly( Side.CLIENT ) -public class BaseBlockRender -{ - private static final int ORIENTATION_BITS = 7; - private static final int FLIP_H_BIT = 8; - private static final int FLIP_V_BIT = 16; - private static final byte[][][] ORIENTATION_MAP = new byte[6][6][6]; - - private final boolean hasTESR; - private final double renderDistance; - private final FloatBuffer rotMat = BufferUtils.createFloatBuffer( 16 ); - - public BaseBlockRender() - { - this( false, 20 ); - } - - public BaseBlockRender( final boolean enableTESR, final double renderDistance ) - { - this.hasTESR = enableTESR; - this.renderDistance = renderDistance; - setOriMap(); - } - - private static void setOriMap() - { - // pointed up... - ORIENTATION_MAP[0][3][1] = 0; - ORIENTATION_MAP[1][3][1] = 0; - ORIENTATION_MAP[2][3][1] = 0; - ORIENTATION_MAP[3][3][1] = 0; - ORIENTATION_MAP[4][3][1] = 0; - ORIENTATION_MAP[5][3][1] = 0; - - ORIENTATION_MAP[0][5][1] = 1; - ORIENTATION_MAP[1][5][1] = 2; - ORIENTATION_MAP[2][5][1] = 0; - ORIENTATION_MAP[3][5][1] = 0; - ORIENTATION_MAP[4][5][1] = 0; - ORIENTATION_MAP[5][5][1] = 0; - - ORIENTATION_MAP[0][2][1] = 3; - ORIENTATION_MAP[1][2][1] = 3; - ORIENTATION_MAP[2][2][1] = 0; - ORIENTATION_MAP[3][2][1] = 0; - ORIENTATION_MAP[4][2][1] = 0; - ORIENTATION_MAP[5][2][1] = 0; - - ORIENTATION_MAP[0][4][1] = 2; - ORIENTATION_MAP[1][4][1] = 1; - ORIENTATION_MAP[2][4][1] = 0; - ORIENTATION_MAP[3][4][1] = 0; - ORIENTATION_MAP[4][4][1] = 0; - ORIENTATION_MAP[5][4][1] = 0; - - // upside down - ORIENTATION_MAP[0][3][0] = FLIP_H_BIT; - ORIENTATION_MAP[1][3][0] = FLIP_H_BIT; - ORIENTATION_MAP[2][3][0] = 3; - ORIENTATION_MAP[3][3][0] = 3; - ORIENTATION_MAP[4][3][0] = 3; - ORIENTATION_MAP[5][3][0] = 3; - - ORIENTATION_MAP[0][4][0] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[1][4][0] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[2][4][0] = 3; - ORIENTATION_MAP[3][4][0] = 3; - ORIENTATION_MAP[4][4][0] = 3; - ORIENTATION_MAP[5][4][0] = 3; - - ORIENTATION_MAP[0][5][0] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[1][5][0] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[2][5][0] = 3; - ORIENTATION_MAP[3][5][0] = 3; - ORIENTATION_MAP[4][5][0] = 3; - ORIENTATION_MAP[5][5][0] = 3; - - ORIENTATION_MAP[0][2][0] = 3 | FLIP_H_BIT; - ORIENTATION_MAP[1][2][0] = 3 | FLIP_H_BIT; - ORIENTATION_MAP[2][2][0] = 3; - ORIENTATION_MAP[3][2][0] = 3; - ORIENTATION_MAP[4][2][0] = 3; - ORIENTATION_MAP[5][2][0] = 3; - - // side 1 - ORIENTATION_MAP[0][3][5] = 1 | FLIP_V_BIT; - ORIENTATION_MAP[1][3][5] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[2][3][5] = 1; - ORIENTATION_MAP[3][3][5] = 1; - ORIENTATION_MAP[4][3][5] = 1; - ORIENTATION_MAP[5][3][5] = 1 | FLIP_V_BIT; - - ORIENTATION_MAP[0][1][5] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[1][1][5] = 1; - ORIENTATION_MAP[2][1][5] = 3 | FLIP_V_BIT; - ORIENTATION_MAP[3][1][5] = 3; - ORIENTATION_MAP[4][1][5] = 1 | FLIP_V_BIT; - ORIENTATION_MAP[5][1][5] = 1; - - ORIENTATION_MAP[0][2][5] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[1][2][5] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[2][2][5] = 1; - ORIENTATION_MAP[3][2][5] = 2 | FLIP_V_BIT; - ORIENTATION_MAP[4][2][5] = 1 | FLIP_V_BIT; - ORIENTATION_MAP[5][2][5] = 1; - - ORIENTATION_MAP[0][0][5] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[1][0][5] = 1; - ORIENTATION_MAP[2][0][5] = 0; - ORIENTATION_MAP[3][0][5] = FLIP_V_BIT; - ORIENTATION_MAP[4][0][5] = 1; - ORIENTATION_MAP[5][0][5] = 1 | FLIP_V_BIT; - - // side 2 - ORIENTATION_MAP[0][1][2] = FLIP_H_BIT; - ORIENTATION_MAP[1][1][2] = 0; - ORIENTATION_MAP[2][1][2] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[3][1][2] = 1; - ORIENTATION_MAP[4][1][2] = 3; - ORIENTATION_MAP[5][1][2] = 3 | FLIP_H_BIT; - - ORIENTATION_MAP[0][4][2] = FLIP_H_BIT; - ORIENTATION_MAP[1][4][2] = FLIP_H_BIT; - ORIENTATION_MAP[2][4][2] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[3][4][2] = 1; - ORIENTATION_MAP[4][4][2] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[5][4][2] = 2; - - ORIENTATION_MAP[0][0][2] = FLIP_V_BIT; - ORIENTATION_MAP[1][0][2] = 0; - ORIENTATION_MAP[2][0][2] = 2; - ORIENTATION_MAP[3][0][2] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[4][0][2] = 3 | FLIP_H_BIT; - ORIENTATION_MAP[5][0][2] = 0; - - ORIENTATION_MAP[0][5][2] = FLIP_H_BIT; - ORIENTATION_MAP[1][5][2] = FLIP_H_BIT; - ORIENTATION_MAP[2][5][2] = 2; - ORIENTATION_MAP[3][5][2] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[4][5][2] = 2; - ORIENTATION_MAP[5][5][2] = 1 | FLIP_H_BIT; - - // side 3 - ORIENTATION_MAP[0][0][3] = 3 | FLIP_H_BIT; - ORIENTATION_MAP[1][0][3] = 3; - ORIENTATION_MAP[2][0][3] = 1; - ORIENTATION_MAP[3][0][3] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[4][0][3] = 0; - ORIENTATION_MAP[5][0][3] = FLIP_H_BIT; - - ORIENTATION_MAP[0][4][3] = 3; - ORIENTATION_MAP[1][4][3] = 3; - ORIENTATION_MAP[2][4][3] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[3][4][3] = 2; - ORIENTATION_MAP[4][4][3] = 1; - ORIENTATION_MAP[5][4][3] = 2 | FLIP_H_BIT; - - ORIENTATION_MAP[0][1][3] = 3 | FLIP_V_BIT; - ORIENTATION_MAP[1][1][3] = 3; - ORIENTATION_MAP[2][1][3] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[3][1][3] = 2; - ORIENTATION_MAP[4][1][3] = 3 | FLIP_H_BIT; - ORIENTATION_MAP[5][1][3] = 0; - - ORIENTATION_MAP[0][5][3] = 3; - ORIENTATION_MAP[1][5][3] = 3; - ORIENTATION_MAP[2][5][3] = 1; - ORIENTATION_MAP[3][5][3] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[4][5][3] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[5][5][3] = 1; - - // side 4 - ORIENTATION_MAP[0][3][4] = 1; - ORIENTATION_MAP[1][3][4] = 2; - ORIENTATION_MAP[2][3][4] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[3][3][4] = 1; - ORIENTATION_MAP[4][3][4] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[5][3][4] = 1; - - ORIENTATION_MAP[0][0][4] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[1][0][4] = 2; - ORIENTATION_MAP[2][0][4] = 0; - ORIENTATION_MAP[3][0][4] = FLIP_H_BIT; - ORIENTATION_MAP[4][0][4] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[5][0][4] = 1; - - ORIENTATION_MAP[0][1][4] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[1][1][4] = 2; - ORIENTATION_MAP[2][1][4] = 3 | FLIP_H_BIT; - ORIENTATION_MAP[3][1][4] = 3; - ORIENTATION_MAP[4][1][4] = 2; - ORIENTATION_MAP[5][1][4] = 1 | FLIP_H_BIT; - - ORIENTATION_MAP[0][2][4] = 1; - ORIENTATION_MAP[1][2][4] = 2; - ORIENTATION_MAP[2][2][4] = 1; - ORIENTATION_MAP[3][2][4] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[4][2][4] = 2; - ORIENTATION_MAP[5][2][4] = 1 | FLIP_H_BIT; - } - - public boolean hasTESR() - { - return this.hasTESR; - } - - protected int adjustBrightness( final int v, final double d ) - { - int r = 0xff & ( v >> 16 ); - int g = 0xff & ( v >> 8 ); - int b = 0xff & ( v ); - - r *= d; - g *= d; - b *= d; - - r = Math.min( 255, Math.max( 0, r ) ); - g = Math.min( 255, Math.max( 0, g ) ); - b = Math.min( 255, Math.max( 0, b ) ); - - return ( r << 16 ) | ( g << 8 ) | b; - } - - double getTesrRenderDistance() - { - return this.renderDistance; - } - - public void renderInventory( final B block, final ItemStack item, final RenderBlocks renderer, final ItemRenderType type, final Object[] data ) - { - final Tessellator tess = Tessellator.instance; - final BlockRenderInfo info = block.getRendererInstance(); - - if( info.isValid() ) - { - if( block.hasSubtypes() ) - { - block.setRenderStateByMeta( item.getItemDamage() ); - } - - renderer.uvRotateBottom = info.getTexture( ForgeDirection.DOWN ).setFlip( getOrientation( ForgeDirection.DOWN, ForgeDirection.SOUTH, ForgeDirection.UP ) ); - renderer.uvRotateTop = info.getTexture( ForgeDirection.UP ).setFlip( getOrientation( ForgeDirection.UP, ForgeDirection.SOUTH, ForgeDirection.UP ) ); - - renderer.uvRotateEast = info.getTexture( ForgeDirection.EAST ).setFlip( getOrientation( ForgeDirection.EAST, ForgeDirection.SOUTH, ForgeDirection.UP ) ); - renderer.uvRotateWest = info.getTexture( ForgeDirection.WEST ).setFlip( getOrientation( ForgeDirection.WEST, ForgeDirection.SOUTH, ForgeDirection.UP ) ); - - renderer.uvRotateNorth = info.getTexture( ForgeDirection.NORTH ).setFlip( getOrientation( ForgeDirection.NORTH, ForgeDirection.SOUTH, ForgeDirection.UP ) ); - renderer.uvRotateSouth = info.getTexture( ForgeDirection.SOUTH ).setFlip( getOrientation( ForgeDirection.SOUTH, ForgeDirection.SOUTH, ForgeDirection.UP ) ); - } - - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), block, item, tess, 0xffffff, renderer ); - - if( block.hasSubtypes() ) - { - info.setTemporaryRenderIcon( null ); - } - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - } - - static int getOrientation( final ForgeDirection in, final ForgeDirection forward, final ForgeDirection up ) - { - if( in == null || in == ForgeDirection.UNKNOWN // 1 - || forward == null || forward == ForgeDirection.UNKNOWN // 2 - || up == null || up == ForgeDirection.UNKNOWN ) - { - return 0; - } - - final int a = in.ordinal(); - final int b = forward.ordinal(); - final int c = up.ordinal(); - - return ORIENTATION_MAP[a][b][c]; - } - - public void renderInvBlock( final EnumSet sides, final B block, final ItemStack item, final Tessellator tess, final int color, final RenderBlocks renderer ) - { - if( block == null ) - { - return; - } - - int meta = 0; - - if( block.hasSubtypes() && item != null ) - { - meta = item.getItemDamage(); - } - - if( sides.contains( ForgeDirection.DOWN ) ) - { - tess.startDrawingQuads(); - tess.setNormal( 0.0F, -1.0F, 0.0F ); - tess.setColorOpaque_I( color ); - renderer.renderFaceYNeg( block, 0.0D, 0.0D, 0.0D, this.firstNotNull( renderer.overrideBlockTexture, block.getRendererInstance().getTexture( ForgeDirection.DOWN ), block.getIcon( ForgeDirection.DOWN.ordinal(), meta ) ) ); - tess.draw(); - } - - if( sides.contains( ForgeDirection.UP ) ) - { - tess.startDrawingQuads(); - tess.setNormal( 0.0F, 1.0F, 0.0F ); - tess.setColorOpaque_I( color ); - renderer.renderFaceYPos( block, 0.0D, 0.0D, 0.0D, this.firstNotNull( renderer.overrideBlockTexture, block.getRendererInstance().getTexture( ForgeDirection.UP ), block.getIcon( ForgeDirection.UP.ordinal(), meta ) ) ); - tess.draw(); - } - - if( sides.contains( ForgeDirection.NORTH ) ) - { - tess.startDrawingQuads(); - tess.setNormal( 0.0F, 0.0F, -1.0F ); - tess.setColorOpaque_I( color ); - renderer.renderFaceZNeg( block, 0.0D, 0.0D, 0.0D, this.firstNotNull( renderer.overrideBlockTexture, block.getRendererInstance().getTexture( ForgeDirection.NORTH ), block.getIcon( ForgeDirection.NORTH.ordinal(), meta ) ) ); - tess.draw(); - } - - if( sides.contains( ForgeDirection.SOUTH ) ) - { - tess.startDrawingQuads(); - tess.setNormal( 0.0F, 0.0F, 1.0F ); - tess.setColorOpaque_I( color ); - renderer.renderFaceZPos( block, 0.0D, 0.0D, 0.0D, this.firstNotNull( renderer.overrideBlockTexture, block.getRendererInstance().getTexture( ForgeDirection.SOUTH ), block.getIcon( ForgeDirection.SOUTH.ordinal(), meta ) ) ); - tess.draw(); - } - - if( sides.contains( ForgeDirection.WEST ) ) - { - tess.startDrawingQuads(); - tess.setNormal( -1.0F, 0.0F, 0.0F ); - tess.setColorOpaque_I( color ); - renderer.renderFaceXNeg( block, 0.0D, 0.0D, 0.0D, this.firstNotNull( renderer.overrideBlockTexture, block.getRendererInstance().getTexture( ForgeDirection.WEST ), block.getIcon( ForgeDirection.WEST.ordinal(), meta ) ) ); - tess.draw(); - } - - if( sides.contains( ForgeDirection.EAST ) ) - { - tess.startDrawingQuads(); - tess.setNormal( 1.0F, 0.0F, 0.0F ); - tess.setColorOpaque_I( color ); - renderer.renderFaceXPos( block, 0.0D, 0.0D, 0.0D, this.firstNotNull( renderer.overrideBlockTexture, block.getRendererInstance().getTexture( ForgeDirection.EAST ), block.getIcon( ForgeDirection.EAST.ordinal(), meta ) ) ); - tess.draw(); - } - } - - private IIcon firstNotNull( final IIcon... s ) - { - for( final IIcon o : s ) - { - if( o != null ) - { - return o; - } - } - - return ExtraBlockTextures.getMissing(); - } - - public boolean renderInWorld( final B block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - this.preRenderInWorld( block, world, x, y, z, renderer ); - - final boolean o = renderer.renderStandardBlock( block, x, y, z ); - - this.postRenderInWorld( renderer ); - - return o; - } - - public void preRenderInWorld( final B block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - - final BlockRenderInfo info = block.getRendererInstance(); - final IOrientable te = this.getOrientable( block, world, x, y, z ); - - if( te != null ) - { - final ForgeDirection forward = te.getForward(); - final ForgeDirection up = te.getUp(); - - renderer.uvRotateBottom = info.getTexture( ForgeDirection.DOWN ).setFlip( getOrientation( ForgeDirection.DOWN, forward, up ) ); - renderer.uvRotateTop = info.getTexture( ForgeDirection.UP ).setFlip( getOrientation( ForgeDirection.UP, forward, up ) ); - - renderer.uvRotateEast = info.getTexture( ForgeDirection.EAST ).setFlip( getOrientation( ForgeDirection.EAST, forward, up ) ); - renderer.uvRotateWest = info.getTexture( ForgeDirection.WEST ).setFlip( getOrientation( ForgeDirection.WEST, forward, up ) ); - - renderer.uvRotateNorth = info.getTexture( ForgeDirection.NORTH ).setFlip( getOrientation( ForgeDirection.NORTH, forward, up ) ); - renderer.uvRotateSouth = info.getTexture( ForgeDirection.SOUTH ).setFlip( getOrientation( ForgeDirection.SOUTH, forward, up ) ); - } - } - - public void postRenderInWorld( final RenderBlocks renderer ) - { - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - } - - @Nullable - public IOrientable getOrientable( final B block, final IBlockAccess w, final int x, final int y, final int z ) - { - return block.getOrientable( w, x, y, z ); - } - - protected void setInvRenderBounds( final RenderBlocks renderer, final int i, final int j, final int k, final int l, final int m, final int n ) - { - renderer.setRenderBounds( i / 16.0, j / 16.0, k / 16.0, l / 16.0, m / 16.0, n / 16.0 ); - } - - protected void renderBlockBounds( final RenderBlocks renderer, double minX, double minY, double minZ, double maxX, double maxY, double maxZ, final ForgeDirection x, final ForgeDirection y, final ForgeDirection z ) - { - minX /= 16.0; - minY /= 16.0; - minZ /= 16.0; - maxX /= 16.0; - maxY /= 16.0; - maxZ /= 16.0; - - double aX = minX * x.offsetX + minY * y.offsetX + minZ * z.offsetX; - double aY = minX * x.offsetY + minY * y.offsetY + minZ * z.offsetY; - double aZ = minX * x.offsetZ + minY * y.offsetZ + minZ * z.offsetZ; - - double bX = maxX * x.offsetX + maxY * y.offsetX + maxZ * z.offsetX; - double bY = maxX * x.offsetY + maxY * y.offsetY + maxZ * z.offsetY; - double bZ = maxX * x.offsetZ + maxY * y.offsetZ + maxZ * z.offsetZ; - - if( x.offsetX + y.offsetX + z.offsetX < 0 ) - { - aX += 1; - bX += 1; - } - - if( x.offsetY + y.offsetY + z.offsetY < 0 ) - { - aY += 1; - bY += 1; - } - - if( x.offsetZ + y.offsetZ + z.offsetZ < 0 ) - { - aZ += 1; - bZ += 1; - } - - renderer.renderMinX = Math.min( aX, bX ); - renderer.renderMinY = Math.min( aY, bY ); - renderer.renderMinZ = Math.min( aZ, bZ ); - renderer.renderMaxX = Math.max( aX, bX ); - renderer.renderMaxY = Math.max( aY, bY ); - renderer.renderMaxZ = Math.max( aZ, bZ ); - } - - @SideOnly( Side.CLIENT ) - protected void renderCutoutFace( final B block, final IIcon ico, final int x, final int y, final int z, final RenderBlocks renderer, final ForgeDirection orientation, final float edgeThickness ) - { - final Tessellator tess = Tessellator.instance; - - double offsetX = 0.0; - double offsetY = 0.0; - double offsetZ = 0.0; - double layerAX = 0.0; - double layerAZ = 0.0; - double layerBY = 0.0; - double layerBZ = 0.0; - - boolean flip = false; - switch( orientation ) - { - case NORTH: - - layerAX = 1.0; - layerBY = 1.0; - flip = true; - - break; - case SOUTH: - - layerAX = 1.0; - layerBY = 1.0; - offsetZ = 1.0; - - break; - case EAST: - - flip = true; - layerAZ = 1.0; - layerBY = 1.0; - offsetX = 1.0; - - break; - case WEST: - - layerAZ = 1.0; - layerBY = 1.0; - - break; - case UP: - - flip = true; - layerAX = 1.0; - layerBZ = 1.0; - offsetY = 1.0; - - break; - case DOWN: - - layerAX = 1.0; - layerBZ = 1.0; - - break; - default: - break; - } - - offsetX += x; - offsetY += y; - offsetZ += z; - - final double layerBX = 0.0; - final double layerAY = 0.0; - this.renderFace( tess, offsetX, offsetY, offsetZ, layerAX, layerAY, layerAZ, layerBX, layerBY, layerBZ, - // u -> u - 0, 1.0, - // v -> v - 0, edgeThickness, ico, flip ); - - this.renderFace( tess, offsetX, offsetY, offsetZ, layerAX, layerAY, layerAZ, layerBX, layerBY, layerBZ, - // u -> u - 0.0, edgeThickness, - // v -> v - edgeThickness, 1.0 - edgeThickness, ico, flip ); - - this.renderFace( tess, offsetX, offsetY, offsetZ, layerAX, layerAY, layerAZ, layerBX, layerBY, layerBZ, - // u -> u - 1.0 - edgeThickness, 1.0, - // v -> v - edgeThickness, 1.0 - edgeThickness, ico, flip ); - - this.renderFace( tess, offsetX, offsetY, offsetZ, layerAX, layerAY, layerAZ, layerBX, layerBY, layerBZ, - // u -> u - 0, 1.0, - // v -> v - 1.0 - edgeThickness, 1.0, ico, flip ); - } - - @SideOnly( Side.CLIENT ) - private void renderFace( final Tessellator tess, final double offsetX, final double offsetY, final double offsetZ, final double ax, final double ay, final double az, final double bx, final double by, final double bz, final double ua, final double ub, final double va, final double vb, final IIcon ico, final boolean flip ) - { - if( flip ) - { - tess.addVertexWithUV( offsetX + ax * ua + bx * va, offsetY + ay * ua + by * va, offsetZ + az * ua + bz * va, ico.getInterpolatedU( ua * 16.0 ), ico.getInterpolatedV( va * 16.0 ) ); - tess.addVertexWithUV( offsetX + ax * ua + bx * vb, offsetY + ay * ua + by * vb, offsetZ + az * ua + bz * vb, ico.getInterpolatedU( ua * 16.0 ), ico.getInterpolatedV( vb * 16.0 ) ); - tess.addVertexWithUV( offsetX + ax * ub + bx * vb, offsetY + ay * ub + by * vb, offsetZ + az * ub + bz * vb, ico.getInterpolatedU( ub * 16.0 ), ico.getInterpolatedV( vb * 16.0 ) ); - tess.addVertexWithUV( offsetX + ax * ub + bx * va, offsetY + ay * ub + by * va, offsetZ + az * ub + bz * va, ico.getInterpolatedU( ub * 16.0 ), ico.getInterpolatedV( va * 16.0 ) ); - } - else - { - tess.addVertexWithUV( offsetX + ax * ua + bx * va, offsetY + ay * ua + by * va, offsetZ + az * ua + bz * va, ico.getInterpolatedU( ua * 16.0 ), ico.getInterpolatedV( va * 16.0 ) ); - tess.addVertexWithUV( offsetX + ax * ub + bx * va, offsetY + ay * ub + by * va, offsetZ + az * ub + bz * va, ico.getInterpolatedU( ub * 16.0 ), ico.getInterpolatedV( va * 16.0 ) ); - tess.addVertexWithUV( offsetX + ax * ub + bx * vb, offsetY + ay * ub + by * vb, offsetZ + az * ub + bz * vb, ico.getInterpolatedU( ub * 16.0 ), ico.getInterpolatedV( vb * 16.0 ) ); - tess.addVertexWithUV( offsetX + ax * ua + bx * vb, offsetY + ay * ua + by * vb, offsetZ + az * ua + bz * vb, ico.getInterpolatedU( ua * 16.0 ), ico.getInterpolatedV( vb * 16.0 ) ); - } - } - - @SideOnly( Side.CLIENT ) - protected void renderFace( final int x, final int y, final int z, final B block, final IIcon ico, final RenderBlocks renderer, final ForgeDirection orientation ) - { - switch( orientation ) - { - case NORTH: - renderer.renderFaceZNeg( block, x, y, z, ico ); - break; - case SOUTH: - renderer.renderFaceZPos( block, x, y, z, ico ); - break; - case EAST: - renderer.renderFaceXPos( block, x, y, z, ico ); - break; - case WEST: - renderer.renderFaceXNeg( block, x, y, z, ico ); - break; - case UP: - renderer.renderFaceYPos( block, x, y, z, ico ); - break; - case DOWN: - renderer.renderFaceYNeg( block, x, y, z, ico ); - break; - default: - break; - } - } - - public void selectFace( final RenderBlocks renderer, final ForgeDirection west, final ForgeDirection up, final ForgeDirection forward, final int u1, final int u2, int v1, int v2 ) - { - v1 = 16 - v1; - v2 = 16 - v2; - - final double minX = ( forward.offsetX > 0 ? 1 : 0 ) + this.mapFaceUV( west.offsetX, u1 ) + this.mapFaceUV( up.offsetX, v1 ); - final double minY = ( forward.offsetY > 0 ? 1 : 0 ) + this.mapFaceUV( west.offsetY, u1 ) + this.mapFaceUV( up.offsetY, v1 ); - final double minZ = ( forward.offsetZ > 0 ? 1 : 0 ) + this.mapFaceUV( west.offsetZ, u1 ) + this.mapFaceUV( up.offsetZ, v1 ); - - final double maxX = ( forward.offsetX > 0 ? 1 : 0 ) + this.mapFaceUV( west.offsetX, u2 ) + this.mapFaceUV( up.offsetX, v2 ); - final double maxY = ( forward.offsetY > 0 ? 1 : 0 ) + this.mapFaceUV( west.offsetY, u2 ) + this.mapFaceUV( up.offsetY, v2 ); - final double maxZ = ( forward.offsetZ > 0 ? 1 : 0 ) + this.mapFaceUV( west.offsetZ, u2 ) + this.mapFaceUV( up.offsetZ, v2 ); - - renderer.renderMinX = Math.max( 0.0, Math.min( minX, maxX ) - ( forward.offsetX != 0 ? 0 : 0.001 ) ); - renderer.renderMaxX = Math.min( 1.0, Math.max( minX, maxX ) + ( forward.offsetX != 0 ? 0 : 0.001 ) ); - - renderer.renderMinY = Math.max( 0.0, Math.min( minY, maxY ) - ( forward.offsetY != 0 ? 0 : 0.001 ) ); - renderer.renderMaxY = Math.min( 1.0, Math.max( minY, maxY ) + ( forward.offsetY != 0 ? 0 : 0.001 ) ); - - renderer.renderMinZ = Math.max( 0.0, Math.min( minZ, maxZ ) - ( forward.offsetZ != 0 ? 0 : 0.001 ) ); - renderer.renderMaxZ = Math.min( 1.0, Math.max( minZ, maxZ ) + ( forward.offsetZ != 0 ? 0 : 0.001 ) ); - } - - private double mapFaceUV( final int offset, final int uv ) - { - if( offset == 0 ) - { - return 0; - } - - if( offset > 0 ) - { - return uv / 16.0; - } - - return ( 16.0 - uv ) / 16.0; - } - - public void renderTile( final B block, final T tile, final Tessellator tess, final double x, final double y, final double z, final float f, final RenderBlocks renderer ) - { - renderer.uvRotateBottom = renderer.uvRotateTop = renderer.uvRotateEast = renderer.uvRotateWest = renderer.uvRotateNorth = renderer.uvRotateSouth = 0; - - final ForgeDirection up = ForgeDirection.UP; - final ForgeDirection forward = ForgeDirection.SOUTH; - this.applyTESRRotation( x, y, z, forward, up ); - - Minecraft.getMinecraft().getTextureManager().bindTexture( TextureMap.locationBlocksTexture ); - RenderHelper.disableStandardItemLighting(); - - if( Minecraft.isAmbientOcclusionEnabled() ) - { - GL11.glShadeModel( GL11.GL_SMOOTH ); - } - else - { - GL11.glShadeModel( GL11.GL_FLAT ); - } - - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - - tess.setTranslation( -tile.xCoord, -tile.yCoord, -tile.zCoord ); - tess.startDrawingQuads(); - - // note that this is a terrible approach... - renderer.setRenderBoundsFromBlock( block ); - renderer.renderStandardBlock( block, tile.xCoord, tile.yCoord, tile.zCoord ); - - tess.draw(); - tess.setTranslation( 0, 0, 0 ); - RenderHelper.enableStandardItemLighting(); - - renderer.uvRotateBottom = renderer.uvRotateTop = renderer.uvRotateEast = renderer.uvRotateWest = renderer.uvRotateNorth = renderer.uvRotateSouth = 0; - } - - protected void applyTESRRotation( final double x, final double y, final double z, ForgeDirection forward, ForgeDirection up ) - { - if( forward != null && up != null ) - { - if( forward == ForgeDirection.UNKNOWN ) - { - forward = ForgeDirection.SOUTH; - } - - if( up == ForgeDirection.UNKNOWN ) - { - up = ForgeDirection.UP; - } - - final ForgeDirection west = Platform.crossProduct( forward, up ); - - this.rotMat.put( 0, west.offsetX ); - this.rotMat.put( 1, west.offsetY ); - this.rotMat.put( 2, west.offsetZ ); - this.rotMat.put( 3, 0 ); - - this.rotMat.put( 4, up.offsetX ); - this.rotMat.put( 5, up.offsetY ); - this.rotMat.put( 6, up.offsetZ ); - this.rotMat.put( 7, 0 ); - - this.rotMat.put( 8, forward.offsetX ); - this.rotMat.put( 9, forward.offsetY ); - this.rotMat.put( 10, forward.offsetZ ); - this.rotMat.put( 11, 0 ); - - this.rotMat.put( 12, 0 ); - this.rotMat.put( 13, 0 ); - this.rotMat.put( 14, 0 ); - this.rotMat.put( 15, 1 ); - GL11.glTranslated( x + 0.5, y + 0.5, z + 0.5 ); - GL11.glMultMatrix( this.rotMat ); - GL11.glTranslated( -0.5, -0.5, -0.5 ); - } - else - { - GL11.glTranslated( x, y, z ); - } - } - - public void doRenderItem( final ItemStack itemstack, final TileEntity par1EntityItemFrame ) - { - if( itemstack != null ) - { - final EntityItem entityitem = new EntityItem( par1EntityItemFrame.getWorldObj(), 0.0D, 0.0D, 0.0D, itemstack ); - - entityitem.getEntityItem().stackSize = 1; - - // set all this stuff and then do shit? meh? - entityitem.hoverStart = 0; - entityitem.age = 0; - entityitem.rotationYaw = 0; - - GL11.glPushMatrix(); - GL11.glTranslatef( 0, -0.14F, 0 ); - - RenderItem.renderInFrame = true; - RenderManager.instance.renderEntityWithPosYaw( entityitem, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F ); - RenderItem.renderInFrame = false; - - GL11.glPopMatrix(); - } - } +@SideOnly(Side.CLIENT) +public class BaseBlockRender { + private static final int ORIENTATION_BITS = 7; + private static final int FLIP_H_BIT = 8; + private static final int FLIP_V_BIT = 16; + private static final byte[][][] ORIENTATION_MAP = new byte[6][6][6]; + + private final boolean hasTESR; + private final double renderDistance; + private final FloatBuffer rotMat = BufferUtils.createFloatBuffer(16); + + public BaseBlockRender() { + this(false, 20); + } + + public BaseBlockRender(final boolean enableTESR, final double renderDistance) { + this.hasTESR = enableTESR; + this.renderDistance = renderDistance; + setOriMap(); + } + + private static void setOriMap() { + // pointed up... + ORIENTATION_MAP[0][3][1] = 0; + ORIENTATION_MAP[1][3][1] = 0; + ORIENTATION_MAP[2][3][1] = 0; + ORIENTATION_MAP[3][3][1] = 0; + ORIENTATION_MAP[4][3][1] = 0; + ORIENTATION_MAP[5][3][1] = 0; + + ORIENTATION_MAP[0][5][1] = 1; + ORIENTATION_MAP[1][5][1] = 2; + ORIENTATION_MAP[2][5][1] = 0; + ORIENTATION_MAP[3][5][1] = 0; + ORIENTATION_MAP[4][5][1] = 0; + ORIENTATION_MAP[5][5][1] = 0; + + ORIENTATION_MAP[0][2][1] = 3; + ORIENTATION_MAP[1][2][1] = 3; + ORIENTATION_MAP[2][2][1] = 0; + ORIENTATION_MAP[3][2][1] = 0; + ORIENTATION_MAP[4][2][1] = 0; + ORIENTATION_MAP[5][2][1] = 0; + + ORIENTATION_MAP[0][4][1] = 2; + ORIENTATION_MAP[1][4][1] = 1; + ORIENTATION_MAP[2][4][1] = 0; + ORIENTATION_MAP[3][4][1] = 0; + ORIENTATION_MAP[4][4][1] = 0; + ORIENTATION_MAP[5][4][1] = 0; + + // upside down + ORIENTATION_MAP[0][3][0] = FLIP_H_BIT; + ORIENTATION_MAP[1][3][0] = FLIP_H_BIT; + ORIENTATION_MAP[2][3][0] = 3; + ORIENTATION_MAP[3][3][0] = 3; + ORIENTATION_MAP[4][3][0] = 3; + ORIENTATION_MAP[5][3][0] = 3; + + ORIENTATION_MAP[0][4][0] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[1][4][0] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[2][4][0] = 3; + ORIENTATION_MAP[3][4][0] = 3; + ORIENTATION_MAP[4][4][0] = 3; + ORIENTATION_MAP[5][4][0] = 3; + + ORIENTATION_MAP[0][5][0] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[1][5][0] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[2][5][0] = 3; + ORIENTATION_MAP[3][5][0] = 3; + ORIENTATION_MAP[4][5][0] = 3; + ORIENTATION_MAP[5][5][0] = 3; + + ORIENTATION_MAP[0][2][0] = 3 | FLIP_H_BIT; + ORIENTATION_MAP[1][2][0] = 3 | FLIP_H_BIT; + ORIENTATION_MAP[2][2][0] = 3; + ORIENTATION_MAP[3][2][0] = 3; + ORIENTATION_MAP[4][2][0] = 3; + ORIENTATION_MAP[5][2][0] = 3; + + // side 1 + ORIENTATION_MAP[0][3][5] = 1 | FLIP_V_BIT; + ORIENTATION_MAP[1][3][5] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[2][3][5] = 1; + ORIENTATION_MAP[3][3][5] = 1; + ORIENTATION_MAP[4][3][5] = 1; + ORIENTATION_MAP[5][3][5] = 1 | FLIP_V_BIT; + + ORIENTATION_MAP[0][1][5] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[1][1][5] = 1; + ORIENTATION_MAP[2][1][5] = 3 | FLIP_V_BIT; + ORIENTATION_MAP[3][1][5] = 3; + ORIENTATION_MAP[4][1][5] = 1 | FLIP_V_BIT; + ORIENTATION_MAP[5][1][5] = 1; + + ORIENTATION_MAP[0][2][5] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[1][2][5] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[2][2][5] = 1; + ORIENTATION_MAP[3][2][5] = 2 | FLIP_V_BIT; + ORIENTATION_MAP[4][2][5] = 1 | FLIP_V_BIT; + ORIENTATION_MAP[5][2][5] = 1; + + ORIENTATION_MAP[0][0][5] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[1][0][5] = 1; + ORIENTATION_MAP[2][0][5] = 0; + ORIENTATION_MAP[3][0][5] = FLIP_V_BIT; + ORIENTATION_MAP[4][0][5] = 1; + ORIENTATION_MAP[5][0][5] = 1 | FLIP_V_BIT; + + // side 2 + ORIENTATION_MAP[0][1][2] = FLIP_H_BIT; + ORIENTATION_MAP[1][1][2] = 0; + ORIENTATION_MAP[2][1][2] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[3][1][2] = 1; + ORIENTATION_MAP[4][1][2] = 3; + ORIENTATION_MAP[5][1][2] = 3 | FLIP_H_BIT; + + ORIENTATION_MAP[0][4][2] = FLIP_H_BIT; + ORIENTATION_MAP[1][4][2] = FLIP_H_BIT; + ORIENTATION_MAP[2][4][2] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[3][4][2] = 1; + ORIENTATION_MAP[4][4][2] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[5][4][2] = 2; + + ORIENTATION_MAP[0][0][2] = FLIP_V_BIT; + ORIENTATION_MAP[1][0][2] = 0; + ORIENTATION_MAP[2][0][2] = 2; + ORIENTATION_MAP[3][0][2] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[4][0][2] = 3 | FLIP_H_BIT; + ORIENTATION_MAP[5][0][2] = 0; + + ORIENTATION_MAP[0][5][2] = FLIP_H_BIT; + ORIENTATION_MAP[1][5][2] = FLIP_H_BIT; + ORIENTATION_MAP[2][5][2] = 2; + ORIENTATION_MAP[3][5][2] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[4][5][2] = 2; + ORIENTATION_MAP[5][5][2] = 1 | FLIP_H_BIT; + + // side 3 + ORIENTATION_MAP[0][0][3] = 3 | FLIP_H_BIT; + ORIENTATION_MAP[1][0][3] = 3; + ORIENTATION_MAP[2][0][3] = 1; + ORIENTATION_MAP[3][0][3] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[4][0][3] = 0; + ORIENTATION_MAP[5][0][3] = FLIP_H_BIT; + + ORIENTATION_MAP[0][4][3] = 3; + ORIENTATION_MAP[1][4][3] = 3; + ORIENTATION_MAP[2][4][3] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[3][4][3] = 2; + ORIENTATION_MAP[4][4][3] = 1; + ORIENTATION_MAP[5][4][3] = 2 | FLIP_H_BIT; + + ORIENTATION_MAP[0][1][3] = 3 | FLIP_V_BIT; + ORIENTATION_MAP[1][1][3] = 3; + ORIENTATION_MAP[2][1][3] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[3][1][3] = 2; + ORIENTATION_MAP[4][1][3] = 3 | FLIP_H_BIT; + ORIENTATION_MAP[5][1][3] = 0; + + ORIENTATION_MAP[0][5][3] = 3; + ORIENTATION_MAP[1][5][3] = 3; + ORIENTATION_MAP[2][5][3] = 1; + ORIENTATION_MAP[3][5][3] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[4][5][3] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[5][5][3] = 1; + + // side 4 + ORIENTATION_MAP[0][3][4] = 1; + ORIENTATION_MAP[1][3][4] = 2; + ORIENTATION_MAP[2][3][4] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[3][3][4] = 1; + ORIENTATION_MAP[4][3][4] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[5][3][4] = 1; + + ORIENTATION_MAP[0][0][4] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[1][0][4] = 2; + ORIENTATION_MAP[2][0][4] = 0; + ORIENTATION_MAP[3][0][4] = FLIP_H_BIT; + ORIENTATION_MAP[4][0][4] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[5][0][4] = 1; + + ORIENTATION_MAP[0][1][4] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[1][1][4] = 2; + ORIENTATION_MAP[2][1][4] = 3 | FLIP_H_BIT; + ORIENTATION_MAP[3][1][4] = 3; + ORIENTATION_MAP[4][1][4] = 2; + ORIENTATION_MAP[5][1][4] = 1 | FLIP_H_BIT; + + ORIENTATION_MAP[0][2][4] = 1; + ORIENTATION_MAP[1][2][4] = 2; + ORIENTATION_MAP[2][2][4] = 1; + ORIENTATION_MAP[3][2][4] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[4][2][4] = 2; + ORIENTATION_MAP[5][2][4] = 1 | FLIP_H_BIT; + } + + public boolean hasTESR() { + return this.hasTESR; + } + + protected int adjustBrightness(final int v, final double d) { + int r = 0xff & (v >> 16); + int g = 0xff & (v >> 8); + int b = 0xff & (v); + + r *= d; + g *= d; + b *= d; + + r = Math.min(255, Math.max(0, r)); + g = Math.min(255, Math.max(0, g)); + b = Math.min(255, Math.max(0, b)); + + return (r << 16) | (g << 8) | b; + } + + double getTesrRenderDistance() { + return this.renderDistance; + } + + public void renderInventory( + final B block, + final ItemStack item, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] data) { + final Tessellator tess = Tessellator.instance; + final BlockRenderInfo info = block.getRendererInstance(); + + if (info.isValid()) { + if (block.hasSubtypes()) { + block.setRenderStateByMeta(item.getItemDamage()); + } + + renderer.uvRotateBottom = info.getTexture(ForgeDirection.DOWN) + .setFlip(getOrientation(ForgeDirection.DOWN, ForgeDirection.SOUTH, ForgeDirection.UP)); + renderer.uvRotateTop = info.getTexture(ForgeDirection.UP) + .setFlip(getOrientation(ForgeDirection.UP, ForgeDirection.SOUTH, ForgeDirection.UP)); + + renderer.uvRotateEast = info.getTexture(ForgeDirection.EAST) + .setFlip(getOrientation(ForgeDirection.EAST, ForgeDirection.SOUTH, ForgeDirection.UP)); + renderer.uvRotateWest = info.getTexture(ForgeDirection.WEST) + .setFlip(getOrientation(ForgeDirection.WEST, ForgeDirection.SOUTH, ForgeDirection.UP)); + + renderer.uvRotateNorth = info.getTexture(ForgeDirection.NORTH) + .setFlip(getOrientation(ForgeDirection.NORTH, ForgeDirection.SOUTH, ForgeDirection.UP)); + renderer.uvRotateSouth = info.getTexture(ForgeDirection.SOUTH) + .setFlip(getOrientation(ForgeDirection.SOUTH, ForgeDirection.SOUTH, ForgeDirection.UP)); + } + + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), block, item, tess, 0xffffff, renderer); + + if (block.hasSubtypes()) { + info.setTemporaryRenderIcon(null); + } + + renderer.uvRotateBottom = renderer.uvRotateEast = + renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + } + + static int getOrientation(final ForgeDirection in, final ForgeDirection forward, final ForgeDirection up) { + if (in == null + || in == ForgeDirection.UNKNOWN // 1 + || forward == null + || forward == ForgeDirection.UNKNOWN // 2 + || up == null + || up == ForgeDirection.UNKNOWN) { + return 0; + } + + final int a = in.ordinal(); + final int b = forward.ordinal(); + final int c = up.ordinal(); + + return ORIENTATION_MAP[a][b][c]; + } + + public void renderInvBlock( + final EnumSet sides, + final B block, + final ItemStack item, + final Tessellator tess, + final int color, + final RenderBlocks renderer) { + if (block == null) { + return; + } + + int meta = 0; + + if (block.hasSubtypes() && item != null) { + meta = item.getItemDamage(); + } + + if (sides.contains(ForgeDirection.DOWN)) { + tess.startDrawingQuads(); + tess.setNormal(0.0F, -1.0F, 0.0F); + tess.setColorOpaque_I(color); + renderer.renderFaceYNeg( + block, + 0.0D, + 0.0D, + 0.0D, + this.firstNotNull( + renderer.overrideBlockTexture, + block.getRendererInstance().getTexture(ForgeDirection.DOWN), + block.getIcon(ForgeDirection.DOWN.ordinal(), meta))); + tess.draw(); + } + + if (sides.contains(ForgeDirection.UP)) { + tess.startDrawingQuads(); + tess.setNormal(0.0F, 1.0F, 0.0F); + tess.setColorOpaque_I(color); + renderer.renderFaceYPos( + block, + 0.0D, + 0.0D, + 0.0D, + this.firstNotNull( + renderer.overrideBlockTexture, + block.getRendererInstance().getTexture(ForgeDirection.UP), + block.getIcon(ForgeDirection.UP.ordinal(), meta))); + tess.draw(); + } + + if (sides.contains(ForgeDirection.NORTH)) { + tess.startDrawingQuads(); + tess.setNormal(0.0F, 0.0F, -1.0F); + tess.setColorOpaque_I(color); + renderer.renderFaceZNeg( + block, + 0.0D, + 0.0D, + 0.0D, + this.firstNotNull( + renderer.overrideBlockTexture, + block.getRendererInstance().getTexture(ForgeDirection.NORTH), + block.getIcon(ForgeDirection.NORTH.ordinal(), meta))); + tess.draw(); + } + + if (sides.contains(ForgeDirection.SOUTH)) { + tess.startDrawingQuads(); + tess.setNormal(0.0F, 0.0F, 1.0F); + tess.setColorOpaque_I(color); + renderer.renderFaceZPos( + block, + 0.0D, + 0.0D, + 0.0D, + this.firstNotNull( + renderer.overrideBlockTexture, + block.getRendererInstance().getTexture(ForgeDirection.SOUTH), + block.getIcon(ForgeDirection.SOUTH.ordinal(), meta))); + tess.draw(); + } + + if (sides.contains(ForgeDirection.WEST)) { + tess.startDrawingQuads(); + tess.setNormal(-1.0F, 0.0F, 0.0F); + tess.setColorOpaque_I(color); + renderer.renderFaceXNeg( + block, + 0.0D, + 0.0D, + 0.0D, + this.firstNotNull( + renderer.overrideBlockTexture, + block.getRendererInstance().getTexture(ForgeDirection.WEST), + block.getIcon(ForgeDirection.WEST.ordinal(), meta))); + tess.draw(); + } + + if (sides.contains(ForgeDirection.EAST)) { + tess.startDrawingQuads(); + tess.setNormal(1.0F, 0.0F, 0.0F); + tess.setColorOpaque_I(color); + renderer.renderFaceXPos( + block, + 0.0D, + 0.0D, + 0.0D, + this.firstNotNull( + renderer.overrideBlockTexture, + block.getRendererInstance().getTexture(ForgeDirection.EAST), + block.getIcon(ForgeDirection.EAST.ordinal(), meta))); + tess.draw(); + } + } + + private IIcon firstNotNull(final IIcon... s) { + for (final IIcon o : s) { + if (o != null) { + return o; + } + } + + return ExtraBlockTextures.getMissing(); + } + + public boolean renderInWorld( + final B block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + this.preRenderInWorld(block, world, x, y, z, renderer); + + final boolean o = renderer.renderStandardBlock(block, x, y, z); + + this.postRenderInWorld(renderer); + + return o; + } + + public void preRenderInWorld( + final B block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + + final BlockRenderInfo info = block.getRendererInstance(); + final IOrientable te = this.getOrientable(block, world, x, y, z); + + if (te != null) { + final ForgeDirection forward = te.getForward(); + final ForgeDirection up = te.getUp(); + + renderer.uvRotateBottom = + info.getTexture(ForgeDirection.DOWN).setFlip(getOrientation(ForgeDirection.DOWN, forward, up)); + renderer.uvRotateTop = + info.getTexture(ForgeDirection.UP).setFlip(getOrientation(ForgeDirection.UP, forward, up)); + + renderer.uvRotateEast = + info.getTexture(ForgeDirection.EAST).setFlip(getOrientation(ForgeDirection.EAST, forward, up)); + renderer.uvRotateWest = + info.getTexture(ForgeDirection.WEST).setFlip(getOrientation(ForgeDirection.WEST, forward, up)); + + renderer.uvRotateNorth = + info.getTexture(ForgeDirection.NORTH).setFlip(getOrientation(ForgeDirection.NORTH, forward, up)); + renderer.uvRotateSouth = + info.getTexture(ForgeDirection.SOUTH).setFlip(getOrientation(ForgeDirection.SOUTH, forward, up)); + } + } + + public void postRenderInWorld(final RenderBlocks renderer) { + renderer.uvRotateBottom = renderer.uvRotateEast = + renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + } + + @Nullable + public IOrientable getOrientable(final B block, final IBlockAccess w, final int x, final int y, final int z) { + return block.getOrientable(w, x, y, z); + } + + protected void setInvRenderBounds( + final RenderBlocks renderer, final int i, final int j, final int k, final int l, final int m, final int n) { + renderer.setRenderBounds(i / 16.0, j / 16.0, k / 16.0, l / 16.0, m / 16.0, n / 16.0); + } + + protected void renderBlockBounds( + final RenderBlocks renderer, + double minX, + double minY, + double minZ, + double maxX, + double maxY, + double maxZ, + final ForgeDirection x, + final ForgeDirection y, + final ForgeDirection z) { + minX /= 16.0; + minY /= 16.0; + minZ /= 16.0; + maxX /= 16.0; + maxY /= 16.0; + maxZ /= 16.0; + + double aX = minX * x.offsetX + minY * y.offsetX + minZ * z.offsetX; + double aY = minX * x.offsetY + minY * y.offsetY + minZ * z.offsetY; + double aZ = minX * x.offsetZ + minY * y.offsetZ + minZ * z.offsetZ; + + double bX = maxX * x.offsetX + maxY * y.offsetX + maxZ * z.offsetX; + double bY = maxX * x.offsetY + maxY * y.offsetY + maxZ * z.offsetY; + double bZ = maxX * x.offsetZ + maxY * y.offsetZ + maxZ * z.offsetZ; + + if (x.offsetX + y.offsetX + z.offsetX < 0) { + aX += 1; + bX += 1; + } + + if (x.offsetY + y.offsetY + z.offsetY < 0) { + aY += 1; + bY += 1; + } + + if (x.offsetZ + y.offsetZ + z.offsetZ < 0) { + aZ += 1; + bZ += 1; + } + + renderer.renderMinX = Math.min(aX, bX); + renderer.renderMinY = Math.min(aY, bY); + renderer.renderMinZ = Math.min(aZ, bZ); + renderer.renderMaxX = Math.max(aX, bX); + renderer.renderMaxY = Math.max(aY, bY); + renderer.renderMaxZ = Math.max(aZ, bZ); + } + + @SideOnly(Side.CLIENT) + protected void renderCutoutFace( + final B block, + final IIcon ico, + final int x, + final int y, + final int z, + final RenderBlocks renderer, + final ForgeDirection orientation, + final float edgeThickness) { + final Tessellator tess = Tessellator.instance; + + double offsetX = 0.0; + double offsetY = 0.0; + double offsetZ = 0.0; + double layerAX = 0.0; + double layerAZ = 0.0; + double layerBY = 0.0; + double layerBZ = 0.0; + + boolean flip = false; + switch (orientation) { + case NORTH: + layerAX = 1.0; + layerBY = 1.0; + flip = true; + + break; + case SOUTH: + layerAX = 1.0; + layerBY = 1.0; + offsetZ = 1.0; + + break; + case EAST: + flip = true; + layerAZ = 1.0; + layerBY = 1.0; + offsetX = 1.0; + + break; + case WEST: + layerAZ = 1.0; + layerBY = 1.0; + + break; + case UP: + flip = true; + layerAX = 1.0; + layerBZ = 1.0; + offsetY = 1.0; + + break; + case DOWN: + layerAX = 1.0; + layerBZ = 1.0; + + break; + default: + break; + } + + offsetX += x; + offsetY += y; + offsetZ += z; + + final double layerBX = 0.0; + final double layerAY = 0.0; + this.renderFace( + tess, + offsetX, + offsetY, + offsetZ, + layerAX, + layerAY, + layerAZ, + layerBX, + layerBY, + layerBZ, + // u -> u + 0, + 1.0, + // v -> v + 0, + edgeThickness, + ico, + flip); + + this.renderFace( + tess, + offsetX, + offsetY, + offsetZ, + layerAX, + layerAY, + layerAZ, + layerBX, + layerBY, + layerBZ, + // u -> u + 0.0, + edgeThickness, + // v -> v + edgeThickness, + 1.0 - edgeThickness, + ico, + flip); + + this.renderFace( + tess, + offsetX, + offsetY, + offsetZ, + layerAX, + layerAY, + layerAZ, + layerBX, + layerBY, + layerBZ, + // u -> u + 1.0 - edgeThickness, + 1.0, + // v -> v + edgeThickness, + 1.0 - edgeThickness, + ico, + flip); + + this.renderFace( + tess, + offsetX, + offsetY, + offsetZ, + layerAX, + layerAY, + layerAZ, + layerBX, + layerBY, + layerBZ, + // u -> u + 0, + 1.0, + // v -> v + 1.0 - edgeThickness, + 1.0, + ico, + flip); + } + + @SideOnly(Side.CLIENT) + private void renderFace( + final Tessellator tess, + final double offsetX, + final double offsetY, + final double offsetZ, + final double ax, + final double ay, + final double az, + final double bx, + final double by, + final double bz, + final double ua, + final double ub, + final double va, + final double vb, + final IIcon ico, + final boolean flip) { + if (flip) { + tess.addVertexWithUV( + offsetX + ax * ua + bx * va, + offsetY + ay * ua + by * va, + offsetZ + az * ua + bz * va, + ico.getInterpolatedU(ua * 16.0), + ico.getInterpolatedV(va * 16.0)); + tess.addVertexWithUV( + offsetX + ax * ua + bx * vb, + offsetY + ay * ua + by * vb, + offsetZ + az * ua + bz * vb, + ico.getInterpolatedU(ua * 16.0), + ico.getInterpolatedV(vb * 16.0)); + tess.addVertexWithUV( + offsetX + ax * ub + bx * vb, + offsetY + ay * ub + by * vb, + offsetZ + az * ub + bz * vb, + ico.getInterpolatedU(ub * 16.0), + ico.getInterpolatedV(vb * 16.0)); + tess.addVertexWithUV( + offsetX + ax * ub + bx * va, + offsetY + ay * ub + by * va, + offsetZ + az * ub + bz * va, + ico.getInterpolatedU(ub * 16.0), + ico.getInterpolatedV(va * 16.0)); + } else { + tess.addVertexWithUV( + offsetX + ax * ua + bx * va, + offsetY + ay * ua + by * va, + offsetZ + az * ua + bz * va, + ico.getInterpolatedU(ua * 16.0), + ico.getInterpolatedV(va * 16.0)); + tess.addVertexWithUV( + offsetX + ax * ub + bx * va, + offsetY + ay * ub + by * va, + offsetZ + az * ub + bz * va, + ico.getInterpolatedU(ub * 16.0), + ico.getInterpolatedV(va * 16.0)); + tess.addVertexWithUV( + offsetX + ax * ub + bx * vb, + offsetY + ay * ub + by * vb, + offsetZ + az * ub + bz * vb, + ico.getInterpolatedU(ub * 16.0), + ico.getInterpolatedV(vb * 16.0)); + tess.addVertexWithUV( + offsetX + ax * ua + bx * vb, + offsetY + ay * ua + by * vb, + offsetZ + az * ua + bz * vb, + ico.getInterpolatedU(ua * 16.0), + ico.getInterpolatedV(vb * 16.0)); + } + } + + @SideOnly(Side.CLIENT) + protected void renderFace( + final int x, + final int y, + final int z, + final B block, + final IIcon ico, + final RenderBlocks renderer, + final ForgeDirection orientation) { + switch (orientation) { + case NORTH: + renderer.renderFaceZNeg(block, x, y, z, ico); + break; + case SOUTH: + renderer.renderFaceZPos(block, x, y, z, ico); + break; + case EAST: + renderer.renderFaceXPos(block, x, y, z, ico); + break; + case WEST: + renderer.renderFaceXNeg(block, x, y, z, ico); + break; + case UP: + renderer.renderFaceYPos(block, x, y, z, ico); + break; + case DOWN: + renderer.renderFaceYNeg(block, x, y, z, ico); + break; + default: + break; + } + } + + public void selectFace( + final RenderBlocks renderer, + final ForgeDirection west, + final ForgeDirection up, + final ForgeDirection forward, + final int u1, + final int u2, + int v1, + int v2) { + v1 = 16 - v1; + v2 = 16 - v2; + + final double minX = + (forward.offsetX > 0 ? 1 : 0) + this.mapFaceUV(west.offsetX, u1) + this.mapFaceUV(up.offsetX, v1); + final double minY = + (forward.offsetY > 0 ? 1 : 0) + this.mapFaceUV(west.offsetY, u1) + this.mapFaceUV(up.offsetY, v1); + final double minZ = + (forward.offsetZ > 0 ? 1 : 0) + this.mapFaceUV(west.offsetZ, u1) + this.mapFaceUV(up.offsetZ, v1); + + final double maxX = + (forward.offsetX > 0 ? 1 : 0) + this.mapFaceUV(west.offsetX, u2) + this.mapFaceUV(up.offsetX, v2); + final double maxY = + (forward.offsetY > 0 ? 1 : 0) + this.mapFaceUV(west.offsetY, u2) + this.mapFaceUV(up.offsetY, v2); + final double maxZ = + (forward.offsetZ > 0 ? 1 : 0) + this.mapFaceUV(west.offsetZ, u2) + this.mapFaceUV(up.offsetZ, v2); + + renderer.renderMinX = Math.max(0.0, Math.min(minX, maxX) - (forward.offsetX != 0 ? 0 : 0.001)); + renderer.renderMaxX = Math.min(1.0, Math.max(minX, maxX) + (forward.offsetX != 0 ? 0 : 0.001)); + + renderer.renderMinY = Math.max(0.0, Math.min(minY, maxY) - (forward.offsetY != 0 ? 0 : 0.001)); + renderer.renderMaxY = Math.min(1.0, Math.max(minY, maxY) + (forward.offsetY != 0 ? 0 : 0.001)); + + renderer.renderMinZ = Math.max(0.0, Math.min(minZ, maxZ) - (forward.offsetZ != 0 ? 0 : 0.001)); + renderer.renderMaxZ = Math.min(1.0, Math.max(minZ, maxZ) + (forward.offsetZ != 0 ? 0 : 0.001)); + } + + private double mapFaceUV(final int offset, final int uv) { + if (offset == 0) { + return 0; + } + + if (offset > 0) { + return uv / 16.0; + } + + return (16.0 - uv) / 16.0; + } + + public void renderTile( + final B block, + final T tile, + final Tessellator tess, + final double x, + final double y, + final double z, + final float f, + final RenderBlocks renderer) { + renderer.uvRotateBottom = renderer.uvRotateTop = + renderer.uvRotateEast = renderer.uvRotateWest = renderer.uvRotateNorth = renderer.uvRotateSouth = 0; + + final ForgeDirection up = ForgeDirection.UP; + final ForgeDirection forward = ForgeDirection.SOUTH; + this.applyTESRRotation(x, y, z, forward, up); + + Minecraft.getMinecraft().getTextureManager().bindTexture(TextureMap.locationBlocksTexture); + RenderHelper.disableStandardItemLighting(); + + if (Minecraft.isAmbientOcclusionEnabled()) { + GL11.glShadeModel(GL11.GL_SMOOTH); + } else { + GL11.glShadeModel(GL11.GL_FLAT); + } + + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + + tess.setTranslation(-tile.xCoord, -tile.yCoord, -tile.zCoord); + tess.startDrawingQuads(); + + // note that this is a terrible approach... + renderer.setRenderBoundsFromBlock(block); + renderer.renderStandardBlock(block, tile.xCoord, tile.yCoord, tile.zCoord); + + tess.draw(); + tess.setTranslation(0, 0, 0); + RenderHelper.enableStandardItemLighting(); + + renderer.uvRotateBottom = renderer.uvRotateTop = + renderer.uvRotateEast = renderer.uvRotateWest = renderer.uvRotateNorth = renderer.uvRotateSouth = 0; + } + + protected void applyTESRRotation( + final double x, final double y, final double z, ForgeDirection forward, ForgeDirection up) { + if (forward != null && up != null) { + if (forward == ForgeDirection.UNKNOWN) { + forward = ForgeDirection.SOUTH; + } + + if (up == ForgeDirection.UNKNOWN) { + up = ForgeDirection.UP; + } + + final ForgeDirection west = Platform.crossProduct(forward, up); + + this.rotMat.put(0, west.offsetX); + this.rotMat.put(1, west.offsetY); + this.rotMat.put(2, west.offsetZ); + this.rotMat.put(3, 0); + + this.rotMat.put(4, up.offsetX); + this.rotMat.put(5, up.offsetY); + this.rotMat.put(6, up.offsetZ); + this.rotMat.put(7, 0); + + this.rotMat.put(8, forward.offsetX); + this.rotMat.put(9, forward.offsetY); + this.rotMat.put(10, forward.offsetZ); + this.rotMat.put(11, 0); + + this.rotMat.put(12, 0); + this.rotMat.put(13, 0); + this.rotMat.put(14, 0); + this.rotMat.put(15, 1); + GL11.glTranslated(x + 0.5, y + 0.5, z + 0.5); + GL11.glMultMatrix(this.rotMat); + GL11.glTranslated(-0.5, -0.5, -0.5); + } else { + GL11.glTranslated(x, y, z); + } + } + + public void doRenderItem(final ItemStack itemstack, final TileEntity par1EntityItemFrame) { + if (itemstack != null) { + final EntityItem entityitem = + new EntityItem(par1EntityItemFrame.getWorldObj(), 0.0D, 0.0D, 0.0D, itemstack); + + entityitem.getEntityItem().stackSize = 1; + + // set all this stuff and then do shit? meh? + entityitem.hoverStart = 0; + entityitem.age = 0; + entityitem.rotationYaw = 0; + + GL11.glPushMatrix(); + GL11.glTranslatef(0, -0.14F, 0); + + RenderItem.renderInFrame = true; + RenderManager.instance.renderEntityWithPosYaw(entityitem, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F); + RenderItem.renderInFrame = false; + + GL11.glPopMatrix(); + } + } } diff --git a/src/main/java/appeng/client/render/BlockPosHighlighter.java b/src/main/java/appeng/client/render/BlockPosHighlighter.java index 0cd9c99fa78..e5527ee8fe1 100644 --- a/src/main/java/appeng/client/render/BlockPosHighlighter.java +++ b/src/main/java/appeng/client/render/BlockPosHighlighter.java @@ -3,8 +3,7 @@ import appeng.api.util.DimensionalCoord; // taken from McJty's McJtyLib -public class BlockPosHighlighter -{ +public class BlockPosHighlighter { private static DimensionalCoord highlightedBlock; private static long expireHighlight; diff --git a/src/main/java/appeng/client/render/BlockRenderInfo.java b/src/main/java/appeng/client/render/BlockRenderInfo.java index 928a5d6e97b..2089b195b2e 100644 --- a/src/main/java/appeng/client/render/BlockRenderInfo.java +++ b/src/main/java/appeng/client/render/BlockRenderInfo.java @@ -18,7 +18,6 @@ package appeng.client.render; - import appeng.block.AEBaseBlock; import appeng.client.texture.FlippableIcon; import appeng.client.texture.TmpFlippableIcon; @@ -26,120 +25,122 @@ import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; +public class BlockRenderInfo { -public class BlockRenderInfo -{ - - private final BaseBlockRender rendererInstance; - private final TmpFlippableIcon tmpTopIcon = new TmpFlippableIcon(); - private final TmpFlippableIcon tmpBottomIcon = new TmpFlippableIcon(); - private final TmpFlippableIcon tmpSouthIcon = new TmpFlippableIcon(); - private final TmpFlippableIcon tmpNorthIcon = new TmpFlippableIcon(); - private final TmpFlippableIcon tmpEastIcon = new TmpFlippableIcon(); - private final TmpFlippableIcon tmpWestIcon = new TmpFlippableIcon(); - private boolean useTmp = false; - private FlippableIcon topIcon = null; - private FlippableIcon bottomIcon = null; - private FlippableIcon southIcon = null; - private FlippableIcon northIcon = null; - private FlippableIcon eastIcon = null; - private FlippableIcon westIcon = null; + private final BaseBlockRender rendererInstance; + private final TmpFlippableIcon tmpTopIcon = new TmpFlippableIcon(); + private final TmpFlippableIcon tmpBottomIcon = new TmpFlippableIcon(); + private final TmpFlippableIcon tmpSouthIcon = new TmpFlippableIcon(); + private final TmpFlippableIcon tmpNorthIcon = new TmpFlippableIcon(); + private final TmpFlippableIcon tmpEastIcon = new TmpFlippableIcon(); + private final TmpFlippableIcon tmpWestIcon = new TmpFlippableIcon(); + private boolean useTmp = false; + private FlippableIcon topIcon = null; + private FlippableIcon bottomIcon = null; + private FlippableIcon southIcon = null; + private FlippableIcon northIcon = null; + private FlippableIcon eastIcon = null; + private FlippableIcon westIcon = null; - public BlockRenderInfo( final BaseBlockRender inst ) - { - this.rendererInstance = inst; - } + public BlockRenderInfo(final BaseBlockRender inst) { + this.rendererInstance = inst; + } - public void updateIcons( final FlippableIcon bottom, final FlippableIcon top, final FlippableIcon north, final FlippableIcon south, final FlippableIcon east, final FlippableIcon west ) - { - this.topIcon = top; - this.bottomIcon = bottom; - this.southIcon = south; - this.northIcon = north; - this.eastIcon = east; - this.westIcon = west; - } + public void updateIcons( + final FlippableIcon bottom, + final FlippableIcon top, + final FlippableIcon north, + final FlippableIcon south, + final FlippableIcon east, + final FlippableIcon west) { + this.topIcon = top; + this.bottomIcon = bottom; + this.southIcon = south; + this.northIcon = north; + this.eastIcon = east; + this.westIcon = west; + } - public void setTemporaryRenderIcon( final IIcon icon ) - { - if( icon == null ) - { - this.useTmp = false; - } - else - { - this.useTmp = true; - this.tmpTopIcon.setOriginal( icon ); - this.tmpBottomIcon.setOriginal( icon ); - this.tmpSouthIcon.setOriginal( icon ); - this.tmpNorthIcon.setOriginal( icon ); - this.tmpEastIcon.setOriginal( icon ); - this.tmpWestIcon.setOriginal( icon ); - } - } + public void setTemporaryRenderIcon(final IIcon icon) { + if (icon == null) { + this.useTmp = false; + } else { + this.useTmp = true; + this.tmpTopIcon.setOriginal(icon); + this.tmpBottomIcon.setOriginal(icon); + this.tmpSouthIcon.setOriginal(icon); + this.tmpNorthIcon.setOriginal(icon); + this.tmpEastIcon.setOriginal(icon); + this.tmpWestIcon.setOriginal(icon); + } + } - public void setTemporaryRenderIcons( final IIcon nTopIcon, final IIcon nBottomIcon, final IIcon nSouthIcon, final IIcon nNorthIcon, final IIcon nEastIcon, final IIcon nWestIcon ) - { - this.tmpTopIcon.setOriginal( nTopIcon == null ? this.getTexture( ForgeDirection.UP ) : nTopIcon ); - this.tmpBottomIcon.setOriginal( nBottomIcon == null ? this.getTexture( ForgeDirection.DOWN ) : nBottomIcon ); - this.tmpSouthIcon.setOriginal( nSouthIcon == null ? this.getTexture( ForgeDirection.SOUTH ) : nSouthIcon ); - this.tmpNorthIcon.setOriginal( nNorthIcon == null ? this.getTexture( ForgeDirection.NORTH ) : nNorthIcon ); - this.tmpEastIcon.setOriginal( nEastIcon == null ? this.getTexture( ForgeDirection.EAST ) : nEastIcon ); - this.tmpWestIcon.setOriginal( nWestIcon == null ? this.getTexture( ForgeDirection.WEST ) : nWestIcon ); - this.useTmp = true; - } + public void setTemporaryRenderIcons( + final IIcon nTopIcon, + final IIcon nBottomIcon, + final IIcon nSouthIcon, + final IIcon nNorthIcon, + final IIcon nEastIcon, + final IIcon nWestIcon) { + this.tmpTopIcon.setOriginal(nTopIcon == null ? this.getTexture(ForgeDirection.UP) : nTopIcon); + this.tmpBottomIcon.setOriginal(nBottomIcon == null ? this.getTexture(ForgeDirection.DOWN) : nBottomIcon); + this.tmpSouthIcon.setOriginal(nSouthIcon == null ? this.getTexture(ForgeDirection.SOUTH) : nSouthIcon); + this.tmpNorthIcon.setOriginal(nNorthIcon == null ? this.getTexture(ForgeDirection.NORTH) : nNorthIcon); + this.tmpEastIcon.setOriginal(nEastIcon == null ? this.getTexture(ForgeDirection.EAST) : nEastIcon); + this.tmpWestIcon.setOriginal(nWestIcon == null ? this.getTexture(ForgeDirection.WEST) : nWestIcon); + this.useTmp = true; + } - public FlippableIcon getTexture( final ForgeDirection dir ) - { - if( this.useTmp ) - { - switch( dir ) - { - case DOWN: - return this.tmpBottomIcon; - case UP: - return this.tmpTopIcon; - case NORTH: - return this.tmpNorthIcon; - case SOUTH: - return this.tmpSouthIcon; - case EAST: - return this.tmpEastIcon; - case WEST: - return this.tmpWestIcon; - default: - break; - } - } + public FlippableIcon getTexture(final ForgeDirection dir) { + if (this.useTmp) { + switch (dir) { + case DOWN: + return this.tmpBottomIcon; + case UP: + return this.tmpTopIcon; + case NORTH: + return this.tmpNorthIcon; + case SOUTH: + return this.tmpSouthIcon; + case EAST: + return this.tmpEastIcon; + case WEST: + return this.tmpWestIcon; + default: + break; + } + } - switch( dir ) - { - case DOWN: - return this.bottomIcon; - case UP: - return this.topIcon; - case NORTH: - return this.northIcon; - case SOUTH: - return this.southIcon; - case EAST: - return this.eastIcon; - case WEST: - return this.westIcon; - default: - break; - } + switch (dir) { + case DOWN: + return this.bottomIcon; + case UP: + return this.topIcon; + case NORTH: + return this.northIcon; + case SOUTH: + return this.southIcon; + case EAST: + return this.eastIcon; + case WEST: + return this.westIcon; + default: + break; + } - return this.topIcon; - } + return this.topIcon; + } - boolean isValid() - { - return this.topIcon != null && this.bottomIcon != null && this.southIcon != null && this.northIcon != null && this.eastIcon != null && this.westIcon != null; - } + boolean isValid() { + return this.topIcon != null + && this.bottomIcon != null + && this.southIcon != null + && this.northIcon != null + && this.eastIcon != null + && this.westIcon != null; + } - public BaseBlockRender getRendererInstance() - { - return this.rendererInstance; - } + public BaseBlockRender getRendererInstance() { + return this.rendererInstance; + } } diff --git a/src/main/java/appeng/client/render/BusRenderHelper.java b/src/main/java/appeng/client/render/BusRenderHelper.java index a60d6865750..ad923018f66 100644 --- a/src/main/java/appeng/client/render/BusRenderHelper.java +++ b/src/main/java/appeng/client/render/BusRenderHelper.java @@ -18,7 +18,6 @@ package appeng.client.render; - import appeng.api.AEApi; import appeng.api.exceptions.MissingDefinition; import appeng.api.parts.IBoxProvider; @@ -34,600 +33,576 @@ import com.google.common.base.Optional; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nullable; -import java.util.EnumSet; - - -@SideOnly( Side.CLIENT ) -public final class BusRenderHelper implements IPartRenderHelper -{ - public static final BusRenderHelper INSTANCE = new BusRenderHelper(); - private static final int HEX_WHITE = 0xffffff; - - private final BoundBoxCalculator bbc; - private final boolean noAlphaPass; - private final BaseBlockRender bbr; - private final Optional maybeBlock; - private final Optional maybeBaseBlock; - private int renderingForPass; - private int currentPass; - private int itemsRendered; - private double minX; - private double minY; - private double minZ; - private double maxX; - private double maxY; - private double maxZ; - private ForgeDirection ax; - private ForgeDirection ay; - private ForgeDirection az; - private int color; - - public BusRenderHelper() - { - this.bbc = new BoundBoxCalculator( this ); - this.noAlphaPass = !AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ); - this.bbr = new BaseBlockRender(); - this.renderingForPass = 0; - this.currentPass = 0; - this.itemsRendered = 0; - this.minX = 0; - this.minY = 0; - this.minZ = 0; - this.maxX = 16; - this.maxY = 16; - this.maxZ = 16; - this.ax = ForgeDirection.EAST; - this.az = ForgeDirection.SOUTH; - this.ay = ForgeDirection.UP; - this.color = HEX_WHITE; - this.maybeBlock = AEApi.instance().definitions().blocks().multiPart().maybeBlock(); - this.maybeBaseBlock = this.maybeBlock.transform( new BaseBlockTransformFunction() ); - } - - public int getItemsRendered() - { - return this.itemsRendered; - } - - public void setPass( final int pass ) - { - this.renderingForPass = 0; - this.currentPass = pass; - this.itemsRendered = 0; - } - - public double getBound( final ForgeDirection side ) - { - switch( side ) - { - default: - case UNKNOWN: - return 0.5; - case DOWN: - return this.minY; - case EAST: - return this.maxX; - case NORTH: - return this.minZ; - case SOUTH: - return this.maxZ; - case UP: - return this.maxY; - case WEST: - return this.minX; - } - } - - public void setRenderColor( final int color ) - { - for( final Block block : AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet() ) - { - final BlockCableBus cableBus = (BlockCableBus) block; - cableBus.setRenderColor( color ); - } - } - - public void setOrientation( final ForgeDirection dx, final ForgeDirection dy, final ForgeDirection dz ) - { - this.ax = dx == null ? ForgeDirection.EAST : dx; - this.ay = dy == null ? ForgeDirection.UP : dy; - this.az = dz == null ? ForgeDirection.SOUTH : dz; - } - - public double[] getBounds() - { - return new double[] { this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ }; - } - - public void setBounds( final double[] bounds ) - { - if( bounds == null || bounds.length != 6 ) - { - return; - } - - this.minX = bounds[0]; - this.minY = bounds[1]; - this.minZ = bounds[2]; - this.maxX = bounds[3]; - this.maxY = bounds[4]; - this.maxZ = bounds[5]; - } - - private static class BoundBoxCalculator implements IPartCollisionHelper - { - private final BusRenderHelper helper; - private boolean started = false; - - private float minX; - private float minY; - private float minZ; - - private float maxX; - private float maxY; - private float maxZ; - - public BoundBoxCalculator( final BusRenderHelper helper ) - { - this.helper = helper; - } - - @Override - public void addBox( final double minX, final double minY, final double minZ, final double maxX, final double maxY, final double maxZ ) - { - if( this.started ) - { - this.minX = Math.min( this.minX, (float) minX ); - this.minY = Math.min( this.minY, (float) minY ); - this.minZ = Math.min( this.minZ, (float) minZ ); - this.maxX = Math.max( this.maxX, (float) maxX ); - this.maxY = Math.max( this.maxY, (float) maxY ); - this.maxZ = Math.max( this.maxZ, (float) maxZ ); - } - else - { - this.started = true; - this.minX = (float) minX; - this.minY = (float) minY; - this.minZ = (float) minZ; - this.maxX = (float) maxX; - this.maxY = (float) maxY; - this.maxZ = (float) maxZ; - } - } - - @Override - public ForgeDirection getWorldX() - { - return this.helper.ax; - } - - @Override - public ForgeDirection getWorldY() - { - return this.helper.ay; - } - - @Override - public ForgeDirection getWorldZ() - { - return this.helper.az; - } - - @Override - public boolean isBBCollision() - { - return false; - } - } - - - private static final class BaseBlockTransformFunction implements Function - { - @Nullable - @Override - public AEBaseBlock apply( final Block input ) - { - if( input instanceof AEBaseBlock ) - { - return ( (AEBaseBlock) input ); - } - - return null; - } - } - - @Override - public void renderForPass( final int pass ) - { - this.renderingForPass = pass; - } - - private boolean renderThis() - { - if( this.renderingForPass == this.currentPass || this.noAlphaPass ) - { - this.itemsRendered++; - return true; - } - return false; - } - - @Override - public void normalRendering() - { - final RenderBlocksWorkaround rbw = BusRenderer.INSTANCE.getRenderer(); - rbw.setCalculations( true ); - rbw.setUseTextures( true ); - rbw.enableAO = false; - } - - @Override - public ISimplifiedBundle useSimplifiedRendering( final int x, final int y, final int z, final IBoxProvider p, final ISimplifiedBundle sim ) - { - final RenderBlocksWorkaround rbw = BusRenderer.INSTANCE.getRenderer(); - - if( sim != null && this.maybeBlock.isPresent() && rbw.similarLighting( this.maybeBlock.get(), rbw.blockAccess, x, y, z, sim ) ) - { - rbw.populate( sim ); - rbw.setFaces( EnumSet.allOf( ForgeDirection.class ) ); - rbw.setCalculations( false ); - rbw.setUseTextures( false ); - - return sim; - } - else - { - final boolean allFaces = rbw.renderAllFaces; - rbw.renderAllFaces = true; - rbw.setCalculations( true ); - rbw.getFaces().clear(); - - this.bbc.started = false; - if( p == null ) - { - this.bbc.minX = this.bbc.minY = this.bbc.minZ = 0; - this.bbc.maxX = this.bbc.maxY = this.bbc.maxZ = 16; - } - else - { - p.getBoxes( this.bbc ); - - if( this.bbc.minX < 1 ) - { - this.bbc.minX = 1; - } - if( this.bbc.minY < 1 ) - { - this.bbc.minY = 1; - } - if( this.bbc.minZ < 1 ) - { - this.bbc.minZ = 1; - } - - if( this.bbc.maxX > 15 ) - { - this.bbc.maxX = 15; - } - if( this.bbc.maxY > 15 ) - { - this.bbc.maxY = 15; - } - if( this.bbc.maxZ > 15 ) - { - this.bbc.maxZ = 15; - } - } - - this.setBounds( this.bbc.minX, this.bbc.minY, this.bbc.minZ, this.bbc.maxX, this.bbc.maxY, this.bbc.maxZ ); - - this.bbr.renderBlockBounds( rbw, this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ, this.ax, this.ay, this.az ); - - for( final Block block : this.maybeBlock.asSet() ) - { - rbw.renderStandardBlock( block, x, y, z ); - } - - rbw.setFaces( EnumSet.allOf( ForgeDirection.class ) ); - rbw.renderAllFaces = allFaces; - rbw.setCalculations( false ); - rbw.setUseTextures( false ); - - return rbw.getLightingCache(); - } - } - - @Override - public void setBounds( final float minX, final float minY, final float minZ, final float maxX, final float maxY, final float maxZ ) - { - this.minX = minX; - this.minY = minY; - this.minZ = minZ; - this.maxX = maxX; - this.maxY = maxY; - this.maxZ = maxZ; - } - - @Override - public void setInvColor( final int newColor ) - { - this.color = newColor; - } - - @Override - public void setTexture( final IIcon ico ) - { - for( final AEBaseBlock baseBlock : this.maybeBaseBlock.asSet() ) - { - baseBlock.getRendererInstance().setTemporaryRenderIcon( ico ); - } - } - - @Override - public void setTexture( final IIcon down, final IIcon up, final IIcon north, final IIcon south, final IIcon west, final IIcon east ) - { - final IIcon[] list = new IIcon[6]; - - list[0] = down; - list[1] = up; - list[2] = north; - list[3] = south; - list[4] = west; - list[5] = east; - - for( final AEBaseBlock baseBlock : this.maybeBaseBlock.asSet() ) - { - baseBlock.getRendererInstance().setTemporaryRenderIcons( list[this.mapRotation( ForgeDirection.UP ).ordinal()], list[this.mapRotation( ForgeDirection.DOWN ).ordinal()], list[this.mapRotation( ForgeDirection.SOUTH ).ordinal()], list[this.mapRotation( ForgeDirection.NORTH ).ordinal()], list[this.mapRotation( ForgeDirection.EAST ).ordinal()], list[this.mapRotation( ForgeDirection.WEST ).ordinal()] ); - } - } - - private ForgeDirection mapRotation( final ForgeDirection dir ) - { - final ForgeDirection forward = this.az; - final ForgeDirection up = this.ay; - - if( forward == null || up == null ) - { - return dir; - } - - final int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; - final int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; - final int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; - - ForgeDirection west = ForgeDirection.UNKNOWN; - for( final ForgeDirection dx : ForgeDirection.VALID_DIRECTIONS ) - { - if( dx.offsetX == west_x && dx.offsetY == west_y && dx.offsetZ == west_z ) - { - west = dx; - } - } - - if( dir == forward ) - { - return ForgeDirection.SOUTH; - } - if( dir == forward.getOpposite() ) - { - return ForgeDirection.NORTH; - } - - if( dir == up ) - { - return ForgeDirection.UP; - } - if( dir == up.getOpposite() ) - { - return ForgeDirection.DOWN; - } - - if( dir == west ) - { - return ForgeDirection.WEST; - } - if( dir == west.getOpposite() ) - { - return ForgeDirection.EAST; - } - - return ForgeDirection.UNKNOWN; - } - - @Override - public void renderInventoryBox( final RenderBlocks renderer ) - { - renderer.setRenderBounds( this.minX / 16.0, this.minY / 16.0, this.minZ / 16.0, this.maxX / 16.0, this.maxY / 16.0, this.maxZ / 16.0 ); - - for( final AEBaseBlock baseBlock : this.maybeBaseBlock.asSet() ) - { - this.bbr.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), baseBlock, null, Tessellator.instance, this.color, renderer ); - } - } - - @Override - public void renderInventoryFace( final IIcon icon, final ForgeDirection face, final RenderBlocks renderer ) - { - renderer.setRenderBounds( this.minX / 16.0, this.minY / 16.0, this.minZ / 16.0, this.maxX / 16.0, this.maxY / 16.0, this.maxZ / 16.0 ); - this.setTexture( icon ); - - for( final AEBaseBlock baseBlock : this.maybeBaseBlock.asSet() ) - { - this.bbr.renderInvBlock( EnumSet.of( face ), baseBlock, null, Tessellator.instance, this.color, renderer ); - } - } - - @Override - public void renderBlock( final int x, final int y, final int z, final RenderBlocks renderer ) - { - if( !this.renderThis() ) - { - return; - } - - for( final Block multiPart : AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet() ) - { - final AEBaseBlock block = (AEBaseBlock) multiPart; - - final BlockRenderInfo info = block.getRendererInstance(); - final ForgeDirection forward = BusRenderHelper.INSTANCE.az; - final ForgeDirection up = BusRenderHelper.INSTANCE.ay; - - renderer.uvRotateBottom = info.getTexture( ForgeDirection.DOWN ).setFlip( BaseBlockRender.getOrientation( ForgeDirection.DOWN, forward, up ) ); - renderer.uvRotateTop = info.getTexture( ForgeDirection.UP ).setFlip( BaseBlockRender.getOrientation( ForgeDirection.UP, forward, up ) ); - - renderer.uvRotateEast = info.getTexture( ForgeDirection.EAST ).setFlip( BaseBlockRender.getOrientation( ForgeDirection.EAST, forward, up ) ); - renderer.uvRotateWest = info.getTexture( ForgeDirection.WEST ).setFlip( BaseBlockRender.getOrientation( ForgeDirection.WEST, forward, up ) ); - - renderer.uvRotateNorth = info.getTexture( ForgeDirection.NORTH ).setFlip( BaseBlockRender.getOrientation( ForgeDirection.NORTH, forward, up ) ); - renderer.uvRotateSouth = info.getTexture( ForgeDirection.SOUTH ).setFlip( BaseBlockRender.getOrientation( ForgeDirection.SOUTH, forward, up ) ); - - this.bbr.renderBlockBounds( renderer, this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ, this.ax, this.ay, this.az ); - - renderer.renderStandardBlock( block, x, y, z ); - } - } - - @Override - public Block getBlock() - { - for( final Block block : AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet() ) - { - return block; - } - - throw new MissingDefinition( "Tried to access the multi part block without it being defined." ); - } - - public void prepareBounds( final RenderBlocks renderer ) - { - this.bbr.renderBlockBounds( renderer, this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ, this.ax, this.ay, this.az ); - } - - @Override - public void setFacesToRender( final EnumSet faces ) - { - BusRenderer.INSTANCE.getRenderer().setRenderFaces( faces ); - } - - @Override - public void renderBlockCurrentBounds( final int x, final int y, final int z, final RenderBlocks renderer ) - { - if( !this.renderThis() ) - { - return; - } - - for( final Block block : this.maybeBlock.asSet() ) - { - renderer.renderStandardBlock( block, x, y, z ); - } - } - - @Override - public void renderFaceCutout( final int x, final int y, final int z, final IIcon ico, ForgeDirection face, final float edgeThickness, final RenderBlocks renderer ) - { - if( !this.renderThis() ) - { - return; - } - - switch( face ) - { - case DOWN: - face = this.ay.getOpposite(); - break; - case EAST: - face = this.ax; - break; - case NORTH: - face = this.az.getOpposite(); - break; - case SOUTH: - face = this.az; - break; - case UP: - face = this.ay; - break; - case WEST: - face = this.ax.getOpposite(); - break; - case UNKNOWN: - break; - default: - break; - } - - for( final AEBaseBlock block : this.maybeBaseBlock.asSet() ) - { - this.bbr.renderCutoutFace( block, ico, x, y, z, renderer, face, edgeThickness ); - } - } - - @Override - public void renderFace( final int x, final int y, final int z, final IIcon ico, ForgeDirection face, final RenderBlocks renderer ) - { - if( !this.renderThis() ) - { - return; - } - - this.prepareBounds( renderer ); - switch( face ) - { - case DOWN: - face = this.ay.getOpposite(); - break; - case EAST: - face = this.ax; - break; - case NORTH: - face = this.az.getOpposite(); - break; - case SOUTH: - face = this.az; - break; - case UP: - face = this.ay; - break; - case WEST: - face = this.ax.getOpposite(); - break; - case UNKNOWN: - break; - default: - break; - } - - for( final AEBaseBlock block : this.maybeBaseBlock.asSet() ) - { - this.bbr.renderFace( x, y, z, block, ico, renderer, face ); - } - } - - @Override - public ForgeDirection getWorldX() - { - return this.ax; - } - - @Override - public ForgeDirection getWorldY() - { - return this.ay; - } - - @Override - public ForgeDirection getWorldZ() - { - return this.az; - } +@SideOnly(Side.CLIENT) +public final class BusRenderHelper implements IPartRenderHelper { + public static final BusRenderHelper INSTANCE = new BusRenderHelper(); + private static final int HEX_WHITE = 0xffffff; + + private final BoundBoxCalculator bbc; + private final boolean noAlphaPass; + private final BaseBlockRender bbr; + private final Optional maybeBlock; + private final Optional maybeBaseBlock; + private int renderingForPass; + private int currentPass; + private int itemsRendered; + private double minX; + private double minY; + private double minZ; + private double maxX; + private double maxY; + private double maxZ; + private ForgeDirection ax; + private ForgeDirection ay; + private ForgeDirection az; + private int color; + + public BusRenderHelper() { + this.bbc = new BoundBoxCalculator(this); + this.noAlphaPass = !AEConfig.instance.isFeatureEnabled(AEFeature.AlphaPass); + this.bbr = new BaseBlockRender(); + this.renderingForPass = 0; + this.currentPass = 0; + this.itemsRendered = 0; + this.minX = 0; + this.minY = 0; + this.minZ = 0; + this.maxX = 16; + this.maxY = 16; + this.maxZ = 16; + this.ax = ForgeDirection.EAST; + this.az = ForgeDirection.SOUTH; + this.ay = ForgeDirection.UP; + this.color = HEX_WHITE; + this.maybeBlock = AEApi.instance().definitions().blocks().multiPart().maybeBlock(); + this.maybeBaseBlock = this.maybeBlock.transform(new BaseBlockTransformFunction()); + } + + public int getItemsRendered() { + return this.itemsRendered; + } + + public void setPass(final int pass) { + this.renderingForPass = 0; + this.currentPass = pass; + this.itemsRendered = 0; + } + + public double getBound(final ForgeDirection side) { + switch (side) { + default: + case UNKNOWN: + return 0.5; + case DOWN: + return this.minY; + case EAST: + return this.maxX; + case NORTH: + return this.minZ; + case SOUTH: + return this.maxZ; + case UP: + return this.maxY; + case WEST: + return this.minX; + } + } + + public void setRenderColor(final int color) { + for (final Block block : + AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet()) { + final BlockCableBus cableBus = (BlockCableBus) block; + cableBus.setRenderColor(color); + } + } + + public void setOrientation(final ForgeDirection dx, final ForgeDirection dy, final ForgeDirection dz) { + this.ax = dx == null ? ForgeDirection.EAST : dx; + this.ay = dy == null ? ForgeDirection.UP : dy; + this.az = dz == null ? ForgeDirection.SOUTH : dz; + } + + public double[] getBounds() { + return new double[] {this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ}; + } + + public void setBounds(final double[] bounds) { + if (bounds == null || bounds.length != 6) { + return; + } + + this.minX = bounds[0]; + this.minY = bounds[1]; + this.minZ = bounds[2]; + this.maxX = bounds[3]; + this.maxY = bounds[4]; + this.maxZ = bounds[5]; + } + + private static class BoundBoxCalculator implements IPartCollisionHelper { + private final BusRenderHelper helper; + private boolean started = false; + + private float minX; + private float minY; + private float minZ; + + private float maxX; + private float maxY; + private float maxZ; + + public BoundBoxCalculator(final BusRenderHelper helper) { + this.helper = helper; + } + + @Override + public void addBox( + final double minX, + final double minY, + final double minZ, + final double maxX, + final double maxY, + final double maxZ) { + if (this.started) { + this.minX = Math.min(this.minX, (float) minX); + this.minY = Math.min(this.minY, (float) minY); + this.minZ = Math.min(this.minZ, (float) minZ); + this.maxX = Math.max(this.maxX, (float) maxX); + this.maxY = Math.max(this.maxY, (float) maxY); + this.maxZ = Math.max(this.maxZ, (float) maxZ); + } else { + this.started = true; + this.minX = (float) minX; + this.minY = (float) minY; + this.minZ = (float) minZ; + this.maxX = (float) maxX; + this.maxY = (float) maxY; + this.maxZ = (float) maxZ; + } + } + + @Override + public ForgeDirection getWorldX() { + return this.helper.ax; + } + + @Override + public ForgeDirection getWorldY() { + return this.helper.ay; + } + + @Override + public ForgeDirection getWorldZ() { + return this.helper.az; + } + + @Override + public boolean isBBCollision() { + return false; + } + } + + private static final class BaseBlockTransformFunction implements Function { + @Nullable + @Override + public AEBaseBlock apply(final Block input) { + if (input instanceof AEBaseBlock) { + return ((AEBaseBlock) input); + } + + return null; + } + } + + @Override + public void renderForPass(final int pass) { + this.renderingForPass = pass; + } + + private boolean renderThis() { + if (this.renderingForPass == this.currentPass || this.noAlphaPass) { + this.itemsRendered++; + return true; + } + return false; + } + + @Override + public void normalRendering() { + final RenderBlocksWorkaround rbw = BusRenderer.INSTANCE.getRenderer(); + rbw.setCalculations(true); + rbw.setUseTextures(true); + rbw.enableAO = false; + } + + @Override + public ISimplifiedBundle useSimplifiedRendering( + final int x, final int y, final int z, final IBoxProvider p, final ISimplifiedBundle sim) { + final RenderBlocksWorkaround rbw = BusRenderer.INSTANCE.getRenderer(); + + if (sim != null + && this.maybeBlock.isPresent() + && rbw.similarLighting(this.maybeBlock.get(), rbw.blockAccess, x, y, z, sim)) { + rbw.populate(sim); + rbw.setFaces(EnumSet.allOf(ForgeDirection.class)); + rbw.setCalculations(false); + rbw.setUseTextures(false); + + return sim; + } else { + final boolean allFaces = rbw.renderAllFaces; + rbw.renderAllFaces = true; + rbw.setCalculations(true); + rbw.getFaces().clear(); + + this.bbc.started = false; + if (p == null) { + this.bbc.minX = this.bbc.minY = this.bbc.minZ = 0; + this.bbc.maxX = this.bbc.maxY = this.bbc.maxZ = 16; + } else { + p.getBoxes(this.bbc); + + if (this.bbc.minX < 1) { + this.bbc.minX = 1; + } + if (this.bbc.minY < 1) { + this.bbc.minY = 1; + } + if (this.bbc.minZ < 1) { + this.bbc.minZ = 1; + } + + if (this.bbc.maxX > 15) { + this.bbc.maxX = 15; + } + if (this.bbc.maxY > 15) { + this.bbc.maxY = 15; + } + if (this.bbc.maxZ > 15) { + this.bbc.maxZ = 15; + } + } + + this.setBounds(this.bbc.minX, this.bbc.minY, this.bbc.minZ, this.bbc.maxX, this.bbc.maxY, this.bbc.maxZ); + + this.bbr.renderBlockBounds( + rbw, this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ, this.ax, this.ay, this.az); + + for (final Block block : this.maybeBlock.asSet()) { + rbw.renderStandardBlock(block, x, y, z); + } + + rbw.setFaces(EnumSet.allOf(ForgeDirection.class)); + rbw.renderAllFaces = allFaces; + rbw.setCalculations(false); + rbw.setUseTextures(false); + + return rbw.getLightingCache(); + } + } + + @Override + public void setBounds( + final float minX, + final float minY, + final float minZ, + final float maxX, + final float maxY, + final float maxZ) { + this.minX = minX; + this.minY = minY; + this.minZ = minZ; + this.maxX = maxX; + this.maxY = maxY; + this.maxZ = maxZ; + } + + @Override + public void setInvColor(final int newColor) { + this.color = newColor; + } + + @Override + public void setTexture(final IIcon ico) { + for (final AEBaseBlock baseBlock : this.maybeBaseBlock.asSet()) { + baseBlock.getRendererInstance().setTemporaryRenderIcon(ico); + } + } + + @Override + public void setTexture( + final IIcon down, + final IIcon up, + final IIcon north, + final IIcon south, + final IIcon west, + final IIcon east) { + final IIcon[] list = new IIcon[6]; + + list[0] = down; + list[1] = up; + list[2] = north; + list[3] = south; + list[4] = west; + list[5] = east; + + for (final AEBaseBlock baseBlock : this.maybeBaseBlock.asSet()) { + baseBlock + .getRendererInstance() + .setTemporaryRenderIcons( + list[this.mapRotation(ForgeDirection.UP).ordinal()], + list[this.mapRotation(ForgeDirection.DOWN).ordinal()], + list[this.mapRotation(ForgeDirection.SOUTH).ordinal()], + list[this.mapRotation(ForgeDirection.NORTH).ordinal()], + list[this.mapRotation(ForgeDirection.EAST).ordinal()], + list[this.mapRotation(ForgeDirection.WEST).ordinal()]); + } + } + + private ForgeDirection mapRotation(final ForgeDirection dir) { + final ForgeDirection forward = this.az; + final ForgeDirection up = this.ay; + + if (forward == null || up == null) { + return dir; + } + + final int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; + final int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; + final int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; + + ForgeDirection west = ForgeDirection.UNKNOWN; + for (final ForgeDirection dx : ForgeDirection.VALID_DIRECTIONS) { + if (dx.offsetX == west_x && dx.offsetY == west_y && dx.offsetZ == west_z) { + west = dx; + } + } + + if (dir == forward) { + return ForgeDirection.SOUTH; + } + if (dir == forward.getOpposite()) { + return ForgeDirection.NORTH; + } + + if (dir == up) { + return ForgeDirection.UP; + } + if (dir == up.getOpposite()) { + return ForgeDirection.DOWN; + } + + if (dir == west) { + return ForgeDirection.WEST; + } + if (dir == west.getOpposite()) { + return ForgeDirection.EAST; + } + + return ForgeDirection.UNKNOWN; + } + + @Override + public void renderInventoryBox(final RenderBlocks renderer) { + renderer.setRenderBounds( + this.minX / 16.0, + this.minY / 16.0, + this.minZ / 16.0, + this.maxX / 16.0, + this.maxY / 16.0, + this.maxZ / 16.0); + + for (final AEBaseBlock baseBlock : this.maybeBaseBlock.asSet()) { + this.bbr.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), baseBlock, null, Tessellator.instance, this.color, renderer); + } + } + + @Override + public void renderInventoryFace(final IIcon icon, final ForgeDirection face, final RenderBlocks renderer) { + renderer.setRenderBounds( + this.minX / 16.0, + this.minY / 16.0, + this.minZ / 16.0, + this.maxX / 16.0, + this.maxY / 16.0, + this.maxZ / 16.0); + this.setTexture(icon); + + for (final AEBaseBlock baseBlock : this.maybeBaseBlock.asSet()) { + this.bbr.renderInvBlock(EnumSet.of(face), baseBlock, null, Tessellator.instance, this.color, renderer); + } + } + + @Override + public void renderBlock(final int x, final int y, final int z, final RenderBlocks renderer) { + if (!this.renderThis()) { + return; + } + + for (final Block multiPart : + AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet()) { + final AEBaseBlock block = (AEBaseBlock) multiPart; + + final BlockRenderInfo info = block.getRendererInstance(); + final ForgeDirection forward = BusRenderHelper.INSTANCE.az; + final ForgeDirection up = BusRenderHelper.INSTANCE.ay; + + renderer.uvRotateBottom = info.getTexture(ForgeDirection.DOWN) + .setFlip(BaseBlockRender.getOrientation(ForgeDirection.DOWN, forward, up)); + renderer.uvRotateTop = info.getTexture(ForgeDirection.UP) + .setFlip(BaseBlockRender.getOrientation(ForgeDirection.UP, forward, up)); + + renderer.uvRotateEast = info.getTexture(ForgeDirection.EAST) + .setFlip(BaseBlockRender.getOrientation(ForgeDirection.EAST, forward, up)); + renderer.uvRotateWest = info.getTexture(ForgeDirection.WEST) + .setFlip(BaseBlockRender.getOrientation(ForgeDirection.WEST, forward, up)); + + renderer.uvRotateNorth = info.getTexture(ForgeDirection.NORTH) + .setFlip(BaseBlockRender.getOrientation(ForgeDirection.NORTH, forward, up)); + renderer.uvRotateSouth = info.getTexture(ForgeDirection.SOUTH) + .setFlip(BaseBlockRender.getOrientation(ForgeDirection.SOUTH, forward, up)); + + this.bbr.renderBlockBounds( + renderer, this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ, this.ax, this.ay, + this.az); + + renderer.renderStandardBlock(block, x, y, z); + } + } + + @Override + public Block getBlock() { + for (final Block block : + AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet()) { + return block; + } + + throw new MissingDefinition("Tried to access the multi part block without it being defined."); + } + + public void prepareBounds(final RenderBlocks renderer) { + this.bbr.renderBlockBounds( + renderer, this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ, this.ax, this.ay, this.az); + } + + @Override + public void setFacesToRender(final EnumSet faces) { + BusRenderer.INSTANCE.getRenderer().setRenderFaces(faces); + } + + @Override + public void renderBlockCurrentBounds(final int x, final int y, final int z, final RenderBlocks renderer) { + if (!this.renderThis()) { + return; + } + + for (final Block block : this.maybeBlock.asSet()) { + renderer.renderStandardBlock(block, x, y, z); + } + } + + @Override + public void renderFaceCutout( + final int x, + final int y, + final int z, + final IIcon ico, + ForgeDirection face, + final float edgeThickness, + final RenderBlocks renderer) { + if (!this.renderThis()) { + return; + } + + switch (face) { + case DOWN: + face = this.ay.getOpposite(); + break; + case EAST: + face = this.ax; + break; + case NORTH: + face = this.az.getOpposite(); + break; + case SOUTH: + face = this.az; + break; + case UP: + face = this.ay; + break; + case WEST: + face = this.ax.getOpposite(); + break; + case UNKNOWN: + break; + default: + break; + } + + for (final AEBaseBlock block : this.maybeBaseBlock.asSet()) { + this.bbr.renderCutoutFace(block, ico, x, y, z, renderer, face, edgeThickness); + } + } + + @Override + public void renderFace( + final int x, final int y, final int z, final IIcon ico, ForgeDirection face, final RenderBlocks renderer) { + if (!this.renderThis()) { + return; + } + + this.prepareBounds(renderer); + switch (face) { + case DOWN: + face = this.ay.getOpposite(); + break; + case EAST: + face = this.ax; + break; + case NORTH: + face = this.az.getOpposite(); + break; + case SOUTH: + face = this.az; + break; + case UP: + face = this.ay; + break; + case WEST: + face = this.ax.getOpposite(); + break; + case UNKNOWN: + break; + default: + break; + } + + for (final AEBaseBlock block : this.maybeBaseBlock.asSet()) { + this.bbr.renderFace(x, y, z, block, ico, renderer, face); + } + } + + @Override + public ForgeDirection getWorldX() { + return this.ax; + } + + @Override + public ForgeDirection getWorldY() { + return this.ay; + } + + @Override + public ForgeDirection getWorldZ() { + return this.az; + } } diff --git a/src/main/java/appeng/client/render/BusRenderer.java b/src/main/java/appeng/client/render/BusRenderer.java index 0660bf57a19..94762bf0006 100644 --- a/src/main/java/appeng/client/render/BusRenderer.java +++ b/src/main/java/appeng/client/render/BusRenderer.java @@ -18,7 +18,6 @@ package appeng.client.render; - import appeng.api.parts.IAlphaPassItem; import appeng.api.parts.IFacadePart; import appeng.api.parts.IPart; @@ -30,6 +29,9 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; import net.minecraft.client.renderer.Tessellator; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -37,153 +39,131 @@ import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import javax.annotation.Nullable; -import java.util.HashMap; -import java.util.Map; - - -@SideOnly( Side.CLIENT ) -public class BusRenderer implements IItemRenderer -{ - - public static final BusRenderer INSTANCE = new BusRenderer(); - private static final Map RENDER_PART = new HashMap(); - private final RenderBlocksWorkaround renderer = new RenderBlocksWorkaround(); - - @Override - public boolean handleRenderType( final ItemStack item, final ItemRenderType type ) - { - return true; - } - - @Override - public boolean shouldUseRenderHelper( final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper ) - { - return true; - } - - @Override - public void renderItem( final ItemRenderType type, final ItemStack item, final Object... data ) - { - if( item == null ) - { - return; - } - - GL11.glPushMatrix(); - GL11.glPushAttrib( GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT ); - GL11.glEnable( GL11.GL_DEPTH_TEST ); - GL11.glEnable( GL11.GL_TEXTURE_2D ); - GL11.glEnable( GL11.GL_LIGHTING ); - - if( AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) && item.getItem() instanceof IAlphaPassItem && ( (IAlphaPassItem) item.getItem() ).useAlphaPass( item ) ) - { - GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - GL11.glDisable( GL11.GL_ALPHA_TEST ); - GL11.glEnable( GL11.GL_BLEND ); - } - else - { - GL11.glAlphaFunc( GL11.GL_GREATER, 0.4f ); - GL11.glEnable( GL11.GL_ALPHA_TEST ); - GL11.glDisable( GL11.GL_BLEND ); - } - - if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) - { - GL11.glTranslatef( -0.2f, -0.1f, -0.3f ); - } - - if( type == ItemRenderType.ENTITY ) - { - GL11.glRotatef( 90.0f, 0.0f, 1.0f, 0.0f ); - GL11.glScalef( 0.8f, 0.8f, 0.8f ); - GL11.glTranslatef( -0.8f, -0.87f, -0.7f ); - } - - if( type == ItemRenderType.INVENTORY ) - { - GL11.glTranslatef( 0.0f, -0.1f, 0.0f ); - } - - GL11.glTranslated( 0.2, 0.3, 0.1 ); - GL11.glScaled( 1.2, 1.2, 1. ); - - GL11.glColor4f( 1, 1, 1, 1 ); - Tessellator.instance.setColorOpaque_F( 1, 1, 1 ); - Tessellator.instance.setBrightness( 14 << 20 | 14 << 4 ); - - BusRenderHelper.INSTANCE.setBounds( 0, 0, 0, 1, 1, 1 ); - BusRenderHelper.INSTANCE.setTexture( null ); - BusRenderHelper.INSTANCE.setInvColor( 0xffffff ); - this.getRenderer().blockAccess = ClientHelper.proxy.getWorld(); - - BusRenderHelper.INSTANCE.setOrientation( ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH ); - - this.getRenderer().uvRotateBottom = this.getRenderer().uvRotateEast = this.getRenderer().uvRotateNorth = this.getRenderer().uvRotateSouth = this.getRenderer().uvRotateTop = this.getRenderer().uvRotateWest = 0; - this.getRenderer().useInventoryTint = false; - this.getRenderer().overrideBlockTexture = null; - - if( item.getItem() instanceof IFacadeItem ) - { - final IFacadeItem fi = (IFacadeItem) item.getItem(); - final IFacadePart fp = fi.createPartFromItemStack( item, ForgeDirection.SOUTH ); - - if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) - { - GL11.glRotatef( 160.0f, 0.0f, 1.0f, 0.0f ); - GL11.glTranslated( -0.4, 0.1, -1.6 ); - } - - if( fp != null ) - { - fp.renderInventory( BusRenderHelper.INSTANCE, this.getRenderer() ); - } - } - else - { - final IPart ip = this.getRenderer( item, (IPartItem) item.getItem() ); - - if( ip != null ) - { - if( type == ItemRenderType.ENTITY ) - { - final int depth = ip.cableConnectionRenderTo(); - GL11.glTranslatef( 0.0f, 0.0f, -0.04f * ( 8 - depth ) - 0.06f ); - } - - ip.renderInventory( BusRenderHelper.INSTANCE, this.getRenderer() ); - } - } - - this.getRenderer().uvRotateBottom = this.getRenderer().uvRotateEast = this.getRenderer().uvRotateNorth = this.getRenderer().uvRotateSouth = this.getRenderer().uvRotateTop = this.getRenderer().uvRotateWest = 0; - - GL11.glPopAttrib(); - GL11.glPopMatrix(); - } - - @Nullable - private IPart getRenderer( final ItemStack is, final IPartItem c ) - { - final int id = ( Item.getIdFromItem( is.getItem() ) << Platform.DEF_OFFSET ) | is.getItemDamage(); - - IPart part = RENDER_PART.get( id ); - - if( part == null ) - { - part = c.createPartFromItemStack( is ); - if( part != null ) - { - RENDER_PART.put( id, part ); - } - } - - return part; - } - - public RenderBlocksWorkaround getRenderer() - { - return this.renderer; - } +@SideOnly(Side.CLIENT) +public class BusRenderer implements IItemRenderer { + + public static final BusRenderer INSTANCE = new BusRenderer(); + private static final Map RENDER_PART = new HashMap(); + private final RenderBlocksWorkaround renderer = new RenderBlocksWorkaround(); + + @Override + public boolean handleRenderType(final ItemStack item, final ItemRenderType type) { + return true; + } + + @Override + public boolean shouldUseRenderHelper( + final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper) { + return true; + } + + @Override + public void renderItem(final ItemRenderType type, final ItemStack item, final Object... data) { + if (item == null) { + return; + } + + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_LIGHTING); + + if (AEConfig.instance.isFeatureEnabled(AEFeature.AlphaPass) + && item.getItem() instanceof IAlphaPassItem + && ((IAlphaPassItem) item.getItem()).useAlphaPass(item)) { + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_BLEND); + } else { + GL11.glAlphaFunc(GL11.GL_GREATER, 0.4f); + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glDisable(GL11.GL_BLEND); + } + + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + GL11.glTranslatef(-0.2f, -0.1f, -0.3f); + } + + if (type == ItemRenderType.ENTITY) { + GL11.glRotatef(90.0f, 0.0f, 1.0f, 0.0f); + GL11.glScalef(0.8f, 0.8f, 0.8f); + GL11.glTranslatef(-0.8f, -0.87f, -0.7f); + } + + if (type == ItemRenderType.INVENTORY) { + GL11.glTranslatef(0.0f, -0.1f, 0.0f); + } + + GL11.glTranslated(0.2, 0.3, 0.1); + GL11.glScaled(1.2, 1.2, 1.); + + GL11.glColor4f(1, 1, 1, 1); + Tessellator.instance.setColorOpaque_F(1, 1, 1); + Tessellator.instance.setBrightness(14 << 20 | 14 << 4); + + BusRenderHelper.INSTANCE.setBounds(0, 0, 0, 1, 1, 1); + BusRenderHelper.INSTANCE.setTexture(null); + BusRenderHelper.INSTANCE.setInvColor(0xffffff); + this.getRenderer().blockAccess = ClientHelper.proxy.getWorld(); + + BusRenderHelper.INSTANCE.setOrientation(ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH); + + this.getRenderer().uvRotateBottom = this.getRenderer().uvRotateEast = this.getRenderer().uvRotateNorth = + this.getRenderer().uvRotateSouth = this.getRenderer().uvRotateTop = this.getRenderer().uvRotateWest = 0; + this.getRenderer().useInventoryTint = false; + this.getRenderer().overrideBlockTexture = null; + + if (item.getItem() instanceof IFacadeItem) { + final IFacadeItem fi = (IFacadeItem) item.getItem(); + final IFacadePart fp = fi.createPartFromItemStack(item, ForgeDirection.SOUTH); + + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + GL11.glRotatef(160.0f, 0.0f, 1.0f, 0.0f); + GL11.glTranslated(-0.4, 0.1, -1.6); + } + + if (fp != null) { + fp.renderInventory(BusRenderHelper.INSTANCE, this.getRenderer()); + } + } else { + final IPart ip = this.getRenderer(item, (IPartItem) item.getItem()); + + if (ip != null) { + if (type == ItemRenderType.ENTITY) { + final int depth = ip.cableConnectionRenderTo(); + GL11.glTranslatef(0.0f, 0.0f, -0.04f * (8 - depth) - 0.06f); + } + + ip.renderInventory(BusRenderHelper.INSTANCE, this.getRenderer()); + } + } + + this.getRenderer().uvRotateBottom = this.getRenderer().uvRotateEast = this.getRenderer().uvRotateNorth = + this.getRenderer().uvRotateSouth = this.getRenderer().uvRotateTop = this.getRenderer().uvRotateWest = 0; + + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } + + @Nullable + private IPart getRenderer(final ItemStack is, final IPartItem c) { + final int id = (Item.getIdFromItem(is.getItem()) << Platform.DEF_OFFSET) | is.getItemDamage(); + + IPart part = RENDER_PART.get(id); + + if (part == null) { + part = c.createPartFromItemStack(is); + if (part != null) { + RENDER_PART.put(id, part); + } + } + + return part; + } + + public RenderBlocksWorkaround getRenderer() { + return this.renderer; + } } diff --git a/src/main/java/appeng/client/render/CableRenderHelper.java b/src/main/java/appeng/client/render/CableRenderHelper.java index 68e237d4ef4..53d89998990 100644 --- a/src/main/java/appeng/client/render/CableRenderHelper.java +++ b/src/main/java/appeng/client/render/CableRenderHelper.java @@ -18,253 +18,237 @@ package appeng.client.render; - import appeng.api.parts.IFacadeContainer; import appeng.api.parts.IFacadePart; import appeng.api.parts.IPart; import appeng.parts.BusCollisionHelper; import appeng.parts.CableBusContainer; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; - - -public class CableRenderHelper -{ - - private static final CableRenderHelper INSTANCE = new CableRenderHelper(); - - public static CableRenderHelper getInstance() - { - return INSTANCE; - } - - public void renderStatic( final CableBusContainer cableBusContainer, final IFacadeContainer iFacadeContainer ) - { - final TileEntity te = cableBusContainer.getTile(); - final RenderBlocksWorkaround renderer = BusRenderer.INSTANCE.getRenderer(); - - if( renderer.overrideBlockTexture != null ) - { - BusRenderHelper.INSTANCE.setPass( 0 ); - } - - if( renderer.blockAccess == null ) - { - renderer.blockAccess = Minecraft.getMinecraft().theWorld; - } - - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = cableBusContainer.getPart( s ); - if( part != null ) - { - this.setSide( s ); - renderer.renderAllFaces = true; - - renderer.flipTexture = false; - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - - part.renderStatic( te.xCoord, te.yCoord, te.zCoord, BusRenderHelper.INSTANCE, renderer ); - - renderer.setFaces( EnumSet.allOf( ForgeDirection.class ) ); - renderer.setCalculations( true ); - renderer.setUseTextures( true ); - } - } - - if( !iFacadeContainer.isEmpty() ) - { - /** - * snag list of boxes... - */ - final List boxes = new ArrayList(); - - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = cableBusContainer.getPart( s ); - if( part != null ) - { - this.setSide( s ); - final BusRenderHelper brh = BusRenderHelper.INSTANCE; - final BusCollisionHelper bch = new BusCollisionHelper( boxes, brh.getWorldX(), brh.getWorldY(), brh.getWorldZ(), null, true ); - part.getBoxes( bch ); - } - } - - boolean useThinFacades = false; - final double min = 2.0 / 16.0; - final double max = 14.0 / 16.0; - - for( final AxisAlignedBB bb : boxes ) - { - int o = 0; - o += bb.maxX > max ? 1 : 0; - o += bb.maxY > max ? 1 : 0; - o += bb.maxZ > max ? 1 : 0; - o += bb.minX < min ? 1 : 0; - o += bb.minY < min ? 1 : 0; - o += bb.minZ < min ? 1 : 0; - - if( o >= 2 ) - { - useThinFacades = true; - } - } - - for( final ForgeDirection s : ForgeDirection.VALID_DIRECTIONS ) - { - final IFacadePart fPart = iFacadeContainer.getFacade( s ); - - if( fPart != null ) - { - fPart.setThinFacades( useThinFacades ); - final AxisAlignedBB pb = fPart.getPrimaryBox(); - AxisAlignedBB b = null; - for( final AxisAlignedBB bb : boxes ) - { - if( bb.intersectsWith( pb ) ) - { - if( b == null ) - { - b = bb; - } - else - { - b.maxX = Math.max( b.maxX, bb.maxX ); - b.maxY = Math.max( b.maxY, bb.maxY ); - b.maxZ = Math.max( b.maxZ, bb.maxZ ); - b.minX = Math.min( b.minX, bb.minX ); - b.minY = Math.min( b.minY, bb.minY ); - b.minZ = Math.min( b.minZ, bb.minZ ); - } - } - } - - renderer.flipTexture = false; - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - - this.setSide( s ); - fPart.renderStatic( te.xCoord, te.yCoord, te.zCoord, BusRenderHelper.INSTANCE, renderer, iFacadeContainer, b, cableBusContainer.getPart( s ) == null ); - } - } - - renderer.setFacade( false ); - renderer.enableAO = false; - renderer.setTexture( null ); - renderer.setCalculations( true ); - } - } - - private void setSide( final ForgeDirection s ) - { - final ForgeDirection ax; - final ForgeDirection ay; - final ForgeDirection az; - - switch( s ) - { - case DOWN: - ax = ForgeDirection.EAST; - ay = ForgeDirection.NORTH; - az = ForgeDirection.DOWN; - break; - case UP: - ax = ForgeDirection.EAST; - ay = ForgeDirection.SOUTH; - az = ForgeDirection.UP; - break; - case EAST: - ax = ForgeDirection.SOUTH; - ay = ForgeDirection.UP; - az = ForgeDirection.EAST; - break; - case WEST: - ax = ForgeDirection.NORTH; - ay = ForgeDirection.UP; - az = ForgeDirection.WEST; - break; - case NORTH: - ax = ForgeDirection.WEST; - ay = ForgeDirection.UP; - az = ForgeDirection.NORTH; - break; - case SOUTH: - ax = ForgeDirection.EAST; - ay = ForgeDirection.UP; - az = ForgeDirection.SOUTH; - break; - case UNKNOWN: - default: - ax = ForgeDirection.EAST; - ay = ForgeDirection.UP; - az = ForgeDirection.SOUTH; - break; - } - - BusRenderHelper.INSTANCE.setOrientation( ax, ay, az ); - } - - public void renderDynamic( final CableBusContainer cableBusContainer, final double x, final double y, final double z ) - { - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = cableBusContainer.getPart( s ); - - if( part != null ) - { - final ForgeDirection ax; - final ForgeDirection ay; - final ForgeDirection az; - - switch( s ) - { - case DOWN: - ax = ForgeDirection.EAST; - ay = ForgeDirection.NORTH; - az = ForgeDirection.DOWN; - break; - case UP: - ax = ForgeDirection.EAST; - ay = ForgeDirection.SOUTH; - az = ForgeDirection.UP; - break; - case EAST: - ax = ForgeDirection.SOUTH; - ay = ForgeDirection.UP; - az = ForgeDirection.EAST; - break; - case WEST: - ax = ForgeDirection.NORTH; - ay = ForgeDirection.UP; - az = ForgeDirection.WEST; - break; - case NORTH: - ax = ForgeDirection.WEST; - ay = ForgeDirection.UP; - az = ForgeDirection.NORTH; - break; - case SOUTH: - ax = ForgeDirection.EAST; - ay = ForgeDirection.UP; - az = ForgeDirection.SOUTH; - break; - case UNKNOWN: - default: - ax = ForgeDirection.EAST; - ay = ForgeDirection.UP; - az = ForgeDirection.SOUTH; - break; - } - - BusRenderHelper.INSTANCE.setOrientation( ax, ay, az ); - part.renderDynamic( x, y, z, BusRenderHelper.INSTANCE, BusRenderer.INSTANCE.getRenderer() ); - } - } - } +public class CableRenderHelper { + + private static final CableRenderHelper INSTANCE = new CableRenderHelper(); + + public static CableRenderHelper getInstance() { + return INSTANCE; + } + + public void renderStatic(final CableBusContainer cableBusContainer, final IFacadeContainer iFacadeContainer) { + final TileEntity te = cableBusContainer.getTile(); + final RenderBlocksWorkaround renderer = BusRenderer.INSTANCE.getRenderer(); + + if (renderer.overrideBlockTexture != null) { + BusRenderHelper.INSTANCE.setPass(0); + } + + if (renderer.blockAccess == null) { + renderer.blockAccess = Minecraft.getMinecraft().theWorld; + } + + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = cableBusContainer.getPart(s); + if (part != null) { + this.setSide(s); + renderer.renderAllFaces = true; + + renderer.flipTexture = false; + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = + renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + + part.renderStatic(te.xCoord, te.yCoord, te.zCoord, BusRenderHelper.INSTANCE, renderer); + + renderer.setFaces(EnumSet.allOf(ForgeDirection.class)); + renderer.setCalculations(true); + renderer.setUseTextures(true); + } + } + + if (!iFacadeContainer.isEmpty()) { + /** + * snag list of boxes... + */ + final List boxes = new ArrayList(); + + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = cableBusContainer.getPart(s); + if (part != null) { + this.setSide(s); + final BusRenderHelper brh = BusRenderHelper.INSTANCE; + final BusCollisionHelper bch = new BusCollisionHelper( + boxes, brh.getWorldX(), brh.getWorldY(), brh.getWorldZ(), null, true); + part.getBoxes(bch); + } + } + + boolean useThinFacades = false; + final double min = 2.0 / 16.0; + final double max = 14.0 / 16.0; + + for (final AxisAlignedBB bb : boxes) { + int o = 0; + o += bb.maxX > max ? 1 : 0; + o += bb.maxY > max ? 1 : 0; + o += bb.maxZ > max ? 1 : 0; + o += bb.minX < min ? 1 : 0; + o += bb.minY < min ? 1 : 0; + o += bb.minZ < min ? 1 : 0; + + if (o >= 2) { + useThinFacades = true; + } + } + + for (final ForgeDirection s : ForgeDirection.VALID_DIRECTIONS) { + final IFacadePart fPart = iFacadeContainer.getFacade(s); + + if (fPart != null) { + fPart.setThinFacades(useThinFacades); + final AxisAlignedBB pb = fPart.getPrimaryBox(); + AxisAlignedBB b = null; + for (final AxisAlignedBB bb : boxes) { + if (bb.intersectsWith(pb)) { + if (b == null) { + b = bb; + } else { + b.maxX = Math.max(b.maxX, bb.maxX); + b.maxY = Math.max(b.maxY, bb.maxY); + b.maxZ = Math.max(b.maxZ, bb.maxZ); + b.minX = Math.min(b.minX, bb.minX); + b.minY = Math.min(b.minY, bb.minY); + b.minZ = Math.min(b.minZ, bb.minZ); + } + } + } + + renderer.flipTexture = false; + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = + renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + + this.setSide(s); + fPart.renderStatic( + te.xCoord, + te.yCoord, + te.zCoord, + BusRenderHelper.INSTANCE, + renderer, + iFacadeContainer, + b, + cableBusContainer.getPart(s) == null); + } + } + + renderer.setFacade(false); + renderer.enableAO = false; + renderer.setTexture(null); + renderer.setCalculations(true); + } + } + + private void setSide(final ForgeDirection s) { + final ForgeDirection ax; + final ForgeDirection ay; + final ForgeDirection az; + + switch (s) { + case DOWN: + ax = ForgeDirection.EAST; + ay = ForgeDirection.NORTH; + az = ForgeDirection.DOWN; + break; + case UP: + ax = ForgeDirection.EAST; + ay = ForgeDirection.SOUTH; + az = ForgeDirection.UP; + break; + case EAST: + ax = ForgeDirection.SOUTH; + ay = ForgeDirection.UP; + az = ForgeDirection.EAST; + break; + case WEST: + ax = ForgeDirection.NORTH; + ay = ForgeDirection.UP; + az = ForgeDirection.WEST; + break; + case NORTH: + ax = ForgeDirection.WEST; + ay = ForgeDirection.UP; + az = ForgeDirection.NORTH; + break; + case SOUTH: + ax = ForgeDirection.EAST; + ay = ForgeDirection.UP; + az = ForgeDirection.SOUTH; + break; + case UNKNOWN: + default: + ax = ForgeDirection.EAST; + ay = ForgeDirection.UP; + az = ForgeDirection.SOUTH; + break; + } + + BusRenderHelper.INSTANCE.setOrientation(ax, ay, az); + } + + public void renderDynamic( + final CableBusContainer cableBusContainer, final double x, final double y, final double z) { + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = cableBusContainer.getPart(s); + + if (part != null) { + final ForgeDirection ax; + final ForgeDirection ay; + final ForgeDirection az; + + switch (s) { + case DOWN: + ax = ForgeDirection.EAST; + ay = ForgeDirection.NORTH; + az = ForgeDirection.DOWN; + break; + case UP: + ax = ForgeDirection.EAST; + ay = ForgeDirection.SOUTH; + az = ForgeDirection.UP; + break; + case EAST: + ax = ForgeDirection.SOUTH; + ay = ForgeDirection.UP; + az = ForgeDirection.EAST; + break; + case WEST: + ax = ForgeDirection.NORTH; + ay = ForgeDirection.UP; + az = ForgeDirection.WEST; + break; + case NORTH: + ax = ForgeDirection.WEST; + ay = ForgeDirection.UP; + az = ForgeDirection.NORTH; + break; + case SOUTH: + ax = ForgeDirection.EAST; + ay = ForgeDirection.UP; + az = ForgeDirection.SOUTH; + break; + case UNKNOWN: + default: + ax = ForgeDirection.EAST; + ay = ForgeDirection.UP; + az = ForgeDirection.SOUTH; + break; + } + + BusRenderHelper.INSTANCE.setOrientation(ax, ay, az); + part.renderDynamic(x, y, z, BusRenderHelper.INSTANCE, BusRenderer.INSTANCE.getRenderer()); + } + } + } } diff --git a/src/main/java/appeng/client/render/ItemRenderer.java b/src/main/java/appeng/client/render/ItemRenderer.java index c51c3c33d6e..e38449a761c 100644 --- a/src/main/java/appeng/client/render/ItemRenderer.java +++ b/src/main/java/appeng/client/render/ItemRenderer.java @@ -18,52 +18,45 @@ package appeng.client.render; - import net.minecraft.item.ItemStack; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; - -public class ItemRenderer implements IItemRenderer -{ - - public static final ItemRenderer INSTANCE = new ItemRenderer(); - - @Override - public boolean handleRenderType( final ItemStack item, final ItemRenderType type ) - { - return true; - } - - @Override - public boolean shouldUseRenderHelper( final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper ) - { - return true; - } - - @Override - public void renderItem( final ItemRenderType type, final ItemStack item, final Object... data ) - { - GL11.glPushMatrix(); - GL11.glPushAttrib( GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT ); - GL11.glEnable( GL11.GL_ALPHA_TEST ); - GL11.glEnable( GL11.GL_DEPTH_TEST ); - GL11.glEnable( GL11.GL_BLEND ); - GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - - if( type == ItemRenderType.ENTITY ) - { - GL11.glTranslatef( -0.5f, -0.5f, -0.5f ); - } - if( type == ItemRenderType.INVENTORY ) - { - GL11.glTranslatef( 0.0f, -0.1f, 0.0f ); - } - - WorldRender.INSTANCE.renderItemBlock( item, type, data ); - - GL11.glPopAttrib(); - GL11.glPopMatrix(); - } +public class ItemRenderer implements IItemRenderer { + + public static final ItemRenderer INSTANCE = new ItemRenderer(); + + @Override + public boolean handleRenderType(final ItemStack item, final ItemRenderType type) { + return true; + } + + @Override + public boolean shouldUseRenderHelper( + final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper) { + return true; + } + + @Override + public void renderItem(final ItemRenderType type, final ItemStack item, final Object... data) { + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT); + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + + if (type == ItemRenderType.ENTITY) { + GL11.glTranslatef(-0.5f, -0.5f, -0.5f); + } + if (type == ItemRenderType.INVENTORY) { + GL11.glTranslatef(0.0f, -0.1f, 0.0f); + } + + WorldRender.INSTANCE.renderItemBlock(item, type, data); + + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } } diff --git a/src/main/java/appeng/client/render/RenderBlocksWorkaround.java b/src/main/java/appeng/client/render/RenderBlocksWorkaround.java index d4277dc8843..ee52c81dabb 100644 --- a/src/main/java/appeng/client/render/RenderBlocksWorkaround.java +++ b/src/main/java/appeng/client/render/RenderBlocksWorkaround.java @@ -18,11 +18,14 @@ package appeng.client.render; - import appeng.api.parts.ISimplifiedBundle; import appeng.core.AELog; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.Set; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; @@ -30,758 +33,692 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; -import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.Set; - - -@SideOnly( Side.CLIENT ) -public class RenderBlocksWorkaround extends RenderBlocks -{ - - private final int[] lightHashTmp = new int[27]; - private boolean calculations = true; - private EnumSet renderFaces = EnumSet.allOf( ForgeDirection.class ); - private EnumSet faces = EnumSet.allOf( ForgeDirection.class ); - private boolean isFacade = false; - private boolean useTextures = true; - private float opacity = 1.0f; - private Field fBrightness = null; - private Field fColor = null; - private LightingCache lightState = new LightingCache(); - - private int getCurrentColor() - { - try - { - if( this.fColor == null ) - { - try - { - this.fColor = Tessellator.class.getDeclaredField( "color" ); - } - catch( final Throwable t ) - { - this.fColor = Tessellator.class.getDeclaredField( "field_78402_m" ); - } - this.fColor.setAccessible( true ); - } - return (Integer) this.fColor.get( Tessellator.instance ); - } - catch( final Throwable t ) - { - return 0; - } - } - - private int getCurrentBrightness() - { - try - { - if( this.fBrightness == null ) - { - try - { - this.fBrightness = Tessellator.class.getDeclaredField( "brightness" ); - } - catch( final Throwable t ) - { - this.fBrightness = Tessellator.class.getDeclaredField( "field_78401_l" ); - } - this.fBrightness.setAccessible( true ); - } - return (Integer) this.fBrightness.get( Tessellator.instance ); - } - catch( final Throwable t ) - { - return 0; - } - } - - void setTexture( final IIcon ico ) - { - this.lightState.rXPos = this.lightState.rXNeg = this.lightState.rYPos = this.lightState.rYNeg = this.lightState.rZPos = this.lightState.rZNeg = ico; - } - - public void setTexture( final IIcon rYNeg, final IIcon rYPos, final IIcon rZNeg, final IIcon rZPos, final IIcon rXNeg, final IIcon rXPos ) - { - this.lightState.rXPos = rXPos; - this.lightState.rXNeg = rXNeg; - this.lightState.rYPos = rYPos; - this.lightState.rYNeg = rYNeg; - this.lightState.rZPos = rZPos; - this.lightState.rZNeg = rZNeg; - } - - private boolean renderStandardBlockNoCalculations( final Block b, final int x, final int y, final int z ) - { - Tessellator.instance.setBrightness( this.lightState.bXPos ); - this.restoreAO( this.lightState.aoXPos, this.lightState.foXPos ); - this.renderFaceXPos( b, x, y, z, this.isUseTextures() ? this.lightState.rXPos : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.EAST.ordinal() ) ); - - Tessellator.instance.setBrightness( this.lightState.bXNeg ); - this.restoreAO( this.lightState.aoXNeg, this.lightState.foXNeg ); - this.renderFaceXNeg( b, x, y, z, this.isUseTextures() ? this.lightState.rXNeg : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.WEST.ordinal() ) ); - - Tessellator.instance.setBrightness( this.lightState.bYPos ); - this.restoreAO( this.lightState.aoYPos, this.lightState.foYPos ); - this.renderFaceYPos( b, x, y, z, this.isUseTextures() ? this.lightState.rYPos : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.UP.ordinal() ) ); - - Tessellator.instance.setBrightness( this.lightState.bYNeg ); - this.restoreAO( this.lightState.aoYNeg, this.lightState.foYNeg ); - this.renderFaceYNeg( b, x, y, z, this.isUseTextures() ? this.lightState.rYNeg : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.DOWN.ordinal() ) ); - - Tessellator.instance.setBrightness( this.lightState.bZPos ); - this.restoreAO( this.lightState.aoZPos, this.lightState.foZPos ); - this.renderFaceZPos( b, x, y, z, this.isUseTextures() ? this.lightState.rZPos : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.SOUTH.ordinal() ) ); - - Tessellator.instance.setBrightness( this.lightState.bZNeg ); - this.restoreAO( this.lightState.aoZNeg, this.lightState.foZNeg ); - this.renderFaceZNeg( b, x, y, z, this.isUseTextures() ? this.lightState.rZNeg : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.NORTH.ordinal() ) ); - - return true; - } - - private void restoreAO( final int[] z, final float[] c ) - { - this.brightnessBottomLeft = z[0]; - this.brightnessBottomRight = z[1]; - this.brightnessTopLeft = z[2]; - this.brightnessTopRight = z[3]; - Tessellator.instance.setColorRGBA_I( z[4], (int) ( this.getOpacity() * 255 ) ); - - this.colorRedTopLeft = c[0]; - this.colorGreenTopLeft = c[1]; - this.colorBlueTopLeft = c[2]; - this.colorRedBottomLeft = c[3]; - this.colorGreenBottomLeft = c[4]; - this.colorBlueBottomLeft = c[5]; - this.colorRedBottomRight = c[6]; - this.colorGreenBottomRight = c[7]; - this.colorBlueBottomRight = c[8]; - this.colorRedTopRight = c[9]; - this.colorGreenTopRight = c[10]; - this.colorBlueTopRight = c[11]; - } - - private void saveAO( final int[] z, final float[] c ) - { - z[0] = this.brightnessBottomLeft; - z[1] = this.brightnessBottomRight; - z[2] = this.brightnessTopLeft; - z[3] = this.brightnessTopRight; - z[4] = this.getCurrentColor(); - - c[0] = this.colorRedTopLeft; - c[1] = this.colorGreenTopLeft; - c[2] = this.colorBlueTopLeft; - c[3] = this.colorRedBottomLeft; - c[4] = this.colorGreenBottomLeft; - c[5] = this.colorBlueBottomLeft; - c[6] = this.colorRedBottomRight; - c[7] = this.colorGreenBottomRight; - c[8] = this.colorBlueBottomRight; - c[9] = this.colorRedTopRight; - c[10] = this.colorGreenTopRight; - c[11] = this.colorBlueTopRight; - } - - @Override - public boolean renderStandardBlock( final Block blk, final int x, final int y, final int z ) - { - try - { - if( this.isCalculations() ) - { - this.lightState.lightHash = this.getLightingHash( blk, this.blockAccess, x, y, z ); - return super.renderStandardBlock( blk, x, y, z ); - } - else - { - this.enableAO = this.lightState.isAO; - final boolean out = this.renderStandardBlockNoCalculations( blk, x, y, z ); - this.enableAO = false; - return out; - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - // meh - } - return false; - } - - @Override - public void renderFaceYNeg( final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon ) - { - if( this.getFaces().contains( ForgeDirection.DOWN ) ) - { - if( !this.getRenderFaces().contains( ForgeDirection.DOWN ) ) - { - return; - } - - if( this.isFacade() ) - { - final Tessellator tessellator = Tessellator.instance; - - final double d3 = par8Icon.getInterpolatedU( this.renderMinX * 16.0D ); - final double d4 = par8Icon.getInterpolatedU( this.renderMaxX * 16.0D ); - final double d5 = par8Icon.getInterpolatedV( this.renderMinZ * 16.0D ); - final double d6 = par8Icon.getInterpolatedV( this.renderMaxZ * 16.0D ); - - final double d11 = par2 + this.renderMinX; - final double d12 = par2 + this.renderMaxX; - final double d13 = par4 + this.renderMinY; - final double d14 = par6 + this.renderMinZ; - final double d15 = par6 + this.renderMaxZ; - - if( this.enableAO ) - { - this.partialLightingColoring( 1.0 - this.renderMinX, this.renderMaxZ ); - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - this.partialLightingColoring( 1.0 - this.renderMinX, this.renderMinZ ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - this.partialLightingColoring( 1.0 - this.renderMaxX, this.renderMinZ ); - tessellator.addVertexWithUV( d12, d13, d14, d4, d5 ); - this.partialLightingColoring( 1.0 - this.renderMaxX, this.renderMaxZ ); - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - } - else - { - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - tessellator.addVertexWithUV( d12, d13, d14, d4, d5 ); - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - } - } - else - { - super.renderFaceYNeg( par1Block, par2, par4, par6, par8Icon ); - } - } - else - { - this.lightState.isAO = this.enableAO; - this.lightState.rYNeg = par8Icon; - this.saveAO( this.lightState.aoYNeg, this.lightState.foYNeg ); - this.lightState.bYNeg = this.getCurrentBrightness(); - } - } - - @Override - public void renderFaceYPos( final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon ) - { - if( this.getFaces().contains( ForgeDirection.UP ) ) - { - if( !this.getRenderFaces().contains( ForgeDirection.UP ) ) - { - return; - } - - if( this.isFacade() ) - { - final Tessellator tessellator = Tessellator.instance; - - final double d3 = par8Icon.getInterpolatedU( this.renderMinX * 16.0D ); - final double d4 = par8Icon.getInterpolatedU( this.renderMaxX * 16.0D ); - final double d5 = par8Icon.getInterpolatedV( this.renderMinZ * 16.0D ); - final double d6 = par8Icon.getInterpolatedV( this.renderMaxZ * 16.0D ); - - final double d11 = par2 + this.renderMinX; - final double d12 = par2 + this.renderMaxX; - final double d13 = par4 + this.renderMaxY; - final double d14 = par6 + this.renderMinZ; - final double d15 = par6 + this.renderMaxZ; - - if( this.enableAO ) - { - this.partialLightingColoring( this.renderMaxX, this.renderMaxZ ); - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - this.partialLightingColoring( this.renderMaxX, this.renderMinZ ); - tessellator.addVertexWithUV( d12, d13, d14, d4, d5 ); - this.partialLightingColoring( this.renderMinX, this.renderMinZ ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - this.partialLightingColoring( this.renderMinX, this.renderMaxZ ); - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - } - else - { - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - tessellator.addVertexWithUV( d12, d13, d14, d4, d5 ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - } - } - else - { - super.renderFaceYPos( par1Block, par2, par4, par6, par8Icon ); - } - } - else - { - this.lightState.isAO = this.enableAO; - this.lightState.rYPos = par8Icon; - this.saveAO( this.lightState.aoYPos, this.lightState.foYPos ); - this.lightState.bYPos = this.getCurrentBrightness(); - } - } - - @Override - public void renderFaceZNeg( final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon ) - { - if( this.getFaces().contains( ForgeDirection.NORTH ) ) - { - if( !this.getRenderFaces().contains( ForgeDirection.NORTH ) ) - { - return; - } - - if( this.isFacade() ) - { - final Tessellator tessellator = Tessellator.instance; - - final double d3 = par8Icon.getInterpolatedU( 16.0D - this.renderMinX * 16.0D ); - final double d4 = par8Icon.getInterpolatedU( 16.0D - this.renderMaxX * 16.0D ); - final double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); - final double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); - - final double d11 = par2 + this.renderMinX; - final double d12 = par2 + this.renderMaxX; - final double d13 = par4 + this.renderMinY; - final double d14 = par4 + this.renderMaxY; - final double d15 = par6 + this.renderMinZ; - - if( this.enableAO ) - { - this.partialLightingColoring( this.renderMaxY, 1.0 - this.renderMinX ); - tessellator.addVertexWithUV( d11, d14, d15, d3, d5 ); - this.partialLightingColoring( this.renderMaxY, 1.0 - this.renderMaxX ); - tessellator.addVertexWithUV( d12, d14, d15, d4, d5 ); - this.partialLightingColoring( this.renderMinY, 1.0 - this.renderMaxX ); - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - this.partialLightingColoring( this.renderMinY, 1.0 - this.renderMinX ); - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - } - else - { - tessellator.addVertexWithUV( d11, d14, d15, d3, d5 ); - tessellator.addVertexWithUV( d12, d14, d15, d4, d5 ); - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - } - } - else - { - super.renderFaceZNeg( par1Block, par2, par4, par6, par8Icon ); - } - } - else - { - this.lightState.isAO = this.enableAO; - this.lightState.rZNeg = par8Icon; - this.saveAO( this.lightState.aoZNeg, this.lightState.foZNeg ); - this.lightState.bZNeg = this.getCurrentBrightness(); - } - } - - @Override - public void renderFaceZPos( final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon ) - { - if( this.getFaces().contains( ForgeDirection.SOUTH ) ) - { - if( !this.getRenderFaces().contains( ForgeDirection.SOUTH ) ) - { - return; - } - - if( this.isFacade() ) - { - final Tessellator tessellator = Tessellator.instance; - - final double d3 = par8Icon.getInterpolatedU( this.renderMinX * 16.0D ); - final double d4 = par8Icon.getInterpolatedU( this.renderMaxX * 16.0D ); - final double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); - final double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); - - final double d11 = par2 + this.renderMinX; - final double d12 = par2 + this.renderMaxX; - final double d13 = par4 + this.renderMinY; - final double d14 = par4 + this.renderMaxY; - final double d15 = par6 + this.renderMaxZ; - - if( this.enableAO ) - { - this.partialLightingColoring( 1.0 - this.renderMinX, this.renderMaxY ); - tessellator.addVertexWithUV( d11, d14, d15, d3, d5 ); - this.partialLightingColoring( 1.0 - this.renderMinX, this.renderMinY ); - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - this.partialLightingColoring( 1.0 - this.renderMaxX, this.renderMinY ); - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - this.partialLightingColoring( 1.0 - this.renderMaxX, this.renderMaxY ); - tessellator.addVertexWithUV( d12, d14, d15, d4, d5 ); - } - else - { - tessellator.addVertexWithUV( d11, d14, d15, d3, d5 ); - tessellator.addVertexWithUV( d11, d13, d15, d3, d6 ); - tessellator.addVertexWithUV( d12, d13, d15, d4, d6 ); - tessellator.addVertexWithUV( d12, d14, d15, d4, d5 ); - } - } - else - { - super.renderFaceZPos( par1Block, par2, par4, par6, par8Icon ); - } - } - else - { - this.lightState.isAO = this.enableAO; - this.lightState.rZPos = par8Icon; - this.saveAO( this.lightState.aoZPos, this.lightState.foZPos ); - this.lightState.bZPos = this.getCurrentBrightness(); - } - } - - @Override - public void renderFaceXNeg( final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon ) - { - if( this.getFaces().contains( ForgeDirection.WEST ) ) - { - if( !this.getRenderFaces().contains( ForgeDirection.WEST ) ) - { - return; - } - - if( this.isFacade() ) - { - final Tessellator tessellator = Tessellator.instance; - - final double d3 = par8Icon.getInterpolatedU( this.renderMinZ * 16.0D ); - final double d4 = par8Icon.getInterpolatedU( this.renderMaxZ * 16.0D ); - final double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); - final double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); - - final double d11 = par2 + this.renderMinX; - final double d12 = par4 + this.renderMinY; - final double d13 = par4 + this.renderMaxY; - final double d14 = par6 + this.renderMinZ; - final double d15 = par6 + this.renderMaxZ; - - if( this.enableAO ) - { - this.partialLightingColoring( this.renderMaxY, this.renderMaxZ ); - tessellator.addVertexWithUV( d11, d13, d15, d4, d5 ); - this.partialLightingColoring( this.renderMaxY, this.renderMinZ ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - this.partialLightingColoring( this.renderMinY, this.renderMinZ ); - tessellator.addVertexWithUV( d11, d12, d14, d3, d6 ); - this.partialLightingColoring( this.renderMinY, this.renderMaxZ ); - tessellator.addVertexWithUV( d11, d12, d15, d4, d6 ); - } - else - { - tessellator.addVertexWithUV( d11, d13, d15, d4, d5 ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - tessellator.addVertexWithUV( d11, d12, d14, d3, d6 ); - tessellator.addVertexWithUV( d11, d12, d15, d4, d6 ); - } - } - else - { - super.renderFaceXNeg( par1Block, par2, par4, par6, par8Icon ); - } - } - else - { - this.lightState.isAO = this.enableAO; - this.lightState.rXNeg = par8Icon; - this.saveAO( this.lightState.aoXNeg, this.lightState.foXNeg ); - this.lightState.bXNeg = this.getCurrentBrightness(); - } - } - - @Override - public void renderFaceXPos( final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon ) - { - if( this.getFaces().contains( ForgeDirection.EAST ) ) - { - if( !this.getRenderFaces().contains( ForgeDirection.EAST ) ) - { - return; - } - - if( this.isFacade() ) - { - final Tessellator tessellator = Tessellator.instance; - - final double d3 = par8Icon.getInterpolatedU( 16.0D - this.renderMinZ * 16.0D ); - final double d4 = par8Icon.getInterpolatedU( 16.0D - this.renderMaxZ * 16.0D ); - final double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); - final double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); - - final double d11 = par2 + this.renderMaxX; - final double d12 = par4 + this.renderMinY; - final double d13 = par4 + this.renderMaxY; - final double d14 = par6 + this.renderMinZ; - final double d15 = par6 + this.renderMaxZ; - - if( this.enableAO ) - { - this.partialLightingColoring( 1.0 - this.renderMinY, this.renderMaxZ ); - tessellator.addVertexWithUV( d11, d12, d15, d4, d6 ); - this.partialLightingColoring( 1.0 - this.renderMinY, this.renderMinZ ); - tessellator.addVertexWithUV( d11, d12, d14, d3, d6 ); - this.partialLightingColoring( 1.0 - this.renderMaxY, this.renderMinZ ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - this.partialLightingColoring( 1.0 - this.renderMaxY, this.renderMaxZ ); - tessellator.addVertexWithUV( d11, d13, d15, d4, d5 ); - } - else - { - tessellator.addVertexWithUV( d11, d12, d15, d4, d6 ); - tessellator.addVertexWithUV( d11, d12, d14, d3, d6 ); - tessellator.addVertexWithUV( d11, d13, d14, d3, d5 ); - tessellator.addVertexWithUV( d11, d13, d15, d4, d5 ); - } - } - else - { - super.renderFaceXPos( par1Block, par2, par4, par6, par8Icon ); - } - } - else - { - this.lightState.isAO = this.enableAO; - this.lightState.rXPos = par8Icon; - this.saveAO( this.lightState.aoXPos, this.lightState.foXPos ); - this.lightState.bXPos = this.getCurrentBrightness(); - } - } - - private void partialLightingColoring( final double u, final double v ) - { - final double rA = this.colorRedTopLeft * u + ( 1.0 - u ) * this.colorRedTopRight; - final double rB = this.colorRedBottomLeft * u + ( 1.0 - u ) * this.colorRedBottomRight; - final float r = (float) ( rA * v + rB * ( 1.0 - v ) ); - - final double gA = this.colorGreenTopLeft * u + ( 1.0 - u ) * this.colorGreenTopRight; - final double gB = this.colorGreenBottomLeft * u + ( 1.0 - u ) * this.colorGreenBottomRight; - final float g = (float) ( gA * v + gB * ( 1.0 - v ) ); - - final double bA = this.colorBlueTopLeft * u + ( 1.0 - u ) * this.colorBlueTopRight; - final double bB = this.colorBlueBottomLeft * u + ( 1.0 - u ) * this.colorBlueBottomRight; - final float b = (float) ( bA * v + bB * ( 1.0 - v ) ); - - final double highA = ( this.brightnessTopLeft >> 16 & 255 ) * u + ( 1.0 - u ) * ( this.brightnessTopRight >> 16 & 255 ); - final double highB = ( this.brightnessBottomLeft >> 16 & 255 ) * u + ( 1.0 - u ) * ( this.brightnessBottomRight >> 16 & 255 ); - final int high = ( (int) ( highA * v + highB * ( 1.0 - v ) ) ) & 255; - - final double lowA = ( ( this.brightnessTopLeft & 255 ) ) * u + ( 1.0 - u ) * ( ( this.brightnessTopRight & 255 ) ); - final double lowB = ( ( this.brightnessBottomLeft & 255 ) ) * u + ( 1.0 - u ) * ( ( this.brightnessBottomRight & 255 ) ); - final int low = ( (int) ( lowA * v + lowB * ( 1.0 - v ) ) ) & 255; - - final int out = ( high << 16 ) | low; - - Tessellator.instance.setColorRGBA_F( r, g, b, this.getOpacity() ); - Tessellator.instance.setBrightness( out ); - } - - public boolean similarLighting( final Block blk, final IBlockAccess w, final int x, final int y, final int z, final ISimplifiedBundle sim ) - { - final int lh = this.getLightingHash( blk, w, x, y, z ); - return ( (LightingCache) sim ).lightHash == lh; - } - - private int getLightingHash( final Block blk, final IBlockAccess w, final int x, final int y, final int z ) - { - int o = 0; - - for( int i = -1; i <= 1; i++ ) - { - for( int j = -1; j <= 1; j++ ) - { - for( int k = -1; k <= 1; k++ ) - { - - this.lightHashTmp[o] = blk.getMixedBrightnessForBlock( this.blockAccess, x + i, y + j, z + k ); - o++; - } - } - } - - return Arrays.hashCode( this.lightHashTmp ); - } - - public void populate( final ISimplifiedBundle sim ) - { - this.lightState = new LightingCache( (LightingCache) sim ); - } - - public ISimplifiedBundle getLightingCache() - { - return new LightingCache( this.lightState ); - } - - Set getFaces() - { - return this.faces; - } - - public void setFaces( final EnumSet faces ) - { - this.faces = faces; - } - - private boolean isCalculations() - { - return this.calculations; - } - - public void setCalculations( final boolean calculations ) - { - this.calculations = calculations; - } - - private boolean isUseTextures() - { - return this.useTextures; - } - - void setUseTextures( final boolean useTextures ) - { - this.useTextures = useTextures; - } - - private boolean isFacade() - { - return this.isFacade; - } - - public void setFacade( final boolean isFacade ) - { - this.isFacade = isFacade; - } - - private float getOpacity() - { - return this.opacity; - } - - public void setOpacity( final float opacity ) - { - this.opacity = opacity; - } - - private EnumSet getRenderFaces() - { - return this.renderFaces; - } - - void setRenderFaces( final EnumSet renderFaces ) - { - this.renderFaces = renderFaces; - } - - private static class LightingCache implements ISimplifiedBundle - { - public final int[] aoXPos; - public final int[] aoXNeg; - public final int[] aoYPos; - public final int[] aoYNeg; - public final int[] aoZPos; - public final int[] aoZNeg; - public final float[] foXPos; - public final float[] foXNeg; - public final float[] foYPos; - public final float[] foYNeg; - public final float[] foZPos; - public final float[] foZNeg; - public IIcon rXPos; - public IIcon rXNeg; - public IIcon rYPos; - public IIcon rYNeg; - public IIcon rZPos; - public IIcon rZNeg; - public boolean isAO; - public int bXPos; - public int bXNeg; - public int bYPos; - public int bYNeg; - public int bZPos; - public int bZNeg; - public int lightHash; - - public LightingCache( final LightingCache secondCSrc ) - { - this.rXPos = secondCSrc.rXPos; - this.rXNeg = secondCSrc.rXNeg; - this.rYPos = secondCSrc.rYPos; - this.rYNeg = secondCSrc.rYNeg; - this.rZPos = secondCSrc.rZPos; - this.rZNeg = secondCSrc.rZNeg; - - this.isAO = secondCSrc.isAO; - - this.bXPos = secondCSrc.bXPos; - this.bXNeg = secondCSrc.bXNeg; - this.bYPos = secondCSrc.bYPos; - this.bYNeg = secondCSrc.bYNeg; - this.bZPos = secondCSrc.bZPos; - this.bZNeg = secondCSrc.bZNeg; - - this.aoXPos = secondCSrc.aoXPos.clone(); - this.aoXNeg = secondCSrc.aoXNeg.clone(); - this.aoYPos = secondCSrc.aoYPos.clone(); - this.aoYNeg = secondCSrc.aoYNeg.clone(); - this.aoZPos = secondCSrc.aoZPos.clone(); - this.aoZNeg = secondCSrc.aoZNeg.clone(); - - this.foXPos = secondCSrc.foXPos.clone(); - this.foXNeg = secondCSrc.foXNeg.clone(); - this.foYPos = secondCSrc.foYPos.clone(); - this.foYNeg = secondCSrc.foYNeg.clone(); - this.foZPos = secondCSrc.foZPos.clone(); - this.foZNeg = secondCSrc.foZNeg.clone(); - - this.lightHash = secondCSrc.lightHash; - } - - public LightingCache() - { - this.rXPos = null; - this.rXNeg = null; - this.rYPos = null; - this.rYNeg = null; - this.rZPos = null; - this.rZNeg = null; - - this.isAO = false; - - this.bXPos = 0; - this.bXNeg = 0; - this.bYPos = 0; - this.bYNeg = 0; - this.bZPos = 0; - this.bZNeg = 0; - - this.aoXPos = new int[5]; - this.aoXNeg = new int[5]; - this.aoYPos = new int[5]; - this.aoYNeg = new int[5]; - this.aoZPos = new int[5]; - this.aoZNeg = new int[5]; - - this.foXPos = new float[12]; - this.foXNeg = new float[12]; - this.foYPos = new float[12]; - this.foYNeg = new float[12]; - this.foZPos = new float[12]; - this.foZNeg = new float[12]; - - this.lightHash = 0; - } - } +@SideOnly(Side.CLIENT) +public class RenderBlocksWorkaround extends RenderBlocks { + + private final int[] lightHashTmp = new int[27]; + private boolean calculations = true; + private EnumSet renderFaces = EnumSet.allOf(ForgeDirection.class); + private EnumSet faces = EnumSet.allOf(ForgeDirection.class); + private boolean isFacade = false; + private boolean useTextures = true; + private float opacity = 1.0f; + private Field fBrightness = null; + private Field fColor = null; + private LightingCache lightState = new LightingCache(); + + private int getCurrentColor() { + try { + if (this.fColor == null) { + try { + this.fColor = Tessellator.class.getDeclaredField("color"); + } catch (final Throwable t) { + this.fColor = Tessellator.class.getDeclaredField("field_78402_m"); + } + this.fColor.setAccessible(true); + } + return (Integer) this.fColor.get(Tessellator.instance); + } catch (final Throwable t) { + return 0; + } + } + + private int getCurrentBrightness() { + try { + if (this.fBrightness == null) { + try { + this.fBrightness = Tessellator.class.getDeclaredField("brightness"); + } catch (final Throwable t) { + this.fBrightness = Tessellator.class.getDeclaredField("field_78401_l"); + } + this.fBrightness.setAccessible(true); + } + return (Integer) this.fBrightness.get(Tessellator.instance); + } catch (final Throwable t) { + return 0; + } + } + + void setTexture(final IIcon ico) { + this.lightState.rXPos = this.lightState.rXNeg = + this.lightState.rYPos = this.lightState.rYNeg = this.lightState.rZPos = this.lightState.rZNeg = ico; + } + + public void setTexture( + final IIcon rYNeg, + final IIcon rYPos, + final IIcon rZNeg, + final IIcon rZPos, + final IIcon rXNeg, + final IIcon rXPos) { + this.lightState.rXPos = rXPos; + this.lightState.rXNeg = rXNeg; + this.lightState.rYPos = rYPos; + this.lightState.rYNeg = rYNeg; + this.lightState.rZPos = rZPos; + this.lightState.rZNeg = rZNeg; + } + + private boolean renderStandardBlockNoCalculations(final Block b, final int x, final int y, final int z) { + Tessellator.instance.setBrightness(this.lightState.bXPos); + this.restoreAO(this.lightState.aoXPos, this.lightState.foXPos); + this.renderFaceXPos( + b, + x, + y, + z, + this.isUseTextures() + ? this.lightState.rXPos + : this.getBlockIcon(b, this.blockAccess, x, y, z, ForgeDirection.EAST.ordinal())); + + Tessellator.instance.setBrightness(this.lightState.bXNeg); + this.restoreAO(this.lightState.aoXNeg, this.lightState.foXNeg); + this.renderFaceXNeg( + b, + x, + y, + z, + this.isUseTextures() + ? this.lightState.rXNeg + : this.getBlockIcon(b, this.blockAccess, x, y, z, ForgeDirection.WEST.ordinal())); + + Tessellator.instance.setBrightness(this.lightState.bYPos); + this.restoreAO(this.lightState.aoYPos, this.lightState.foYPos); + this.renderFaceYPos( + b, + x, + y, + z, + this.isUseTextures() + ? this.lightState.rYPos + : this.getBlockIcon(b, this.blockAccess, x, y, z, ForgeDirection.UP.ordinal())); + + Tessellator.instance.setBrightness(this.lightState.bYNeg); + this.restoreAO(this.lightState.aoYNeg, this.lightState.foYNeg); + this.renderFaceYNeg( + b, + x, + y, + z, + this.isUseTextures() + ? this.lightState.rYNeg + : this.getBlockIcon(b, this.blockAccess, x, y, z, ForgeDirection.DOWN.ordinal())); + + Tessellator.instance.setBrightness(this.lightState.bZPos); + this.restoreAO(this.lightState.aoZPos, this.lightState.foZPos); + this.renderFaceZPos( + b, + x, + y, + z, + this.isUseTextures() + ? this.lightState.rZPos + : this.getBlockIcon(b, this.blockAccess, x, y, z, ForgeDirection.SOUTH.ordinal())); + + Tessellator.instance.setBrightness(this.lightState.bZNeg); + this.restoreAO(this.lightState.aoZNeg, this.lightState.foZNeg); + this.renderFaceZNeg( + b, + x, + y, + z, + this.isUseTextures() + ? this.lightState.rZNeg + : this.getBlockIcon(b, this.blockAccess, x, y, z, ForgeDirection.NORTH.ordinal())); + + return true; + } + + private void restoreAO(final int[] z, final float[] c) { + this.brightnessBottomLeft = z[0]; + this.brightnessBottomRight = z[1]; + this.brightnessTopLeft = z[2]; + this.brightnessTopRight = z[3]; + Tessellator.instance.setColorRGBA_I(z[4], (int) (this.getOpacity() * 255)); + + this.colorRedTopLeft = c[0]; + this.colorGreenTopLeft = c[1]; + this.colorBlueTopLeft = c[2]; + this.colorRedBottomLeft = c[3]; + this.colorGreenBottomLeft = c[4]; + this.colorBlueBottomLeft = c[5]; + this.colorRedBottomRight = c[6]; + this.colorGreenBottomRight = c[7]; + this.colorBlueBottomRight = c[8]; + this.colorRedTopRight = c[9]; + this.colorGreenTopRight = c[10]; + this.colorBlueTopRight = c[11]; + } + + private void saveAO(final int[] z, final float[] c) { + z[0] = this.brightnessBottomLeft; + z[1] = this.brightnessBottomRight; + z[2] = this.brightnessTopLeft; + z[3] = this.brightnessTopRight; + z[4] = this.getCurrentColor(); + + c[0] = this.colorRedTopLeft; + c[1] = this.colorGreenTopLeft; + c[2] = this.colorBlueTopLeft; + c[3] = this.colorRedBottomLeft; + c[4] = this.colorGreenBottomLeft; + c[5] = this.colorBlueBottomLeft; + c[6] = this.colorRedBottomRight; + c[7] = this.colorGreenBottomRight; + c[8] = this.colorBlueBottomRight; + c[9] = this.colorRedTopRight; + c[10] = this.colorGreenTopRight; + c[11] = this.colorBlueTopRight; + } + + @Override + public boolean renderStandardBlock(final Block blk, final int x, final int y, final int z) { + try { + if (this.isCalculations()) { + this.lightState.lightHash = this.getLightingHash(blk, this.blockAccess, x, y, z); + return super.renderStandardBlock(blk, x, y, z); + } else { + this.enableAO = this.lightState.isAO; + final boolean out = this.renderStandardBlockNoCalculations(blk, x, y, z); + this.enableAO = false; + return out; + } + } catch (final Throwable t) { + AELog.debug(t); + // meh + } + return false; + } + + @Override + public void renderFaceYNeg( + final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon) { + if (this.getFaces().contains(ForgeDirection.DOWN)) { + if (!this.getRenderFaces().contains(ForgeDirection.DOWN)) { + return; + } + + if (this.isFacade()) { + final Tessellator tessellator = Tessellator.instance; + + final double d3 = par8Icon.getInterpolatedU(this.renderMinX * 16.0D); + final double d4 = par8Icon.getInterpolatedU(this.renderMaxX * 16.0D); + final double d5 = par8Icon.getInterpolatedV(this.renderMinZ * 16.0D); + final double d6 = par8Icon.getInterpolatedV(this.renderMaxZ * 16.0D); + + final double d11 = par2 + this.renderMinX; + final double d12 = par2 + this.renderMaxX; + final double d13 = par4 + this.renderMinY; + final double d14 = par6 + this.renderMinZ; + final double d15 = par6 + this.renderMaxZ; + + if (this.enableAO) { + this.partialLightingColoring(1.0 - this.renderMinX, this.renderMaxZ); + tessellator.addVertexWithUV(d11, d13, d15, d3, d6); + this.partialLightingColoring(1.0 - this.renderMinX, this.renderMinZ); + tessellator.addVertexWithUV(d11, d13, d14, d3, d5); + this.partialLightingColoring(1.0 - this.renderMaxX, this.renderMinZ); + tessellator.addVertexWithUV(d12, d13, d14, d4, d5); + this.partialLightingColoring(1.0 - this.renderMaxX, this.renderMaxZ); + tessellator.addVertexWithUV(d12, d13, d15, d4, d6); + } else { + tessellator.addVertexWithUV(d11, d13, d15, d3, d6); + tessellator.addVertexWithUV(d11, d13, d14, d3, d5); + tessellator.addVertexWithUV(d12, d13, d14, d4, d5); + tessellator.addVertexWithUV(d12, d13, d15, d4, d6); + } + } else { + super.renderFaceYNeg(par1Block, par2, par4, par6, par8Icon); + } + } else { + this.lightState.isAO = this.enableAO; + this.lightState.rYNeg = par8Icon; + this.saveAO(this.lightState.aoYNeg, this.lightState.foYNeg); + this.lightState.bYNeg = this.getCurrentBrightness(); + } + } + + @Override + public void renderFaceYPos( + final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon) { + if (this.getFaces().contains(ForgeDirection.UP)) { + if (!this.getRenderFaces().contains(ForgeDirection.UP)) { + return; + } + + if (this.isFacade()) { + final Tessellator tessellator = Tessellator.instance; + + final double d3 = par8Icon.getInterpolatedU(this.renderMinX * 16.0D); + final double d4 = par8Icon.getInterpolatedU(this.renderMaxX * 16.0D); + final double d5 = par8Icon.getInterpolatedV(this.renderMinZ * 16.0D); + final double d6 = par8Icon.getInterpolatedV(this.renderMaxZ * 16.0D); + + final double d11 = par2 + this.renderMinX; + final double d12 = par2 + this.renderMaxX; + final double d13 = par4 + this.renderMaxY; + final double d14 = par6 + this.renderMinZ; + final double d15 = par6 + this.renderMaxZ; + + if (this.enableAO) { + this.partialLightingColoring(this.renderMaxX, this.renderMaxZ); + tessellator.addVertexWithUV(d12, d13, d15, d4, d6); + this.partialLightingColoring(this.renderMaxX, this.renderMinZ); + tessellator.addVertexWithUV(d12, d13, d14, d4, d5); + this.partialLightingColoring(this.renderMinX, this.renderMinZ); + tessellator.addVertexWithUV(d11, d13, d14, d3, d5); + this.partialLightingColoring(this.renderMinX, this.renderMaxZ); + tessellator.addVertexWithUV(d11, d13, d15, d3, d6); + } else { + tessellator.addVertexWithUV(d12, d13, d15, d4, d6); + tessellator.addVertexWithUV(d12, d13, d14, d4, d5); + tessellator.addVertexWithUV(d11, d13, d14, d3, d5); + tessellator.addVertexWithUV(d11, d13, d15, d3, d6); + } + } else { + super.renderFaceYPos(par1Block, par2, par4, par6, par8Icon); + } + } else { + this.lightState.isAO = this.enableAO; + this.lightState.rYPos = par8Icon; + this.saveAO(this.lightState.aoYPos, this.lightState.foYPos); + this.lightState.bYPos = this.getCurrentBrightness(); + } + } + + @Override + public void renderFaceZNeg( + final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon) { + if (this.getFaces().contains(ForgeDirection.NORTH)) { + if (!this.getRenderFaces().contains(ForgeDirection.NORTH)) { + return; + } + + if (this.isFacade()) { + final Tessellator tessellator = Tessellator.instance; + + final double d3 = par8Icon.getInterpolatedU(16.0D - this.renderMinX * 16.0D); + final double d4 = par8Icon.getInterpolatedU(16.0D - this.renderMaxX * 16.0D); + final double d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); + final double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); + + final double d11 = par2 + this.renderMinX; + final double d12 = par2 + this.renderMaxX; + final double d13 = par4 + this.renderMinY; + final double d14 = par4 + this.renderMaxY; + final double d15 = par6 + this.renderMinZ; + + if (this.enableAO) { + this.partialLightingColoring(this.renderMaxY, 1.0 - this.renderMinX); + tessellator.addVertexWithUV(d11, d14, d15, d3, d5); + this.partialLightingColoring(this.renderMaxY, 1.0 - this.renderMaxX); + tessellator.addVertexWithUV(d12, d14, d15, d4, d5); + this.partialLightingColoring(this.renderMinY, 1.0 - this.renderMaxX); + tessellator.addVertexWithUV(d12, d13, d15, d4, d6); + this.partialLightingColoring(this.renderMinY, 1.0 - this.renderMinX); + tessellator.addVertexWithUV(d11, d13, d15, d3, d6); + } else { + tessellator.addVertexWithUV(d11, d14, d15, d3, d5); + tessellator.addVertexWithUV(d12, d14, d15, d4, d5); + tessellator.addVertexWithUV(d12, d13, d15, d4, d6); + tessellator.addVertexWithUV(d11, d13, d15, d3, d6); + } + } else { + super.renderFaceZNeg(par1Block, par2, par4, par6, par8Icon); + } + } else { + this.lightState.isAO = this.enableAO; + this.lightState.rZNeg = par8Icon; + this.saveAO(this.lightState.aoZNeg, this.lightState.foZNeg); + this.lightState.bZNeg = this.getCurrentBrightness(); + } + } + + @Override + public void renderFaceZPos( + final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon) { + if (this.getFaces().contains(ForgeDirection.SOUTH)) { + if (!this.getRenderFaces().contains(ForgeDirection.SOUTH)) { + return; + } + + if (this.isFacade()) { + final Tessellator tessellator = Tessellator.instance; + + final double d3 = par8Icon.getInterpolatedU(this.renderMinX * 16.0D); + final double d4 = par8Icon.getInterpolatedU(this.renderMaxX * 16.0D); + final double d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); + final double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); + + final double d11 = par2 + this.renderMinX; + final double d12 = par2 + this.renderMaxX; + final double d13 = par4 + this.renderMinY; + final double d14 = par4 + this.renderMaxY; + final double d15 = par6 + this.renderMaxZ; + + if (this.enableAO) { + this.partialLightingColoring(1.0 - this.renderMinX, this.renderMaxY); + tessellator.addVertexWithUV(d11, d14, d15, d3, d5); + this.partialLightingColoring(1.0 - this.renderMinX, this.renderMinY); + tessellator.addVertexWithUV(d11, d13, d15, d3, d6); + this.partialLightingColoring(1.0 - this.renderMaxX, this.renderMinY); + tessellator.addVertexWithUV(d12, d13, d15, d4, d6); + this.partialLightingColoring(1.0 - this.renderMaxX, this.renderMaxY); + tessellator.addVertexWithUV(d12, d14, d15, d4, d5); + } else { + tessellator.addVertexWithUV(d11, d14, d15, d3, d5); + tessellator.addVertexWithUV(d11, d13, d15, d3, d6); + tessellator.addVertexWithUV(d12, d13, d15, d4, d6); + tessellator.addVertexWithUV(d12, d14, d15, d4, d5); + } + } else { + super.renderFaceZPos(par1Block, par2, par4, par6, par8Icon); + } + } else { + this.lightState.isAO = this.enableAO; + this.lightState.rZPos = par8Icon; + this.saveAO(this.lightState.aoZPos, this.lightState.foZPos); + this.lightState.bZPos = this.getCurrentBrightness(); + } + } + + @Override + public void renderFaceXNeg( + final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon) { + if (this.getFaces().contains(ForgeDirection.WEST)) { + if (!this.getRenderFaces().contains(ForgeDirection.WEST)) { + return; + } + + if (this.isFacade()) { + final Tessellator tessellator = Tessellator.instance; + + final double d3 = par8Icon.getInterpolatedU(this.renderMinZ * 16.0D); + final double d4 = par8Icon.getInterpolatedU(this.renderMaxZ * 16.0D); + final double d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); + final double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); + + final double d11 = par2 + this.renderMinX; + final double d12 = par4 + this.renderMinY; + final double d13 = par4 + this.renderMaxY; + final double d14 = par6 + this.renderMinZ; + final double d15 = par6 + this.renderMaxZ; + + if (this.enableAO) { + this.partialLightingColoring(this.renderMaxY, this.renderMaxZ); + tessellator.addVertexWithUV(d11, d13, d15, d4, d5); + this.partialLightingColoring(this.renderMaxY, this.renderMinZ); + tessellator.addVertexWithUV(d11, d13, d14, d3, d5); + this.partialLightingColoring(this.renderMinY, this.renderMinZ); + tessellator.addVertexWithUV(d11, d12, d14, d3, d6); + this.partialLightingColoring(this.renderMinY, this.renderMaxZ); + tessellator.addVertexWithUV(d11, d12, d15, d4, d6); + } else { + tessellator.addVertexWithUV(d11, d13, d15, d4, d5); + tessellator.addVertexWithUV(d11, d13, d14, d3, d5); + tessellator.addVertexWithUV(d11, d12, d14, d3, d6); + tessellator.addVertexWithUV(d11, d12, d15, d4, d6); + } + } else { + super.renderFaceXNeg(par1Block, par2, par4, par6, par8Icon); + } + } else { + this.lightState.isAO = this.enableAO; + this.lightState.rXNeg = par8Icon; + this.saveAO(this.lightState.aoXNeg, this.lightState.foXNeg); + this.lightState.bXNeg = this.getCurrentBrightness(); + } + } + + @Override + public void renderFaceXPos( + final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon) { + if (this.getFaces().contains(ForgeDirection.EAST)) { + if (!this.getRenderFaces().contains(ForgeDirection.EAST)) { + return; + } + + if (this.isFacade()) { + final Tessellator tessellator = Tessellator.instance; + + final double d3 = par8Icon.getInterpolatedU(16.0D - this.renderMinZ * 16.0D); + final double d4 = par8Icon.getInterpolatedU(16.0D - this.renderMaxZ * 16.0D); + final double d5 = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); + final double d6 = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); + + final double d11 = par2 + this.renderMaxX; + final double d12 = par4 + this.renderMinY; + final double d13 = par4 + this.renderMaxY; + final double d14 = par6 + this.renderMinZ; + final double d15 = par6 + this.renderMaxZ; + + if (this.enableAO) { + this.partialLightingColoring(1.0 - this.renderMinY, this.renderMaxZ); + tessellator.addVertexWithUV(d11, d12, d15, d4, d6); + this.partialLightingColoring(1.0 - this.renderMinY, this.renderMinZ); + tessellator.addVertexWithUV(d11, d12, d14, d3, d6); + this.partialLightingColoring(1.0 - this.renderMaxY, this.renderMinZ); + tessellator.addVertexWithUV(d11, d13, d14, d3, d5); + this.partialLightingColoring(1.0 - this.renderMaxY, this.renderMaxZ); + tessellator.addVertexWithUV(d11, d13, d15, d4, d5); + } else { + tessellator.addVertexWithUV(d11, d12, d15, d4, d6); + tessellator.addVertexWithUV(d11, d12, d14, d3, d6); + tessellator.addVertexWithUV(d11, d13, d14, d3, d5); + tessellator.addVertexWithUV(d11, d13, d15, d4, d5); + } + } else { + super.renderFaceXPos(par1Block, par2, par4, par6, par8Icon); + } + } else { + this.lightState.isAO = this.enableAO; + this.lightState.rXPos = par8Icon; + this.saveAO(this.lightState.aoXPos, this.lightState.foXPos); + this.lightState.bXPos = this.getCurrentBrightness(); + } + } + + private void partialLightingColoring(final double u, final double v) { + final double rA = this.colorRedTopLeft * u + (1.0 - u) * this.colorRedTopRight; + final double rB = this.colorRedBottomLeft * u + (1.0 - u) * this.colorRedBottomRight; + final float r = (float) (rA * v + rB * (1.0 - v)); + + final double gA = this.colorGreenTopLeft * u + (1.0 - u) * this.colorGreenTopRight; + final double gB = this.colorGreenBottomLeft * u + (1.0 - u) * this.colorGreenBottomRight; + final float g = (float) (gA * v + gB * (1.0 - v)); + + final double bA = this.colorBlueTopLeft * u + (1.0 - u) * this.colorBlueTopRight; + final double bB = this.colorBlueBottomLeft * u + (1.0 - u) * this.colorBlueBottomRight; + final float b = (float) (bA * v + bB * (1.0 - v)); + + final double highA = + (this.brightnessTopLeft >> 16 & 255) * u + (1.0 - u) * (this.brightnessTopRight >> 16 & 255); + final double highB = + (this.brightnessBottomLeft >> 16 & 255) * u + (1.0 - u) * (this.brightnessBottomRight >> 16 & 255); + final int high = ((int) (highA * v + highB * (1.0 - v))) & 255; + + final double lowA = ((this.brightnessTopLeft & 255)) * u + (1.0 - u) * ((this.brightnessTopRight & 255)); + final double lowB = ((this.brightnessBottomLeft & 255)) * u + (1.0 - u) * ((this.brightnessBottomRight & 255)); + final int low = ((int) (lowA * v + lowB * (1.0 - v))) & 255; + + final int out = (high << 16) | low; + + Tessellator.instance.setColorRGBA_F(r, g, b, this.getOpacity()); + Tessellator.instance.setBrightness(out); + } + + public boolean similarLighting( + final Block blk, final IBlockAccess w, final int x, final int y, final int z, final ISimplifiedBundle sim) { + final int lh = this.getLightingHash(blk, w, x, y, z); + return ((LightingCache) sim).lightHash == lh; + } + + private int getLightingHash(final Block blk, final IBlockAccess w, final int x, final int y, final int z) { + int o = 0; + + for (int i = -1; i <= 1; i++) { + for (int j = -1; j <= 1; j++) { + for (int k = -1; k <= 1; k++) { + + this.lightHashTmp[o] = blk.getMixedBrightnessForBlock(this.blockAccess, x + i, y + j, z + k); + o++; + } + } + } + + return Arrays.hashCode(this.lightHashTmp); + } + + public void populate(final ISimplifiedBundle sim) { + this.lightState = new LightingCache((LightingCache) sim); + } + + public ISimplifiedBundle getLightingCache() { + return new LightingCache(this.lightState); + } + + Set getFaces() { + return this.faces; + } + + public void setFaces(final EnumSet faces) { + this.faces = faces; + } + + private boolean isCalculations() { + return this.calculations; + } + + public void setCalculations(final boolean calculations) { + this.calculations = calculations; + } + + private boolean isUseTextures() { + return this.useTextures; + } + + void setUseTextures(final boolean useTextures) { + this.useTextures = useTextures; + } + + private boolean isFacade() { + return this.isFacade; + } + + public void setFacade(final boolean isFacade) { + this.isFacade = isFacade; + } + + private float getOpacity() { + return this.opacity; + } + + public void setOpacity(final float opacity) { + this.opacity = opacity; + } + + private EnumSet getRenderFaces() { + return this.renderFaces; + } + + void setRenderFaces(final EnumSet renderFaces) { + this.renderFaces = renderFaces; + } + + private static class LightingCache implements ISimplifiedBundle { + public final int[] aoXPos; + public final int[] aoXNeg; + public final int[] aoYPos; + public final int[] aoYNeg; + public final int[] aoZPos; + public final int[] aoZNeg; + public final float[] foXPos; + public final float[] foXNeg; + public final float[] foYPos; + public final float[] foYNeg; + public final float[] foZPos; + public final float[] foZNeg; + public IIcon rXPos; + public IIcon rXNeg; + public IIcon rYPos; + public IIcon rYNeg; + public IIcon rZPos; + public IIcon rZNeg; + public boolean isAO; + public int bXPos; + public int bXNeg; + public int bYPos; + public int bYNeg; + public int bZPos; + public int bZNeg; + public int lightHash; + + public LightingCache(final LightingCache secondCSrc) { + this.rXPos = secondCSrc.rXPos; + this.rXNeg = secondCSrc.rXNeg; + this.rYPos = secondCSrc.rYPos; + this.rYNeg = secondCSrc.rYNeg; + this.rZPos = secondCSrc.rZPos; + this.rZNeg = secondCSrc.rZNeg; + + this.isAO = secondCSrc.isAO; + + this.bXPos = secondCSrc.bXPos; + this.bXNeg = secondCSrc.bXNeg; + this.bYPos = secondCSrc.bYPos; + this.bYNeg = secondCSrc.bYNeg; + this.bZPos = secondCSrc.bZPos; + this.bZNeg = secondCSrc.bZNeg; + + this.aoXPos = secondCSrc.aoXPos.clone(); + this.aoXNeg = secondCSrc.aoXNeg.clone(); + this.aoYPos = secondCSrc.aoYPos.clone(); + this.aoYNeg = secondCSrc.aoYNeg.clone(); + this.aoZPos = secondCSrc.aoZPos.clone(); + this.aoZNeg = secondCSrc.aoZNeg.clone(); + + this.foXPos = secondCSrc.foXPos.clone(); + this.foXNeg = secondCSrc.foXNeg.clone(); + this.foYPos = secondCSrc.foYPos.clone(); + this.foYNeg = secondCSrc.foYNeg.clone(); + this.foZPos = secondCSrc.foZPos.clone(); + this.foZNeg = secondCSrc.foZNeg.clone(); + + this.lightHash = secondCSrc.lightHash; + } + + public LightingCache() { + this.rXPos = null; + this.rXNeg = null; + this.rYPos = null; + this.rYNeg = null; + this.rZPos = null; + this.rZNeg = null; + + this.isAO = false; + + this.bXPos = 0; + this.bXNeg = 0; + this.bYPos = 0; + this.bYNeg = 0; + this.bZPos = 0; + this.bZNeg = 0; + + this.aoXPos = new int[5]; + this.aoXNeg = new int[5]; + this.aoYPos = new int[5]; + this.aoYNeg = new int[5]; + this.aoZPos = new int[5]; + this.aoZNeg = new int[5]; + + this.foXPos = new float[12]; + this.foXNeg = new float[12]; + this.foYPos = new float[12]; + this.foYNeg = new float[12]; + this.foZPos = new float[12]; + this.foZNeg = new float[12]; + + this.lightHash = 0; + } + } } diff --git a/src/main/java/appeng/client/render/SpatialSkyRender.java b/src/main/java/appeng/client/render/SpatialSkyRender.java index 66e04cba171..a4683f58abb 100644 --- a/src/main/java/appeng/client/render/SpatialSkyRender.java +++ b/src/main/java/appeng/client/render/SpatialSkyRender.java @@ -18,7 +18,7 @@ package appeng.client.render; - +import java.util.Random; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.renderer.GLAllocation; @@ -28,162 +28,147 @@ import net.minecraftforge.client.IRenderHandler; import org.lwjgl.opengl.GL11; -import java.util.Random; - - -public class SpatialSkyRender extends IRenderHandler -{ - - private static final SpatialSkyRender INSTANCE = new SpatialSkyRender(); - - private final Random random = new Random(); - private final int dspList; - private long cycle = 0; - - public SpatialSkyRender() - { - this.dspList = GLAllocation.generateDisplayLists( 1 ); - } - - public static IRenderHandler getInstance() - { - return INSTANCE; - } - - @Override - public void render( final float partialTicks, final WorldClient world, final Minecraft mc ) - { - final long now = System.currentTimeMillis(); - - if( now - this.cycle > 2000 ) - { - this.cycle = now; - GL11.glNewList( this.dspList, GL11.GL_COMPILE ); - this.renderTwinkles(); - GL11.glEndList(); - } - - float fade = now - this.cycle; - fade /= 1000; - fade = 0.15f * ( 1.0f - Math.abs( ( fade - 1.0f ) * ( fade - 1.0f ) ) ); - - GL11.glDisable( GL11.GL_FOG ); - GL11.glDisable( GL11.GL_ALPHA_TEST ); - GL11.glDisable( GL11.GL_BLEND ); - GL11.glDepthMask( false ); - GL11.glColor4f( 0.0f, 0.0f, 0.0f, 1.0f ); - - final Tessellator tessellator = Tessellator.instance; - - for( int i = 0; i < 6; ++i ) - { - GL11.glPushMatrix(); - - switch( i ) - { - case 1: - GL11.glRotatef( 90.0F, 1.0F, 0.0F, 0.0F ); - break; - case 2: - GL11.glRotatef( -90.0F, 1.0F, 0.0F, 0.0F ); - break; - case 3: - GL11.glRotatef( 180.0F, 1.0F, 0.0F, 0.0F ); - break; - case 4: - GL11.glRotatef( 90.0F, 0.0F, 0.0F, 1.0F ); - break; - case 5: - GL11.glRotatef( -90.0F, 0.0F, 0.0F, 1.0F ); - break; - default: - break; - } - - tessellator.startDrawingQuads(); - tessellator.setColorOpaque_I( 0 ); - tessellator.addVertexWithUV( -100.0D, -100.0D, -100.0D, 0.0D, 0.0D ); - tessellator.addVertexWithUV( -100.0D, -100.0D, 100.0D, 0.0D, 16.0D ); - tessellator.addVertexWithUV( 100.0D, -100.0D, 100.0D, 16.0D, 16.0D ); - tessellator.addVertexWithUV( 100.0D, -100.0D, -100.0D, 16.0D, 0.0D ); - tessellator.draw(); - - GL11.glPopMatrix(); - } - - if( fade > 0.0f ) - { - GL11.glEnable( GL11.GL_BLEND ); - GL11.glDisable( GL11.GL_TEXTURE_2D ); - - OpenGlHelper.glBlendFunc( 770, 771, 1, 0 ); - RenderHelper.disableStandardItemLighting(); - - GL11.glEnable( GL11.GL_TEXTURE_2D ); - GL11.glColor4f( fade, fade, fade, 1.0f ); - GL11.glCallList( this.dspList ); - - RenderHelper.enableStandardItemLighting(); - } - - GL11.glEnable( GL11.GL_FOG ); - GL11.glEnable( GL11.GL_ALPHA_TEST ); - GL11.glEnable( GL11.GL_BLEND ); - GL11.glDepthMask( true ); - - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - } - - private void renderTwinkles() - { - final Tessellator tessellator = Tessellator.instance; - tessellator.startDrawingQuads(); - - for( int i = 0; i < 50; ++i ) - { - double iX = this.random.nextFloat() * 2.0F - 1.0F; - double iY = this.random.nextFloat() * 2.0F - 1.0F; - double iZ = this.random.nextFloat() * 2.0F - 1.0F; - final double d3 = 0.05F + this.random.nextFloat() * 0.1F; - double dist = iX * iX + iY * iY + iZ * iZ; - - if( dist < 1.0D && dist > 0.01D ) - { - dist = 1.0D / Math.sqrt( dist ); - iX *= dist; - iY *= dist; - iZ *= dist; - - final double x = iX * 100.0D; - final double y = iY * 100.0D; - final double z = iZ * 100.0D; - final double d8 = Math.atan2( iX, iZ ); - final double d9 = Math.sin( d8 ); - final double d10 = Math.cos( d8 ); - final double d11 = Math.atan2( Math.sqrt( iX * iX + iZ * iZ ), iY ); - final double d12 = Math.sin( d11 ); - final double d13 = Math.cos( d11 ); - final double d14 = this.random.nextDouble() * Math.PI * 2.0D; - final double d15 = Math.sin( d14 ); - final double d16 = Math.cos( d14 ); - - for( int j = 0; j < 4; ++j ) - { - final double d17 = 0.0D; - final double d18 = ( ( j & 2 ) - 1 ) * d3; - final double d19 = ( ( j + 1 & 2 ) - 1 ) * d3; - final double d20 = d18 * d16 - d19 * d15; - final double d21 = d19 * d16 + d18 * d15; - final double d22 = d20 * d12 + d17 * d13; - final double d23 = d17 * d12 - d20 * d13; - final double d24 = d23 * d9 - d21 * d10; - final double d25 = d21 * d9 + d23 * d10; - - tessellator.addVertex( x + d24, y + d22, z + d25 ); - } - } - } - - tessellator.draw(); - } +public class SpatialSkyRender extends IRenderHandler { + + private static final SpatialSkyRender INSTANCE = new SpatialSkyRender(); + + private final Random random = new Random(); + private final int dspList; + private long cycle = 0; + + public SpatialSkyRender() { + this.dspList = GLAllocation.generateDisplayLists(1); + } + + public static IRenderHandler getInstance() { + return INSTANCE; + } + + @Override + public void render(final float partialTicks, final WorldClient world, final Minecraft mc) { + final long now = System.currentTimeMillis(); + + if (now - this.cycle > 2000) { + this.cycle = now; + GL11.glNewList(this.dspList, GL11.GL_COMPILE); + this.renderTwinkles(); + GL11.glEndList(); + } + + float fade = now - this.cycle; + fade /= 1000; + fade = 0.15f * (1.0f - Math.abs((fade - 1.0f) * (fade - 1.0f))); + + GL11.glDisable(GL11.GL_FOG); + GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glDisable(GL11.GL_BLEND); + GL11.glDepthMask(false); + GL11.glColor4f(0.0f, 0.0f, 0.0f, 1.0f); + + final Tessellator tessellator = Tessellator.instance; + + for (int i = 0; i < 6; ++i) { + GL11.glPushMatrix(); + + switch (i) { + case 1: + GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F); + break; + case 2: + GL11.glRotatef(-90.0F, 1.0F, 0.0F, 0.0F); + break; + case 3: + GL11.glRotatef(180.0F, 1.0F, 0.0F, 0.0F); + break; + case 4: + GL11.glRotatef(90.0F, 0.0F, 0.0F, 1.0F); + break; + case 5: + GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F); + break; + default: + break; + } + + tessellator.startDrawingQuads(); + tessellator.setColorOpaque_I(0); + tessellator.addVertexWithUV(-100.0D, -100.0D, -100.0D, 0.0D, 0.0D); + tessellator.addVertexWithUV(-100.0D, -100.0D, 100.0D, 0.0D, 16.0D); + tessellator.addVertexWithUV(100.0D, -100.0D, 100.0D, 16.0D, 16.0D); + tessellator.addVertexWithUV(100.0D, -100.0D, -100.0D, 16.0D, 0.0D); + tessellator.draw(); + + GL11.glPopMatrix(); + } + + if (fade > 0.0f) { + GL11.glEnable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_TEXTURE_2D); + + OpenGlHelper.glBlendFunc(770, 771, 1, 0); + RenderHelper.disableStandardItemLighting(); + + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(fade, fade, fade, 1.0f); + GL11.glCallList(this.dspList); + + RenderHelper.enableStandardItemLighting(); + } + + GL11.glEnable(GL11.GL_FOG); + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_BLEND); + GL11.glDepthMask(true); + + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } + + private void renderTwinkles() { + final Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + + for (int i = 0; i < 50; ++i) { + double iX = this.random.nextFloat() * 2.0F - 1.0F; + double iY = this.random.nextFloat() * 2.0F - 1.0F; + double iZ = this.random.nextFloat() * 2.0F - 1.0F; + final double d3 = 0.05F + this.random.nextFloat() * 0.1F; + double dist = iX * iX + iY * iY + iZ * iZ; + + if (dist < 1.0D && dist > 0.01D) { + dist = 1.0D / Math.sqrt(dist); + iX *= dist; + iY *= dist; + iZ *= dist; + + final double x = iX * 100.0D; + final double y = iY * 100.0D; + final double z = iZ * 100.0D; + final double d8 = Math.atan2(iX, iZ); + final double d9 = Math.sin(d8); + final double d10 = Math.cos(d8); + final double d11 = Math.atan2(Math.sqrt(iX * iX + iZ * iZ), iY); + final double d12 = Math.sin(d11); + final double d13 = Math.cos(d11); + final double d14 = this.random.nextDouble() * Math.PI * 2.0D; + final double d15 = Math.sin(d14); + final double d16 = Math.cos(d14); + + for (int j = 0; j < 4; ++j) { + final double d17 = 0.0D; + final double d18 = ((j & 2) - 1) * d3; + final double d19 = ((j + 1 & 2) - 1) * d3; + final double d20 = d18 * d16 - d19 * d15; + final double d21 = d19 * d16 + d18 * d15; + final double d22 = d20 * d12 + d17 * d13; + final double d23 = d17 * d12 - d20 * d13; + final double d24 = d23 * d9 - d21 * d10; + final double d25 = d21 * d9 + d23 * d10; + + tessellator.addVertex(x + d24, y + d22, z + d25); + } + } + } + + tessellator.draw(); + } } diff --git a/src/main/java/appeng/client/render/TESRWrapper.java b/src/main/java/appeng/client/render/TESRWrapper.java index 57347f9bece..1be13e73fae 100644 --- a/src/main/java/appeng/client/render/TESRWrapper.java +++ b/src/main/java/appeng/client/render/TESRWrapper.java @@ -18,7 +18,6 @@ package appeng.client.render; - import appeng.block.AEBaseBlock; import appeng.core.AELog; import appeng.tile.AEBaseTile; @@ -31,55 +30,49 @@ import net.minecraft.tileentity.TileEntity; import org.lwjgl.opengl.GL11; +@SideOnly(Side.CLIENT) +public class TESRWrapper extends TileEntitySpecialRenderer { -@SideOnly( Side.CLIENT ) -public class TESRWrapper extends TileEntitySpecialRenderer -{ - - private final RenderBlocks renderBlocksInstance = new RenderBlocks(); + private final RenderBlocks renderBlocksInstance = new RenderBlocks(); - private final BaseBlockRender blkRender; - private final double maxDistance; + private final BaseBlockRender blkRender; + private final double maxDistance; - public TESRWrapper( final BaseBlockRender render ) - { - this.blkRender = render; - this.maxDistance = this.blkRender.getTesrRenderDistance(); - } + public TESRWrapper(final BaseBlockRender render) { + this.blkRender = render; + this.maxDistance = this.blkRender.getTesrRenderDistance(); + } - @Override - public final void renderTileEntityAt( final TileEntity te, final double x, final double y, final double z, final float f ) - { - if( te instanceof AEBaseTile ) - { - final Block b = te.getBlockType(); + @Override + public final void renderTileEntityAt( + final TileEntity te, final double x, final double y, final double z, final float f) { + if (te instanceof AEBaseTile) { + final Block b = te.getBlockType(); - if( b instanceof AEBaseBlock && ( (AEBaseTile) te ).requiresTESR() ) - { - if( Math.abs( x ) > this.maxDistance || Math.abs( y ) > this.maxDistance || Math.abs( z ) > this.maxDistance ) - { - return; - } + if (b instanceof AEBaseBlock && ((AEBaseTile) te).requiresTESR()) { + if (Math.abs(x) > this.maxDistance + || Math.abs(y) > this.maxDistance + || Math.abs(z) > this.maxDistance) { + return; + } - final Tessellator tess = Tessellator.instance; + final Tessellator tess = Tessellator.instance; - try - { - GL11.glPushMatrix(); + try { + GL11.glPushMatrix(); - this.renderBlocksInstance.blockAccess = te.getWorldObj(); - this.blkRender.renderTile( (AEBaseBlock) b, (AEBaseTile) te, tess, x, y, z, f, this.renderBlocksInstance ); + this.renderBlocksInstance.blockAccess = te.getWorldObj(); + this.blkRender.renderTile( + (AEBaseBlock) b, (AEBaseTile) te, tess, x, y, z, f, this.renderBlocksInstance); - GL11.glPopMatrix(); - } - catch( final Throwable t ) - { - AELog.error( "Hi, Looks like there was a crash while rendering something..." ); - t.printStackTrace(); - AELog.error( "MC will now crash ( probably )!" ); - throw new IllegalStateException( t ); - } - } - } - } + GL11.glPopMatrix(); + } catch (final Throwable t) { + AELog.error("Hi, Looks like there was a crash while rendering something..."); + t.printStackTrace(); + AELog.error("MC will now crash ( probably )!"); + throw new IllegalStateException(t); + } + } + } + } } diff --git a/src/main/java/appeng/client/render/WorldRender.java b/src/main/java/appeng/client/render/WorldRender.java index d93cf0a0d46..e4f881865ee 100644 --- a/src/main/java/appeng/client/render/WorldRender.java +++ b/src/main/java/appeng/client/render/WorldRender.java @@ -18,94 +18,87 @@ package appeng.client.render; - import appeng.block.AEBaseBlock; import appeng.core.AELog; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import cpw.mods.fml.client.registry.RenderingRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.HashMap; +import java.util.Map; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; -import java.util.HashMap; -import java.util.Map; - - -@SideOnly( Side.CLIENT ) -public final class WorldRender implements ISimpleBlockRenderingHandler -{ - - public static final WorldRender INSTANCE = new WorldRender(); - private final Map blockRenders = new HashMap(); - private final int renderID = RenderingRegistry.getNextAvailableRenderId(); - private final RenderBlocks renderer = new RenderBlocks(); - private boolean hasError = false; - - private WorldRender() - { - } - - void setRender( final AEBaseBlock in, final BaseBlockRender r ) - { - this.blockRenders.put( in, r ); - } - - @Override - public void renderInventoryBlock( final Block block, final int metadata, final int modelID, final RenderBlocks renderer ) - { - // wtf is this for? - } - - @Override - public boolean renderWorldBlock( final IBlockAccess world, final int x, final int y, final int z, final Block block, final int modelId, final RenderBlocks renderer ) - { - final AEBaseBlock blk = (AEBaseBlock) block; - renderer.setRenderBoundsFromBlock( block ); - return this.getRender( blk ).renderInWorld( blk, world, x, y, z, renderer ); - } - - @Override - public boolean shouldRender3DInInventory( final int modelId ) - { - return true; - } - - @Override - public int getRenderId() - { - return this.renderID; - } - - private BaseBlockRender getRender( final AEBaseBlock block ) - { - return block.getRendererInstance().getRendererInstance(); - } - - void renderItemBlock( final ItemStack item, final ItemRenderType type, final Object[] data ) - { - final Block blk = Block.getBlockFromItem( item.getItem() ); - if( blk instanceof AEBaseBlock ) - { - final AEBaseBlock block = (AEBaseBlock) blk; - this.renderer.setRenderBoundsFromBlock( block ); - - this.renderer.uvRotateBottom = this.renderer.uvRotateEast = this.renderer.uvRotateNorth = this.renderer.uvRotateSouth = this.renderer.uvRotateTop = this.renderer.uvRotateWest = 0; - this.getRender( block ).renderInventory( block, item, this.renderer, type, data ); - this.renderer.uvRotateBottom = this.renderer.uvRotateEast = this.renderer.uvRotateNorth = this.renderer.uvRotateSouth = this.renderer.uvRotateTop = this.renderer.uvRotateWest = 0; - } - else - { - if( !this.hasError ) - { - this.hasError = true; - AELog.error( "Invalid render - item/block mismatch" ); - AELog.error( " item: " + item.getUnlocalizedName() ); - AELog.error( " block: " + blk.getUnlocalizedName() ); - } - } - } +@SideOnly(Side.CLIENT) +public final class WorldRender implements ISimpleBlockRenderingHandler { + + public static final WorldRender INSTANCE = new WorldRender(); + private final Map blockRenders = new HashMap(); + private final int renderID = RenderingRegistry.getNextAvailableRenderId(); + private final RenderBlocks renderer = new RenderBlocks(); + private boolean hasError = false; + + private WorldRender() {} + + void setRender(final AEBaseBlock in, final BaseBlockRender r) { + this.blockRenders.put(in, r); + } + + @Override + public void renderInventoryBlock( + final Block block, final int metadata, final int modelID, final RenderBlocks renderer) { + // wtf is this for? + } + + @Override + public boolean renderWorldBlock( + final IBlockAccess world, + final int x, + final int y, + final int z, + final Block block, + final int modelId, + final RenderBlocks renderer) { + final AEBaseBlock blk = (AEBaseBlock) block; + renderer.setRenderBoundsFromBlock(block); + return this.getRender(blk).renderInWorld(blk, world, x, y, z, renderer); + } + + @Override + public boolean shouldRender3DInInventory(final int modelId) { + return true; + } + + @Override + public int getRenderId() { + return this.renderID; + } + + private BaseBlockRender getRender(final AEBaseBlock block) { + return block.getRendererInstance().getRendererInstance(); + } + + void renderItemBlock(final ItemStack item, final ItemRenderType type, final Object[] data) { + final Block blk = Block.getBlockFromItem(item.getItem()); + if (blk instanceof AEBaseBlock) { + final AEBaseBlock block = (AEBaseBlock) blk; + this.renderer.setRenderBoundsFromBlock(block); + + this.renderer.uvRotateBottom = this.renderer.uvRotateEast = this.renderer.uvRotateNorth = + this.renderer.uvRotateSouth = this.renderer.uvRotateTop = this.renderer.uvRotateWest = 0; + this.getRender(block).renderInventory(block, item, this.renderer, type, data); + this.renderer.uvRotateBottom = this.renderer.uvRotateEast = this.renderer.uvRotateNorth = + this.renderer.uvRotateSouth = this.renderer.uvRotateTop = this.renderer.uvRotateWest = 0; + } else { + if (!this.hasError) { + this.hasError = true; + AELog.error("Invalid render - item/block mismatch"); + AELog.error(" item: " + item.getUnlocalizedName()); + AELog.error(" block: " + blk.getUnlocalizedName()); + } + } + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockAssembler.java b/src/main/java/appeng/client/render/blocks/RenderBlockAssembler.java index a08e060e5fd..440032b0e7e 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockAssembler.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockAssembler.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.api.networking.IGridHost; import appeng.api.parts.IBoxProvider; import appeng.api.parts.IPart; @@ -34,6 +33,7 @@ import appeng.parts.networking.PartCable; import appeng.tile.crafting.TileMolecularAssembler; import appeng.util.Platform; +import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.item.ItemStack; @@ -43,250 +43,292 @@ import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class RenderBlockAssembler extends BaseBlockRender implements IBoxProvider -{ - - public RenderBlockAssembler() - { - super( false, 20 ); - } - - @Override - public void renderInventory( final BlockMolecularAssembler blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - renderer.setOverrideBlockTexture( blk.getIcon( 0, 0 ) ); - - this.setInvRenderBounds( renderer, 2, 14, 0, 14, 16, 2 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); - - this.setInvRenderBounds( renderer, 0, 14, 2, 2, 16, 14 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); - - this.setInvRenderBounds( renderer, 2, 0, 14, 14, 2, 16 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); - - this.setInvRenderBounds( renderer, 14, 0, 2, 16, 2, 14 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); - - this.setInvRenderBounds( renderer, 0, 0, 0, 16, 2, 2 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); - - this.setInvRenderBounds( renderer, 0, 2, 0, 2, 16, 2 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); - - this.setInvRenderBounds( renderer, 0, 0, 2, 2, 2, 16 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); - - this.setInvRenderBounds( renderer, 0, 14, 14, 16, 16, 16 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); - - this.setInvRenderBounds( renderer, 14, 0, 14, 16, 14, 16 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); - - this.setInvRenderBounds( renderer, 14, 14, 0, 16, 16, 14 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); - - this.setInvRenderBounds( renderer, 14, 2, 0, 16, 14, 2 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); +public class RenderBlockAssembler extends BaseBlockRender + implements IBoxProvider { - this.setInvRenderBounds( renderer, 0, 2, 14, 2, 14, 16 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); + public RenderBlockAssembler() { + super(false, 20); + } - this.setInvRenderBounds( renderer, 1, 1, 1, 15, 15, 15 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); + @Override + public void renderInventory( + final BlockMolecularAssembler blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + renderer.setOverrideBlockTexture(blk.getIcon(0, 0)); - renderer.setOverrideBlockTexture( null ); - } + this.setInvRenderBounds(renderer, 2, 14, 0, 14, 16, 2); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, Tessellator.instance, 0xffffff, renderer); - @Override - public boolean renderInWorld( final BlockMolecularAssembler maBlock, final IBlockAccess world, final int x, final int y, final int z, RenderBlocks renderer ) - { - final TileMolecularAssembler tma = maBlock.getTileEntity( world, x, y, z ); + this.setInvRenderBounds(renderer, 0, 14, 2, 2, 16, 14); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, Tessellator.instance, 0xffffff, renderer); - if( BlockMolecularAssembler.isBooleanAlphaPass() ) - { - if( tma.isPowered() ) - { - this.renderBlockBounds( renderer, 1, 1, 1, 15, 15, 15, ForgeDirection.WEST, ForgeDirection.UP, ForgeDirection.SOUTH ); - final TaughtIcon lights = new TaughtIcon( ExtraBlockTextures.BlockMolecularAssemblerLights.getIcon(), -2.0f ); - Tessellator.instance.setColorRGBA_F( 1, 1, 1, 0.3f ); - Tessellator.instance.setBrightness( 14 << 20 | 14 << 4 ); - renderer.renderFaceXNeg( maBlock, x, y, z, lights ); - renderer.renderFaceXPos( maBlock, x, y, z, lights ); - renderer.renderFaceYNeg( maBlock, x, y, z, lights ); - renderer.renderFaceYPos( maBlock, x, y, z, lights ); - renderer.renderFaceZNeg( maBlock, x, y, z, lights ); - renderer.renderFaceZPos( maBlock, x, y, z, lights ); - return true; - } - return false; - } + this.setInvRenderBounds(renderer, 2, 0, 14, 14, 2, 16); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, Tessellator.instance, 0xffffff, renderer); - BusRenderer.INSTANCE.getRenderer().blockAccess = renderer.blockAccess; - renderer = BusRenderer.INSTANCE.getRenderer(); + this.setInvRenderBounds(renderer, 14, 0, 2, 16, 2, 14); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, Tessellator.instance, 0xffffff, renderer); - this.preRenderInWorld( maBlock, world, x, y, z, renderer ); + this.setInvRenderBounds(renderer, 0, 0, 0, 16, 2, 2); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, Tessellator.instance, 0xffffff, renderer); - tma.setLightCache( BusRenderHelper.INSTANCE.useSimplifiedRendering( x, y, z, this, tma.getLightCache() ) ); + this.setInvRenderBounds(renderer, 0, 2, 0, 2, 16, 2); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, Tessellator.instance, 0xffffff, renderer); - BusRenderer.INSTANCE.getRenderer().setFacade( true ); - final IOrientable te = this.getOrientable( maBlock, world, x, y, z ); + this.setInvRenderBounds(renderer, 0, 0, 2, 2, 2, 16); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, Tessellator.instance, 0xffffff, renderer); - final ForgeDirection fdy = te.getUp(); - final ForgeDirection fdz = te.getForward(); - final ForgeDirection fdx = Platform.crossProduct( fdz, fdy ).getOpposite(); + this.setInvRenderBounds(renderer, 0, 14, 14, 16, 16, 16); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, Tessellator.instance, 0xffffff, renderer); - renderer.renderAllFaces = true; + this.setInvRenderBounds(renderer, 14, 0, 14, 16, 14, 16); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, Tessellator.instance, 0xffffff, renderer); - this.renderCableAt( 0.11D, world, x, y, z, maBlock, renderer, 0.141D, false ); - this.renderCableAt( 0.188D, world, x, y, z, maBlock, renderer, 0.1875D, true ); + this.setInvRenderBounds(renderer, 14, 14, 0, 16, 16, 14); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, Tessellator.instance, 0xffffff, renderer); - maBlock.getRendererInstance().setTemporaryRenderIcon( maBlock.getIcon( 0, 0 ) ); + this.setInvRenderBounds(renderer, 14, 2, 0, 16, 14, 2); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, Tessellator.instance, 0xffffff, renderer); - this.renderBlockBounds( renderer, 2, 14, 0, 14, 16, 2, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + this.setInvRenderBounds(renderer, 0, 2, 14, 2, 14, 16); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, Tessellator.instance, 0xffffff, renderer); - this.renderBlockBounds( renderer, 0, 14, 2, 2, 16, 14, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + this.setInvRenderBounds(renderer, 1, 1, 1, 15, 15, 15); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, Tessellator.instance, 0xffffff, renderer); - this.renderBlockBounds( renderer, 2, 0, 14, 14, 2, 16, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + renderer.setOverrideBlockTexture(null); + } - this.renderBlockBounds( renderer, 14, 0, 2, 16, 2, 14, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + @Override + public boolean renderInWorld( + final BlockMolecularAssembler maBlock, + final IBlockAccess world, + final int x, + final int y, + final int z, + RenderBlocks renderer) { + final TileMolecularAssembler tma = maBlock.getTileEntity(world, x, y, z); - // sides... - this.renderBlockBounds( renderer, 0, 0, 0, 16, 2, 2, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + if (BlockMolecularAssembler.isBooleanAlphaPass()) { + if (tma.isPowered()) { + this.renderBlockBounds( + renderer, 1, 1, 1, 15, 15, 15, ForgeDirection.WEST, ForgeDirection.UP, ForgeDirection.SOUTH); + final TaughtIcon lights = + new TaughtIcon(ExtraBlockTextures.BlockMolecularAssemblerLights.getIcon(), -2.0f); + Tessellator.instance.setColorRGBA_F(1, 1, 1, 0.3f); + Tessellator.instance.setBrightness(14 << 20 | 14 << 4); + renderer.renderFaceXNeg(maBlock, x, y, z, lights); + renderer.renderFaceXPos(maBlock, x, y, z, lights); + renderer.renderFaceYNeg(maBlock, x, y, z, lights); + renderer.renderFaceYPos(maBlock, x, y, z, lights); + renderer.renderFaceZNeg(maBlock, x, y, z, lights); + renderer.renderFaceZPos(maBlock, x, y, z, lights); + return true; + } + return false; + } - this.renderBlockBounds( renderer, 0, 2, 0, 2, 16, 2, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + BusRenderer.INSTANCE.getRenderer().blockAccess = renderer.blockAccess; + renderer = BusRenderer.INSTANCE.getRenderer(); - this.renderBlockBounds( renderer, 0, 0, 2, 2, 2, 16, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + this.preRenderInWorld(maBlock, world, x, y, z, renderer); - this.renderBlockBounds( renderer, 0, 14, 14, 16, 16, 16, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + tma.setLightCache(BusRenderHelper.INSTANCE.useSimplifiedRendering(x, y, z, this, tma.getLightCache())); - this.renderBlockBounds( renderer, 14, 0, 14, 16, 14, 16, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); - - this.renderBlockBounds( renderer, 14, 14, 0, 16, 16, 14, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); - - this.renderBlockBounds( renderer, 14, 2, 0, 16, 14, 2, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); - - this.renderBlockBounds( renderer, 0, 2, 14, 2, 14, 16, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); - - this.renderBlockBounds( renderer, 1, 1, 1, 15, 15, 15, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); - - BusRenderHelper.INSTANCE.normalRendering(); - - maBlock.getRendererInstance().setTemporaryRenderIcon( null ); - - renderer.renderAllFaces = false; - BusRenderer.INSTANCE.getRenderer().setFacade( false ); - - this.postRenderInWorld( renderer ); - - return true; - } - - private void renderCableAt( final double thickness, final IBlockAccess world, final int x, final int y, final int z, final BlockMolecularAssembler block, final RenderBlocks renderer, final double pull, final boolean covered ) - { - IIcon texture = null; - - texture = this.getConnectedCable( world, x, y, z, ForgeDirection.WEST, covered ); - block.getRendererInstance().setTemporaryRenderIcon( texture ); - if( texture != null ) - { - renderer.setRenderBounds( 0.0D, 0.5D - thickness, 0.5D - thickness, 0.5D - thickness - pull, 0.5D + thickness, 0.5D + thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - texture = this.getConnectedCable( world, x, y, z, ForgeDirection.EAST, covered ); - block.getRendererInstance().setTemporaryRenderIcon( texture ); - if( texture != null ) - { - renderer.setRenderBounds( 0.5D + thickness + pull, 0.5D - thickness, 0.5D - thickness, 1.0D, 0.5D + thickness, 0.5D + thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - texture = this.getConnectedCable( world, x, y, z, ForgeDirection.NORTH, covered ); - block.getRendererInstance().setTemporaryRenderIcon( texture ); - if( texture != null ) - { - renderer.setRenderBounds( 0.5D - thickness, 0.5D - thickness, 0.0D, 0.5D + thickness, 0.5D + thickness, 0.5D - thickness - pull ); - renderer.renderStandardBlock( block, x, y, z ); - } - - texture = this.getConnectedCable( world, x, y, z, ForgeDirection.SOUTH, covered ); - block.getRendererInstance().setTemporaryRenderIcon( texture ); - if( texture != null ) - { - renderer.setRenderBounds( 0.5D - thickness, 0.5D - thickness, 0.5D + thickness + pull, 0.5D + thickness, 0.5D + thickness, 1.0D ); - renderer.renderStandardBlock( block, x, y, z ); - } - - texture = this.getConnectedCable( world, x, y, z, ForgeDirection.DOWN, covered ); - block.getRendererInstance().setTemporaryRenderIcon( texture ); - if( texture != null ) - { - renderer.setRenderBounds( 0.5D - thickness, 0.0D, 0.5D - thickness, 0.5D + thickness, 0.5D - thickness - pull, 0.5D + thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - texture = this.getConnectedCable( world, x, y, z, ForgeDirection.UP, covered ); - block.getRendererInstance().setTemporaryRenderIcon( texture ); - if( texture != null ) - { - renderer.setRenderBounds( 0.5D - thickness, 0.5D + thickness + pull, 0.5D - thickness, 0.5D + thickness, 1.0D, 0.5D + thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - block.getRendererInstance().setTemporaryRenderIcon( null ); - } - - private IIcon getConnectedCable( final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection side, final boolean covered ) - { - final int tileYPos = y + side.offsetY; - - if( -1 < tileYPos && tileYPos < 256 ) - { - final TileEntity ne = world.getTileEntity( x + side.offsetX, tileYPos, z + side.offsetZ ); - if( ne instanceof IGridHost && ne instanceof IPartHost ) - { - final IPartHost ph = (IPartHost) ne; - final IPart pcx = ph.getPart( ForgeDirection.UNKNOWN ); - - if( pcx instanceof PartCable ) - { - final PartCable pc = (PartCable) pcx; - - if( pc.isConnected( side.getOpposite() ) ) - { - if( covered ) - { - return pc.getCoveredTexture( pc.getCableColor() ); - } - return pc.getGlassTexture( pc.getCableColor() ); - } - } - } - } - - return null; - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 0, 0, 0, 16, 16, 16 ); - } + BusRenderer.INSTANCE.getRenderer().setFacade(true); + final IOrientable te = this.getOrientable(maBlock, world, x, y, z); + + final ForgeDirection fdy = te.getUp(); + final ForgeDirection fdz = te.getForward(); + final ForgeDirection fdx = Platform.crossProduct(fdz, fdy).getOpposite(); + + renderer.renderAllFaces = true; + + this.renderCableAt(0.11D, world, x, y, z, maBlock, renderer, 0.141D, false); + this.renderCableAt(0.188D, world, x, y, z, maBlock, renderer, 0.1875D, true); + + maBlock.getRendererInstance().setTemporaryRenderIcon(maBlock.getIcon(0, 0)); + + this.renderBlockBounds(renderer, 2, 14, 0, 14, 16, 2, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); + + this.renderBlockBounds(renderer, 0, 14, 2, 2, 16, 14, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); + + this.renderBlockBounds(renderer, 2, 0, 14, 14, 2, 16, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); + + this.renderBlockBounds(renderer, 14, 0, 2, 16, 2, 14, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); + + // sides... + this.renderBlockBounds(renderer, 0, 0, 0, 16, 2, 2, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); + + this.renderBlockBounds(renderer, 0, 2, 0, 2, 16, 2, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); + + this.renderBlockBounds(renderer, 0, 0, 2, 2, 2, 16, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); + + this.renderBlockBounds(renderer, 0, 14, 14, 16, 16, 16, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); + + this.renderBlockBounds(renderer, 14, 0, 14, 16, 14, 16, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); + + this.renderBlockBounds(renderer, 14, 14, 0, 16, 16, 14, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); + + this.renderBlockBounds(renderer, 14, 2, 0, 16, 14, 2, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); + + this.renderBlockBounds(renderer, 0, 2, 14, 2, 14, 16, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); + + this.renderBlockBounds(renderer, 1, 1, 1, 15, 15, 15, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); + + BusRenderHelper.INSTANCE.normalRendering(); + + maBlock.getRendererInstance().setTemporaryRenderIcon(null); + + renderer.renderAllFaces = false; + BusRenderer.INSTANCE.getRenderer().setFacade(false); + + this.postRenderInWorld(renderer); + + return true; + } + + private void renderCableAt( + final double thickness, + final IBlockAccess world, + final int x, + final int y, + final int z, + final BlockMolecularAssembler block, + final RenderBlocks renderer, + final double pull, + final boolean covered) { + IIcon texture = null; + + texture = this.getConnectedCable(world, x, y, z, ForgeDirection.WEST, covered); + block.getRendererInstance().setTemporaryRenderIcon(texture); + if (texture != null) { + renderer.setRenderBounds( + 0.0D, + 0.5D - thickness, + 0.5D - thickness, + 0.5D - thickness - pull, + 0.5D + thickness, + 0.5D + thickness); + renderer.renderStandardBlock(block, x, y, z); + } + + texture = this.getConnectedCable(world, x, y, z, ForgeDirection.EAST, covered); + block.getRendererInstance().setTemporaryRenderIcon(texture); + if (texture != null) { + renderer.setRenderBounds( + 0.5D + thickness + pull, + 0.5D - thickness, + 0.5D - thickness, + 1.0D, + 0.5D + thickness, + 0.5D + thickness); + renderer.renderStandardBlock(block, x, y, z); + } + + texture = this.getConnectedCable(world, x, y, z, ForgeDirection.NORTH, covered); + block.getRendererInstance().setTemporaryRenderIcon(texture); + if (texture != null) { + renderer.setRenderBounds( + 0.5D - thickness, + 0.5D - thickness, + 0.0D, + 0.5D + thickness, + 0.5D + thickness, + 0.5D - thickness - pull); + renderer.renderStandardBlock(block, x, y, z); + } + + texture = this.getConnectedCable(world, x, y, z, ForgeDirection.SOUTH, covered); + block.getRendererInstance().setTemporaryRenderIcon(texture); + if (texture != null) { + renderer.setRenderBounds( + 0.5D - thickness, + 0.5D - thickness, + 0.5D + thickness + pull, + 0.5D + thickness, + 0.5D + thickness, + 1.0D); + renderer.renderStandardBlock(block, x, y, z); + } + + texture = this.getConnectedCable(world, x, y, z, ForgeDirection.DOWN, covered); + block.getRendererInstance().setTemporaryRenderIcon(texture); + if (texture != null) { + renderer.setRenderBounds( + 0.5D - thickness, + 0.0D, + 0.5D - thickness, + 0.5D + thickness, + 0.5D - thickness - pull, + 0.5D + thickness); + renderer.renderStandardBlock(block, x, y, z); + } + + texture = this.getConnectedCable(world, x, y, z, ForgeDirection.UP, covered); + block.getRendererInstance().setTemporaryRenderIcon(texture); + if (texture != null) { + renderer.setRenderBounds( + 0.5D - thickness, + 0.5D + thickness + pull, + 0.5D - thickness, + 0.5D + thickness, + 1.0D, + 0.5D + thickness); + renderer.renderStandardBlock(block, x, y, z); + } + + block.getRendererInstance().setTemporaryRenderIcon(null); + } + + private IIcon getConnectedCable( + final IBlockAccess world, + final int x, + final int y, + final int z, + final ForgeDirection side, + final boolean covered) { + final int tileYPos = y + side.offsetY; + + if (-1 < tileYPos && tileYPos < 256) { + final TileEntity ne = world.getTileEntity(x + side.offsetX, tileYPos, z + side.offsetZ); + if (ne instanceof IGridHost && ne instanceof IPartHost) { + final IPartHost ph = (IPartHost) ne; + final IPart pcx = ph.getPart(ForgeDirection.UNKNOWN); + + if (pcx instanceof PartCable) { + final PartCable pc = (PartCable) pcx; + + if (pc.isConnected(side.getOpposite())) { + if (covered) { + return pc.getCoveredTexture(pc.getCableColor()); + } + return pc.getGlassTexture(pc.getCableColor()); + } + } + } + } + + return null; + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(0, 0, 0, 16, 16, 16); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockCharger.java b/src/main/java/appeng/client/render/blocks/RenderBlockCharger.java index 9cc1a5aeafe..511b6bb0630 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockCharger.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockCharger.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.api.util.IOrientable; import appeng.block.misc.BlockCharger; import appeng.client.render.BaseBlockRender; @@ -26,6 +25,7 @@ import appeng.core.AELog; import appeng.tile.misc.TileCharger; import appeng.util.Platform; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.RenderBlocks; @@ -37,144 +37,151 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import java.util.EnumSet; - - -public class RenderBlockCharger extends BaseBlockRender -{ - - public RenderBlockCharger() - { - super( true, 30 ); - } - - @Override - public void renderInventory( final BlockCharger blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - final Tessellator tess = Tessellator.instance; - - renderer.renderAllFaces = true; - this.setInvRenderBounds( renderer, 6, 1, 0, 10, 15, 2 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - - blk.getRendererInstance().setTemporaryRenderIcons( ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null, null ); +public class RenderBlockCharger extends BaseBlockRender { - this.setInvRenderBounds( renderer, 2, 0, 2, 14, 3, 14 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + public RenderBlockCharger() { + super(true, 30); + } - this.setInvRenderBounds( renderer, 3, 3, 3, 13, 4, 13 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + @Override + public void renderInventory( + final BlockCharger blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + final Tessellator tess = Tessellator.instance; - blk.getRendererInstance().setTemporaryRenderIcon( null ); + renderer.renderAllFaces = true; + this.setInvRenderBounds(renderer, 6, 1, 0, 10, 15, 2); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); - blk.getRendererInstance().setTemporaryRenderIcons( null, ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null ); + blk.getRendererInstance() + .setTemporaryRenderIcons(ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null, null); - this.setInvRenderBounds( renderer, 2, 13, 2, 14, 16, 14 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 2, 0, 2, 14, 3, 14); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); - this.setInvRenderBounds( renderer, 3, 12, 3, 13, 13, 13 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 3, 3, 3, 13, 4, 13); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); - renderer.renderAllFaces = false; - blk.getRendererInstance().setTemporaryRenderIcon( null ); - } + blk.getRendererInstance().setTemporaryRenderIcon(null); - @Override - public boolean renderInWorld( final BlockCharger block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - this.preRenderInWorld( block, world, x, y, z, renderer ); + blk.getRendererInstance() + .setTemporaryRenderIcons(null, ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null); - final IOrientable te = this.getOrientable( block, world, x, y, z ); + this.setInvRenderBounds(renderer, 2, 13, 2, 14, 16, 14); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); - final ForgeDirection fdy = te.getUp(); - final ForgeDirection fdz = te.getForward(); - final ForgeDirection fdx = Platform.crossProduct( fdz, fdy ).getOpposite(); + this.setInvRenderBounds(renderer, 3, 12, 3, 13, 13, 13); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); - renderer.renderAllFaces = true; - this.renderBlockBounds( renderer, 6, 1, 0, 10, 15, 2, fdx, fdy, fdz ); - boolean out = renderer.renderStandardBlock( block, x, y, z ); + renderer.renderAllFaces = false; + blk.getRendererInstance().setTemporaryRenderIcon(null); + } - block.getRendererInstance().setTemporaryRenderIcons( ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null, null ); + @Override + public boolean renderInWorld( + final BlockCharger block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + this.preRenderInWorld(block, world, x, y, z, renderer); - this.renderBlockBounds( renderer, 2, 0, 2, 14, 3, 14, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + final IOrientable te = this.getOrientable(block, world, x, y, z); - this.renderBlockBounds( renderer, 3, 3, 3, 13, 4, 13, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + final ForgeDirection fdy = te.getUp(); + final ForgeDirection fdz = te.getForward(); + final ForgeDirection fdx = Platform.crossProduct(fdz, fdy).getOpposite(); - block.getRendererInstance().setTemporaryRenderIcon( null ); + renderer.renderAllFaces = true; + this.renderBlockBounds(renderer, 6, 1, 0, 10, 15, 2, fdx, fdy, fdz); + boolean out = renderer.renderStandardBlock(block, x, y, z); - block.getRendererInstance().setTemporaryRenderIcons( null, ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null ); + block.getRendererInstance() + .setTemporaryRenderIcons(ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null, null); - this.renderBlockBounds( renderer, 2, 13, 2, 14, 16, 14, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + this.renderBlockBounds(renderer, 2, 0, 2, 14, 3, 14, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); - this.renderBlockBounds( renderer, 3, 12, 3, 13, 13, 13, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + this.renderBlockBounds(renderer, 3, 3, 3, 13, 4, 13, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); - renderer.renderAllFaces = false; - block.getRendererInstance().setTemporaryRenderIcon( null ); + block.getRendererInstance().setTemporaryRenderIcon(null); - this.postRenderInWorld( renderer ); - return out; - } + block.getRendererInstance() + .setTemporaryRenderIcons(null, ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null); - @Override - public void renderTile( final BlockCharger block, final TileCharger tile, final Tessellator tess, final double x, final double y, final double z, final float f, final RenderBlocks renderer ) - { - if( tile == null ) - { - return; - } + this.renderBlockBounds(renderer, 2, 13, 2, 14, 16, 14, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); - final ItemStack sis = tile.getStackInSlot( 0 ); + this.renderBlockBounds(renderer, 3, 12, 3, 13, 13, 13, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); - if( sis == null ) - { - return; - } + renderer.renderAllFaces = false; + block.getRendererInstance().setTemporaryRenderIcon(null); - GL11.glPushMatrix(); - this.applyTESRRotation( x, y, z, tile.getForward(), tile.getUp() ); + this.postRenderInWorld(renderer); + return out; + } - try - { - GL11.glTranslatef( 0.5f, 0.45f, 0.5f ); - GL11.glScalef( 1.0f / 1.1f, 1.0f / 1.1f, 1.0f / 1.1f ); - GL11.glScalef( 1.0f, 1.0f, 1.0f ); + @Override + public void renderTile( + final BlockCharger block, + final TileCharger tile, + final Tessellator tess, + final double x, + final double y, + final double z, + final float f, + final RenderBlocks renderer) { + if (tile == null) { + return; + } + + final ItemStack sis = tile.getStackInSlot(0); - final Block blk = Block.getBlockFromItem( sis.getItem() ); + if (sis == null) { + return; + } - if( sis.getItemSpriteNumber() == 0 && block != null && RenderBlocks.renderItemIn3d( blk.getRenderType() ) ) - { - GL11.glRotatef( 25.0f, 1.0f, 0.0f, 0.0f ); - GL11.glRotatef( 15.0f, 0.0f, 1.0f, 0.0f ); - GL11.glRotatef( 30.0f, 0.0f, 1.0f, 0.0f ); - } - final int br = tile.getWorldObj().getLightBrightnessForSkyBlocks( tile.xCoord, tile.yCoord, tile.zCoord, 0 ); - final int var11 = br % 65536; - final int var12 = br / 65536; + GL11.glPushMatrix(); + this.applyTESRRotation(x, y, z, tile.getForward(), tile.getUp()); - OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, var11, var12 ); + try { + GL11.glTranslatef(0.5f, 0.45f, 0.5f); + GL11.glScalef(1.0f / 1.1f, 1.0f / 1.1f, 1.0f / 1.1f); + GL11.glScalef(1.0f, 1.0f, 1.0f); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + final Block blk = Block.getBlockFromItem(sis.getItem()); - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - tess.setColorOpaque_F( 1.0f, 1.0f, 1.0f ); + if (sis.getItemSpriteNumber() == 0 && block != null && RenderBlocks.renderItemIn3d(blk.getRenderType())) { + GL11.glRotatef(25.0f, 1.0f, 0.0f, 0.0f); + GL11.glRotatef(15.0f, 0.0f, 1.0f, 0.0f); + GL11.glRotatef(30.0f, 0.0f, 1.0f, 0.0f); + } + final int br = tile.getWorldObj().getLightBrightnessForSkyBlocks(tile.xCoord, tile.yCoord, tile.zCoord, 0); + final int var11 = br % 65536; + final int var12 = br / 65536; - this.doRenderItem( sis, tile ); - } - catch( final Exception err ) - { - AELog.debug( err ); - } - finally - { - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glEnable( GL11.GL_LIGHTING ); - } + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, var11, var12); + + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glPopMatrix(); - } + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + tess.setColorOpaque_F(1.0f, 1.0f, 1.0f); + + this.doRenderItem(sis, tile); + } catch (final Exception err) { + AELog.debug(err); + } finally { + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glEnable(GL11.GL_LIGHTING); + } + + GL11.glPopMatrix(); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockController.java b/src/main/java/appeng/client/render/blocks/RenderBlockController.java index cec1c5ae5cb..1c115017ed5 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockController.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockController.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.networking.BlockController; import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; @@ -28,159 +27,130 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; - -public class RenderBlockController extends BaseBlockRender -{ - - public RenderBlockController() - { - super( false, 20 ); - } - - @Override - public boolean renderInWorld( final BlockController blk, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - - final boolean xx = this.getTileEntity( world, x - 1, y, z ) instanceof TileController && this.getTileEntity( world, x + 1, y, z ) instanceof TileController; - final boolean yy = this.getTileEntity( world, x, y - 1, z ) instanceof TileController && this.getTileEntity( world, x, y + 1, z ) instanceof TileController; - final boolean zz = this.getTileEntity( world, x, y, z - 1 ) instanceof TileController && this.getTileEntity( world, x, y, z + 1 ) instanceof TileController; - - final int meta = world.getBlockMetadata( x, y, z ); - final boolean hasPower = meta > 0; - final boolean isConflict = meta == 2; - - ExtraBlockTextures lights = null; - - if( xx && !yy && !zz ) - { - if( hasPower ) - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumnPowered.getIcon() ); - if( isConflict ) - { - lights = ExtraBlockTextures.BlockControllerColumnConflict; - } - else - { - lights = ExtraBlockTextures.BlockControllerColumnLights; - } - } - else - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumn.getIcon() ); - } - - renderer.uvRotateEast = 1; - renderer.uvRotateWest = 1; - renderer.uvRotateTop = 1; - renderer.uvRotateBottom = 1; - } - else if( !xx && yy && !zz ) - { - if( hasPower ) - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumnPowered.getIcon() ); - if( isConflict ) - { - lights = ExtraBlockTextures.BlockControllerColumnConflict; - } - else - { - lights = ExtraBlockTextures.BlockControllerColumnLights; - } - } - else - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumn.getIcon() ); - } - - renderer.uvRotateEast = 0; - renderer.uvRotateNorth = 0; - } - else if( !xx && !yy && zz ) - { - if( hasPower ) - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumnPowered.getIcon() ); - if( isConflict ) - { - lights = ExtraBlockTextures.BlockControllerColumnConflict; - } - else - { - lights = ExtraBlockTextures.BlockControllerColumnLights; - } - } - else - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumn.getIcon() ); - } - - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 1; - renderer.uvRotateTop = 0; - } - else if( ( xx ? 1 : 0 ) + ( yy ? 1 : 0 ) + ( zz ? 1 : 0 ) >= 2 ) - { - final int v = ( Math.abs( x ) + Math.abs( y ) + Math.abs( z ) ) % 2; - - renderer.uvRotateEast = renderer.uvRotateBottom = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - - if( v == 0 ) - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerInsideA.getIcon() ); - } - else - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerInsideB.getIcon() ); - } - } - else - { - if( hasPower ) - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerPowered.getIcon() ); - - if( isConflict ) - { - lights = ExtraBlockTextures.BlockControllerConflict; - } - else - { - lights = ExtraBlockTextures.BlockControllerLights; - } - } - else - { - blk.getRendererInstance().setTemporaryRenderIcon( null ); - } - } - - final boolean out = renderer.renderStandardBlock( blk, x, y, z ); - - if( lights != null ) - { - Tessellator.instance.setColorOpaque_F( 1.0f, 1.0f, 1.0f ); - Tessellator.instance.setBrightness( 14 << 20 | 14 << 4 ); - renderer.renderFaceXNeg( blk, x, y, z, lights.getIcon() ); - renderer.renderFaceXPos( blk, x, y, z, lights.getIcon() ); - renderer.renderFaceYNeg( blk, x, y, z, lights.getIcon() ); - renderer.renderFaceYPos( blk, x, y, z, lights.getIcon() ); - renderer.renderFaceZNeg( blk, x, y, z, lights.getIcon() ); - renderer.renderFaceZPos( blk, x, y, z, lights.getIcon() ); - } - - blk.getRendererInstance().setTemporaryRenderIcon( null ); - renderer.uvRotateEast = renderer.uvRotateBottom = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - return out; - } - - private TileEntity getTileEntity( final IBlockAccess world, final int x, final int y, final int z ) - { - if( y >= 0 ) - { - return world.getTileEntity( x, y, z ); - } - return null; - } +public class RenderBlockController extends BaseBlockRender { + + public RenderBlockController() { + super(false, 20); + } + + @Override + public boolean renderInWorld( + final BlockController blk, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + + final boolean xx = this.getTileEntity(world, x - 1, y, z) instanceof TileController + && this.getTileEntity(world, x + 1, y, z) instanceof TileController; + final boolean yy = this.getTileEntity(world, x, y - 1, z) instanceof TileController + && this.getTileEntity(world, x, y + 1, z) instanceof TileController; + final boolean zz = this.getTileEntity(world, x, y, z - 1) instanceof TileController + && this.getTileEntity(world, x, y, z + 1) instanceof TileController; + + final int meta = world.getBlockMetadata(x, y, z); + final boolean hasPower = meta > 0; + final boolean isConflict = meta == 2; + + ExtraBlockTextures lights = null; + + if (xx && !yy && !zz) { + if (hasPower) { + blk.getRendererInstance() + .setTemporaryRenderIcon(ExtraBlockTextures.BlockControllerColumnPowered.getIcon()); + if (isConflict) { + lights = ExtraBlockTextures.BlockControllerColumnConflict; + } else { + lights = ExtraBlockTextures.BlockControllerColumnLights; + } + } else { + blk.getRendererInstance().setTemporaryRenderIcon(ExtraBlockTextures.BlockControllerColumn.getIcon()); + } + + renderer.uvRotateEast = 1; + renderer.uvRotateWest = 1; + renderer.uvRotateTop = 1; + renderer.uvRotateBottom = 1; + } else if (!xx && yy && !zz) { + if (hasPower) { + blk.getRendererInstance() + .setTemporaryRenderIcon(ExtraBlockTextures.BlockControllerColumnPowered.getIcon()); + if (isConflict) { + lights = ExtraBlockTextures.BlockControllerColumnConflict; + } else { + lights = ExtraBlockTextures.BlockControllerColumnLights; + } + } else { + blk.getRendererInstance().setTemporaryRenderIcon(ExtraBlockTextures.BlockControllerColumn.getIcon()); + } + + renderer.uvRotateEast = 0; + renderer.uvRotateNorth = 0; + } else if (!xx && !yy && zz) { + if (hasPower) { + blk.getRendererInstance() + .setTemporaryRenderIcon(ExtraBlockTextures.BlockControllerColumnPowered.getIcon()); + if (isConflict) { + lights = ExtraBlockTextures.BlockControllerColumnConflict; + } else { + lights = ExtraBlockTextures.BlockControllerColumnLights; + } + } else { + blk.getRendererInstance().setTemporaryRenderIcon(ExtraBlockTextures.BlockControllerColumn.getIcon()); + } + + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 1; + renderer.uvRotateTop = 0; + } else if ((xx ? 1 : 0) + (yy ? 1 : 0) + (zz ? 1 : 0) >= 2) { + final int v = (Math.abs(x) + Math.abs(y) + Math.abs(z)) % 2; + + renderer.uvRotateEast = renderer.uvRotateBottom = + renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + + if (v == 0) { + blk.getRendererInstance().setTemporaryRenderIcon(ExtraBlockTextures.BlockControllerInsideA.getIcon()); + } else { + blk.getRendererInstance().setTemporaryRenderIcon(ExtraBlockTextures.BlockControllerInsideB.getIcon()); + } + } else { + if (hasPower) { + blk.getRendererInstance().setTemporaryRenderIcon(ExtraBlockTextures.BlockControllerPowered.getIcon()); + + if (isConflict) { + lights = ExtraBlockTextures.BlockControllerConflict; + } else { + lights = ExtraBlockTextures.BlockControllerLights; + } + } else { + blk.getRendererInstance().setTemporaryRenderIcon(null); + } + } + + final boolean out = renderer.renderStandardBlock(blk, x, y, z); + + if (lights != null) { + Tessellator.instance.setColorOpaque_F(1.0f, 1.0f, 1.0f); + Tessellator.instance.setBrightness(14 << 20 | 14 << 4); + renderer.renderFaceXNeg(blk, x, y, z, lights.getIcon()); + renderer.renderFaceXPos(blk, x, y, z, lights.getIcon()); + renderer.renderFaceYNeg(blk, x, y, z, lights.getIcon()); + renderer.renderFaceYPos(blk, x, y, z, lights.getIcon()); + renderer.renderFaceZNeg(blk, x, y, z, lights.getIcon()); + renderer.renderFaceZPos(blk, x, y, z, lights.getIcon()); + } + + blk.getRendererInstance().setTemporaryRenderIcon(null); + renderer.uvRotateEast = renderer.uvRotateBottom = + renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + return out; + } + + private TileEntity getTileEntity(final IBlockAccess world, final int x, final int y, final int z) { + if (y >= 0) { + return world.getTileEntity(x, y, z); + } + return null; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPU.java b/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPU.java index 221e55e0931..bdfe2e8ada6 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPU.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPU.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.api.AEApi; import appeng.api.util.AEColor; import appeng.block.crafting.BlockCraftingMonitor; @@ -29,6 +28,7 @@ import appeng.client.texture.ExtraBlockTextures; import appeng.tile.crafting.TileCraftingMonitorTile; import appeng.tile.crafting.TileCraftingTile; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; @@ -37,324 +37,331 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class RenderBlockCraftingCPU extends BaseBlockRender -{ - - protected RenderBlockCraftingCPU( final boolean useTESR, final int range ) - { - super( useTESR, range ); - } - - public RenderBlockCraftingCPU() - { - super( false, 20 ); - } - - @Override - public boolean renderInWorld( final B blk, final IBlockAccess w, final int x, final int y, final int z, RenderBlocks renderer ) - { - final TileCraftingTile craftingTile = blk.getTileEntity( w, x, y, z ); - - if( craftingTile == null ) - { - return false; - } - - final boolean formed = craftingTile.isFormed(); - final boolean emitsLight = craftingTile.isPowered(); - final int meta = w.getBlockMetadata( x, y, z ) & 3; - final boolean isMonitor = blk.getClass() == BlockCraftingMonitor.class; - final IIcon theIcon = blk.getIcon( ForgeDirection.SOUTH.ordinal(), meta | ( formed ? 8 : 0 ) ); - IIcon nonForward = theIcon; - - if( isMonitor ) - { - for( final Block craftingBlock : AEApi.instance().definitions().blocks().craftingUnit().maybeBlock().asSet() ) - { - nonForward = craftingBlock.getIcon( 0, meta | ( formed ? 8 : 0 ) ); - } - } - - if( formed && renderer.overrideBlockTexture == null ) - { - renderer = BusRenderer.INSTANCE.getRenderer(); - final BusRenderHelper i = BusRenderHelper.INSTANCE; - BusRenderer.INSTANCE.getRenderer().setFacade( true ); - - renderer.blockAccess = w; - i.setPass( 0 ); - i.setOrientation( ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH ); - - try - { - craftingTile.setLightCache( i.useSimplifiedRendering( x, y, z, null, craftingTile.getLightCache() ) ); - } - catch( final Throwable ignored ) - { - - } - - final float highX = this.isConnected( w, x, y, z, ForgeDirection.EAST ) ? 16 : 13.01f; - final float lowX = this.isConnected( w, x, y, z, ForgeDirection.WEST ) ? 0 : 2.99f; - - final float highY = this.isConnected( w, x, y, z, ForgeDirection.UP ) ? 16 : 13.01f; - final float lowY = this.isConnected( w, x, y, z, ForgeDirection.DOWN ) ? 0 : 2.99f; - - final float highZ = this.isConnected( w, x, y, z, ForgeDirection.SOUTH ) ? 16 : 13.01f; - final float lowZ = this.isConnected( w, x, y, z, ForgeDirection.NORTH ) ? 0 : 2.99f; - - this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.UP, ForgeDirection.EAST, ForgeDirection.NORTH ); - this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.UP, ForgeDirection.EAST, ForgeDirection.SOUTH ); - this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.UP, ForgeDirection.WEST, ForgeDirection.NORTH ); - this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.UP, ForgeDirection.WEST, ForgeDirection.SOUTH ); - this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.DOWN, ForgeDirection.EAST, ForgeDirection.NORTH ); - this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.DOWN, ForgeDirection.EAST, ForgeDirection.SOUTH ); - this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.DOWN, ForgeDirection.WEST, ForgeDirection.NORTH ); - this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.DOWN, ForgeDirection.WEST, ForgeDirection.SOUTH ); - - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - i.setBounds( this.fso( side, lowX, ForgeDirection.WEST ), this.fso( side, lowY, ForgeDirection.DOWN ), this.fso( side, lowZ, ForgeDirection.NORTH ), this.fso( side, highX, ForgeDirection.EAST ), this.fso( side, highY, ForgeDirection.UP ), this.fso( side, highZ, ForgeDirection.SOUTH ) ); - i.prepareBounds( renderer ); - - boolean localEmit = emitsLight; - - if( blk instanceof BlockCraftingMonitor && craftingTile.getForward() != side ) - { - localEmit = false; - } - - this.handleSide( blk, meta, x, y, z, i, renderer, craftingTile.getForward() == side ? theIcon : nonForward, localEmit, isMonitor, side, w ); - } - - BusRenderer.INSTANCE.getRenderer().setFacade( false ); - i.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - i.normalRendering(); - - return true; - } - else - { - final double a = 0.0 / 16.0; - final double o = 16.0 / 16.0; - renderer.setRenderBounds( a, a, a, o, o, o ); - - return renderer.renderStandardBlock( blk, x, y, z ); - } - } - - private boolean isConnected( final IBlockAccess w, final int x, final int y, final int z, final ForgeDirection side ) - { - final int tileYPos = y + side.offsetY; - - if( 0 <= tileYPos && tileYPos <= 255 ) - { - final TileEntity tile = w.getTileEntity( x + side.offsetX, tileYPos, z + side.offsetZ ); - - return tile instanceof TileCraftingTile; - } - else - { - return false; - } - } - - private void renderCorner( final BusRenderHelper i, final RenderBlocks renderer, final IBlockAccess w, final int x, final int y, final int z, final ForgeDirection up, final ForgeDirection east, final ForgeDirection south ) - { - if( this.isConnected( w, x, y, z, up ) || this.isConnected( w, x, y, z, east ) || this.isConnected( w, x, y, z, south ) ) - { - return; - } - - i.setBounds( this.gso( east, 3, ForgeDirection.WEST ), this.gso( up, 3, ForgeDirection.DOWN ), this.gso( south, 3, ForgeDirection.NORTH ), this.gso( east, 13, ForgeDirection.EAST ), this.gso( up, 13, ForgeDirection.UP ), this.gso( south, 13, ForgeDirection.SOUTH ) ); - i.prepareBounds( renderer ); - i.setTexture( ExtraBlockTextures.BlockCraftingUnitRing.getIcon() ); - i.renderBlockCurrentBounds( x, y, z, renderer ); - } - - private float fso( final ForgeDirection side, final float def, final ForgeDirection target ) - { - if( side == target ) - { - if( side.offsetX > 0 || side.offsetY > 0 || side.offsetZ > 0 ) - { - return 16; - } - return 0; - } - return def; - } - - private void handleSide( final B blk, final int meta, final int x, final int y, final int z, final BusRenderHelper i, final RenderBlocks renderer, final IIcon color, final boolean emitsLight, final boolean isMonitor, final ForgeDirection side, final IBlockAccess w ) - { - if( this.isConnected( w, x, y, z, side ) ) - { - return; - } - - i.setFacesToRender( EnumSet.of( side ) ); - - if( meta == 0 && blk.getClass() == BlockCraftingUnit.class ) - { - i.setTexture( ExtraBlockTextures.BlockCraftingUnitFit.getIcon() ); - i.renderBlockCurrentBounds( x, y, z, renderer ); - } - else - { - if( color == ExtraBlockTextures.BlockCraftingMonitorFit_Light.getIcon() ) - { - i.setTexture( ExtraBlockTextures.BlockCraftingMonitorOuter.getIcon() ); - } - else - { - i.setTexture( ExtraBlockTextures.BlockCraftingFitSolid.getIcon() ); - } - - i.renderBlockCurrentBounds( x, y, z, renderer ); - - if( color != null ) - { - i.setTexture( color ); - - if( !emitsLight ) - { - if( color == ExtraBlockTextures.BlockCraftingMonitorFit_Light.getIcon() ) - { - final int b = w.getLightBrightnessForSkyBlocks( x + side.offsetX, y + side.offsetY, z + side.offsetZ, 0 ); - - final TileCraftingMonitorTile sr = blk.getTileEntity( w, x, y, z ); - final AEColor col = sr.getColor(); - - Tessellator.instance.setBrightness( b ); - Tessellator.instance.setColorOpaque_I( col.whiteVariant ); - i.renderFace( x, y, z, color, side, renderer ); - - Tessellator.instance.setColorOpaque_I( col.mediumVariant ); - i.renderFace( x, y, z, ExtraBlockTextures.BlockCraftingMonitorFit_Medium.getIcon(), side, renderer ); - - Tessellator.instance.setColorOpaque_I( col.blackVariant ); - i.renderFace( x, y, z, ExtraBlockTextures.BlockCraftingMonitorFit_Dark.getIcon(), side, renderer ); - } - else - { - i.renderBlockCurrentBounds( x, y, z, renderer ); - } - } - else - { - if( isMonitor ) - { - final TileCraftingMonitorTile sr = blk.getTileEntity( w, x, y, z ); - final AEColor col = sr.getColor(); - - Tessellator.instance.setColorOpaque_I( col.whiteVariant ); - Tessellator.instance.setBrightness( 13 << 20 | 13 << 4 ); - i.renderFace( x, y, z, color, side, renderer ); - - Tessellator.instance.setColorOpaque_I( col.mediumVariant ); - Tessellator.instance.setBrightness( 13 << 20 | 13 << 4 ); - i.renderFace( x, y, z, ExtraBlockTextures.BlockCraftingMonitorFit_Medium.getIcon(), side, renderer ); - - Tessellator.instance.setColorOpaque_I( col.blackVariant ); - Tessellator.instance.setBrightness( 13 << 20 | 13 << 4 ); - i.renderFace( x, y, z, ExtraBlockTextures.BlockCraftingMonitorFit_Dark.getIcon(), side, renderer ); - } - else - { - Tessellator.instance.setColorOpaque_F( 1.0f, 1.0f, 1.0f ); - Tessellator.instance.setBrightness( 13 << 20 | 13 << 4 ); - i.renderFace( x, y, z, color, side, renderer ); - } - } - } - } - - for( final ForgeDirection a : ForgeDirection.VALID_DIRECTIONS ) - { - if( a == side || a == side.getOpposite() ) - { - continue; - } - - if( ( side.offsetX != 0 || side.offsetZ != 0 ) && ( a == ForgeDirection.NORTH || a == ForgeDirection.EAST || a == ForgeDirection.WEST || a == ForgeDirection.SOUTH ) ) - { - i.setTexture( ExtraBlockTextures.BlockCraftingUnitRingLongRotated.getIcon() ); - } - else if( ( side.offsetY != 0 ) && ( a == ForgeDirection.EAST || a == ForgeDirection.WEST ) ) - { - i.setTexture( ExtraBlockTextures.BlockCraftingUnitRingLongRotated.getIcon() ); - } - else - { - i.setTexture( ExtraBlockTextures.BlockCraftingUnitRingLong.getIcon() ); - } - - if( !( i.getBound( a ) < 0.001 || i.getBound( a ) > 15.999 ) ) - { - final double width = 3.0 / 16.0; - - switch( a ) - { - case DOWN: - renderer.renderMinY = 0; - renderer.renderMaxY = width; - break; - case EAST: - renderer.renderMaxX = 1; - renderer.renderMinX = 1.0 - width; - renderer.uvRotateTop = 1; - renderer.uvRotateBottom = 1; - renderer.uvRotateWest = 1; - renderer.uvRotateEast = 1; - break; - case NORTH: - renderer.renderMinZ = 0; - renderer.renderMaxZ = width; - renderer.uvRotateWest = 1; - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 1; - break; - case SOUTH: - renderer.renderMaxZ = 1; - renderer.renderMinZ = 1.0 - width; - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 1; - break; - case UP: - renderer.renderMaxY = 1; - renderer.renderMinY = 1.0 - width; - break; - case WEST: - renderer.renderMinX = 0; - renderer.renderMaxX = width; - renderer.uvRotateTop = 1; - renderer.uvRotateBottom = 1; - renderer.uvRotateWest = 1; - renderer.uvRotateEast = 1; - break; - case UNKNOWN: - default: - } - - i.renderBlockCurrentBounds( x, y, z, renderer ); - i.prepareBounds( renderer ); - } - } - } - - private float gso( final ForgeDirection side, final float def, final ForgeDirection target ) - { - if( side != target ) - { - if( side.offsetX > 0 || side.offsetY > 0 || side.offsetZ > 0 ) - { - return 16; - } - return 0; - } - return def; - } +public class RenderBlockCraftingCPU + extends BaseBlockRender { + + protected RenderBlockCraftingCPU(final boolean useTESR, final int range) { + super(useTESR, range); + } + + public RenderBlockCraftingCPU() { + super(false, 20); + } + + @Override + public boolean renderInWorld( + final B blk, final IBlockAccess w, final int x, final int y, final int z, RenderBlocks renderer) { + final TileCraftingTile craftingTile = blk.getTileEntity(w, x, y, z); + + if (craftingTile == null) { + return false; + } + + final boolean formed = craftingTile.isFormed(); + final boolean emitsLight = craftingTile.isPowered(); + final int meta = w.getBlockMetadata(x, y, z) & 3; + final boolean isMonitor = blk.getClass() == BlockCraftingMonitor.class; + final IIcon theIcon = blk.getIcon(ForgeDirection.SOUTH.ordinal(), meta | (formed ? 8 : 0)); + IIcon nonForward = theIcon; + + if (isMonitor) { + for (final Block craftingBlock : AEApi.instance() + .definitions() + .blocks() + .craftingUnit() + .maybeBlock() + .asSet()) { + nonForward = craftingBlock.getIcon(0, meta | (formed ? 8 : 0)); + } + } + + if (formed && renderer.overrideBlockTexture == null) { + renderer = BusRenderer.INSTANCE.getRenderer(); + final BusRenderHelper i = BusRenderHelper.INSTANCE; + BusRenderer.INSTANCE.getRenderer().setFacade(true); + + renderer.blockAccess = w; + i.setPass(0); + i.setOrientation(ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH); + + try { + craftingTile.setLightCache(i.useSimplifiedRendering(x, y, z, null, craftingTile.getLightCache())); + } catch (final Throwable ignored) { + + } + + final float highX = this.isConnected(w, x, y, z, ForgeDirection.EAST) ? 16 : 13.01f; + final float lowX = this.isConnected(w, x, y, z, ForgeDirection.WEST) ? 0 : 2.99f; + + final float highY = this.isConnected(w, x, y, z, ForgeDirection.UP) ? 16 : 13.01f; + final float lowY = this.isConnected(w, x, y, z, ForgeDirection.DOWN) ? 0 : 2.99f; + + final float highZ = this.isConnected(w, x, y, z, ForgeDirection.SOUTH) ? 16 : 13.01f; + final float lowZ = this.isConnected(w, x, y, z, ForgeDirection.NORTH) ? 0 : 2.99f; + + this.renderCorner(i, renderer, w, x, y, z, ForgeDirection.UP, ForgeDirection.EAST, ForgeDirection.NORTH); + this.renderCorner(i, renderer, w, x, y, z, ForgeDirection.UP, ForgeDirection.EAST, ForgeDirection.SOUTH); + this.renderCorner(i, renderer, w, x, y, z, ForgeDirection.UP, ForgeDirection.WEST, ForgeDirection.NORTH); + this.renderCorner(i, renderer, w, x, y, z, ForgeDirection.UP, ForgeDirection.WEST, ForgeDirection.SOUTH); + this.renderCorner(i, renderer, w, x, y, z, ForgeDirection.DOWN, ForgeDirection.EAST, ForgeDirection.NORTH); + this.renderCorner(i, renderer, w, x, y, z, ForgeDirection.DOWN, ForgeDirection.EAST, ForgeDirection.SOUTH); + this.renderCorner(i, renderer, w, x, y, z, ForgeDirection.DOWN, ForgeDirection.WEST, ForgeDirection.NORTH); + this.renderCorner(i, renderer, w, x, y, z, ForgeDirection.DOWN, ForgeDirection.WEST, ForgeDirection.SOUTH); + + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + i.setBounds( + this.fso(side, lowX, ForgeDirection.WEST), + this.fso(side, lowY, ForgeDirection.DOWN), + this.fso(side, lowZ, ForgeDirection.NORTH), + this.fso(side, highX, ForgeDirection.EAST), + this.fso(side, highY, ForgeDirection.UP), + this.fso(side, highZ, ForgeDirection.SOUTH)); + i.prepareBounds(renderer); + + boolean localEmit = emitsLight; + + if (blk instanceof BlockCraftingMonitor && craftingTile.getForward() != side) { + localEmit = false; + } + + this.handleSide( + blk, + meta, + x, + y, + z, + i, + renderer, + craftingTile.getForward() == side ? theIcon : nonForward, + localEmit, + isMonitor, + side, + w); + } + + BusRenderer.INSTANCE.getRenderer().setFacade(false); + i.setFacesToRender(EnumSet.allOf(ForgeDirection.class)); + i.normalRendering(); + + return true; + } else { + final double a = 0.0 / 16.0; + final double o = 16.0 / 16.0; + renderer.setRenderBounds(a, a, a, o, o, o); + + return renderer.renderStandardBlock(blk, x, y, z); + } + } + + private boolean isConnected( + final IBlockAccess w, final int x, final int y, final int z, final ForgeDirection side) { + final int tileYPos = y + side.offsetY; + + if (0 <= tileYPos && tileYPos <= 255) { + final TileEntity tile = w.getTileEntity(x + side.offsetX, tileYPos, z + side.offsetZ); + + return tile instanceof TileCraftingTile; + } else { + return false; + } + } + + private void renderCorner( + final BusRenderHelper i, + final RenderBlocks renderer, + final IBlockAccess w, + final int x, + final int y, + final int z, + final ForgeDirection up, + final ForgeDirection east, + final ForgeDirection south) { + if (this.isConnected(w, x, y, z, up) + || this.isConnected(w, x, y, z, east) + || this.isConnected(w, x, y, z, south)) { + return; + } + + i.setBounds( + this.gso(east, 3, ForgeDirection.WEST), + this.gso(up, 3, ForgeDirection.DOWN), + this.gso(south, 3, ForgeDirection.NORTH), + this.gso(east, 13, ForgeDirection.EAST), + this.gso(up, 13, ForgeDirection.UP), + this.gso(south, 13, ForgeDirection.SOUTH)); + i.prepareBounds(renderer); + i.setTexture(ExtraBlockTextures.BlockCraftingUnitRing.getIcon()); + i.renderBlockCurrentBounds(x, y, z, renderer); + } + + private float fso(final ForgeDirection side, final float def, final ForgeDirection target) { + if (side == target) { + if (side.offsetX > 0 || side.offsetY > 0 || side.offsetZ > 0) { + return 16; + } + return 0; + } + return def; + } + + private void handleSide( + final B blk, + final int meta, + final int x, + final int y, + final int z, + final BusRenderHelper i, + final RenderBlocks renderer, + final IIcon color, + final boolean emitsLight, + final boolean isMonitor, + final ForgeDirection side, + final IBlockAccess w) { + if (this.isConnected(w, x, y, z, side)) { + return; + } + + i.setFacesToRender(EnumSet.of(side)); + + if (meta == 0 && blk.getClass() == BlockCraftingUnit.class) { + i.setTexture(ExtraBlockTextures.BlockCraftingUnitFit.getIcon()); + i.renderBlockCurrentBounds(x, y, z, renderer); + } else { + if (color == ExtraBlockTextures.BlockCraftingMonitorFit_Light.getIcon()) { + i.setTexture(ExtraBlockTextures.BlockCraftingMonitorOuter.getIcon()); + } else { + i.setTexture(ExtraBlockTextures.BlockCraftingFitSolid.getIcon()); + } + + i.renderBlockCurrentBounds(x, y, z, renderer); + + if (color != null) { + i.setTexture(color); + + if (!emitsLight) { + if (color == ExtraBlockTextures.BlockCraftingMonitorFit_Light.getIcon()) { + final int b = w.getLightBrightnessForSkyBlocks( + x + side.offsetX, y + side.offsetY, z + side.offsetZ, 0); + + final TileCraftingMonitorTile sr = blk.getTileEntity(w, x, y, z); + final AEColor col = sr.getColor(); + + Tessellator.instance.setBrightness(b); + Tessellator.instance.setColorOpaque_I(col.whiteVariant); + i.renderFace(x, y, z, color, side, renderer); + + Tessellator.instance.setColorOpaque_I(col.mediumVariant); + i.renderFace( + x, y, z, ExtraBlockTextures.BlockCraftingMonitorFit_Medium.getIcon(), side, renderer); + + Tessellator.instance.setColorOpaque_I(col.blackVariant); + i.renderFace( + x, y, z, ExtraBlockTextures.BlockCraftingMonitorFit_Dark.getIcon(), side, renderer); + } else { + i.renderBlockCurrentBounds(x, y, z, renderer); + } + } else { + if (isMonitor) { + final TileCraftingMonitorTile sr = blk.getTileEntity(w, x, y, z); + final AEColor col = sr.getColor(); + + Tessellator.instance.setColorOpaque_I(col.whiteVariant); + Tessellator.instance.setBrightness(13 << 20 | 13 << 4); + i.renderFace(x, y, z, color, side, renderer); + + Tessellator.instance.setColorOpaque_I(col.mediumVariant); + Tessellator.instance.setBrightness(13 << 20 | 13 << 4); + i.renderFace( + x, y, z, ExtraBlockTextures.BlockCraftingMonitorFit_Medium.getIcon(), side, renderer); + + Tessellator.instance.setColorOpaque_I(col.blackVariant); + Tessellator.instance.setBrightness(13 << 20 | 13 << 4); + i.renderFace( + x, y, z, ExtraBlockTextures.BlockCraftingMonitorFit_Dark.getIcon(), side, renderer); + } else { + Tessellator.instance.setColorOpaque_F(1.0f, 1.0f, 1.0f); + Tessellator.instance.setBrightness(13 << 20 | 13 << 4); + i.renderFace(x, y, z, color, side, renderer); + } + } + } + } + + for (final ForgeDirection a : ForgeDirection.VALID_DIRECTIONS) { + if (a == side || a == side.getOpposite()) { + continue; + } + + if ((side.offsetX != 0 || side.offsetZ != 0) + && (a == ForgeDirection.NORTH + || a == ForgeDirection.EAST + || a == ForgeDirection.WEST + || a == ForgeDirection.SOUTH)) { + i.setTexture(ExtraBlockTextures.BlockCraftingUnitRingLongRotated.getIcon()); + } else if ((side.offsetY != 0) && (a == ForgeDirection.EAST || a == ForgeDirection.WEST)) { + i.setTexture(ExtraBlockTextures.BlockCraftingUnitRingLongRotated.getIcon()); + } else { + i.setTexture(ExtraBlockTextures.BlockCraftingUnitRingLong.getIcon()); + } + + if (!(i.getBound(a) < 0.001 || i.getBound(a) > 15.999)) { + final double width = 3.0 / 16.0; + + switch (a) { + case DOWN: + renderer.renderMinY = 0; + renderer.renderMaxY = width; + break; + case EAST: + renderer.renderMaxX = 1; + renderer.renderMinX = 1.0 - width; + renderer.uvRotateTop = 1; + renderer.uvRotateBottom = 1; + renderer.uvRotateWest = 1; + renderer.uvRotateEast = 1; + break; + case NORTH: + renderer.renderMinZ = 0; + renderer.renderMaxZ = width; + renderer.uvRotateWest = 1; + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 1; + break; + case SOUTH: + renderer.renderMaxZ = 1; + renderer.renderMinZ = 1.0 - width; + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 1; + break; + case UP: + renderer.renderMaxY = 1; + renderer.renderMinY = 1.0 - width; + break; + case WEST: + renderer.renderMinX = 0; + renderer.renderMaxX = width; + renderer.uvRotateTop = 1; + renderer.uvRotateBottom = 1; + renderer.uvRotateWest = 1; + renderer.uvRotateEast = 1; + break; + case UNKNOWN: + default: + } + + i.renderBlockCurrentBounds(x, y, z, renderer); + i.prepareBounds(renderer); + } + } + } + + private float gso(final ForgeDirection side, final float def, final ForgeDirection target) { + if (side != target) { + if (side.offsetX > 0 || side.offsetY > 0 || side.offsetZ > 0) { + return 16; + } + return 0; + } + return def; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPUMonitor.java b/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPUMonitor.java index 2fa0eb70ca8..29452a540e2 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPUMonitor.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPUMonitor.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.api.storage.data.IAEItemStack; import appeng.block.crafting.BlockCraftingMonitor; import appeng.client.ClientHelper; @@ -38,149 +37,139 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv1 */ -public class RenderBlockCraftingCPUMonitor extends RenderBlockCraftingCPU -{ - private static final IWideReadableNumberConverter NUMBER_CONVERTER = ReadableNumberConverter.INSTANCE; - - public RenderBlockCraftingCPUMonitor() - { - super( true, 20 ); - } - - @Override - public void renderTile( final BlockCraftingMonitor block, final TileCraftingMonitorTile tile, final Tessellator tess, final double x, final double y, final double z, final float f, final RenderBlocks renderer ) - { - if( tile != null ) - { - final IAEItemStack ais = tile.getJobProgress(); - - if( tile.getDisplayList() == null ) - { - tile.setUpdateList( true ); - tile.setDisplayList( GLAllocation.generateDisplayLists( 1 ) ); - } - else - { - GL11.glPushMatrix(); - GL11.glTranslated( x + 0.5, y + 0.5, z + 0.5 ); - - if( tile.isUpdateList() ) - { - tile.setUpdateList( false ); - GL11.glNewList( tile.getDisplayList(), GL11.GL_COMPILE_AND_EXECUTE ); - this.tesrRenderScreen( tess, tile, ais ); - GL11.glEndList(); - } - else - { - GL11.glCallList( tile.getDisplayList() ); - } - - GL11.glPopMatrix(); - } - } - } - - private void tesrRenderScreen( final Tessellator tess, final TileCraftingMonitorTile cmt, final IAEItemStack ais ) - { - final ForgeDirection side = cmt.getForward(); - - ForgeDirection walrus = side.offsetY != 0 ? ForgeDirection.SOUTH : ForgeDirection.UP; - int spin = 0; - int max = 5; - - while( walrus != cmt.getUp() && max > 0 ) - { - max--; - spin++; - walrus = Platform.rotateAround( walrus, side ); - } - max--; - - GL11.glTranslated( side.offsetX * 0.69, side.offsetY * 0.69, side.offsetZ * 0.69 ); - - final float scale = 0.7f; - GL11.glScalef( scale, scale, scale ); - - switch( side ) - { - case UP: - GL11.glScalef( 1.0f, -1.0f, 1.0f ); - GL11.glRotatef( 90.0f, 1.0f, 0.0f, 0.0f ); - GL11.glRotatef( spin * 90.0F, 0, 0, 1 ); - break; - case DOWN: - GL11.glScalef( 1.0f, -1.0f, 1.0f ); - GL11.glRotatef( -90.0f, 1.0f, 0.0f, 0.0f ); - GL11.glRotatef( spin * -90.0F, 0, 0, 1 ); - break; - case EAST: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - GL11.glRotatef( -90.0f, 0.0f, 1.0f, 0.0f ); - break; - case WEST: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - GL11.glRotatef( 90.0f, 0.0f, 1.0f, 0.0f ); - break; - case NORTH: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - break; - case SOUTH: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - GL11.glRotatef( 180.0f, 0.0f, 1.0f, 0.0f ); - break; - - default: - break; - } - - try - { - final ItemStack sis = ais.getItemStack(); - sis.stackSize = 1; - - final int br = 16 << 20 | 16 << 4; - final int var11 = br % 65536; - final int var12 = br / 65536; - - OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, var11 * 0.8F, var12 * 0.8F ); - - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - // RenderHelper.enableGUIStandardItemLighting(); - tess.setColorOpaque_F( 1.0f, 1.0f, 1.0f ); - - ClientHelper.proxy.doRenderItem( sis, cmt.getWorldObj() ); - } - catch( final Exception e ) - { - AELog.debug( e ); - } - finally - { - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glEnable( GL11.GL_LIGHTING ); - } - - GL11.glTranslatef( 0.0f, 0.14f, -0.24f ); - GL11.glScalef( 1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f ); - - final long stackSize = ais.getStackSize(); - final String renderedStackSize = NUMBER_CONVERTER.toWideReadableForm( stackSize ); - - final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - final int width = fr.getStringWidth( renderedStackSize ); - - GL11.glTranslatef( -0.5f * width, 0.0f, -1.0f ); - fr.drawString( renderedStackSize, 0, 0, 0 ); - } +public class RenderBlockCraftingCPUMonitor + extends RenderBlockCraftingCPU { + private static final IWideReadableNumberConverter NUMBER_CONVERTER = ReadableNumberConverter.INSTANCE; + + public RenderBlockCraftingCPUMonitor() { + super(true, 20); + } + + @Override + public void renderTile( + final BlockCraftingMonitor block, + final TileCraftingMonitorTile tile, + final Tessellator tess, + final double x, + final double y, + final double z, + final float f, + final RenderBlocks renderer) { + if (tile != null) { + final IAEItemStack ais = tile.getJobProgress(); + + if (tile.getDisplayList() == null) { + tile.setUpdateList(true); + tile.setDisplayList(GLAllocation.generateDisplayLists(1)); + } else { + GL11.glPushMatrix(); + GL11.glTranslated(x + 0.5, y + 0.5, z + 0.5); + + if (tile.isUpdateList()) { + tile.setUpdateList(false); + GL11.glNewList(tile.getDisplayList(), GL11.GL_COMPILE_AND_EXECUTE); + this.tesrRenderScreen(tess, tile, ais); + GL11.glEndList(); + } else { + GL11.glCallList(tile.getDisplayList()); + } + + GL11.glPopMatrix(); + } + } + } + + private void tesrRenderScreen(final Tessellator tess, final TileCraftingMonitorTile cmt, final IAEItemStack ais) { + final ForgeDirection side = cmt.getForward(); + + ForgeDirection walrus = side.offsetY != 0 ? ForgeDirection.SOUTH : ForgeDirection.UP; + int spin = 0; + int max = 5; + + while (walrus != cmt.getUp() && max > 0) { + max--; + spin++; + walrus = Platform.rotateAround(walrus, side); + } + max--; + + GL11.glTranslated(side.offsetX * 0.69, side.offsetY * 0.69, side.offsetZ * 0.69); + + final float scale = 0.7f; + GL11.glScalef(scale, scale, scale); + + switch (side) { + case UP: + GL11.glScalef(1.0f, -1.0f, 1.0f); + GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f); + GL11.glRotatef(spin * 90.0F, 0, 0, 1); + break; + case DOWN: + GL11.glScalef(1.0f, -1.0f, 1.0f); + GL11.glRotatef(-90.0f, 1.0f, 0.0f, 0.0f); + GL11.glRotatef(spin * -90.0F, 0, 0, 1); + break; + case EAST: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(-90.0f, 0.0f, 1.0f, 0.0f); + break; + case WEST: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(90.0f, 0.0f, 1.0f, 0.0f); + break; + case NORTH: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + break; + case SOUTH: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(180.0f, 0.0f, 1.0f, 0.0f); + break; + + default: + break; + } + + try { + final ItemStack sis = ais.getItemStack(); + sis.stackSize = 1; + + final int br = 16 << 20 | 16 << 4; + final int var11 = br % 65536; + final int var12 = br / 65536; + + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, var11 * 0.8F, var12 * 0.8F); + + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + // RenderHelper.enableGUIStandardItemLighting(); + tess.setColorOpaque_F(1.0f, 1.0f, 1.0f); + + ClientHelper.proxy.doRenderItem(sis, cmt.getWorldObj()); + } catch (final Exception e) { + AELog.debug(e); + } finally { + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glEnable(GL11.GL_LIGHTING); + } + + GL11.glTranslatef(0.0f, 0.14f, -0.24f); + GL11.glScalef(1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f); + + final long stackSize = ais.getStackSize(); + final String renderedStackSize = NUMBER_CONVERTER.toWideReadableForm(stackSize); + + final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + final int width = fr.getStringWidth(renderedStackSize); + + GL11.glTranslatef(-0.5f * width, 0.0f, -1.0f); + fr.drawString(renderedStackSize, 0, 0, 0); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockCrank.java b/src/main/java/appeng/client/render/blocks/RenderBlockCrank.java index 6a8935364ee..62697e3900c 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockCrank.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockCrank.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.grindstone.BlockCrank; import appeng.client.render.BaseBlockRender; import appeng.tile.grindstone.TileCrank; @@ -33,81 +32,90 @@ import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; - -public class RenderBlockCrank extends BaseBlockRender -{ - - public RenderBlockCrank() - { - super( true, 60 ); - } - - @Override - public void renderInventory( final BlockCrank blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - renderer.renderAllFaces = true; - - renderer.setRenderBounds( 0.5D - 0.05, 0.5D - 0.5, 0.5D - 0.05, 0.5D + 0.05, 0.5D + 0.3, 0.5D + 0.05 ); - super.renderInventory( blk, is, renderer, type, obj ); - - renderer.setRenderBounds( 0.70D - 0.15, 0.75D - 0.05, 0.5D - 0.05, 0.70D + 0.28, 0.75D + 0.05, 0.5D + 0.05 ); - super.renderInventory( blk, is, renderer, type, obj ); - - renderer.renderAllFaces = false; - } - - @Override - public boolean renderInWorld( final BlockCrank imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - return true; - } - - @Override - public void renderTile( final BlockCrank blk, final TileCrank tile, final Tessellator tess, final double x, final double y, final double z, final float f, final RenderBlocks renderBlocks ) - { - if( tile.getUp() == null || tile.getUp() == ForgeDirection.UNKNOWN ) - { - return; - } - Minecraft.getMinecraft().getTextureManager().bindTexture( TextureMap.locationBlocksTexture ); - RenderHelper.disableStandardItemLighting(); - - if( Minecraft.isAmbientOcclusionEnabled() ) - { - GL11.glShadeModel( GL11.GL_SMOOTH ); - } - else - { - GL11.glShadeModel( GL11.GL_FLAT ); - } - - GL11.glCullFace( GL11.GL_FRONT ); - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - - this.applyTESRRotation( x, y, z, tile.getForward(), tile.getUp() ); - - GL11.glTranslated( 0.5, 0, 0.5 ); - GL11.glRotatef( tile.getVisibleRotation(), 0, 1, 0 ); - GL11.glTranslated( -0.5, 0, -0.5 ); - - tess.setTranslation( -tile.xCoord, -tile.yCoord, -tile.zCoord ); - tess.startDrawingQuads(); - renderBlocks.renderAllFaces = true; - renderBlocks.blockAccess = tile.getWorldObj(); - - renderBlocks.setRenderBounds( 0.5D - 0.05, 0.5D - 0.5, 0.5D - 0.05, 0.5D + 0.05, 0.5D + 0.1, 0.5D + 0.05 ); - - renderBlocks.renderStandardBlock( blk, tile.xCoord, tile.yCoord, tile.zCoord ); - - renderBlocks.setRenderBounds( 0.70D - 0.15, 0.55D - 0.05, 0.5D - 0.05, 0.70D + 0.15, 0.55D + 0.05, 0.5D + 0.05 ); - - renderBlocks.renderStandardBlock( blk, tile.xCoord, tile.yCoord, tile.zCoord ); - - tess.draw(); - tess.setTranslation( 0, 0, 0 ); - - GL11.glCullFace( GL11.GL_BACK ); - - RenderHelper.enableStandardItemLighting(); - } +public class RenderBlockCrank extends BaseBlockRender { + + public RenderBlockCrank() { + super(true, 60); + } + + @Override + public void renderInventory( + final BlockCrank blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + renderer.renderAllFaces = true; + + renderer.setRenderBounds(0.5D - 0.05, 0.5D - 0.5, 0.5D - 0.05, 0.5D + 0.05, 0.5D + 0.3, 0.5D + 0.05); + super.renderInventory(blk, is, renderer, type, obj); + + renderer.setRenderBounds(0.70D - 0.15, 0.75D - 0.05, 0.5D - 0.05, 0.70D + 0.28, 0.75D + 0.05, 0.5D + 0.05); + super.renderInventory(blk, is, renderer, type, obj); + + renderer.renderAllFaces = false; + } + + @Override + public boolean renderInWorld( + final BlockCrank imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + return true; + } + + @Override + public void renderTile( + final BlockCrank blk, + final TileCrank tile, + final Tessellator tess, + final double x, + final double y, + final double z, + final float f, + final RenderBlocks renderBlocks) { + if (tile.getUp() == null || tile.getUp() == ForgeDirection.UNKNOWN) { + return; + } + Minecraft.getMinecraft().getTextureManager().bindTexture(TextureMap.locationBlocksTexture); + RenderHelper.disableStandardItemLighting(); + + if (Minecraft.isAmbientOcclusionEnabled()) { + GL11.glShadeModel(GL11.GL_SMOOTH); + } else { + GL11.glShadeModel(GL11.GL_FLAT); + } + + GL11.glCullFace(GL11.GL_FRONT); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + + this.applyTESRRotation(x, y, z, tile.getForward(), tile.getUp()); + + GL11.glTranslated(0.5, 0, 0.5); + GL11.glRotatef(tile.getVisibleRotation(), 0, 1, 0); + GL11.glTranslated(-0.5, 0, -0.5); + + tess.setTranslation(-tile.xCoord, -tile.yCoord, -tile.zCoord); + tess.startDrawingQuads(); + renderBlocks.renderAllFaces = true; + renderBlocks.blockAccess = tile.getWorldObj(); + + renderBlocks.setRenderBounds(0.5D - 0.05, 0.5D - 0.5, 0.5D - 0.05, 0.5D + 0.05, 0.5D + 0.1, 0.5D + 0.05); + + renderBlocks.renderStandardBlock(blk, tile.xCoord, tile.yCoord, tile.zCoord); + + renderBlocks.setRenderBounds(0.70D - 0.15, 0.55D - 0.05, 0.5D - 0.05, 0.70D + 0.15, 0.55D + 0.05, 0.5D + 0.05); + + renderBlocks.renderStandardBlock(blk, tile.xCoord, tile.yCoord, tile.zCoord); + + tess.draw(); + tess.setTranslation(0, 0, 0); + + GL11.glCullFace(GL11.GL_BACK); + + RenderHelper.enableStandardItemLighting(); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockEnergyCube.java b/src/main/java/appeng/client/render/blocks/RenderBlockEnergyCube.java index 5219ff2b044..1fe2d3846b9 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockEnergyCube.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockEnergyCube.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.api.implementations.items.IAEItemPowerStorage; import appeng.block.networking.BlockEnergyCell; import appeng.client.render.BaseBlockRender; @@ -28,48 +27,52 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; +public class RenderBlockEnergyCube extends BaseBlockRender { -public class RenderBlockEnergyCube extends BaseBlockRender -{ - - public RenderBlockEnergyCube() - { - super( false, 20 ); - } + public RenderBlockEnergyCube() { + super(false, 20); + } - @Override - public void renderInventory( final BlockEnergyCell blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - final IAEItemPowerStorage myItem = (IAEItemPowerStorage) is.getItem(); - final double internalCurrentPower = myItem.getAECurrentPower( is ); - final double internalMaxPower = myItem.getAEMaxPower( is ); + @Override + public void renderInventory( + final BlockEnergyCell blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + final IAEItemPowerStorage myItem = (IAEItemPowerStorage) is.getItem(); + final double internalCurrentPower = myItem.getAECurrentPower(is); + final double internalMaxPower = myItem.getAEMaxPower(is); - int meta = (int) ( 8.0 * ( internalCurrentPower / internalMaxPower ) ); + int meta = (int) (8.0 * (internalCurrentPower / internalMaxPower)); - if( meta > 7 ) - { - meta = 7; - } - if( meta < 0 ) - { - meta = 0; - } + if (meta > 7) { + meta = 7; + } + if (meta < 0) { + meta = 0; + } - renderer.setOverrideBlockTexture( blk.getIcon( 0, meta ) ); - super.renderInventory( blk, is, renderer, type, obj ); - renderer.setOverrideBlockTexture( null ); - } + renderer.setOverrideBlockTexture(blk.getIcon(0, meta)); + super.renderInventory(blk, is, renderer, type, obj); + renderer.setOverrideBlockTexture(null); + } - @Override - public boolean renderInWorld( final BlockEnergyCell blk, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final int meta = world.getBlockMetadata( x, y, z ); + @Override + public boolean renderInWorld( + final BlockEnergyCell blk, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + final int meta = world.getBlockMetadata(x, y, z); - renderer.overrideBlockTexture = blk.getIcon( 0, meta ); + renderer.overrideBlockTexture = blk.getIcon(0, meta); - final boolean out = renderer.renderStandardBlock( blk, x, y, z ); - renderer.overrideBlockTexture = null; + final boolean out = renderer.renderStandardBlock(blk, x, y, z); + renderer.overrideBlockTexture = null; - return out; - } + return out; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockInscriber.java b/src/main/java/appeng/client/render/blocks/RenderBlockInscriber.java index 8ea64317256..8123d8ccddd 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockInscriber.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockInscriber.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.api.features.IInscriberRecipe; import appeng.api.util.IOrientable; import appeng.block.AEBaseBlock; @@ -29,6 +28,7 @@ import appeng.tile.AEBaseTile; import appeng.tile.misc.TileInscriber; import appeng.util.Platform; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.OpenGlHelper; @@ -43,283 +43,308 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import java.util.EnumSet; - - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class RenderBlockInscriber extends BaseBlockRender -{ - private static final float ITEM_RENDER_SCALE = 1.0f / 1.1f; - - public RenderBlockInscriber() - { - super( true, 30 ); - } - - @Override - public void renderInventory( final BlockInscriber blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - final Tessellator tess = Tessellator.instance; - - renderer.renderAllFaces = true; - this.setInvRenderBounds( renderer, 6, 1, 0, 10, 15, 2 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - - // sides... - this.setInvRenderBounds( renderer, 3, 1, 0, 13, 15, 3 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - - this.setInvRenderBounds( renderer, 0, 1, 0, 3, 15, 16 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - - this.setInvRenderBounds( renderer, 13, 1, 0, 16, 15, 16 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - - this.setInvRenderBounds( renderer, 1, 0, 1, 15, 2, 15 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - - this.setInvRenderBounds( renderer, 1, 14, 1, 15, 16, 15 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockInscriberInside.getIcon() ); - - // press - this.setInvRenderBounds( renderer, 3, 2, 3, 13, 3, 13 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - - this.setInvRenderBounds( renderer, 3, 13, 3, 13, 15, 13 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - - blk.getRendererInstance().setTemporaryRenderIcon( null ); +public class RenderBlockInscriber extends BaseBlockRender { + private static final float ITEM_RENDER_SCALE = 1.0f / 1.1f; - renderer.renderAllFaces = false; - // blk.getRendererInstance().setTemporaryRenderIcon( null ); + public RenderBlockInscriber() { + super(true, 30); + } - } + @Override + public void renderInventory( + final BlockInscriber blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + final Tessellator tess = Tessellator.instance; - @Override - public boolean renderInWorld( final BlockInscriber block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final IOrientable te = this.getOrientable( block, world, x, y, z ); + renderer.renderAllFaces = true; + this.setInvRenderBounds(renderer, 6, 1, 0, 10, 15, 2); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); - if( te == null ) - { - return false; - } + // sides... + this.setInvRenderBounds(renderer, 3, 1, 0, 13, 15, 3); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); - this.preRenderInWorld( block, world, x, y, z, renderer ); + this.setInvRenderBounds(renderer, 0, 1, 0, 3, 15, 16); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); - final ForgeDirection fdy = te.getUp(); - final ForgeDirection fdz = te.getForward(); - final ForgeDirection fdx = Platform.crossProduct( fdz, fdy ).getOpposite(); + this.setInvRenderBounds(renderer, 13, 1, 0, 16, 15, 16); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); - renderer.renderAllFaces = true; + this.setInvRenderBounds(renderer, 1, 0, 1, 15, 2, 15); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); - // sides... - this.renderBlockBounds( renderer, 3, 1, 0, 13, 15, 3, fdx, fdy, fdz ); - boolean out = renderer.renderStandardBlock( block, x, y, z ); + this.setInvRenderBounds(renderer, 1, 14, 1, 15, 16, 15); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); - this.renderBlockBounds( renderer, 0, 1, 0, 3, 15, 16, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + blk.getRendererInstance().setTemporaryRenderIcon(ExtraBlockTextures.BlockInscriberInside.getIcon()); - this.renderBlockBounds( renderer, 13, 1, 0, 16, 15, 16, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + // press + this.setInvRenderBounds(renderer, 3, 2, 3, 13, 3, 13); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); - // top bottom.. - this.renderBlockBounds( renderer, 1, 0, 1, 15, 4, 15, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + this.setInvRenderBounds(renderer, 3, 13, 3, 13, 15, 13); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); - this.renderBlockBounds( renderer, 1, 12, 1, 15, 16, 15, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + blk.getRendererInstance().setTemporaryRenderIcon(null); - block.getRendererInstance().setTemporaryRenderIcon( null ); + renderer.renderAllFaces = false; + // blk.getRendererInstance().setTemporaryRenderIcon( null ); - renderer.renderAllFaces = false; - block.getRendererInstance().setTemporaryRenderIcon( null ); + } - this.postRenderInWorld( renderer ); - return out; - } + @Override + public boolean renderInWorld( + final BlockInscriber block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + final IOrientable te = this.getOrientable(block, world, x, y, z); - @Override - public void renderTile( final BlockInscriber block, final TileInscriber tile, final Tessellator tess, final double x, final double y, final double z, final float f, final RenderBlocks renderer ) - { - // render inscriber + if (te == null) { + return false; + } - GL11.glPushMatrix(); - this.applyTESRRotation( x, y, z, tile.getForward(), tile.getUp() ); - - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - - // render sides of stamps - GL11.glCullFace( GL11.GL_FRONT ); - - final Minecraft mc = Minecraft.getMinecraft(); - mc.renderEngine.bindTexture( TextureMap.locationBlocksTexture ); - - // << 20 | light << 4; - final int br = tile.getWorldObj().getLightBrightnessForSkyBlocks( tile.xCoord, tile.yCoord, tile.zCoord, 0 ); - final int var11 = br % 65536; - final int var12 = br / 65536; - - OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, var11, var12 ); - - long absoluteProgress = 0; - - if( tile.isSmash() ) - { - final long currentTime = System.currentTimeMillis(); - absoluteProgress = currentTime - tile.getClientStart(); - if( absoluteProgress > 800 ) - { - tile.setSmash( false ); - } - } - - final float relativeProgress = absoluteProgress % 800 / 400.0f; - float progress = relativeProgress; - - if( progress > 1.0f ) - { - progress = 1.0f - ( progress - 1.0f ); - } - float press = 0.2f; - press -= progress / 5.0f; - - final IIcon ic = ExtraBlockTextures.BlockInscriberInside.getIcon(); - tess.startDrawingQuads(); - - float middle = 0.5f; - middle += 0.02f; - final float TwoPx = 2.0f / 16.0f; - tess.addVertexWithUV( TwoPx, middle + press, TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 2 ) ); - tess.addVertexWithUV( 1.0 - TwoPx, middle + press, TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 2 ) ); - tess.addVertexWithUV( 1.0 - TwoPx, middle + press, 1.0 - TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 13 ) ); - tess.addVertexWithUV( TwoPx, middle + press, 1.0 - TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 13 ) ); - - tess.addVertexWithUV( TwoPx, middle + press, 1.0 - TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 3 ) ); - tess.addVertexWithUV( 1.0 - TwoPx, middle + press, 1.0 - TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 3 ) ); - final float base = 0.4f; - tess.addVertexWithUV( 1.0 - TwoPx, middle + base, 1.0 - TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 3 - 16 * ( press - base ) ) ); - tess.addVertexWithUV( TwoPx, middle + base, 1.0 - TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 3 - 16 * ( press - base ) ) ); - - middle -= 2.0f * 0.02f; - tess.addVertexWithUV( 1.0 - TwoPx, middle - press, TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 2 ) ); - tess.addVertexWithUV( TwoPx, middle - press, TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 2 ) ); - tess.addVertexWithUV( TwoPx, middle - press, 1.0 - TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 13 ) ); - tess.addVertexWithUV( 1.0 - TwoPx, middle - press, 1.0 - TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 13 ) ); - - tess.addVertexWithUV( 1.0 - TwoPx, middle - press, 1.0 - TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 3 ) ); - tess.addVertexWithUV( TwoPx, middle - press, 1.0 - TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 3 ) ); - tess.addVertexWithUV( TwoPx, middle - base, 1.0 - TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 3 - 16 * ( press - base ) ) ); - tess.addVertexWithUV( 1.0 - TwoPx, middle + -base, 1.0 - TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 3 - 16 * ( press - base ) ) ); - - tess.draw(); - - GL11.glPopMatrix(); - - // render items. - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - - int items = 0; - if( tile.getStackInSlot( 0 ) != null ) - { - items++; - } - if( tile.getStackInSlot( 1 ) != null ) - { - items++; - } - if( tile.getStackInSlot( 2 ) != null ) - { - items++; - } - - if( relativeProgress > 1.0f || items == 0 ) - { - ItemStack is = tile.getStackInSlot( 3 ); - - if( is == null ) - { - final IInscriberRecipe ir = tile.getTask(); - if( ir != null ) - { - is = ir.getOutput().copy(); - } - } - - this.renderItem( is, 0.0f, block, tile, tess, x, y, z, f, renderer ); - } - else - { - this.renderItem( tile.getStackInSlot( 0 ), press, block, tile, tess, x, y, z, f, renderer ); - this.renderItem( tile.getStackInSlot( 1 ), -press, block, tile, tess, x, y, z, f, renderer ); - this.renderItem( tile.getStackInSlot( 2 ), 0.0f, block, tile, tess, x, y, z, f, renderer ); - } - - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glCullFace( GL11.GL_BACK ); - } - - private void renderItem( ItemStack sis, final float o, final AEBaseBlock block, final AEBaseTile tile, final Tessellator tess, final double x, final double y, final double z, final float f, final RenderBlocks renderer ) - { - if( sis != null ) - { - sis = sis.copy(); - - GL11.glPushMatrix(); - // fix to inscriber - this.applyTESRRotation( x, y, z, tile.getForward(), tile.getUp() ); - - try - { - // move to center - GL11.glTranslatef( 0.5f, 0.5f + o, 0.5f ); - - // set scale - GL11.glScalef( ITEM_RENDER_SCALE, ITEM_RENDER_SCALE, ITEM_RENDER_SCALE ); - - final Block blk = Block.getBlockFromItem( sis.getItem() ); - - // is a block - if( sis.getItemSpriteNumber() == 0 && block != null && RenderBlocks.renderItemIn3d( blk.getRenderType() ) ) - { - // rotate block in angle to make it more plastic - GL11.glRotatef( 22.5f, 1f, 0f, 0f ); - GL11.glRotatef( -33.75f, 0f, 1f, 0f ); - } - else - { - // rotate item to match the inventory icon orientation. - GL11.glRotatef( -90.0f, 1f, 0f, 0f ); - GL11.glRotatef( 180.0f, 0f, 1f, 0f ); - } - - // << 20 | light << 4; - final int br = tile.getWorldObj().getLightBrightnessForSkyBlocks( tile.xCoord, tile.yCoord, tile.zCoord, 0 ); - final int var11 = br % 65536; - final int var12 = br / 65536; - - OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, var11, var12 ); - - tess.setColorOpaque_F( 1.0f, 1.0f, 1.0f ); - - this.doRenderItem( sis, tile ); - } - catch( final Exception err ) - { - AELog.debug( err ); - } - - GL11.glPopMatrix(); - } - } + this.preRenderInWorld(block, world, x, y, z, renderer); + + final ForgeDirection fdy = te.getUp(); + final ForgeDirection fdz = te.getForward(); + final ForgeDirection fdx = Platform.crossProduct(fdz, fdy).getOpposite(); + + renderer.renderAllFaces = true; + + // sides... + this.renderBlockBounds(renderer, 3, 1, 0, 13, 15, 3, fdx, fdy, fdz); + boolean out = renderer.renderStandardBlock(block, x, y, z); + + this.renderBlockBounds(renderer, 0, 1, 0, 3, 15, 16, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); + + this.renderBlockBounds(renderer, 13, 1, 0, 16, 15, 16, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); + + // top bottom.. + this.renderBlockBounds(renderer, 1, 0, 1, 15, 4, 15, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); + + this.renderBlockBounds(renderer, 1, 12, 1, 15, 16, 15, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); + + block.getRendererInstance().setTemporaryRenderIcon(null); + + renderer.renderAllFaces = false; + block.getRendererInstance().setTemporaryRenderIcon(null); + + this.postRenderInWorld(renderer); + return out; + } + + @Override + public void renderTile( + final BlockInscriber block, + final TileInscriber tile, + final Tessellator tess, + final double x, + final double y, + final double z, + final float f, + final RenderBlocks renderer) { + // render inscriber + + GL11.glPushMatrix(); + this.applyTESRRotation(x, y, z, tile.getForward(), tile.getUp()); + + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + + // render sides of stamps + GL11.glCullFace(GL11.GL_FRONT); + + final Minecraft mc = Minecraft.getMinecraft(); + mc.renderEngine.bindTexture(TextureMap.locationBlocksTexture); + + // << 20 | light << 4; + final int br = tile.getWorldObj().getLightBrightnessForSkyBlocks(tile.xCoord, tile.yCoord, tile.zCoord, 0); + final int var11 = br % 65536; + final int var12 = br / 65536; + + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, var11, var12); + + long absoluteProgress = 0; + + if (tile.isSmash()) { + final long currentTime = System.currentTimeMillis(); + absoluteProgress = currentTime - tile.getClientStart(); + if (absoluteProgress > 800) { + tile.setSmash(false); + } + } + + final float relativeProgress = absoluteProgress % 800 / 400.0f; + float progress = relativeProgress; + + if (progress > 1.0f) { + progress = 1.0f - (progress - 1.0f); + } + float press = 0.2f; + press -= progress / 5.0f; + + final IIcon ic = ExtraBlockTextures.BlockInscriberInside.getIcon(); + tess.startDrawingQuads(); + + float middle = 0.5f; + middle += 0.02f; + final float TwoPx = 2.0f / 16.0f; + tess.addVertexWithUV(TwoPx, middle + press, TwoPx, ic.getInterpolatedU(2), ic.getInterpolatedV(2)); + tess.addVertexWithUV(1.0 - TwoPx, middle + press, TwoPx, ic.getInterpolatedU(14), ic.getInterpolatedV(2)); + tess.addVertexWithUV( + 1.0 - TwoPx, middle + press, 1.0 - TwoPx, ic.getInterpolatedU(14), ic.getInterpolatedV(13)); + tess.addVertexWithUV(TwoPx, middle + press, 1.0 - TwoPx, ic.getInterpolatedU(2), ic.getInterpolatedV(13)); + + tess.addVertexWithUV(TwoPx, middle + press, 1.0 - TwoPx, ic.getInterpolatedU(2), ic.getInterpolatedV(3)); + tess.addVertexWithUV(1.0 - TwoPx, middle + press, 1.0 - TwoPx, ic.getInterpolatedU(14), ic.getInterpolatedV(3)); + final float base = 0.4f; + tess.addVertexWithUV( + 1.0 - TwoPx, + middle + base, + 1.0 - TwoPx, + ic.getInterpolatedU(14), + ic.getInterpolatedV(3 - 16 * (press - base))); + tess.addVertexWithUV( + TwoPx, + middle + base, + 1.0 - TwoPx, + ic.getInterpolatedU(2), + ic.getInterpolatedV(3 - 16 * (press - base))); + + middle -= 2.0f * 0.02f; + tess.addVertexWithUV(1.0 - TwoPx, middle - press, TwoPx, ic.getInterpolatedU(2), ic.getInterpolatedV(2)); + tess.addVertexWithUV(TwoPx, middle - press, TwoPx, ic.getInterpolatedU(14), ic.getInterpolatedV(2)); + tess.addVertexWithUV(TwoPx, middle - press, 1.0 - TwoPx, ic.getInterpolatedU(14), ic.getInterpolatedV(13)); + tess.addVertexWithUV(1.0 - TwoPx, middle - press, 1.0 - TwoPx, ic.getInterpolatedU(2), ic.getInterpolatedV(13)); + + tess.addVertexWithUV(1.0 - TwoPx, middle - press, 1.0 - TwoPx, ic.getInterpolatedU(2), ic.getInterpolatedV(3)); + tess.addVertexWithUV(TwoPx, middle - press, 1.0 - TwoPx, ic.getInterpolatedU(14), ic.getInterpolatedV(3)); + tess.addVertexWithUV( + TwoPx, + middle - base, + 1.0 - TwoPx, + ic.getInterpolatedU(14), + ic.getInterpolatedV(3 - 16 * (press - base))); + tess.addVertexWithUV( + 1.0 - TwoPx, + middle + -base, + 1.0 - TwoPx, + ic.getInterpolatedU(2), + ic.getInterpolatedV(3 - 16 * (press - base))); + + tess.draw(); + + GL11.glPopMatrix(); + + // render items. + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + int items = 0; + if (tile.getStackInSlot(0) != null) { + items++; + } + if (tile.getStackInSlot(1) != null) { + items++; + } + if (tile.getStackInSlot(2) != null) { + items++; + } + + if (relativeProgress > 1.0f || items == 0) { + ItemStack is = tile.getStackInSlot(3); + + if (is == null) { + final IInscriberRecipe ir = tile.getTask(); + if (ir != null) { + is = ir.getOutput().copy(); + } + } + + this.renderItem(is, 0.0f, block, tile, tess, x, y, z, f, renderer); + } else { + this.renderItem(tile.getStackInSlot(0), press, block, tile, tess, x, y, z, f, renderer); + this.renderItem(tile.getStackInSlot(1), -press, block, tile, tess, x, y, z, f, renderer); + this.renderItem(tile.getStackInSlot(2), 0.0f, block, tile, tess, x, y, z, f, renderer); + } + + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glCullFace(GL11.GL_BACK); + } + + private void renderItem( + ItemStack sis, + final float o, + final AEBaseBlock block, + final AEBaseTile tile, + final Tessellator tess, + final double x, + final double y, + final double z, + final float f, + final RenderBlocks renderer) { + if (sis != null) { + sis = sis.copy(); + + GL11.glPushMatrix(); + // fix to inscriber + this.applyTESRRotation(x, y, z, tile.getForward(), tile.getUp()); + + try { + // move to center + GL11.glTranslatef(0.5f, 0.5f + o, 0.5f); + + // set scale + GL11.glScalef(ITEM_RENDER_SCALE, ITEM_RENDER_SCALE, ITEM_RENDER_SCALE); + + final Block blk = Block.getBlockFromItem(sis.getItem()); + + // is a block + if (sis.getItemSpriteNumber() == 0 + && block != null + && RenderBlocks.renderItemIn3d(blk.getRenderType())) { + // rotate block in angle to make it more plastic + GL11.glRotatef(22.5f, 1f, 0f, 0f); + GL11.glRotatef(-33.75f, 0f, 1f, 0f); + } else { + // rotate item to match the inventory icon orientation. + GL11.glRotatef(-90.0f, 1f, 0f, 0f); + GL11.glRotatef(180.0f, 0f, 1f, 0f); + } + + // << 20 | light << 4; + final int br = + tile.getWorldObj().getLightBrightnessForSkyBlocks(tile.xCoord, tile.yCoord, tile.zCoord, 0); + final int var11 = br % 65536; + final int var12 = br / 65536; + + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, var11, var12); + + tess.setColorOpaque_F(1.0f, 1.0f, 1.0f); + + this.doRenderItem(sis, tile); + } catch (final Exception err) { + AELog.debug(err); + } + + GL11.glPopMatrix(); + } + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockInterface.java b/src/main/java/appeng/client/render/blocks/RenderBlockInterface.java index ecd8527f413..02163e45373 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockInterface.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockInterface.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.misc.BlockInterface; import appeng.client.render.BaseBlockRender; import appeng.client.render.BlockRenderInfo; @@ -29,31 +28,33 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; +public class RenderBlockInterface extends BaseBlockRender { -public class RenderBlockInterface extends BaseBlockRender -{ - - public RenderBlockInterface() - { - super( false, 20 ); - } + public RenderBlockInterface() { + super(false, 20); + } - @Override - public boolean renderInWorld( final BlockInterface block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TileInterface ti = block.getTileEntity( world, x, y, z ); - final BlockRenderInfo info = block.getRendererInstance(); + @Override + public boolean renderInWorld( + final BlockInterface block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + final TileInterface ti = block.getTileEntity(world, x, y, z); + final BlockRenderInfo info = block.getRendererInstance(); - if( ti != null && ti.getForward() != ForgeDirection.UNKNOWN ) - { - final IIcon side = ExtraBlockTextures.BlockInterfaceAlternateArrow.getIcon(); - info.setTemporaryRenderIcons( ExtraBlockTextures.BlockInterfaceAlternate.getIcon(), block.getIcon( 0, 0 ), side, side, side, side ); - } + if (ti != null && ti.getForward() != ForgeDirection.UNKNOWN) { + final IIcon side = ExtraBlockTextures.BlockInterfaceAlternateArrow.getIcon(); + info.setTemporaryRenderIcons( + ExtraBlockTextures.BlockInterfaceAlternate.getIcon(), block.getIcon(0, 0), side, side, side, side); + } - final boolean fz = super.renderInWorld( block, world, x, y, z, renderer ); + final boolean fz = super.renderInWorld(block, world, x, y, z, renderer); - info.setTemporaryRenderIcon( null ); + info.setTemporaryRenderIcon(null); - return fz; - } + return fz; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockPaint.java b/src/main/java/appeng/client/render/blocks/RenderBlockPaint.java index 3d3755253f0..9d406cd46fb 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockPaint.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockPaint.java @@ -18,12 +18,12 @@ package appeng.client.render.blocks; - import appeng.block.misc.BlockPaint; import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; import appeng.helpers.Splotch; import appeng.tile.misc.TilePaint; +import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.item.ItemStack; @@ -32,154 +32,142 @@ import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class RenderBlockPaint extends BaseBlockRender -{ - - public RenderBlockPaint() - { - super( false, 0 ); - } - - @Override - public void renderInventory( final BlockPaint block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - - } - - @Override - public boolean renderInWorld( final BlockPaint imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TilePaint tp = imb.getTileEntity( world, x, y, z ); - boolean out = false; - - if( tp != null ) - { - // super.renderInWorld( imb, world, x, y, z, renderer ); - - final IIcon[] icoSet = { imb.getIcon( 0, 0 ), ExtraBlockTextures.BlockPaint2.getIcon(), ExtraBlockTextures.BlockPaint3.getIcon() }; - - final Tessellator tess = Tessellator.instance; - - final int brightness = imb.getMixedBrightnessForBlock( world, x, y, z ); - - final EnumSet validSides = EnumSet.noneOf( ForgeDirection.class ); - - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - if( tp.isSideValid( side ) ) - { - validSides.add( side ); - } - } - - double offsetConstant = 0.001; - final int lumen = 14 << 20 | 14 << 4; - for( final Splotch s : tp.getDots() ) - { - if( !validSides.contains( s.getSide() ) ) - { - continue; - } - - if( s.isLumen() ) - { - tess.setColorOpaque_I( s.getColor().whiteVariant ); - tess.setBrightness( lumen ); - } - else - { - tess.setColorOpaque_I( s.getColor().mediumVariant ); - tess.setBrightness( brightness ); - } - - double offset = offsetConstant; - offsetConstant += 0.001; - - final double buffer = 0.1; - - double pos_x = s.x(); - double pos_y = s.y(); - - pos_x = Math.max( buffer, Math.min( 1.0 - buffer, pos_x ) ); - pos_y = Math.max( buffer, Math.min( 1.0 - buffer, pos_y ) ); - - if( s.getSide() == ForgeDirection.SOUTH || s.getSide() == ForgeDirection.NORTH ) - { - pos_x += x; - pos_y += y; - } - - else if( s.getSide() == ForgeDirection.UP || s.getSide() == ForgeDirection.DOWN ) - { - pos_x += x; - pos_y += z; - } - - else - { - pos_x += y; - pos_y += z; - } - - final IIcon ico = icoSet[s.getSeed() % icoSet.length]; - - switch( s.getSide() ) - { - case UP: - offset = 1.0 - offset; - tess.addVertexWithUV( pos_x - buffer, y + offset, pos_y - buffer, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x + buffer, y + offset, pos_y - buffer, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x + buffer, y + offset, pos_y + buffer, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( pos_x - buffer, y + offset, pos_y + buffer, ico.getMinU(), ico.getMaxV() ); - break; - - case DOWN: - tess.addVertexWithUV( pos_x + buffer, y + offset, pos_y - buffer, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x - buffer, y + offset, pos_y - buffer, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x - buffer, y + offset, pos_y + buffer, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( pos_x + buffer, y + offset, pos_y + buffer, ico.getMinU(), ico.getMaxV() ); - break; - - case EAST: - offset = 1.0 - offset; - tess.addVertexWithUV( x + offset, pos_x + buffer, pos_y - buffer, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( x + offset, pos_x - buffer, pos_y - buffer, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( x + offset, pos_x - buffer, pos_y + buffer, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( x + offset, pos_x + buffer, pos_y + buffer, ico.getMinU(), ico.getMaxV() ); - break; - - case WEST: - tess.addVertexWithUV( x + offset, pos_x - buffer, pos_y - buffer, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( x + offset, pos_x + buffer, pos_y - buffer, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( x + offset, pos_x + buffer, pos_y + buffer, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( x + offset, pos_x - buffer, pos_y + buffer, ico.getMinU(), ico.getMaxV() ); - break; - - case SOUTH: - offset = 1.0 - offset; - tess.addVertexWithUV( pos_x + buffer, pos_y - buffer, z + offset, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x - buffer, pos_y - buffer, z + offset, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x - buffer, pos_y + buffer, z + offset, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( pos_x + buffer, pos_y + buffer, z + offset, ico.getMinU(), ico.getMaxV() ); - break; - - case NORTH: - tess.addVertexWithUV( pos_x - buffer, pos_y - buffer, z + offset, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x + buffer, pos_y - buffer, z + offset, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x + buffer, pos_y + buffer, z + offset, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( pos_x - buffer, pos_y + buffer, z + offset, ico.getMinU(), ico.getMaxV() ); - break; - - default: - } - } - - out = true; - } - - return out; - } +public class RenderBlockPaint extends BaseBlockRender { + + public RenderBlockPaint() { + super(false, 0); + } + + @Override + public void renderInventory( + final BlockPaint block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) {} + + @Override + public boolean renderInWorld( + final BlockPaint imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + final TilePaint tp = imb.getTileEntity(world, x, y, z); + boolean out = false; + + if (tp != null) { + // super.renderInWorld( imb, world, x, y, z, renderer ); + + final IIcon[] icoSet = { + imb.getIcon(0, 0), ExtraBlockTextures.BlockPaint2.getIcon(), ExtraBlockTextures.BlockPaint3.getIcon() + }; + + final Tessellator tess = Tessellator.instance; + + final int brightness = imb.getMixedBrightnessForBlock(world, x, y, z); + + final EnumSet validSides = EnumSet.noneOf(ForgeDirection.class); + + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + if (tp.isSideValid(side)) { + validSides.add(side); + } + } + + double offsetConstant = 0.001; + final int lumen = 14 << 20 | 14 << 4; + for (final Splotch s : tp.getDots()) { + if (!validSides.contains(s.getSide())) { + continue; + } + + if (s.isLumen()) { + tess.setColorOpaque_I(s.getColor().whiteVariant); + tess.setBrightness(lumen); + } else { + tess.setColorOpaque_I(s.getColor().mediumVariant); + tess.setBrightness(brightness); + } + + double offset = offsetConstant; + offsetConstant += 0.001; + + final double buffer = 0.1; + + double pos_x = s.x(); + double pos_y = s.y(); + + pos_x = Math.max(buffer, Math.min(1.0 - buffer, pos_x)); + pos_y = Math.max(buffer, Math.min(1.0 - buffer, pos_y)); + + if (s.getSide() == ForgeDirection.SOUTH || s.getSide() == ForgeDirection.NORTH) { + pos_x += x; + pos_y += y; + } else if (s.getSide() == ForgeDirection.UP || s.getSide() == ForgeDirection.DOWN) { + pos_x += x; + pos_y += z; + } else { + pos_x += y; + pos_y += z; + } + + final IIcon ico = icoSet[s.getSeed() % icoSet.length]; + + switch (s.getSide()) { + case UP: + offset = 1.0 - offset; + tess.addVertexWithUV(pos_x - buffer, y + offset, pos_y - buffer, ico.getMinU(), ico.getMinV()); + tess.addVertexWithUV(pos_x + buffer, y + offset, pos_y - buffer, ico.getMaxU(), ico.getMinV()); + tess.addVertexWithUV(pos_x + buffer, y + offset, pos_y + buffer, ico.getMaxU(), ico.getMaxV()); + tess.addVertexWithUV(pos_x - buffer, y + offset, pos_y + buffer, ico.getMinU(), ico.getMaxV()); + break; + + case DOWN: + tess.addVertexWithUV(pos_x + buffer, y + offset, pos_y - buffer, ico.getMinU(), ico.getMinV()); + tess.addVertexWithUV(pos_x - buffer, y + offset, pos_y - buffer, ico.getMaxU(), ico.getMinV()); + tess.addVertexWithUV(pos_x - buffer, y + offset, pos_y + buffer, ico.getMaxU(), ico.getMaxV()); + tess.addVertexWithUV(pos_x + buffer, y + offset, pos_y + buffer, ico.getMinU(), ico.getMaxV()); + break; + + case EAST: + offset = 1.0 - offset; + tess.addVertexWithUV(x + offset, pos_x + buffer, pos_y - buffer, ico.getMinU(), ico.getMinV()); + tess.addVertexWithUV(x + offset, pos_x - buffer, pos_y - buffer, ico.getMaxU(), ico.getMinV()); + tess.addVertexWithUV(x + offset, pos_x - buffer, pos_y + buffer, ico.getMaxU(), ico.getMaxV()); + tess.addVertexWithUV(x + offset, pos_x + buffer, pos_y + buffer, ico.getMinU(), ico.getMaxV()); + break; + + case WEST: + tess.addVertexWithUV(x + offset, pos_x - buffer, pos_y - buffer, ico.getMinU(), ico.getMinV()); + tess.addVertexWithUV(x + offset, pos_x + buffer, pos_y - buffer, ico.getMaxU(), ico.getMinV()); + tess.addVertexWithUV(x + offset, pos_x + buffer, pos_y + buffer, ico.getMaxU(), ico.getMaxV()); + tess.addVertexWithUV(x + offset, pos_x - buffer, pos_y + buffer, ico.getMinU(), ico.getMaxV()); + break; + + case SOUTH: + offset = 1.0 - offset; + tess.addVertexWithUV(pos_x + buffer, pos_y - buffer, z + offset, ico.getMinU(), ico.getMinV()); + tess.addVertexWithUV(pos_x - buffer, pos_y - buffer, z + offset, ico.getMaxU(), ico.getMinV()); + tess.addVertexWithUV(pos_x - buffer, pos_y + buffer, z + offset, ico.getMaxU(), ico.getMaxV()); + tess.addVertexWithUV(pos_x + buffer, pos_y + buffer, z + offset, ico.getMinU(), ico.getMaxV()); + break; + + case NORTH: + tess.addVertexWithUV(pos_x - buffer, pos_y - buffer, z + offset, ico.getMinU(), ico.getMinV()); + tess.addVertexWithUV(pos_x + buffer, pos_y - buffer, z + offset, ico.getMaxU(), ico.getMinV()); + tess.addVertexWithUV(pos_x + buffer, pos_y + buffer, z + offset, ico.getMaxU(), ico.getMaxV()); + tess.addVertexWithUV(pos_x - buffer, pos_y + buffer, z + offset, ico.getMinU(), ico.getMaxV()); + break; + + default: + } + } + + out = true; + } + + return out; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockQuartzAccelerator.java b/src/main/java/appeng/client/render/blocks/RenderBlockQuartzAccelerator.java index 9d830eb962a..865b37cde3a 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockQuartzAccelerator.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockQuartzAccelerator.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.misc.BlockQuartzGrowthAccelerator; import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; @@ -28,37 +27,38 @@ import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; +public class RenderBlockQuartzAccelerator + extends BaseBlockRender { -public class RenderBlockQuartzAccelerator extends BaseBlockRender -{ - - public RenderBlockQuartzAccelerator() - { - super( false, 20 ); - } + public RenderBlockQuartzAccelerator() { + super(false, 20); + } - @Override - public boolean renderInWorld( final BlockQuartzGrowthAccelerator blk, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TileEntity te = world.getTileEntity( x, y, z ); + @Override + public boolean renderInWorld( + final BlockQuartzGrowthAccelerator blk, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + final TileEntity te = world.getTileEntity(x, y, z); - if( te instanceof TileQuartzGrowthAccelerator ) - { - final TileQuartzGrowthAccelerator tileCGA = (TileQuartzGrowthAccelerator) te; + if (te instanceof TileQuartzGrowthAccelerator) { + final TileQuartzGrowthAccelerator tileCGA = (TileQuartzGrowthAccelerator) te; - if( tileCGA.isPowered() ) - { - final IIcon top_Bottom = ExtraBlockTextures.BlockQuartzGrowthAcceleratorOn.getIcon(); - final IIcon side = ExtraBlockTextures.BlockQuartzGrowthAcceleratorSideOn.getIcon(); + if (tileCGA.isPowered()) { + final IIcon top_Bottom = ExtraBlockTextures.BlockQuartzGrowthAcceleratorOn.getIcon(); + final IIcon side = ExtraBlockTextures.BlockQuartzGrowthAcceleratorSideOn.getIcon(); - blk.getRendererInstance().setTemporaryRenderIcons( top_Bottom, top_Bottom, side, side, side, side ); - } - } + blk.getRendererInstance().setTemporaryRenderIcons(top_Bottom, top_Bottom, side, side, side, side); + } + } - final boolean out = super.renderInWorld( blk, world, x, y, z, renderer ); + final boolean out = super.renderInWorld(blk, world, x, y, z, renderer); - blk.getRendererInstance().setTemporaryRenderIcon( null ); + blk.getRendererInstance().setTemporaryRenderIcon(null); - return out; - } + return out; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockSkyChest.java b/src/main/java/appeng/client/render/blocks/RenderBlockSkyChest.java index c2917dbd256..c28722ee64e 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockSkyChest.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockSkyChest.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.storage.BlockSkyChest; import appeng.client.render.BaseBlockRender; import appeng.tile.storage.TileSkyChest; @@ -33,109 +32,115 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; - -public class RenderBlockSkyChest extends BaseBlockRender -{ - - private static final ResourceLocation SKY_STONE_CHEST = new ResourceLocation( "appliedenergistics2", "textures/models/skychest.png" ); - private static final ResourceLocation SKY_BLOCK_CHEST = new ResourceLocation( "appliedenergistics2", "textures/models/skyblockchest.png" ); - private static final ResourceLocation[] METADATA_TO_TEXTURE = { - SKY_STONE_CHEST, - SKY_BLOCK_CHEST - }; - - private final ModelChest model = new ModelChest(); - - public RenderBlockSkyChest() - { - super( true, 80 ); - } - - @Override - public void renderInventory( final BlockSkyChest blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - - final int metaData = is.getItemDamage(); - final ResourceLocation loc = METADATA_TO_TEXTURE[metaData]; - - Minecraft.getMinecraft().getTextureManager().bindTexture( loc ); - - GL11.glScalef( 1.0F, -1F, -1F ); - GL11.glTranslatef( -0.0F, -1.0F, -1.0F ); - - this.model.chestLid.offsetY = -( 0.9f / 16.0f ); - final float lidAngle = 0.0f; - this.model.chestLid.rotateAngleX = -( ( lidAngle * 3.141593F ) / 2.0F ); - this.model.renderAll(); - - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - } - - @Override - public boolean renderInWorld( final BlockSkyChest blk, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - return true; - } - - @Override - public void renderTile( final BlockSkyChest block, final TileSkyChest skyChest, final Tessellator tess, final double x, final double y, final double z, final float partialTick, final RenderBlocks renderer ) - { - if( skyChest == null || !skyChest.hasWorldObj() ) - { - return; - } - - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - - final int metaData = skyChest.getWorldObj().getBlockMetadata( skyChest.xCoord, skyChest.yCoord, skyChest.zCoord ); - final ResourceLocation loc = METADATA_TO_TEXTURE[metaData]; - - Minecraft.getMinecraft().getTextureManager().bindTexture( loc ); - - this.applyTESRRotation( x, y, z, skyChest.getForward(), skyChest.getUp() ); - - GL11.glScalef( 1.0F, -1F, -1F ); - GL11.glTranslatef( -0.0F, -1.0F, -1.0F ); - - final long now = System.currentTimeMillis(); - final long distance = now - skyChest.getLastEvent(); - - if( skyChest.getPlayerOpen() > 0 ) - { - skyChest.setLidAngle( skyChest.getLidAngle() + distance * 0.0001f ); - } - else - { - skyChest.setLidAngle( skyChest.getLidAngle() - distance * 0.0001f ); - } - - if( skyChest.getLidAngle() > 0.5f ) - { - skyChest.setLidAngle( 0.5f ); - } - - if( skyChest.getLidAngle() < 0.0f ) - { - skyChest.setLidAngle( 0.0f ); - } - - float lidAngle = skyChest.getLidAngle(); - lidAngle = 1.0F - lidAngle; - lidAngle = 1.0F - lidAngle * lidAngle * lidAngle; - - this.model.chestLid.offsetY = -( 1.01f / 16.0f ); - this.model.chestLid.rotateAngleX = -( ( lidAngle * 3.141593F ) / 2.0F ); - - // The vanilla chests wants culling reversed... - GL11.glCullFace( GL11.GL_FRONT ); - this.model.renderAll(); - GL11.glCullFace( GL11.GL_BACK ); - - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - } +public class RenderBlockSkyChest extends BaseBlockRender { + + private static final ResourceLocation SKY_STONE_CHEST = + new ResourceLocation("appliedenergistics2", "textures/models/skychest.png"); + private static final ResourceLocation SKY_BLOCK_CHEST = + new ResourceLocation("appliedenergistics2", "textures/models/skyblockchest.png"); + private static final ResourceLocation[] METADATA_TO_TEXTURE = {SKY_STONE_CHEST, SKY_BLOCK_CHEST}; + + private final ModelChest model = new ModelChest(); + + public RenderBlockSkyChest() { + super(true, 80); + } + + @Override + public void renderInventory( + final BlockSkyChest blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + final int metaData = is.getItemDamage(); + final ResourceLocation loc = METADATA_TO_TEXTURE[metaData]; + + Minecraft.getMinecraft().getTextureManager().bindTexture(loc); + + GL11.glScalef(1.0F, -1F, -1F); + GL11.glTranslatef(-0.0F, -1.0F, -1.0F); + + this.model.chestLid.offsetY = -(0.9f / 16.0f); + final float lidAngle = 0.0f; + this.model.chestLid.rotateAngleX = -((lidAngle * 3.141593F) / 2.0F); + this.model.renderAll(); + + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + } + + @Override + public boolean renderInWorld( + final BlockSkyChest blk, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + return true; + } + + @Override + public void renderTile( + final BlockSkyChest block, + final TileSkyChest skyChest, + final Tessellator tess, + final double x, + final double y, + final double z, + final float partialTick, + final RenderBlocks renderer) { + if (skyChest == null || !skyChest.hasWorldObj()) { + return; + } + + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + final int metaData = skyChest.getWorldObj().getBlockMetadata(skyChest.xCoord, skyChest.yCoord, skyChest.zCoord); + final ResourceLocation loc = METADATA_TO_TEXTURE[metaData]; + + Minecraft.getMinecraft().getTextureManager().bindTexture(loc); + + this.applyTESRRotation(x, y, z, skyChest.getForward(), skyChest.getUp()); + + GL11.glScalef(1.0F, -1F, -1F); + GL11.glTranslatef(-0.0F, -1.0F, -1.0F); + + final long now = System.currentTimeMillis(); + final long distance = now - skyChest.getLastEvent(); + + if (skyChest.getPlayerOpen() > 0) { + skyChest.setLidAngle(skyChest.getLidAngle() + distance * 0.0001f); + } else { + skyChest.setLidAngle(skyChest.getLidAngle() - distance * 0.0001f); + } + + if (skyChest.getLidAngle() > 0.5f) { + skyChest.setLidAngle(0.5f); + } + + if (skyChest.getLidAngle() < 0.0f) { + skyChest.setLidAngle(0.0f); + } + + float lidAngle = skyChest.getLidAngle(); + lidAngle = 1.0F - lidAngle; + lidAngle = 1.0F - lidAngle * lidAngle * lidAngle; + + this.model.chestLid.offsetY = -(1.01f / 16.0f); + this.model.chestLid.rotateAngleX = -((lidAngle * 3.141593F) / 2.0F); + + // The vanilla chests wants culling reversed... + GL11.glCullFace(GL11.GL_FRONT); + this.model.renderAll(); + GL11.glCullFace(GL11.GL_BACK); + + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockSkyCompass.java b/src/main/java/appeng/client/render/blocks/RenderBlockSkyCompass.java index e438f530f82..f5b8b576ad5 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockSkyCompass.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockSkyCompass.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.misc.BlockSkyCompass; import appeng.client.render.BaseBlockRender; import appeng.client.render.model.ModelCompass; @@ -38,208 +37,188 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; - -public class RenderBlockSkyCompass extends BaseBlockRender -{ - private static final ResourceLocation TEXTURE_SKY_COMPASS = new ResourceLocation( "appliedenergistics2", "textures/models/compass.png" ); - - private final ModelCompass model = new ModelCompass(); - - public RenderBlockSkyCompass() - { - super( true, 80 ); - } - - @Override - public void renderInventory( final BlockSkyCompass blk, final ItemStack is, final RenderBlocks renderer, ItemRenderType type, final Object[] obj ) - { - if( type == ItemRenderType.INVENTORY ) - { - boolean isGood = false; - final IInventory inv = Minecraft.getMinecraft().thePlayer.inventory; - - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - if( inv.getStackInSlot( x ) == is ) - { - isGood = true; - } - } - - if( !isGood ) - { - type = ItemRenderType.FIRST_PERSON_MAP; - } - } - - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - - Minecraft.getMinecraft().getTextureManager().bindTexture( TEXTURE_SKY_COMPASS ); - - if( type == ItemRenderType.ENTITY ) - { - GL11.glRotatef( -90.0f, 0.0f, 0.0f, 1.0f ); - GL11.glScalef( 1.0F, -1F, -1F ); - GL11.glScalef( 2.5f, 2.5f, 2.5f ); - GL11.glTranslatef( -0.25F, -1.65F, -0.19F ); - } - else - { - if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) - { - GL11.glRotatef( 15.3f, 0.0f, 0.0f, 1.0f ); - } - - GL11.glScalef( 1.0F, -1F, -1F ); - GL11.glScalef( 2.5f, 2.5f, 2.5f ); - - if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) - { - GL11.glTranslatef( 0.3F, -1.65F, -0.19F ); - } - else - { - GL11.glTranslatef( 0.2F, -1.65F, -0.19F ); - } - } - - long now = System.currentTimeMillis(); - - if( type == ItemRenderType.EQUIPPED_FIRST_PERSON || type == ItemRenderType.INVENTORY || type == ItemRenderType.EQUIPPED ) - { - EntityPlayer p = Minecraft.getMinecraft().thePlayer; - float rYaw = p.rotationYaw; - - if( type == ItemRenderType.EQUIPPED ) - { - p = (EntityPlayer) obj[1]; - rYaw = p.renderYawOffset; - } - - final int x = (int) p.posX; - final int y = (int) p.posY; - final int z = (int) p.posZ; - final CompassResult cr = CompassManager.INSTANCE.getCompassDirection( 0, x, y, z ); - - for( int i = 0; i < 3; i++ ) - { - for( int j = 0; j < 3; j++ ) - { - CompassManager.INSTANCE.getCompassDirection( 0, x + i - 1, y, z + j - 1 ); - } - } - - if( cr.isValidResult() ) - { - if( cr.isSpin() ) - { - now %= 100000; - this.model.renderAll( ( now / 50000.0f ) * (float) Math.PI * 500.0f ); - } - else - { - if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) - { - final float offRads = rYaw / 180.0f * (float) Math.PI; - final float adjustment = (float) Math.PI * 0.74f; - - this.model.renderAll( (float) this.flipidiy( cr.getRad() + offRads + adjustment ) ); - } - else - { - final float offRads = rYaw / 180.0f * (float) Math.PI; - final float adjustment = (float) Math.PI * -0.74f; - - this.model.renderAll( (float) this.flipidiy( cr.getRad() + offRads + adjustment ) ); - } - } - } - else - { - now %= 1000000; - this.model.renderAll( ( now / 500000.0f ) * (float) Math.PI * 500.0f ); - } - } - else - { - now %= 100000; - this.model.renderAll( ( now / 50000.0f ) * (float) Math.PI * 500.0f ); - } - - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - } - - @Override - public boolean renderInWorld( final BlockSkyCompass blk, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - return true; - } - - @Override - public void renderTile( final BlockSkyCompass block, final TileSkyCompass skyCompass, final Tessellator tess, final double x, final double y, final double z, final float partialTick, final RenderBlocks renderer ) - { - if( skyCompass == null ) - { - return; - } - - if( !skyCompass.hasWorldObj() ) - { - return; - } - - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - GL11.glCullFace( GL11.GL_FRONT ); - - Minecraft.getMinecraft().getTextureManager().bindTexture( TEXTURE_SKY_COMPASS ); - - this.applyTESRRotation( x, y, z, skyCompass.getUp(), skyCompass.getForward() ); - - GL11.glScalef( 1.0F, -1F, -1F ); - GL11.glTranslatef( 0.5F, -1.5F, -0.5F ); - - long now = System.currentTimeMillis(); - CompassResult cr = null; - - if( skyCompass.getForward() == ForgeDirection.UP || skyCompass.getForward() == ForgeDirection.DOWN ) - { - cr = CompassManager.INSTANCE.getCompassDirection( 0, skyCompass.xCoord, skyCompass.yCoord, skyCompass.zCoord ); - } - else - { - cr = new CompassResult( false, true, 0 ); - } - - if( cr.isValidResult() ) - { - if( cr.isSpin() ) - { - now %= 100000; - this.model.renderAll( ( now / 50000.0f ) * (float) Math.PI * 500.0f ); - } - else - { - this.model.renderAll( (float) ( skyCompass.getForward() == ForgeDirection.DOWN ? this.flipidiy( cr.getRad() ) : cr.getRad() ) ); - } - } - else - { - now %= 1000000; - this.model.renderAll( ( now / 500000.0f ) * (float) Math.PI * 500.0f ); - } - - GL11.glCullFace( GL11.GL_BACK ); - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - } - - private double flipidiy( final double rad ) - { - final double x = Math.cos( rad ); - final double y = Math.sin( rad ); - return Math.atan2( -y, x ); - } +public class RenderBlockSkyCompass extends BaseBlockRender { + private static final ResourceLocation TEXTURE_SKY_COMPASS = + new ResourceLocation("appliedenergistics2", "textures/models/compass.png"); + + private final ModelCompass model = new ModelCompass(); + + public RenderBlockSkyCompass() { + super(true, 80); + } + + @Override + public void renderInventory( + final BlockSkyCompass blk, + final ItemStack is, + final RenderBlocks renderer, + ItemRenderType type, + final Object[] obj) { + if (type == ItemRenderType.INVENTORY) { + boolean isGood = false; + final IInventory inv = Minecraft.getMinecraft().thePlayer.inventory; + + for (int x = 0; x < inv.getSizeInventory(); x++) { + if (inv.getStackInSlot(x) == is) { + isGood = true; + } + } + + if (!isGood) { + type = ItemRenderType.FIRST_PERSON_MAP; + } + } + + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + Minecraft.getMinecraft().getTextureManager().bindTexture(TEXTURE_SKY_COMPASS); + + if (type == ItemRenderType.ENTITY) { + GL11.glRotatef(-90.0f, 0.0f, 0.0f, 1.0f); + GL11.glScalef(1.0F, -1F, -1F); + GL11.glScalef(2.5f, 2.5f, 2.5f); + GL11.glTranslatef(-0.25F, -1.65F, -0.19F); + } else { + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + GL11.glRotatef(15.3f, 0.0f, 0.0f, 1.0f); + } + + GL11.glScalef(1.0F, -1F, -1F); + GL11.glScalef(2.5f, 2.5f, 2.5f); + + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + GL11.glTranslatef(0.3F, -1.65F, -0.19F); + } else { + GL11.glTranslatef(0.2F, -1.65F, -0.19F); + } + } + + long now = System.currentTimeMillis(); + + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON + || type == ItemRenderType.INVENTORY + || type == ItemRenderType.EQUIPPED) { + EntityPlayer p = Minecraft.getMinecraft().thePlayer; + float rYaw = p.rotationYaw; + + if (type == ItemRenderType.EQUIPPED) { + p = (EntityPlayer) obj[1]; + rYaw = p.renderYawOffset; + } + + final int x = (int) p.posX; + final int y = (int) p.posY; + final int z = (int) p.posZ; + final CompassResult cr = CompassManager.INSTANCE.getCompassDirection(0, x, y, z); + + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + CompassManager.INSTANCE.getCompassDirection(0, x + i - 1, y, z + j - 1); + } + } + + if (cr.isValidResult()) { + if (cr.isSpin()) { + now %= 100000; + this.model.renderAll((now / 50000.0f) * (float) Math.PI * 500.0f); + } else { + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + final float offRads = rYaw / 180.0f * (float) Math.PI; + final float adjustment = (float) Math.PI * 0.74f; + + this.model.renderAll((float) this.flipidiy(cr.getRad() + offRads + adjustment)); + } else { + final float offRads = rYaw / 180.0f * (float) Math.PI; + final float adjustment = (float) Math.PI * -0.74f; + + this.model.renderAll((float) this.flipidiy(cr.getRad() + offRads + adjustment)); + } + } + } else { + now %= 1000000; + this.model.renderAll((now / 500000.0f) * (float) Math.PI * 500.0f); + } + } else { + now %= 100000; + this.model.renderAll((now / 50000.0f) * (float) Math.PI * 500.0f); + } + + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + } + + @Override + public boolean renderInWorld( + final BlockSkyCompass blk, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + return true; + } + + @Override + public void renderTile( + final BlockSkyCompass block, + final TileSkyCompass skyCompass, + final Tessellator tess, + final double x, + final double y, + final double z, + final float partialTick, + final RenderBlocks renderer) { + if (skyCompass == null) { + return; + } + + if (!skyCompass.hasWorldObj()) { + return; + } + + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glCullFace(GL11.GL_FRONT); + + Minecraft.getMinecraft().getTextureManager().bindTexture(TEXTURE_SKY_COMPASS); + + this.applyTESRRotation(x, y, z, skyCompass.getUp(), skyCompass.getForward()); + + GL11.glScalef(1.0F, -1F, -1F); + GL11.glTranslatef(0.5F, -1.5F, -0.5F); + + long now = System.currentTimeMillis(); + CompassResult cr = null; + + if (skyCompass.getForward() == ForgeDirection.UP || skyCompass.getForward() == ForgeDirection.DOWN) { + cr = CompassManager.INSTANCE.getCompassDirection( + 0, skyCompass.xCoord, skyCompass.yCoord, skyCompass.zCoord); + } else { + cr = new CompassResult(false, true, 0); + } + + if (cr.isValidResult()) { + if (cr.isSpin()) { + now %= 100000; + this.model.renderAll((now / 50000.0f) * (float) Math.PI * 500.0f); + } else { + this.model.renderAll((float) + (skyCompass.getForward() == ForgeDirection.DOWN ? this.flipidiy(cr.getRad()) : cr.getRad())); + } + } else { + now %= 1000000; + this.model.renderAll((now / 500000.0f) * (float) Math.PI * 500.0f); + } + + GL11.glCullFace(GL11.GL_BACK); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + } + + private double flipidiy(final double rad) { + final double x = Math.cos(rad); + final double y = Math.sin(rad); + return Math.atan2(-y, x); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockWireless.java b/src/main/java/appeng/client/render/blocks/RenderBlockWireless.java index de105aaf41a..68e4cc1148f 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockWireless.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockWireless.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.api.util.AEColor; import appeng.block.networking.BlockWireless; import appeng.client.render.BaseBlockRender; @@ -28,6 +27,7 @@ import appeng.client.texture.OffsetIcon; import appeng.tile.networking.TileWireless; import appeng.util.Platform; +import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.item.ItemStack; @@ -36,238 +36,302 @@ import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class RenderBlockWireless extends BaseBlockRender -{ - - private int centerX = 0; - private int centerY = 0; - private int centerZ = 0; - private BlockWireless blk; - private boolean hasChan = false; - private boolean hasPower = false; - - public RenderBlockWireless() - { - super( false, 20 ); - } - - @Override - public void renderInventory( final BlockWireless blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - this.blk = blk; - this.centerX = 0; - this.centerY = 0; - this.centerZ = 0; - this.hasChan = false; - this.hasPower = false; - - final BlockRenderInfo ri = blk.getRendererInstance(); - final Tessellator tess = Tessellator.instance; - - renderer.renderAllFaces = true; - - IIcon r = CableBusTextures.PartMonitorSidesStatus.getIcon(); - ri.setTemporaryRenderIcons( r, r, CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon(), r, r ); - this.renderBlockBounds( renderer, 5, 5, 0, 11, 11, 1, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - - r = CableBusTextures.PartWirelessSides.getIcon(); - ri.setTemporaryRenderIcons( r, r, ExtraBlockTextures.BlockWirelessInside.getIcon(), ExtraBlockTextures.BlockWirelessInside.getIcon(), r, r ); - this.renderBlockBounds( renderer, 5, 5, 1, 11, 11, 2, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - - tess.startDrawingQuads(); - ri.setTemporaryRenderIcon( null ); - this.renderTorchAtAngle( renderer, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH ); - super.postRenderInWorld( renderer ); - tess.draw(); - - ri.setTemporaryRenderIcons( r, r, ExtraBlockTextures.BlockWirelessInside.getIcon(), ExtraBlockTextures.BlockWirelessInside.getIcon(), r, r ); - - final ForgeDirection[] sides = { ForgeDirection.EAST, ForgeDirection.WEST, ForgeDirection.UP, ForgeDirection.DOWN }; - - int s = 1; - - for( final ForgeDirection side : sides ) - { - this.renderBlockBounds( renderer, 8 + ( side.offsetX != 0 ? side.offsetX * 2 : -2 ), 8 + ( side.offsetY != 0 ? side.offsetY * 2 : -2 ), 2 + ( side.offsetZ != 0 ? side.offsetZ * 2 : -1 ) + s, 8 + ( side.offsetX != 0 ? side.offsetX * 4 : 2 ), 8 + ( side.offsetY != 0 ? side.offsetY * 4 : 2 ), 2 + ( side.offsetZ != 0 ? side.offsetZ * 5 : 1 ) + s, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - } - - s = 3; - for( final ForgeDirection side : sides ) - { - this.renderBlockBounds( renderer, 8 + ( side.offsetX != 0 ? side.offsetX * 4 : -1 ), 8 + ( side.offsetY != 0 ? side.offsetY * 4 : -1 ), 1 + ( side.offsetZ != 0 ? side.offsetZ * 4 : -1 ) + s, 8 + ( side.offsetX != 0 ? side.offsetX * 5 : 1 ), 8 + ( side.offsetY != 0 ? side.offsetY * 5 : 1 ), 2 + ( side.offsetZ != 0 ? side.offsetZ * 5 : 1 ) + s, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH ); - - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - } - } - - @Override - public boolean renderInWorld( final BlockWireless blk, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TileWireless tw = blk.getTileEntity( world, x, y, z ); - this.blk = blk; - - if( tw != null ) - { - this.hasChan = ( tw.getClientFlags() & ( TileWireless.POWERED_FLAG | TileWireless.CHANNEL_FLAG ) ) == ( TileWireless.POWERED_FLAG | TileWireless.CHANNEL_FLAG ); - this.hasPower = ( tw.getClientFlags() & TileWireless.POWERED_FLAG ) == TileWireless.POWERED_FLAG; - - final BlockRenderInfo ri = blk.getRendererInstance(); - - final ForgeDirection fdy = tw.getUp(); - final ForgeDirection fdz = tw.getForward(); - final ForgeDirection fdx = Platform.crossProduct( fdz, fdy ).getOpposite(); - - renderer.renderAllFaces = true; - - IIcon r = CableBusTextures.PartMonitorSidesStatus.getIcon(); - ri.setTemporaryRenderIcons( r, r, CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon(), r, r ); - this.renderBlockBounds( renderer, 5, 5, 0, 11, 11, 1, fdx, fdy, fdz ); - super.renderInWorld( blk, world, x, y, z, renderer ); - - r = CableBusTextures.PartWirelessSides.getIcon(); - ri.setTemporaryRenderIcons( r, r, ExtraBlockTextures.BlockWirelessInside.getIcon(), ExtraBlockTextures.BlockWirelessInside.getIcon(), r, r ); - this.renderBlockBounds( renderer, 5, 5, 1, 11, 11, 2, fdx, fdy, fdz ); - super.renderInWorld( blk, world, x, y, z, renderer ); - - this.centerX = x; - this.centerY = y; - this.centerZ = z; - ri.setTemporaryRenderIcon( null ); - - this.renderTorchAtAngle( renderer, fdx, fdy, fdz ); - super.postRenderInWorld( renderer ); - - ri.setTemporaryRenderIcons( r, r, ExtraBlockTextures.BlockWirelessInside.getIcon(), ExtraBlockTextures.BlockWirelessInside.getIcon(), r, r ); - - final ForgeDirection[] sides = { ForgeDirection.EAST, ForgeDirection.WEST, ForgeDirection.UP, ForgeDirection.DOWN }; - - int s = 1; - - for( final ForgeDirection side : sides ) - { - this.renderBlockBounds( renderer, 8 + ( side.offsetX != 0 ? side.offsetX * 2 : -2 ), 8 + ( side.offsetY != 0 ? side.offsetY * 2 : -2 ), 2 + ( side.offsetZ != 0 ? side.offsetZ * 2 : -1 ) + s, 8 + ( side.offsetX != 0 ? side.offsetX * 4 : 2 ), 8 + ( side.offsetY != 0 ? side.offsetY * 4 : 2 ), 2 + ( side.offsetZ != 0 ? side.offsetZ * 5 : 1 ) + s, fdx, fdy, fdz ); - super.renderInWorld( blk, world, x, y, z, renderer ); - } - - s = 3; - for( final ForgeDirection side : sides ) - { - this.renderBlockBounds( renderer, 8 + ( side.offsetX != 0 ? side.offsetX * 4 : -1 ), 8 + ( side.offsetY != 0 ? side.offsetY * 4 : -1 ), 1 + ( side.offsetZ != 0 ? side.offsetZ * 4 : -1 ) + s, 8 + ( side.offsetX != 0 ? side.offsetX * 5 : 1 ), 8 + ( side.offsetY != 0 ? side.offsetY * 5 : 1 ), 2 + ( side.offsetZ != 0 ? side.offsetZ * 5 : 1 ) + s, fdx, fdy, fdz ); - super.renderInWorld( blk, world, x, y, z, renderer ); - } - - r = CableBusTextures.PartMonitorSidesStatusLights.getIcon(); - // ri.setTemporaryRenderIcons( r, r, ExtraTextures.BlockChargerInside.getIcon(), - // ExtraTextures.BlockChargerInside.getIcon(), r, r ); - this.renderBlockBounds( renderer, 5, 5, 0, 11, 11, 1, fdx, fdy, fdz ); - - if( this.hasChan ) - { - final int l = 14; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - Tessellator.instance.setColorOpaque_I( AEColor.Transparent.blackVariant ); - } - else if( this.hasPower ) - { - final int l = 9; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - Tessellator.instance.setColorOpaque_I( AEColor.Transparent.whiteVariant ); - } - else - { - Tessellator.instance.setBrightness( 0 ); - Tessellator.instance.setColorOpaque_I( 0x000000 ); - } - - if( ForgeDirection.UP != fdz.getOpposite() ) - { - super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.UP ); - } - if( ForgeDirection.DOWN != fdz.getOpposite() ) - { - super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.DOWN ); - } - if( ForgeDirection.EAST != fdz.getOpposite() ) - { - super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.EAST ); - } - if( ForgeDirection.WEST != fdz.getOpposite() ) - { - super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.WEST ); - } - if( ForgeDirection.SOUTH != fdz.getOpposite() ) - { - super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.SOUTH ); - } - if( ForgeDirection.NORTH != fdz.getOpposite() ) - { - super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.NORTH ); - } - - ri.setTemporaryRenderIcon( null ); - renderer.renderAllFaces = false; - } - - return true; - } - - private void renderTorchAtAngle( final RenderBlocks renderer, final ForgeDirection x, final ForgeDirection y, final ForgeDirection z ) - { - final IIcon r = ( this.hasChan ? CableBusTextures.BlockWirelessOn.getIcon() : this.blk.getIcon( 0, 0 ) ); - final IIcon sides = new OffsetIcon( r, 0.0f, -2.0f ); - - switch( z ) - { - case DOWN: - renderer.uvRotateNorth = 3; - renderer.uvRotateSouth = 3; - renderer.uvRotateEast = 3; - renderer.uvRotateWest = 3; - break; - case EAST: - renderer.uvRotateTop = 1; - renderer.uvRotateBottom = 2; - renderer.uvRotateEast = 2; - renderer.uvRotateWest = 1; - break; - case NORTH: - renderer.uvRotateTop = 0; - renderer.uvRotateBottom = 0; - renderer.uvRotateNorth = 2; - renderer.uvRotateSouth = 1; - break; - case SOUTH: - renderer.uvRotateTop = 3; - renderer.uvRotateBottom = 3; - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 2; - break; - case WEST: - renderer.uvRotateTop = 2; - renderer.uvRotateBottom = 1; - renderer.uvRotateEast = 1; - renderer.uvRotateWest = 2; - break; - default: - break; - } - - Tessellator.instance.setColorOpaque_I( 0xffffff ); - this.renderBlockBounds( renderer, 0, 7, 1, 16, 9, 16, x, y, z ); - this.renderFace( this.centerX, this.centerY, this.centerZ, this.blk, sides, renderer, y ); - this.renderFace( this.centerX, this.centerY, this.centerZ, this.blk, sides, renderer, y.getOpposite() ); - - this.renderBlockBounds( renderer, 7, 0, 1, 9, 16, 16, x, y, z ); - this.renderFace( this.centerX, this.centerY, this.centerZ, this.blk, sides, renderer, x ); - this.renderFace( this.centerX, this.centerY, this.centerZ, this.blk, sides, renderer, x.getOpposite() ); - - this.renderBlockBounds( renderer, 7, 7, 1, 9, 9, 10.6, x, y, z ); - this.renderFace( this.centerX, this.centerY, this.centerZ, this.blk, r, renderer, z ); - } +public class RenderBlockWireless extends BaseBlockRender { + + private int centerX = 0; + private int centerY = 0; + private int centerZ = 0; + private BlockWireless blk; + private boolean hasChan = false; + private boolean hasPower = false; + + public RenderBlockWireless() { + super(false, 20); + } + + @Override + public void renderInventory( + final BlockWireless blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + this.blk = blk; + this.centerX = 0; + this.centerY = 0; + this.centerZ = 0; + this.hasChan = false; + this.hasPower = false; + + final BlockRenderInfo ri = blk.getRendererInstance(); + final Tessellator tess = Tessellator.instance; + + renderer.renderAllFaces = true; + + IIcon r = CableBusTextures.PartMonitorSidesStatus.getIcon(); + ri.setTemporaryRenderIcons( + r, r, CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon(), r, r); + this.renderBlockBounds( + renderer, 5, 5, 0, 11, 11, 1, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); + + r = CableBusTextures.PartWirelessSides.getIcon(); + ri.setTemporaryRenderIcons( + r, + r, + ExtraBlockTextures.BlockWirelessInside.getIcon(), + ExtraBlockTextures.BlockWirelessInside.getIcon(), + r, + r); + this.renderBlockBounds( + renderer, 5, 5, 1, 11, 11, 2, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); + + tess.startDrawingQuads(); + ri.setTemporaryRenderIcon(null); + this.renderTorchAtAngle(renderer, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH); + super.postRenderInWorld(renderer); + tess.draw(); + + ri.setTemporaryRenderIcons( + r, + r, + ExtraBlockTextures.BlockWirelessInside.getIcon(), + ExtraBlockTextures.BlockWirelessInside.getIcon(), + r, + r); + + final ForgeDirection[] sides = {ForgeDirection.EAST, ForgeDirection.WEST, ForgeDirection.UP, ForgeDirection.DOWN + }; + + int s = 1; + + for (final ForgeDirection side : sides) { + this.renderBlockBounds( + renderer, + 8 + (side.offsetX != 0 ? side.offsetX * 2 : -2), + 8 + (side.offsetY != 0 ? side.offsetY * 2 : -2), + 2 + (side.offsetZ != 0 ? side.offsetZ * 2 : -1) + s, + 8 + (side.offsetX != 0 ? side.offsetX * 4 : 2), + 8 + (side.offsetY != 0 ? side.offsetY * 4 : 2), + 2 + (side.offsetZ != 0 ? side.offsetZ * 5 : 1) + s, + ForgeDirection.EAST, + ForgeDirection.UP, + ForgeDirection.SOUTH); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); + } + + s = 3; + for (final ForgeDirection side : sides) { + this.renderBlockBounds( + renderer, + 8 + (side.offsetX != 0 ? side.offsetX * 4 : -1), + 8 + (side.offsetY != 0 ? side.offsetY * 4 : -1), + 1 + (side.offsetZ != 0 ? side.offsetZ * 4 : -1) + s, + 8 + (side.offsetX != 0 ? side.offsetX * 5 : 1), + 8 + (side.offsetY != 0 ? side.offsetY * 5 : 1), + 2 + (side.offsetZ != 0 ? side.offsetZ * 5 : 1) + s, + ForgeDirection.EAST, + ForgeDirection.UP, + ForgeDirection.SOUTH); + + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); + } + } + + @Override + public boolean renderInWorld( + final BlockWireless blk, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + final TileWireless tw = blk.getTileEntity(world, x, y, z); + this.blk = blk; + + if (tw != null) { + this.hasChan = (tw.getClientFlags() & (TileWireless.POWERED_FLAG | TileWireless.CHANNEL_FLAG)) + == (TileWireless.POWERED_FLAG | TileWireless.CHANNEL_FLAG); + this.hasPower = (tw.getClientFlags() & TileWireless.POWERED_FLAG) == TileWireless.POWERED_FLAG; + + final BlockRenderInfo ri = blk.getRendererInstance(); + + final ForgeDirection fdy = tw.getUp(); + final ForgeDirection fdz = tw.getForward(); + final ForgeDirection fdx = Platform.crossProduct(fdz, fdy).getOpposite(); + + renderer.renderAllFaces = true; + + IIcon r = CableBusTextures.PartMonitorSidesStatus.getIcon(); + ri.setTemporaryRenderIcons( + r, + r, + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorSides.getIcon(), + r, + r); + this.renderBlockBounds(renderer, 5, 5, 0, 11, 11, 1, fdx, fdy, fdz); + super.renderInWorld(blk, world, x, y, z, renderer); + + r = CableBusTextures.PartWirelessSides.getIcon(); + ri.setTemporaryRenderIcons( + r, + r, + ExtraBlockTextures.BlockWirelessInside.getIcon(), + ExtraBlockTextures.BlockWirelessInside.getIcon(), + r, + r); + this.renderBlockBounds(renderer, 5, 5, 1, 11, 11, 2, fdx, fdy, fdz); + super.renderInWorld(blk, world, x, y, z, renderer); + + this.centerX = x; + this.centerY = y; + this.centerZ = z; + ri.setTemporaryRenderIcon(null); + + this.renderTorchAtAngle(renderer, fdx, fdy, fdz); + super.postRenderInWorld(renderer); + + ri.setTemporaryRenderIcons( + r, + r, + ExtraBlockTextures.BlockWirelessInside.getIcon(), + ExtraBlockTextures.BlockWirelessInside.getIcon(), + r, + r); + + final ForgeDirection[] sides = { + ForgeDirection.EAST, ForgeDirection.WEST, ForgeDirection.UP, ForgeDirection.DOWN + }; + + int s = 1; + + for (final ForgeDirection side : sides) { + this.renderBlockBounds( + renderer, + 8 + (side.offsetX != 0 ? side.offsetX * 2 : -2), + 8 + (side.offsetY != 0 ? side.offsetY * 2 : -2), + 2 + (side.offsetZ != 0 ? side.offsetZ * 2 : -1) + s, + 8 + (side.offsetX != 0 ? side.offsetX * 4 : 2), + 8 + (side.offsetY != 0 ? side.offsetY * 4 : 2), + 2 + (side.offsetZ != 0 ? side.offsetZ * 5 : 1) + s, + fdx, + fdy, + fdz); + super.renderInWorld(blk, world, x, y, z, renderer); + } + + s = 3; + for (final ForgeDirection side : sides) { + this.renderBlockBounds( + renderer, + 8 + (side.offsetX != 0 ? side.offsetX * 4 : -1), + 8 + (side.offsetY != 0 ? side.offsetY * 4 : -1), + 1 + (side.offsetZ != 0 ? side.offsetZ * 4 : -1) + s, + 8 + (side.offsetX != 0 ? side.offsetX * 5 : 1), + 8 + (side.offsetY != 0 ? side.offsetY * 5 : 1), + 2 + (side.offsetZ != 0 ? side.offsetZ * 5 : 1) + s, + fdx, + fdy, + fdz); + super.renderInWorld(blk, world, x, y, z, renderer); + } + + r = CableBusTextures.PartMonitorSidesStatusLights.getIcon(); + // ri.setTemporaryRenderIcons( r, r, ExtraTextures.BlockChargerInside.getIcon(), + // ExtraTextures.BlockChargerInside.getIcon(), r, r ); + this.renderBlockBounds(renderer, 5, 5, 0, 11, 11, 1, fdx, fdy, fdz); + + if (this.hasChan) { + final int l = 14; + Tessellator.instance.setBrightness(l << 20 | l << 4); + Tessellator.instance.setColorOpaque_I(AEColor.Transparent.blackVariant); + } else if (this.hasPower) { + final int l = 9; + Tessellator.instance.setBrightness(l << 20 | l << 4); + Tessellator.instance.setColorOpaque_I(AEColor.Transparent.whiteVariant); + } else { + Tessellator.instance.setBrightness(0); + Tessellator.instance.setColorOpaque_I(0x000000); + } + + if (ForgeDirection.UP != fdz.getOpposite()) { + super.renderFace(x, y, z, blk, r, renderer, ForgeDirection.UP); + } + if (ForgeDirection.DOWN != fdz.getOpposite()) { + super.renderFace(x, y, z, blk, r, renderer, ForgeDirection.DOWN); + } + if (ForgeDirection.EAST != fdz.getOpposite()) { + super.renderFace(x, y, z, blk, r, renderer, ForgeDirection.EAST); + } + if (ForgeDirection.WEST != fdz.getOpposite()) { + super.renderFace(x, y, z, blk, r, renderer, ForgeDirection.WEST); + } + if (ForgeDirection.SOUTH != fdz.getOpposite()) { + super.renderFace(x, y, z, blk, r, renderer, ForgeDirection.SOUTH); + } + if (ForgeDirection.NORTH != fdz.getOpposite()) { + super.renderFace(x, y, z, blk, r, renderer, ForgeDirection.NORTH); + } + + ri.setTemporaryRenderIcon(null); + renderer.renderAllFaces = false; + } + + return true; + } + + private void renderTorchAtAngle( + final RenderBlocks renderer, final ForgeDirection x, final ForgeDirection y, final ForgeDirection z) { + final IIcon r = (this.hasChan ? CableBusTextures.BlockWirelessOn.getIcon() : this.blk.getIcon(0, 0)); + final IIcon sides = new OffsetIcon(r, 0.0f, -2.0f); + + switch (z) { + case DOWN: + renderer.uvRotateNorth = 3; + renderer.uvRotateSouth = 3; + renderer.uvRotateEast = 3; + renderer.uvRotateWest = 3; + break; + case EAST: + renderer.uvRotateTop = 1; + renderer.uvRotateBottom = 2; + renderer.uvRotateEast = 2; + renderer.uvRotateWest = 1; + break; + case NORTH: + renderer.uvRotateTop = 0; + renderer.uvRotateBottom = 0; + renderer.uvRotateNorth = 2; + renderer.uvRotateSouth = 1; + break; + case SOUTH: + renderer.uvRotateTop = 3; + renderer.uvRotateBottom = 3; + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 2; + break; + case WEST: + renderer.uvRotateTop = 2; + renderer.uvRotateBottom = 1; + renderer.uvRotateEast = 1; + renderer.uvRotateWest = 2; + break; + default: + break; + } + + Tessellator.instance.setColorOpaque_I(0xffffff); + this.renderBlockBounds(renderer, 0, 7, 1, 16, 9, 16, x, y, z); + this.renderFace(this.centerX, this.centerY, this.centerZ, this.blk, sides, renderer, y); + this.renderFace(this.centerX, this.centerY, this.centerZ, this.blk, sides, renderer, y.getOpposite()); + + this.renderBlockBounds(renderer, 7, 0, 1, 9, 16, 16, x, y, z); + this.renderFace(this.centerX, this.centerY, this.centerZ, this.blk, sides, renderer, x); + this.renderFace(this.centerX, this.centerY, this.centerZ, this.blk, sides, renderer, x.getOpposite()); + + this.renderBlockBounds(renderer, 7, 7, 1, 9, 9, 10.6, x, y, z); + this.renderFace(this.centerX, this.centerY, this.centerZ, this.blk, r, renderer, z); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderDrive.java b/src/main/java/appeng/client/render/blocks/RenderDrive.java index 214001198fc..7c383044624 100644 --- a/src/main/java/appeng/client/render/blocks/RenderDrive.java +++ b/src/main/java/appeng/client/render/blocks/RenderDrive.java @@ -18,12 +18,12 @@ package appeng.client.render.blocks; - import appeng.block.storage.BlockDrive; import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; import appeng.tile.storage.TileDrive; import appeng.util.Platform; +import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.item.ItemStack; @@ -32,314 +32,345 @@ import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class RenderDrive extends BaseBlockRender -{ +public class RenderDrive extends BaseBlockRender { - public RenderDrive() - { - super( false, 0 ); - } + public RenderDrive() { + super(false, 0); + } - @Override - public void renderInventory( final BlockDrive block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - renderer.overrideBlockTexture = ExtraBlockTextures.getMissing(); - this.renderInvBlock( EnumSet.of( ForgeDirection.SOUTH ), block, is, Tessellator.instance, 0x000000, renderer ); + @Override + public void renderInventory( + final BlockDrive block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + renderer.overrideBlockTexture = ExtraBlockTextures.getMissing(); + this.renderInvBlock(EnumSet.of(ForgeDirection.SOUTH), block, is, Tessellator.instance, 0x000000, renderer); - renderer.overrideBlockTexture = null; - super.renderInventory( block, is, renderer, type, obj ); - } + renderer.overrideBlockTexture = null; + super.renderInventory(block, is, renderer, type, obj); + } - @Override - public boolean renderInWorld( final BlockDrive imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TileDrive sp = imb.getTileEntity( world, x, y, z ); - final ForgeDirection up = sp.getUp(); - final ForgeDirection forward = sp.getForward(); - final ForgeDirection west = Platform.crossProduct( forward, up ); + @Override + public boolean renderInWorld( + final BlockDrive imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + final TileDrive sp = imb.getTileEntity(world, x, y, z); + final ForgeDirection up = sp.getUp(); + final ForgeDirection forward = sp.getForward(); + final ForgeDirection west = Platform.crossProduct(forward, up); - renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); + renderer.setRenderBounds(0, 0, 0, 1, 1, 1); - final boolean result = super.renderInWorld( imb, world, x, y, z, renderer ); + final boolean result = super.renderInWorld(imb, world, x, y, z, renderer); - final Tessellator tess = Tessellator.instance; - final IIcon ico = ExtraBlockTextures.MEStorageCellTextures.getIcon(); + final Tessellator tess = Tessellator.instance; + final IIcon ico = ExtraBlockTextures.MEStorageCellTextures.getIcon(); - final int b = world.getLightBrightnessForSkyBlocks( x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ, 0 ); + final int b = + world.getLightBrightnessForSkyBlocks(x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ, 0); - for( int yy = 0; yy < 5; yy++ ) - { - for( int xx = 0; xx < 2; xx++ ) - { - final int stat = sp.getCellStatus( yy * 2 + ( 1 - xx ) ); + for (int yy = 0; yy < 5; yy++) { + for (int xx = 0; xx < 2; xx++) { + final int stat = sp.getCellStatus(yy * 2 + (1 - xx)); - this.selectFace( renderer, west, up, forward, 2 + xx * 7, 7 + xx * 7, 1 + yy * 3, 3 + yy * 3 ); + this.selectFace(renderer, west, up, forward, 2 + xx * 7, 7 + xx * 7, 1 + yy * 3, 3 + yy * 3); - int spin = 0; + int spin = 0; - switch( forward.offsetX + forward.offsetY * 2 + forward.offsetZ * 3 ) - { - case 1: - switch( up ) - { - case UP: - spin = 3; - break; - case DOWN: - spin = 1; - break; - case NORTH: - spin = 0; - break; - case SOUTH: - spin = 2; - break; - default: - } - break; - case -1: - switch( up ) - { - case UP: - spin = 1; - break; - case DOWN: - spin = 3; - break; - case NORTH: - spin = 0; - break; - case SOUTH: - spin = 2; - break; - default: - } - break; - case -2: - switch( up ) - { - case EAST: - spin = 1; - break; - case WEST: - spin = 3; - break; - case NORTH: - spin = 2; - break; - case SOUTH: - spin = 0; - break; - default: - } - break; - case 2: - switch( up ) - { - case EAST: - spin = 1; - break; - case WEST: - spin = 3; - break; - case NORTH: - spin = 0; - break; - case SOUTH: - spin = 0; - break; - default: - } - break; - case 3: - switch( up ) - { - case UP: - spin = 2; - break; - case DOWN: - spin = 0; - break; - case EAST: - spin = 3; - break; - case WEST: - spin = 1; - break; - default: - } - break; - case -3: - switch( up ) - { - case UP: - spin = 2; - break; - case DOWN: - spin = 0; - break; - case EAST: - spin = 1; - break; - case WEST: - spin = 3; - break; - default: - } - break; - } + switch (forward.offsetX + forward.offsetY * 2 + forward.offsetZ * 3) { + case 1: + switch (up) { + case UP: + spin = 3; + break; + case DOWN: + spin = 1; + break; + case NORTH: + spin = 0; + break; + case SOUTH: + spin = 2; + break; + default: + } + break; + case -1: + switch (up) { + case UP: + spin = 1; + break; + case DOWN: + spin = 3; + break; + case NORTH: + spin = 0; + break; + case SOUTH: + spin = 2; + break; + default: + } + break; + case -2: + switch (up) { + case EAST: + spin = 1; + break; + case WEST: + spin = 3; + break; + case NORTH: + spin = 2; + break; + case SOUTH: + spin = 0; + break; + default: + } + break; + case 2: + switch (up) { + case EAST: + spin = 1; + break; + case WEST: + spin = 3; + break; + case NORTH: + spin = 0; + break; + case SOUTH: + spin = 0; + break; + default: + } + break; + case 3: + switch (up) { + case UP: + spin = 2; + break; + case DOWN: + spin = 0; + break; + case EAST: + spin = 3; + break; + case WEST: + spin = 1; + break; + default: + } + break; + case -3: + switch (up) { + case UP: + spin = 2; + break; + case DOWN: + spin = 0; + break; + case EAST: + spin = 1; + break; + case WEST: + spin = 3; + break; + default: + } + break; + } - double u1 = ico.getInterpolatedU( ( spin % 4 < 2 ) ? 1 : 6 ); - double u2 = ico.getInterpolatedU( ( ( spin + 1 ) % 4 < 2 ) ? 1 : 6 ); - double u3 = ico.getInterpolatedU( ( ( spin + 2 ) % 4 < 2 ) ? 1 : 6 ); - double u4 = ico.getInterpolatedU( ( ( spin + 3 ) % 4 < 2 ) ? 1 : 6 ); + double u1 = ico.getInterpolatedU((spin % 4 < 2) ? 1 : 6); + double u2 = ico.getInterpolatedU(((spin + 1) % 4 < 2) ? 1 : 6); + double u3 = ico.getInterpolatedU(((spin + 2) % 4 < 2) ? 1 : 6); + double u4 = ico.getInterpolatedU(((spin + 3) % 4 < 2) ? 1 : 6); - int m = 1; - int mx = 3; - if( stat == 0 ) - { - m = 4; - mx = 5; - } + int m = 1; + int mx = 3; + if (stat == 0) { + m = 4; + mx = 5; + } - double v1 = ico.getInterpolatedV( ( ( spin + 1 ) % 4 < 2 ) ? m : mx ); - double v2 = ico.getInterpolatedV( ( ( spin + 2 ) % 4 < 2 ) ? m : mx ); - double v3 = ico.getInterpolatedV( ( ( spin + 3 ) % 4 < 2 ) ? m : mx ); - double v4 = ico.getInterpolatedV( ( ( spin ) % 4 < 2 ) ? m : mx ); + double v1 = ico.getInterpolatedV(((spin + 1) % 4 < 2) ? m : mx); + double v2 = ico.getInterpolatedV(((spin + 2) % 4 < 2) ? m : mx); + double v3 = ico.getInterpolatedV(((spin + 3) % 4 < 2) ? m : mx); + double v4 = ico.getInterpolatedV(((spin) % 4 < 2) ? m : mx); - tess.setBrightness( b ); - tess.setColorOpaque_I( 0xffffff ); - switch( forward.offsetX + forward.offsetY * 2 + forward.offsetZ * 3 ) - { - case 1: - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMinZ, u4, v4 ); - break; - case -1: - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMinZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4 ); - break; - case -2: - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4 ); - break; - case 2: - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4 ); - break; - case 3: - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMinY, z + renderer.renderMaxZ, u4, v4 ); - break; - case -3: - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMinY, z + renderer.renderMaxZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u4, v4 ); - break; - } + tess.setBrightness(b); + tess.setColorOpaque_I(0xffffff); + switch (forward.offsetX + forward.offsetY * 2 + forward.offsetZ * 3) { + case 1: + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u3, v3); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMinZ, u4, v4); + break; + case -1: + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMinZ, u1, v1); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u2, v2); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4); + break; + case -2: + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2); + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3); + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4); + break; + case 2: + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1); + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4); + break; + case 3: + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u1, v1); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2); + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3); + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMinY, z + renderer.renderMaxZ, u4, v4); + break; + case -3: + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMinY, z + renderer.renderMaxZ, u1, v1); + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u4, v4); + break; + } - if( ( forward == ForgeDirection.UP && up == ForgeDirection.SOUTH ) || forward == ForgeDirection.DOWN ) - { - this.selectFace( renderer, west, up, forward, 3 + xx * 7, 4 + xx * 7, 1 + yy * 3, 2 + yy * 3 ); - } - else - { - this.selectFace( renderer, west, up, forward, 5 + xx * 7, 6 + xx * 7, 2 + yy * 3, 3 + yy * 3 ); - } + if ((forward == ForgeDirection.UP && up == ForgeDirection.SOUTH) || forward == ForgeDirection.DOWN) { + this.selectFace(renderer, west, up, forward, 3 + xx * 7, 4 + xx * 7, 1 + yy * 3, 2 + yy * 3); + } else { + this.selectFace(renderer, west, up, forward, 5 + xx * 7, 6 + xx * 7, 2 + yy * 3, 3 + yy * 3); + } - if( stat != 0 ) - { - final IIcon whiteIcon = ExtraBlockTextures.White.getIcon(); - u1 = whiteIcon.getInterpolatedU( ( spin % 4 < 2 ) ? 1 : 6 ); - u2 = whiteIcon.getInterpolatedU( ( ( spin + 1 ) % 4 < 2 ) ? 1 : 6 ); - u3 = whiteIcon.getInterpolatedU( ( ( spin + 2 ) % 4 < 2 ) ? 1 : 6 ); - u4 = whiteIcon.getInterpolatedU( ( ( spin + 3 ) % 4 < 2 ) ? 1 : 6 ); + if (stat != 0) { + final IIcon whiteIcon = ExtraBlockTextures.White.getIcon(); + u1 = whiteIcon.getInterpolatedU((spin % 4 < 2) ? 1 : 6); + u2 = whiteIcon.getInterpolatedU(((spin + 1) % 4 < 2) ? 1 : 6); + u3 = whiteIcon.getInterpolatedU(((spin + 2) % 4 < 2) ? 1 : 6); + u4 = whiteIcon.getInterpolatedU(((spin + 3) % 4 < 2) ? 1 : 6); - v1 = whiteIcon.getInterpolatedV( ( ( spin + 1 ) % 4 < 2 ) ? 1 : 3 ); - v2 = whiteIcon.getInterpolatedV( ( ( spin + 2 ) % 4 < 2 ) ? 1 : 3 ); - v3 = whiteIcon.getInterpolatedV( ( ( spin + 3 ) % 4 < 2 ) ? 1 : 3 ); - v4 = whiteIcon.getInterpolatedV( ( ( spin ) % 4 < 2 ) ? 1 : 3 ); + v1 = whiteIcon.getInterpolatedV(((spin + 1) % 4 < 2) ? 1 : 3); + v2 = whiteIcon.getInterpolatedV(((spin + 2) % 4 < 2) ? 1 : 3); + v3 = whiteIcon.getInterpolatedV(((spin + 3) % 4 < 2) ? 1 : 3); + v4 = whiteIcon.getInterpolatedV(((spin) % 4 < 2) ? 1 : 3); - if( sp.isPowered() ) - { - tess.setBrightness( 15 << 20 | 15 << 4 ); - } - else - { - tess.setBrightness( 0 ); - } + if (sp.isPowered()) { + tess.setBrightness(15 << 20 | 15 << 4); + } else { + tess.setBrightness(0); + } - if( stat == 1 ) - { - Tessellator.instance.setColorOpaque_I( 0x00ff00 ); - } - if( stat == 2 ) - { - Tessellator.instance.setColorOpaque_I( 0xffaa00 ); - } - if( stat == 3 ) - { - Tessellator.instance.setColorOpaque_I( 0xff0000 ); - } + if (stat == 1) { + Tessellator.instance.setColorOpaque_I(0x00ff00); + } + if (stat == 2) { + Tessellator.instance.setColorOpaque_I(0xffaa00); + } + if (stat == 3) { + Tessellator.instance.setColorOpaque_I(0xff0000); + } - switch( forward.offsetX + forward.offsetY * 2 + forward.offsetZ * 3 ) - { - case 1: - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMinZ, u4, v4 ); - break; - case -1: - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMinZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4 ); - break; - case -2: - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4 ); - break; - case 2: - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4 ); - break; - case 3: - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMinY, z + renderer.renderMaxZ, u4, v4 ); - break; - case -3: - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMinY, z + renderer.renderMaxZ, u1, v1 ); - tess.addVertexWithUV( x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3 ); - tess.addVertexWithUV( x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u4, v4 ); - break; - } - } - } - } + switch (forward.offsetX + forward.offsetY * 2 + forward.offsetZ * 3) { + case 1: + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u3, v3); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMinZ, u4, v4); + break; + case -1: + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMinZ, u1, v1); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u2, v2); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4); + break; + case -2: + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2); + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3); + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4); + break; + case 2: + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMinZ, u1, v1); + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMinZ, u4, v4); + break; + case 3: + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u1, v1); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2); + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3); + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMinY, z + renderer.renderMaxZ, u4, v4); + break; + case -3: + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMinY, z + renderer.renderMaxZ, u1, v1); + tess.addVertexWithUV( + x + renderer.renderMinX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u2, v2); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMaxY, z + renderer.renderMaxZ, u3, v3); + tess.addVertexWithUV( + x + renderer.renderMaxX, y + renderer.renderMinY, z + renderer.renderMaxZ, u4, v4); + break; + } + } + } + } - renderer.overrideBlockTexture = null; - return result; - } + renderer.overrideBlockTexture = null; + return result; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderMEChest.java b/src/main/java/appeng/client/render/blocks/RenderMEChest.java index 7eda2f28416..f749fd3deb6 100644 --- a/src/main/java/appeng/client/render/blocks/RenderMEChest.java +++ b/src/main/java/appeng/client/render/blocks/RenderMEChest.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.api.AEApi; import appeng.api.storage.ICellHandler; import appeng.api.util.AEColor; @@ -29,6 +28,7 @@ import appeng.client.texture.OffsetIcon; import appeng.tile.storage.TileChest; import appeng.util.Platform; +import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.item.ItemStack; @@ -37,146 +37,139 @@ import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class RenderMEChest extends BaseBlockRender -{ - - public RenderMEChest() - { - super( false, 0 ); - } - - @Override - public void renderInventory( final BlockChest block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - Tessellator.instance.setBrightness( 0 ); - - renderer.overrideBlockTexture = ExtraBlockTextures.getMissing(); - this.renderInvBlock( EnumSet.of( ForgeDirection.SOUTH ), block, is, Tessellator.instance, 0x000000, renderer ); - - renderer.overrideBlockTexture = ExtraBlockTextures.MEChest.getIcon(); - this.renderInvBlock( EnumSet.of( ForgeDirection.UP ), block, is, Tessellator.instance, this.adjustBrightness( AEColor.Transparent.whiteVariant, 0.7 ), renderer ); - - renderer.overrideBlockTexture = null; - super.renderInventory( block, is, renderer, type, obj ); - } - - @Override - public boolean renderInWorld( final BlockChest imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TileChest sp = imb.getTileEntity( world, x, y, z ); - - if( sp == null ) - { - return false; - } - - renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); - - final ForgeDirection up = sp.getUp(); - final ForgeDirection forward = sp.getForward(); - final ForgeDirection west = Platform.crossProduct( forward, up ); - - this.preRenderInWorld( imb, world, x, y, z, renderer ); - - final int stat = sp.getCellStatus( 0 ); - final boolean result = renderer.renderStandardBlock( imb, x, y, z ); - - this.selectFace( renderer, west, up, forward, 5, 16 - 5, 9, 12 ); - - int offsetV = 8; - if( stat == 0 ) - { - offsetV = 3; - } - - int b = world.getLightBrightnessForSkyBlocks( x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ, 0 ); - Tessellator.instance.setBrightness( b ); - Tessellator.instance.setColorOpaque_I( 0xffffff ); - - final int offsetU = -4; - final FlippableIcon flippableIcon = new FlippableIcon( new OffsetIcon( ExtraBlockTextures.MEStorageCellTextures.getIcon(), offsetU, offsetV ) ); - - if( forward == ForgeDirection.EAST && ( up == ForgeDirection.NORTH || up == ForgeDirection.SOUTH ) ) - { - flippableIcon.setFlip( true, false ); - } - else if( forward == ForgeDirection.NORTH && up == ForgeDirection.EAST ) - { - flippableIcon.setFlip( false, true ); - } - else if( forward == ForgeDirection.NORTH && up == ForgeDirection.WEST ) - { - flippableIcon.setFlip( true, false ); - } - else if( forward == ForgeDirection.DOWN && up == ForgeDirection.EAST ) - { - flippableIcon.setFlip( false, true ); - } - else if( forward == ForgeDirection.DOWN ) - { - flippableIcon.setFlip( true, false ); - } - - this.renderFace( x, y, z, imb, flippableIcon, renderer, forward ); - - if( stat != 0 ) - { - b = 0; - if( sp.isPowered() ) - { - b = 15 << 20 | 15 << 4; - } - - Tessellator.instance.setBrightness( b ); - if( stat == 1 ) - { - Tessellator.instance.setColorOpaque_I( 0x00ff00 ); - } - if( stat == 2 ) - { - Tessellator.instance.setColorOpaque_I( 0xffaa00 ); - } - if( stat == 3 ) - { - Tessellator.instance.setColorOpaque_I( 0xff0000 ); - } - this.selectFace( renderer, west, up, forward, 9, 10, 11, 12 ); - this.renderFace( x, y, z, imb, ExtraBlockTextures.White.getIcon(), renderer, forward ); - } - - b = world.getLightBrightnessForSkyBlocks( x + up.offsetX, y + up.offsetY, z + up.offsetZ, 0 ); - if( sp.isPowered() ) - { - b = 15 << 20 | 15 << 4; - } - - Tessellator.instance.setBrightness( b ); - Tessellator.instance.setColorOpaque_I( 0xffffff ); - renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); - - final ICellHandler ch = AEApi.instance().registries().cell().getHandler( sp.getStorageType() ); - - Tessellator.instance.setColorOpaque_I( sp.getColor().whiteVariant ); - IIcon ico = ch == null ? null : ch.getTopTexture_Light(); - this.renderFace( x, y, z, imb, ico == null ? ExtraBlockTextures.MEChest.getIcon() : ico, renderer, up ); - - if( ico != null ) - { - Tessellator.instance.setColorOpaque_I( sp.getColor().mediumVariant ); - ico = ch == null ? null : ch.getTopTexture_Medium(); - this.renderFace( x, y, z, imb, ico == null ? ExtraBlockTextures.MEChest.getIcon() : ico, renderer, up ); - - Tessellator.instance.setColorOpaque_I( sp.getColor().blackVariant ); - ico = ch == null ? null : ch.getTopTexture_Dark(); - this.renderFace( x, y, z, imb, ico == null ? ExtraBlockTextures.MEChest.getIcon() : ico, renderer, up ); - } - - renderer.overrideBlockTexture = null; - this.postRenderInWorld( renderer ); - - return result; - } +public class RenderMEChest extends BaseBlockRender { + + public RenderMEChest() { + super(false, 0); + } + + @Override + public void renderInventory( + final BlockChest block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + Tessellator.instance.setBrightness(0); + + renderer.overrideBlockTexture = ExtraBlockTextures.getMissing(); + this.renderInvBlock(EnumSet.of(ForgeDirection.SOUTH), block, is, Tessellator.instance, 0x000000, renderer); + + renderer.overrideBlockTexture = ExtraBlockTextures.MEChest.getIcon(); + this.renderInvBlock( + EnumSet.of(ForgeDirection.UP), + block, + is, + Tessellator.instance, + this.adjustBrightness(AEColor.Transparent.whiteVariant, 0.7), + renderer); + + renderer.overrideBlockTexture = null; + super.renderInventory(block, is, renderer, type, obj); + } + + @Override + public boolean renderInWorld( + final BlockChest imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + final TileChest sp = imb.getTileEntity(world, x, y, z); + + if (sp == null) { + return false; + } + + renderer.setRenderBounds(0, 0, 0, 1, 1, 1); + + final ForgeDirection up = sp.getUp(); + final ForgeDirection forward = sp.getForward(); + final ForgeDirection west = Platform.crossProduct(forward, up); + + this.preRenderInWorld(imb, world, x, y, z, renderer); + + final int stat = sp.getCellStatus(0); + final boolean result = renderer.renderStandardBlock(imb, x, y, z); + + this.selectFace(renderer, west, up, forward, 5, 16 - 5, 9, 12); + + int offsetV = 8; + if (stat == 0) { + offsetV = 3; + } + + int b = world.getLightBrightnessForSkyBlocks(x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ, 0); + Tessellator.instance.setBrightness(b); + Tessellator.instance.setColorOpaque_I(0xffffff); + + final int offsetU = -4; + final FlippableIcon flippableIcon = + new FlippableIcon(new OffsetIcon(ExtraBlockTextures.MEStorageCellTextures.getIcon(), offsetU, offsetV)); + + if (forward == ForgeDirection.EAST && (up == ForgeDirection.NORTH || up == ForgeDirection.SOUTH)) { + flippableIcon.setFlip(true, false); + } else if (forward == ForgeDirection.NORTH && up == ForgeDirection.EAST) { + flippableIcon.setFlip(false, true); + } else if (forward == ForgeDirection.NORTH && up == ForgeDirection.WEST) { + flippableIcon.setFlip(true, false); + } else if (forward == ForgeDirection.DOWN && up == ForgeDirection.EAST) { + flippableIcon.setFlip(false, true); + } else if (forward == ForgeDirection.DOWN) { + flippableIcon.setFlip(true, false); + } + + this.renderFace(x, y, z, imb, flippableIcon, renderer, forward); + + if (stat != 0) { + b = 0; + if (sp.isPowered()) { + b = 15 << 20 | 15 << 4; + } + + Tessellator.instance.setBrightness(b); + if (stat == 1) { + Tessellator.instance.setColorOpaque_I(0x00ff00); + } + if (stat == 2) { + Tessellator.instance.setColorOpaque_I(0xffaa00); + } + if (stat == 3) { + Tessellator.instance.setColorOpaque_I(0xff0000); + } + this.selectFace(renderer, west, up, forward, 9, 10, 11, 12); + this.renderFace(x, y, z, imb, ExtraBlockTextures.White.getIcon(), renderer, forward); + } + + b = world.getLightBrightnessForSkyBlocks(x + up.offsetX, y + up.offsetY, z + up.offsetZ, 0); + if (sp.isPowered()) { + b = 15 << 20 | 15 << 4; + } + + Tessellator.instance.setBrightness(b); + Tessellator.instance.setColorOpaque_I(0xffffff); + renderer.setRenderBounds(0, 0, 0, 1, 1, 1); + + final ICellHandler ch = AEApi.instance().registries().cell().getHandler(sp.getStorageType()); + + Tessellator.instance.setColorOpaque_I(sp.getColor().whiteVariant); + IIcon ico = ch == null ? null : ch.getTopTexture_Light(); + this.renderFace(x, y, z, imb, ico == null ? ExtraBlockTextures.MEChest.getIcon() : ico, renderer, up); + + if (ico != null) { + Tessellator.instance.setColorOpaque_I(sp.getColor().mediumVariant); + ico = ch == null ? null : ch.getTopTexture_Medium(); + this.renderFace(x, y, z, imb, ico == null ? ExtraBlockTextures.MEChest.getIcon() : ico, renderer, up); + + Tessellator.instance.setColorOpaque_I(sp.getColor().blackVariant); + ico = ch == null ? null : ch.getTopTexture_Dark(); + this.renderFace(x, y, z, imb, ico == null ? ExtraBlockTextures.MEChest.getIcon() : ico, renderer, up); + } + + renderer.overrideBlockTexture = null; + this.postRenderInWorld(renderer); + + return result; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderNull.java b/src/main/java/appeng/client/render/blocks/RenderNull.java index 78bfc587227..bd4f9800277 100644 --- a/src/main/java/appeng/client/render/blocks/RenderNull.java +++ b/src/main/java/appeng/client/render/blocks/RenderNull.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.AEBaseBlock; import appeng.client.render.BaseBlockRender; import appeng.tile.AEBaseTile; @@ -27,24 +26,28 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; - -public class RenderNull extends BaseBlockRender -{ - - public RenderNull() - { - super( false, 20 ); - } - - @Override - public void renderInventory( final AEBaseBlock block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - - } - - @Override - public boolean renderInWorld( final AEBaseBlock block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - return true; - } +public class RenderNull extends BaseBlockRender { + + public RenderNull() { + super(false, 20); + } + + @Override + public void renderInventory( + final AEBaseBlock block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) {} + + @Override + public boolean renderInWorld( + final AEBaseBlock block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + return true; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderQNB.java b/src/main/java/appeng/client/render/blocks/RenderQNB.java index 32c3c51e848..b47f4e23f76 100644 --- a/src/main/java/appeng/client/render/blocks/RenderQNB.java +++ b/src/main/java/appeng/client/render/blocks/RenderQNB.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.api.AEApi; import appeng.api.definitions.IBlocks; import appeng.api.definitions.IDefinitions; @@ -28,6 +27,8 @@ import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; import appeng.tile.qnb.TileQuantumBridge; +import java.util.Collection; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; @@ -38,168 +39,272 @@ import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collection; -import java.util.EnumSet; - - -public class RenderQNB extends BaseBlockRender -{ - private static final float DEFAULT_RENDER_MIN = 2.0f / 16.0f; - private static final float DEFAULT_RENDER_MAX = 14.0f / 16.0f; - - private static final float CORNER_POWERED_RENDER_MIN = 3.9f / 16.0f; - private static final float CORNER_POWERED_RENDER_MAX = 12.1f / 16.0f; - - private static final float CENTER_POWERED_RENDER_MIN = -0.01f / 16.0f; - private static final float CENTER_POWERED_RENDER_MAX = 16.01f / 16.0f; - - @Override - public void renderInventory( final BlockQuantumBase block, final ItemStack item, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - renderer.setRenderBounds( DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX ); - super.renderInventory( block, item, renderer, type, obj ); - } - - @Override - public boolean renderInWorld( final BlockQuantumBase block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TileQuantumBridge tqb = block.getTileEntity( world, x, y, z ); - - if( tqb == null ) - { - return false; - } - - renderer.renderAllFaces = true; - - final IDefinitions definitions = AEApi.instance().definitions(); - final IBlocks blocks = definitions.blocks(); - final IParts parts = definitions.parts(); - - for( final Block linkBlock : blocks.quantumLink().maybeBlock().asSet() ) - { - if( tqb.getBlockType() == linkBlock ) - { - if( tqb.isFormed() ) - { - final EnumSet sides = tqb.getConnections(); - - final Item transGlassCable = parts.cableGlass().item( AEColor.Transparent ); - this.renderCableAt( 0.11D, world, x, y, z, block, renderer, transGlassCable.getIconIndex( parts.cableGlass().stack( AEColor.Transparent, 1 ) ), 0.141D, sides ); - - final Item transCoveredCable = parts.cableCovered().item( AEColor.Transparent ); - this.renderCableAt( 0.188D, world, x, y, z, block, renderer, transCoveredCable.getIconIndex( parts.cableCovered().stack( AEColor.Transparent, 1 ) ), 0.1875D, sides ); - } - - renderer.setRenderBounds( DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX ); - renderer.renderStandardBlock( block, x, y, z ); - } - else - { - if( !tqb.isFormed() ) - { - renderer.setRenderBounds( DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX ); - renderer.renderStandardBlock( block, x, y, z ); - } - else if( tqb.isCorner() ) - { - final Item transCoveredCable = parts.cableCovered().item( AEColor.Transparent ); - - this.renderCableAt( 0.188D, world, x, y, z, block, renderer, transCoveredCable.getIconIndex( parts.cableCovered().stack( AEColor.Transparent, 1 ) ), 0.05D, tqb.getConnections() ); - - renderer.setRenderBounds( DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX ); - renderer.renderStandardBlock( block, x, y, z ); - - if( tqb.isPowered() ) - { - renderer.setRenderBounds( CORNER_POWERED_RENDER_MIN, CORNER_POWERED_RENDER_MIN, CORNER_POWERED_RENDER_MIN, CORNER_POWERED_RENDER_MAX, CORNER_POWERED_RENDER_MAX, CORNER_POWERED_RENDER_MAX ); - - Tessellator.instance.setColorOpaque_F( 1.0F, 1.0F, 1.0F ); - final int bn = 15; - Tessellator.instance.setBrightness( bn << 20 | bn << 4 ); - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - this.renderFace( x, y, z, block, ExtraBlockTextures.BlockQRingCornerLight.getIcon(), renderer, side ); - } - } - } - else - { - renderer.setRenderBounds( 0, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, 1, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX ); - renderer.renderStandardBlock( block, x, y, z ); - - renderer.setRenderBounds( DEFAULT_RENDER_MIN, 0, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, 1, DEFAULT_RENDER_MAX ); - renderer.renderStandardBlock( block, x, y, z ); - - renderer.setRenderBounds( DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, 0, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, 1 ); - renderer.renderStandardBlock( block, x, y, z ); - - if( tqb.isPowered() ) - { - renderer.setRenderBounds( CENTER_POWERED_RENDER_MIN, CENTER_POWERED_RENDER_MIN, CENTER_POWERED_RENDER_MIN, CENTER_POWERED_RENDER_MAX, CENTER_POWERED_RENDER_MAX, CENTER_POWERED_RENDER_MAX ); - - Tessellator.instance.setColorOpaque_F( 1.0F, 1.0F, 1.0F ); - final int bn = 15; - Tessellator.instance.setBrightness( bn << 20 | bn << 4 ); - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - this.renderFace( x, y, z, block, ExtraBlockTextures.BlockQRingEdgeLight.getIcon(), renderer, side ); - } - } - } - } - } - - renderer.renderAllFaces = false; - return true; - } - - private void renderCableAt( final double thickness, final IBlockAccess world, final int x, final int y, final int z, final BlockQuantumBase block, final RenderBlocks renderer, final IIcon texture, final double pull, final Collection connections ) - { - block.getRendererInstance().setTemporaryRenderIcon( texture ); - - if( connections.contains( ForgeDirection.UNKNOWN ) ) - { - renderer.setRenderBounds( 0.5D - thickness, 0.5D - thickness, 0.5D - thickness, 0.5D + thickness, 0.5D + thickness, 0.5D + thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - if( connections.contains( ForgeDirection.WEST ) ) - { - renderer.setRenderBounds( 0.0D, 0.5D - thickness, 0.5D - thickness, 0.5D - thickness - pull, 0.5D + thickness, 0.5D + thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - if( connections.contains( ForgeDirection.EAST ) ) - { - renderer.setRenderBounds( 0.5D + thickness + pull, 0.5D - thickness, 0.5D - thickness, 1.0D, 0.5D + thickness, 0.5D + thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - if( connections.contains( ForgeDirection.NORTH ) ) - { - renderer.setRenderBounds( 0.5D - thickness, 0.5D - thickness, 0.0D, 0.5D + thickness, 0.5D + thickness, 0.5D - thickness - pull ); - renderer.renderStandardBlock( block, x, y, z ); - } - - if( connections.contains( ForgeDirection.SOUTH ) ) - { - renderer.setRenderBounds( 0.5D - thickness, 0.5D - thickness, 0.5D + thickness + pull, 0.5D + thickness, 0.5D + thickness, 1.0D ); - renderer.renderStandardBlock( block, x, y, z ); - } - - if( connections.contains( ForgeDirection.DOWN ) ) - { - renderer.setRenderBounds( 0.5D - thickness, 0.0D, 0.5D - thickness, 0.5D + thickness, 0.5D - thickness - pull, 0.5D + thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - if( connections.contains( ForgeDirection.UP ) ) - { - renderer.setRenderBounds( 0.5D - thickness, 0.5D + thickness + pull, 0.5D - thickness, 0.5D + thickness, 1.0D, 0.5D + thickness ); - renderer.renderStandardBlock( block, x, y, z ); - } - - block.getRendererInstance().setTemporaryRenderIcon( null ); - } +public class RenderQNB extends BaseBlockRender { + private static final float DEFAULT_RENDER_MIN = 2.0f / 16.0f; + private static final float DEFAULT_RENDER_MAX = 14.0f / 16.0f; + + private static final float CORNER_POWERED_RENDER_MIN = 3.9f / 16.0f; + private static final float CORNER_POWERED_RENDER_MAX = 12.1f / 16.0f; + + private static final float CENTER_POWERED_RENDER_MIN = -0.01f / 16.0f; + private static final float CENTER_POWERED_RENDER_MAX = 16.01f / 16.0f; + + @Override + public void renderInventory( + final BlockQuantumBase block, + final ItemStack item, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + renderer.setRenderBounds( + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX); + super.renderInventory(block, item, renderer, type, obj); + } + + @Override + public boolean renderInWorld( + final BlockQuantumBase block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + final TileQuantumBridge tqb = block.getTileEntity(world, x, y, z); + + if (tqb == null) { + return false; + } + + renderer.renderAllFaces = true; + + final IDefinitions definitions = AEApi.instance().definitions(); + final IBlocks blocks = definitions.blocks(); + final IParts parts = definitions.parts(); + + for (final Block linkBlock : blocks.quantumLink().maybeBlock().asSet()) { + if (tqb.getBlockType() == linkBlock) { + if (tqb.isFormed()) { + final EnumSet sides = tqb.getConnections(); + + final Item transGlassCable = parts.cableGlass().item(AEColor.Transparent); + this.renderCableAt( + 0.11D, + world, + x, + y, + z, + block, + renderer, + transGlassCable.getIconIndex(parts.cableGlass().stack(AEColor.Transparent, 1)), + 0.141D, + sides); + + final Item transCoveredCable = parts.cableCovered().item(AEColor.Transparent); + this.renderCableAt( + 0.188D, + world, + x, + y, + z, + block, + renderer, + transCoveredCable.getIconIndex(parts.cableCovered().stack(AEColor.Transparent, 1)), + 0.1875D, + sides); + } + + renderer.setRenderBounds( + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX); + renderer.renderStandardBlock(block, x, y, z); + } else { + if (!tqb.isFormed()) { + renderer.setRenderBounds( + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX); + renderer.renderStandardBlock(block, x, y, z); + } else if (tqb.isCorner()) { + final Item transCoveredCable = parts.cableCovered().item(AEColor.Transparent); + + this.renderCableAt( + 0.188D, + world, + x, + y, + z, + block, + renderer, + transCoveredCable.getIconIndex(parts.cableCovered().stack(AEColor.Transparent, 1)), + 0.05D, + tqb.getConnections()); + + renderer.setRenderBounds( + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX); + renderer.renderStandardBlock(block, x, y, z); + + if (tqb.isPowered()) { + renderer.setRenderBounds( + CORNER_POWERED_RENDER_MIN, + CORNER_POWERED_RENDER_MIN, + CORNER_POWERED_RENDER_MIN, + CORNER_POWERED_RENDER_MAX, + CORNER_POWERED_RENDER_MAX, + CORNER_POWERED_RENDER_MAX); + + Tessellator.instance.setColorOpaque_F(1.0F, 1.0F, 1.0F); + final int bn = 15; + Tessellator.instance.setBrightness(bn << 20 | bn << 4); + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + this.renderFace( + x, y, z, block, ExtraBlockTextures.BlockQRingCornerLight.getIcon(), renderer, side); + } + } + } else { + renderer.setRenderBounds( + 0, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, 1, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX); + renderer.renderStandardBlock(block, x, y, z); + + renderer.setRenderBounds( + DEFAULT_RENDER_MIN, 0, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, 1, DEFAULT_RENDER_MAX); + renderer.renderStandardBlock(block, x, y, z); + + renderer.setRenderBounds( + DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, 0, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, 1); + renderer.renderStandardBlock(block, x, y, z); + + if (tqb.isPowered()) { + renderer.setRenderBounds( + CENTER_POWERED_RENDER_MIN, + CENTER_POWERED_RENDER_MIN, + CENTER_POWERED_RENDER_MIN, + CENTER_POWERED_RENDER_MAX, + CENTER_POWERED_RENDER_MAX, + CENTER_POWERED_RENDER_MAX); + + Tessellator.instance.setColorOpaque_F(1.0F, 1.0F, 1.0F); + final int bn = 15; + Tessellator.instance.setBrightness(bn << 20 | bn << 4); + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + this.renderFace( + x, y, z, block, ExtraBlockTextures.BlockQRingEdgeLight.getIcon(), renderer, side); + } + } + } + } + } + + renderer.renderAllFaces = false; + return true; + } + + private void renderCableAt( + final double thickness, + final IBlockAccess world, + final int x, + final int y, + final int z, + final BlockQuantumBase block, + final RenderBlocks renderer, + final IIcon texture, + final double pull, + final Collection connections) { + block.getRendererInstance().setTemporaryRenderIcon(texture); + + if (connections.contains(ForgeDirection.UNKNOWN)) { + renderer.setRenderBounds( + 0.5D - thickness, + 0.5D - thickness, + 0.5D - thickness, + 0.5D + thickness, + 0.5D + thickness, + 0.5D + thickness); + renderer.renderStandardBlock(block, x, y, z); + } + + if (connections.contains(ForgeDirection.WEST)) { + renderer.setRenderBounds( + 0.0D, + 0.5D - thickness, + 0.5D - thickness, + 0.5D - thickness - pull, + 0.5D + thickness, + 0.5D + thickness); + renderer.renderStandardBlock(block, x, y, z); + } + + if (connections.contains(ForgeDirection.EAST)) { + renderer.setRenderBounds( + 0.5D + thickness + pull, + 0.5D - thickness, + 0.5D - thickness, + 1.0D, + 0.5D + thickness, + 0.5D + thickness); + renderer.renderStandardBlock(block, x, y, z); + } + + if (connections.contains(ForgeDirection.NORTH)) { + renderer.setRenderBounds( + 0.5D - thickness, + 0.5D - thickness, + 0.0D, + 0.5D + thickness, + 0.5D + thickness, + 0.5D - thickness - pull); + renderer.renderStandardBlock(block, x, y, z); + } + + if (connections.contains(ForgeDirection.SOUTH)) { + renderer.setRenderBounds( + 0.5D - thickness, + 0.5D - thickness, + 0.5D + thickness + pull, + 0.5D + thickness, + 0.5D + thickness, + 1.0D); + renderer.renderStandardBlock(block, x, y, z); + } + + if (connections.contains(ForgeDirection.DOWN)) { + renderer.setRenderBounds( + 0.5D - thickness, + 0.0D, + 0.5D - thickness, + 0.5D + thickness, + 0.5D - thickness - pull, + 0.5D + thickness); + renderer.renderStandardBlock(block, x, y, z); + } + + if (connections.contains(ForgeDirection.UP)) { + renderer.setRenderBounds( + 0.5D - thickness, + 0.5D + thickness + pull, + 0.5D - thickness, + 0.5D + thickness, + 1.0D, + 0.5D + thickness); + renderer.renderStandardBlock(block, x, y, z); + } + + block.getRendererInstance().setTemporaryRenderIcon(null); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderQuartzGlass.java b/src/main/java/appeng/client/render/blocks/RenderQuartzGlass.java index f9fec893893..0871b5e774d 100644 --- a/src/main/java/appeng/client/render/blocks/RenderQuartzGlass.java +++ b/src/main/java/appeng/client/render/blocks/RenderQuartzGlass.java @@ -18,223 +18,216 @@ package appeng.client.render.blocks; - import appeng.api.AEApi; import appeng.block.solids.BlockQuartzGlass; import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; import appeng.client.texture.OffsetIcon; import appeng.tile.AEBaseTile; +import java.util.Random; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Random; - - -public class RenderQuartzGlass extends BaseBlockRender -{ - - private static final byte[][][] OFFSETS = generateOffsets(); - - public RenderQuartzGlass() - { - super( false, 0 ); - - } - - private static byte[][][] generateOffsets() - { - final Random r = new Random( 924 ); - final byte[][][] offset = new byte[10][10][10]; - - for( int x = 0; x < 10; x++ ) - { - for( int y = 0; y < 10; y++ ) - { - r.nextBytes( offset[x][y] ); - } - } - - return offset; - } - - @Override - public void renderInventory( final BlockQuartzGlass block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - renderer.overrideBlockTexture = ExtraBlockTextures.GlassFrame.getIcon(); - super.renderInventory( block, is, renderer, type, obj ); - renderer.overrideBlockTexture = null; - super.renderInventory( block, is, renderer, type, obj ); - } - - @Override - public boolean renderInWorld( final BlockQuartzGlass imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); - - final int cx = Math.abs( x % 10 ); - final int cy = Math.abs( y % 10 ); - final int cz = Math.abs( z % 10 ); - - final int u = OFFSETS[cx][cy][cz] % 4; - final int v = OFFSETS[9 - cx][9 - cy][9 - cz] % 4; - - switch( Math.abs( ( OFFSETS[cx][cy][cz] + ( x + y + z ) ) % 4 ) ) - { - case 0: - renderer.overrideBlockTexture = new OffsetIcon( imb.getIcon( 0, 0 ), u / 2, v / 2 ); - break; - case 1: - renderer.overrideBlockTexture = new OffsetIcon( ExtraBlockTextures.BlockQuartzGlassB.getIcon(), u / 2, v / 2 ); - break; - case 2: - renderer.overrideBlockTexture = new OffsetIcon( ExtraBlockTextures.BlockQuartzGlassC.getIcon(), u, v ); - break; - case 3: - renderer.overrideBlockTexture = new OffsetIcon( ExtraBlockTextures.BlockQuartzGlassD.getIcon(), u, v ); - break; - } - - final boolean result = renderer.renderStandardBlock( imb, x, y, z ); - - renderer.overrideBlockTexture = null; - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.EAST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.WEST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.NORTH ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.SOUTH ); - - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.EAST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.WEST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.NORTH ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.SOUTH ); - - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.UP ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.DOWN ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.NORTH ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.SOUTH ); - - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.UP ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.DOWN ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.NORTH ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.SOUTH ); - - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.EAST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.WEST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.UP ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.DOWN ); - - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.EAST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.WEST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.UP ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.DOWN ); - - return result; - } - - private void renderEdge( final BlockQuartzGlass imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer, final ForgeDirection side, final ForgeDirection direction ) - { - if( !this.isFlush( imb, world, x + side.offsetX, y + side.offsetY, z + side.offsetZ ) ) - { - if( !this.isFlush( imb, world, x + direction.offsetX, y + direction.offsetY, z + direction.offsetZ ) ) - { - float minX = 0.5f + ( side.offsetX + direction.offsetX ) / 2.0f; - float minY = 0.5f + ( side.offsetY + direction.offsetY ) / 2.0f; - float minZ = 0.5f + ( side.offsetZ + direction.offsetZ ) / 2.0f; - float maxX = 0.5f + ( side.offsetX + direction.offsetX ) / 2.0f; - float maxY = 0.5f + ( side.offsetY + direction.offsetY ) / 2.0f; - float maxZ = 0.5f + ( side.offsetZ + direction.offsetZ ) / 2.0f; - - if( 0 == side.offsetX && 0 == direction.offsetX ) - { - minX = 0.0f; - maxX = 1.0f; - } - if( 0 == side.offsetY && 0 == direction.offsetY ) - { - minY = 0.0f; - maxY = 1.0f; - } - if( 0 == side.offsetZ && 0 == direction.offsetZ ) - { - minZ = 0.0f; - maxZ = 1.0f; - } - - if( maxX <= 0.001f ) - { - maxX += 0.9f / 16.0f; - } - if( maxY <= 0.001f ) - { - maxY += 0.9f / 16.0f; - } - if( maxZ <= 0.001f ) - { - maxZ += 0.9f / 16.0f; - } - - if( minX >= 0.999f ) - { - minX -= 0.9f / 16.0f; - } - if( minY >= 0.999f ) - { - minY -= 0.9f / 16.0f; - } - if( minZ >= 0.999f ) - { - minZ -= 0.9f / 16.0f; - } - - renderer.setRenderBounds( minX, minY, minZ, maxX, maxY, maxZ ); - - switch( side ) - { - case WEST: - renderer.renderFaceXNeg( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); - break; - case EAST: - renderer.renderFaceXPos( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); - break; - case NORTH: - renderer.renderFaceZNeg( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); - break; - case SOUTH: - renderer.renderFaceZPos( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); - break; - case DOWN: - renderer.renderFaceYNeg( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); - break; - case UP: - renderer.renderFaceYPos( imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon() ); - break; - default: - break; - } - } - } - } - - private boolean isFlush( final BlockQuartzGlass imb, final IBlockAccess world, final int x, final int y, final int z ) - { - return this.isGlass( imb, world, x, y, z ); - } - - private boolean isGlass( final BlockQuartzGlass imb, final IBlockAccess world, final int x, final int y, final int z ) - { - return this.isQuartzGlass( world, x, y, z ) || this.isVibrantQuartzGlass( world, x, y, z ); - } - - private boolean isQuartzGlass( final IBlockAccess world, final int x, final int y, final int z ) - { - return AEApi.instance().definitions().blocks().quartzGlass().isSameAs( world, x, y, z ); - } - - private boolean isVibrantQuartzGlass( final IBlockAccess world, final int x, final int y, final int z ) - { - return AEApi.instance().definitions().blocks().quartzVibrantGlass().isSameAs( world, x, y, z ); - } +public class RenderQuartzGlass extends BaseBlockRender { + + private static final byte[][][] OFFSETS = generateOffsets(); + + public RenderQuartzGlass() { + super(false, 0); + } + + private static byte[][][] generateOffsets() { + final Random r = new Random(924); + final byte[][][] offset = new byte[10][10][10]; + + for (int x = 0; x < 10; x++) { + for (int y = 0; y < 10; y++) { + r.nextBytes(offset[x][y]); + } + } + + return offset; + } + + @Override + public void renderInventory( + final BlockQuartzGlass block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + renderer.overrideBlockTexture = ExtraBlockTextures.GlassFrame.getIcon(); + super.renderInventory(block, is, renderer, type, obj); + renderer.overrideBlockTexture = null; + super.renderInventory(block, is, renderer, type, obj); + } + + @Override + public boolean renderInWorld( + final BlockQuartzGlass imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + renderer.setRenderBounds(0, 0, 0, 1, 1, 1); + + final int cx = Math.abs(x % 10); + final int cy = Math.abs(y % 10); + final int cz = Math.abs(z % 10); + + final int u = OFFSETS[cx][cy][cz] % 4; + final int v = OFFSETS[9 - cx][9 - cy][9 - cz] % 4; + + switch (Math.abs((OFFSETS[cx][cy][cz] + (x + y + z)) % 4)) { + case 0: + renderer.overrideBlockTexture = new OffsetIcon(imb.getIcon(0, 0), u / 2, v / 2); + break; + case 1: + renderer.overrideBlockTexture = + new OffsetIcon(ExtraBlockTextures.BlockQuartzGlassB.getIcon(), u / 2, v / 2); + break; + case 2: + renderer.overrideBlockTexture = new OffsetIcon(ExtraBlockTextures.BlockQuartzGlassC.getIcon(), u, v); + break; + case 3: + renderer.overrideBlockTexture = new OffsetIcon(ExtraBlockTextures.BlockQuartzGlassD.getIcon(), u, v); + break; + } + + final boolean result = renderer.renderStandardBlock(imb, x, y, z); + + renderer.overrideBlockTexture = null; + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.EAST); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.WEST); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.NORTH); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.SOUTH); + + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.EAST); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.WEST); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.NORTH); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.SOUTH); + + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.UP); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.DOWN); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.NORTH); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.SOUTH); + + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.UP); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.DOWN); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.NORTH); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.SOUTH); + + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.EAST); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.WEST); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.UP); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.DOWN); + + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.EAST); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.WEST); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.UP); + this.renderEdge(imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.DOWN); + + return result; + } + + private void renderEdge( + final BlockQuartzGlass imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer, + final ForgeDirection side, + final ForgeDirection direction) { + if (!this.isFlush(imb, world, x + side.offsetX, y + side.offsetY, z + side.offsetZ)) { + if (!this.isFlush(imb, world, x + direction.offsetX, y + direction.offsetY, z + direction.offsetZ)) { + float minX = 0.5f + (side.offsetX + direction.offsetX) / 2.0f; + float minY = 0.5f + (side.offsetY + direction.offsetY) / 2.0f; + float minZ = 0.5f + (side.offsetZ + direction.offsetZ) / 2.0f; + float maxX = 0.5f + (side.offsetX + direction.offsetX) / 2.0f; + float maxY = 0.5f + (side.offsetY + direction.offsetY) / 2.0f; + float maxZ = 0.5f + (side.offsetZ + direction.offsetZ) / 2.0f; + + if (0 == side.offsetX && 0 == direction.offsetX) { + minX = 0.0f; + maxX = 1.0f; + } + if (0 == side.offsetY && 0 == direction.offsetY) { + minY = 0.0f; + maxY = 1.0f; + } + if (0 == side.offsetZ && 0 == direction.offsetZ) { + minZ = 0.0f; + maxZ = 1.0f; + } + + if (maxX <= 0.001f) { + maxX += 0.9f / 16.0f; + } + if (maxY <= 0.001f) { + maxY += 0.9f / 16.0f; + } + if (maxZ <= 0.001f) { + maxZ += 0.9f / 16.0f; + } + + if (minX >= 0.999f) { + minX -= 0.9f / 16.0f; + } + if (minY >= 0.999f) { + minY -= 0.9f / 16.0f; + } + if (minZ >= 0.999f) { + minZ -= 0.9f / 16.0f; + } + + renderer.setRenderBounds(minX, minY, minZ, maxX, maxY, maxZ); + + switch (side) { + case WEST: + renderer.renderFaceXNeg(imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon()); + break; + case EAST: + renderer.renderFaceXPos(imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon()); + break; + case NORTH: + renderer.renderFaceZNeg(imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon()); + break; + case SOUTH: + renderer.renderFaceZPos(imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon()); + break; + case DOWN: + renderer.renderFaceYNeg(imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon()); + break; + case UP: + renderer.renderFaceYPos(imb, x, y, z, ExtraBlockTextures.GlassFrame.getIcon()); + break; + default: + break; + } + } + } + } + + private boolean isFlush( + final BlockQuartzGlass imb, final IBlockAccess world, final int x, final int y, final int z) { + return this.isGlass(imb, world, x, y, z); + } + + private boolean isGlass( + final BlockQuartzGlass imb, final IBlockAccess world, final int x, final int y, final int z) { + return this.isQuartzGlass(world, x, y, z) || this.isVibrantQuartzGlass(world, x, y, z); + } + + private boolean isQuartzGlass(final IBlockAccess world, final int x, final int y, final int z) { + return AEApi.instance().definitions().blocks().quartzGlass().isSameAs(world, x, y, z); + } + + private boolean isVibrantQuartzGlass(final IBlockAccess world, final int x, final int y, final int z) { + return AEApi.instance().definitions().blocks().quartzVibrantGlass().isSameAs(world, x, y, z); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderQuartzOre.java b/src/main/java/appeng/client/render/blocks/RenderQuartzOre.java index 50504c108a3..6a70b957db0 100644 --- a/src/main/java/appeng/client/render/blocks/RenderQuartzOre.java +++ b/src/main/java/appeng/client/render/blocks/RenderQuartzOre.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.solids.OreQuartz; import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; @@ -28,35 +27,41 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; +public class RenderQuartzOre extends BaseBlockRender { + + public RenderQuartzOre() { + super(false, 20); + } + + @Override + public void renderInventory( + final OreQuartz blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + super.renderInventory(blk, is, renderer, type, obj); + blk.getRendererInstance().setTemporaryRenderIcon(ExtraBlockTextures.OreQuartzStone.getIcon()); + super.renderInventory(blk, is, renderer, type, obj); + blk.getRendererInstance().setTemporaryRenderIcon(null); + } + + @Override + public boolean renderInWorld( + final OreQuartz quartz, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + quartz.setEnhanceBrightness(true); + super.renderInWorld(quartz, world, x, y, z, renderer); + quartz.setEnhanceBrightness(false); + + quartz.getRendererInstance().setTemporaryRenderIcon(ExtraBlockTextures.OreQuartzStone.getIcon()); + final boolean out = super.renderInWorld(quartz, world, x, y, z, renderer); + quartz.getRendererInstance().setTemporaryRenderIcon(null); -public class RenderQuartzOre extends BaseBlockRender -{ - - public RenderQuartzOre() - { - super( false, 20 ); - } - - @Override - public void renderInventory( final OreQuartz blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - super.renderInventory( blk, is, renderer, type, obj ); - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.OreQuartzStone.getIcon() ); - super.renderInventory( blk, is, renderer, type, obj ); - blk.getRendererInstance().setTemporaryRenderIcon( null ); - } - - @Override - public boolean renderInWorld( final OreQuartz quartz, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - quartz.setEnhanceBrightness( true ); - super.renderInWorld( quartz, world, x, y, z, renderer ); - quartz.setEnhanceBrightness( false ); - - quartz.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.OreQuartzStone.getIcon() ); - final boolean out = super.renderInWorld( quartz, world, x, y, z, renderer ); - quartz.getRendererInstance().setTemporaryRenderIcon( null ); - - return out; - } + return out; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderQuartzTorch.java b/src/main/java/appeng/client/render/blocks/RenderQuartzTorch.java index 5688e67ce03..0e6ab497797 100644 --- a/src/main/java/appeng/client/render/blocks/RenderQuartzTorch.java +++ b/src/main/java/appeng/client/render/blocks/RenderQuartzTorch.java @@ -18,11 +18,11 @@ package appeng.client.render.blocks; - import appeng.api.util.IOrientable; import appeng.block.AEBaseBlock; import appeng.client.render.BaseBlockRender; import appeng.tile.AEBaseTile; +import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.init.Blocks; @@ -31,178 +31,222 @@ import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class RenderQuartzTorch extends BaseBlockRender -{ - - public RenderQuartzTorch() - { - super( false, 20 ); - } - - @Override - public void renderInventory( final AEBaseBlock blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - final Tessellator tess = Tessellator.instance; - - final float Point3 = 7.0f / 16.0f; - final float Point12 = 9.0f / 16.0f; - - final float renderBottom = 5.0f / 16.0f; - final float renderTop = 10.0f / 16.0f; - - final float xOff = 0.0f; - final float yOff = 0.0f; - final float zOff = 0.0f; - - renderer.setRenderBounds( Point3 + xOff, renderBottom + yOff, Point3 + zOff, Point12 + xOff, renderTop + yOff, Point12 + zOff ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - - final float singlePixel = 1.0f / 16.0f; - renderer.setRenderBounds( Point3 + xOff, renderTop + yOff, Point3 + zOff, Point3 + singlePixel + xOff, renderTop + singlePixel + yOff, Point3 + singlePixel + zOff ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - - renderer.setRenderBounds( Point12 - singlePixel + xOff, renderBottom - singlePixel + yOff, Point12 - singlePixel + zOff, Point12 + xOff, renderBottom + yOff, Point12 + zOff ); - - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - - blk.getRendererInstance().setTemporaryRenderIcon( Blocks.hopper.getIcon( 0, 0 ) ); - renderer.renderAllFaces = true; - - final float top = 8.0f / 16.0f; - final float bottom = 7.0f / 16.0f; - final float Point13 = 10.0f / 16.0f; - final float Point2 = 6.0f / 16.0f; - renderer.setRenderBounds( Point2 + xOff, bottom + yOff, Point2 + zOff, Point13 + xOff, top + yOff, Point3 + zOff ); - - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - renderer.setRenderBounds( Point2 + xOff, bottom + yOff, Point12 + zOff, Point13 + xOff, top + yOff, Point13 + zOff ); - - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - renderer.setRenderBounds( Point2 + xOff, bottom + yOff, Point3 + zOff, Point3 + xOff, top + yOff, Point12 + zOff ); - - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - renderer.setRenderBounds( Point12 + xOff, bottom + yOff, Point3 + zOff, Point13 + xOff, top + yOff, Point12 + zOff ); - - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - - renderer.renderAllFaces = false; - blk.getRendererInstance().setTemporaryRenderIcon( null ); - } - - @Override - public boolean renderInWorld( final AEBaseBlock block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final IOrientable te = block.getOrientable( world, x, y, z ); - - float xOff = 0.0f; - float yOff = 0.0f; - float zOff = 0.0f; - - renderer.renderAllFaces = true; - - if( te != null ) - { - final ForgeDirection forward = te.getUp(); - xOff = forward.offsetX * -( 4.0f / 16.0f ); - yOff = forward.offsetY * -( 4.0f / 16.0f ); - zOff = forward.offsetZ * -( 4.0f / 16.0f ); - } - - final float renderTop = 10.0f / 16.0f; - final float renderBottom = 5.0f / 16.0f; - final float Point12 = 9.0f / 16.0f; - final float Point3 = 7.0f / 16.0f; - renderer.setRenderBounds( Point3 + xOff, renderBottom + yOff, Point3 + zOff, Point12 + xOff, renderTop + yOff, Point12 + zOff ); - super.renderInWorld( block, world, x, y, z, renderer ); - - final int r = ( x + y + z ) % 2; - final float singlePixel = 1.0f / 16.0f; - if( r == 0 ) - { - renderer.setRenderBounds( Point3 + xOff, renderTop + yOff, Point3 + zOff, Point3 + singlePixel + xOff, renderTop + singlePixel + yOff, Point3 + singlePixel + zOff ); - super.renderInWorld( block, world, x, y, z, renderer ); - - renderer.setRenderBounds( Point12 - singlePixel + xOff, renderBottom - singlePixel + yOff, Point12 - singlePixel + zOff, Point12 + xOff, renderBottom + yOff, Point12 + zOff ); - super.renderInWorld( block, world, x, y, z, renderer ); - } - else - { - renderer.setRenderBounds( Point3 + xOff, renderBottom - singlePixel + yOff, Point3 + zOff, Point3 + singlePixel + xOff, renderBottom + yOff, Point3 + singlePixel + zOff ); - super.renderInWorld( block, world, x, y, z, renderer ); - - renderer.setRenderBounds( Point12 - singlePixel + xOff, renderTop + yOff, Point12 - singlePixel + zOff, Point12 + xOff, renderTop + singlePixel + yOff, Point12 + zOff ); - super.renderInWorld( block, world, x, y, z, renderer ); - } - - block.getRendererInstance().setTemporaryRenderIcon( Blocks.hopper.getIcon( 0, 0 ) ); - - final float top = 8.0f / 16.0f; - final float bottom = 7.0f / 16.0f; - final float Point13 = 10.0f / 16.0f; - final float Point2 = 6.0f / 16.0f; - renderer.setRenderBounds( Point2 + xOff, bottom + yOff, Point2 + zOff, Point13 + xOff, top + yOff, Point3 + zOff ); - final boolean out = renderer.renderStandardBlock( block, x, y, z ); - - renderer.setRenderBounds( Point2 + xOff, bottom + yOff, Point12 + zOff, Point13 + xOff, top + yOff, Point13 + zOff ); - renderer.renderStandardBlock( block, x, y, z ); - - renderer.setRenderBounds( Point2 + xOff, bottom + yOff, Point3 + zOff, Point3 + xOff, top + yOff, Point12 + zOff ); - renderer.renderStandardBlock( block, x, y, z ); - - renderer.setRenderBounds( Point12 + xOff, bottom + yOff, Point3 + zOff, Point13 + xOff, top + yOff, Point12 + zOff ); - renderer.renderStandardBlock( block, x, y, z ); - - if( te != null ) - { - final ForgeDirection forward = te.getUp(); - switch( forward ) - { - case EAST: - renderer.setRenderBounds( 0, bottom + yOff, bottom + zOff, Point2 + xOff, top + yOff, top + zOff ); - renderer.renderStandardBlock( block, x, y, z ); - break; - case WEST: - renderer.setRenderBounds( Point13 + xOff, bottom + yOff, bottom + zOff, 1.0, top + yOff, top + zOff ); - renderer.renderStandardBlock( block, x, y, z ); - break; - case NORTH: - renderer.setRenderBounds( bottom + xOff, bottom + yOff, Point13 + zOff, top + xOff, top + yOff, 1.0 ); - renderer.renderStandardBlock( block, x, y, z ); - break; - case SOUTH: - renderer.setRenderBounds( bottom + xOff, bottom + yOff, 0, top + xOff, top + yOff, Point2 + zOff ); - renderer.renderStandardBlock( block, x, y, z ); - break; - case UP: - renderer.setRenderBounds( Point2, 0, Point2, Point3, bottom + yOff, Point3 ); - renderer.renderStandardBlock( block, x, y, z ); - renderer.setRenderBounds( Point2, 0, Point12, Point3, bottom + yOff, Point13 ); - renderer.renderStandardBlock( block, x, y, z ); - renderer.setRenderBounds( Point12, 0, Point2, Point13, bottom + yOff, Point3 ); - renderer.renderStandardBlock( block, x, y, z ); - renderer.setRenderBounds( Point12, 0, Point12, Point13, bottom + yOff, Point13 ); - renderer.renderStandardBlock( block, x, y, z ); - break; - case DOWN: - renderer.setRenderBounds( Point2, top + yOff, Point2, Point3, 1.0, Point3 ); - renderer.renderStandardBlock( block, x, y, z ); - renderer.setRenderBounds( Point2, top + yOff, Point12, Point3, 1.0, Point13 ); - renderer.renderStandardBlock( block, x, y, z ); - renderer.setRenderBounds( Point12, top + yOff, Point2, Point13, 1.0, Point3 ); - renderer.renderStandardBlock( block, x, y, z ); - renderer.setRenderBounds( Point12, top + yOff, Point12, Point13, 1.0, Point13 ); - renderer.renderStandardBlock( block, x, y, z ); - break; - default: - } - } - - renderer.renderAllFaces = false; - block.getRendererInstance().setTemporaryRenderIcon( null ); - - return out; - } +public class RenderQuartzTorch extends BaseBlockRender { + + public RenderQuartzTorch() { + super(false, 20); + } + + @Override + public void renderInventory( + final AEBaseBlock blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + final Tessellator tess = Tessellator.instance; + + final float Point3 = 7.0f / 16.0f; + final float Point12 = 9.0f / 16.0f; + + final float renderBottom = 5.0f / 16.0f; + final float renderTop = 10.0f / 16.0f; + + final float xOff = 0.0f; + final float yOff = 0.0f; + final float zOff = 0.0f; + + renderer.setRenderBounds( + Point3 + xOff, renderBottom + yOff, Point3 + zOff, Point12 + xOff, renderTop + yOff, Point12 + zOff); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); + + final float singlePixel = 1.0f / 16.0f; + renderer.setRenderBounds( + Point3 + xOff, + renderTop + yOff, + Point3 + zOff, + Point3 + singlePixel + xOff, + renderTop + singlePixel + yOff, + Point3 + singlePixel + zOff); + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); + + renderer.setRenderBounds( + Point12 - singlePixel + xOff, + renderBottom - singlePixel + yOff, + Point12 - singlePixel + zOff, + Point12 + xOff, + renderBottom + yOff, + Point12 + zOff); + + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); + + blk.getRendererInstance().setTemporaryRenderIcon(Blocks.hopper.getIcon(0, 0)); + renderer.renderAllFaces = true; + + final float top = 8.0f / 16.0f; + final float bottom = 7.0f / 16.0f; + final float Point13 = 10.0f / 16.0f; + final float Point2 = 6.0f / 16.0f; + renderer.setRenderBounds( + Point2 + xOff, bottom + yOff, Point2 + zOff, Point13 + xOff, top + yOff, Point3 + zOff); + + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); + renderer.setRenderBounds( + Point2 + xOff, bottom + yOff, Point12 + zOff, Point13 + xOff, top + yOff, Point13 + zOff); + + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); + renderer.setRenderBounds( + Point2 + xOff, bottom + yOff, Point3 + zOff, Point3 + xOff, top + yOff, Point12 + zOff); + + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); + renderer.setRenderBounds( + Point12 + xOff, bottom + yOff, Point3 + zOff, Point13 + xOff, top + yOff, Point12 + zOff); + + this.renderInvBlock(EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer); + + renderer.renderAllFaces = false; + blk.getRendererInstance().setTemporaryRenderIcon(null); + } + + @Override + public boolean renderInWorld( + final AEBaseBlock block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + final IOrientable te = block.getOrientable(world, x, y, z); + + float xOff = 0.0f; + float yOff = 0.0f; + float zOff = 0.0f; + + renderer.renderAllFaces = true; + + if (te != null) { + final ForgeDirection forward = te.getUp(); + xOff = forward.offsetX * -(4.0f / 16.0f); + yOff = forward.offsetY * -(4.0f / 16.0f); + zOff = forward.offsetZ * -(4.0f / 16.0f); + } + + final float renderTop = 10.0f / 16.0f; + final float renderBottom = 5.0f / 16.0f; + final float Point12 = 9.0f / 16.0f; + final float Point3 = 7.0f / 16.0f; + renderer.setRenderBounds( + Point3 + xOff, renderBottom + yOff, Point3 + zOff, Point12 + xOff, renderTop + yOff, Point12 + zOff); + super.renderInWorld(block, world, x, y, z, renderer); + + final int r = (x + y + z) % 2; + final float singlePixel = 1.0f / 16.0f; + if (r == 0) { + renderer.setRenderBounds( + Point3 + xOff, + renderTop + yOff, + Point3 + zOff, + Point3 + singlePixel + xOff, + renderTop + singlePixel + yOff, + Point3 + singlePixel + zOff); + super.renderInWorld(block, world, x, y, z, renderer); + + renderer.setRenderBounds( + Point12 - singlePixel + xOff, + renderBottom - singlePixel + yOff, + Point12 - singlePixel + zOff, + Point12 + xOff, + renderBottom + yOff, + Point12 + zOff); + super.renderInWorld(block, world, x, y, z, renderer); + } else { + renderer.setRenderBounds( + Point3 + xOff, + renderBottom - singlePixel + yOff, + Point3 + zOff, + Point3 + singlePixel + xOff, + renderBottom + yOff, + Point3 + singlePixel + zOff); + super.renderInWorld(block, world, x, y, z, renderer); + + renderer.setRenderBounds( + Point12 - singlePixel + xOff, + renderTop + yOff, + Point12 - singlePixel + zOff, + Point12 + xOff, + renderTop + singlePixel + yOff, + Point12 + zOff); + super.renderInWorld(block, world, x, y, z, renderer); + } + + block.getRendererInstance().setTemporaryRenderIcon(Blocks.hopper.getIcon(0, 0)); + + final float top = 8.0f / 16.0f; + final float bottom = 7.0f / 16.0f; + final float Point13 = 10.0f / 16.0f; + final float Point2 = 6.0f / 16.0f; + renderer.setRenderBounds( + Point2 + xOff, bottom + yOff, Point2 + zOff, Point13 + xOff, top + yOff, Point3 + zOff); + final boolean out = renderer.renderStandardBlock(block, x, y, z); + + renderer.setRenderBounds( + Point2 + xOff, bottom + yOff, Point12 + zOff, Point13 + xOff, top + yOff, Point13 + zOff); + renderer.renderStandardBlock(block, x, y, z); + + renderer.setRenderBounds( + Point2 + xOff, bottom + yOff, Point3 + zOff, Point3 + xOff, top + yOff, Point12 + zOff); + renderer.renderStandardBlock(block, x, y, z); + + renderer.setRenderBounds( + Point12 + xOff, bottom + yOff, Point3 + zOff, Point13 + xOff, top + yOff, Point12 + zOff); + renderer.renderStandardBlock(block, x, y, z); + + if (te != null) { + final ForgeDirection forward = te.getUp(); + switch (forward) { + case EAST: + renderer.setRenderBounds(0, bottom + yOff, bottom + zOff, Point2 + xOff, top + yOff, top + zOff); + renderer.renderStandardBlock(block, x, y, z); + break; + case WEST: + renderer.setRenderBounds(Point13 + xOff, bottom + yOff, bottom + zOff, 1.0, top + yOff, top + zOff); + renderer.renderStandardBlock(block, x, y, z); + break; + case NORTH: + renderer.setRenderBounds(bottom + xOff, bottom + yOff, Point13 + zOff, top + xOff, top + yOff, 1.0); + renderer.renderStandardBlock(block, x, y, z); + break; + case SOUTH: + renderer.setRenderBounds(bottom + xOff, bottom + yOff, 0, top + xOff, top + yOff, Point2 + zOff); + renderer.renderStandardBlock(block, x, y, z); + break; + case UP: + renderer.setRenderBounds(Point2, 0, Point2, Point3, bottom + yOff, Point3); + renderer.renderStandardBlock(block, x, y, z); + renderer.setRenderBounds(Point2, 0, Point12, Point3, bottom + yOff, Point13); + renderer.renderStandardBlock(block, x, y, z); + renderer.setRenderBounds(Point12, 0, Point2, Point13, bottom + yOff, Point3); + renderer.renderStandardBlock(block, x, y, z); + renderer.setRenderBounds(Point12, 0, Point12, Point13, bottom + yOff, Point13); + renderer.renderStandardBlock(block, x, y, z); + break; + case DOWN: + renderer.setRenderBounds(Point2, top + yOff, Point2, Point3, 1.0, Point3); + renderer.renderStandardBlock(block, x, y, z); + renderer.setRenderBounds(Point2, top + yOff, Point12, Point3, 1.0, Point13); + renderer.renderStandardBlock(block, x, y, z); + renderer.setRenderBounds(Point12, top + yOff, Point2, Point13, 1.0, Point3); + renderer.renderStandardBlock(block, x, y, z); + renderer.setRenderBounds(Point12, top + yOff, Point12, Point13, 1.0, Point13); + renderer.renderStandardBlock(block, x, y, z); + break; + default: + } + } + + renderer.renderAllFaces = false; + block.getRendererInstance().setTemporaryRenderIcon(null); + + return out; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderSpatialPylon.java b/src/main/java/appeng/client/render/blocks/RenderSpatialPylon.java index 1386580bdff..25060e6e0a9 100644 --- a/src/main/java/appeng/client/render/blocks/RenderSpatialPylon.java +++ b/src/main/java/appeng/client/render/blocks/RenderSpatialPylon.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.spatial.BlockSpatialPylon; import appeng.client.render.BaseBlockRender; import appeng.client.render.BlockRenderInfo; @@ -32,184 +31,191 @@ import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; - -public class RenderSpatialPylon extends BaseBlockRender -{ - - public RenderSpatialPylon() - { - super( false, 0 ); - } - - @Override - public void renderInventory( final BlockSpatialPylon block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - renderer.overrideBlockTexture = ExtraBlockTextures.BlockSpatialPylon_dim.getIcon(); - super.renderInventory( block, is, renderer, type, obj ); - renderer.overrideBlockTexture = null; - super.renderInventory( block, is, renderer, type, obj ); - } - - @Override - public boolean renderInWorld( final BlockSpatialPylon imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); - - final TileSpatialPylon sp = imb.getTileEntity( world, x, y, z ); - - final int displayBits = ( sp == null ) ? 0 : sp.getDisplayBits(); - - if( displayBits != 0 ) - { - ForgeDirection ori = ForgeDirection.UNKNOWN; - if( ( displayBits & TileSpatialPylon.DISPLAY_Z ) == TileSpatialPylon.DISPLAY_X ) - { - ori = ForgeDirection.EAST; - - if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MAX ) - { - renderer.uvRotateEast = 1; - renderer.uvRotateWest = 2; - renderer.uvRotateTop = 2; - renderer.uvRotateBottom = 1; - } - else if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MIN ) - { - renderer.uvRotateEast = 2; - renderer.uvRotateWest = 1; - renderer.uvRotateTop = 1; - renderer.uvRotateBottom = 2; - } - else - { - renderer.uvRotateEast = 1; - renderer.uvRotateWest = 1; - renderer.uvRotateTop = 1; - renderer.uvRotateBottom = 1; - } - } - - else if( ( displayBits & TileSpatialPylon.DISPLAY_Z ) == TileSpatialPylon.DISPLAY_Y ) - { - ori = ForgeDirection.UP; - if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MAX ) - { - renderer.uvRotateNorth = 3; - renderer.uvRotateSouth = 3; - renderer.uvRotateEast = 3; - renderer.uvRotateWest = 3; - } - } - - else if( ( displayBits & TileSpatialPylon.DISPLAY_Z ) == TileSpatialPylon.DISPLAY_Z ) - { - ori = ForgeDirection.NORTH; - if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MAX ) - { - renderer.uvRotateSouth = 1; - renderer.uvRotateNorth = 2; - } - else if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MIN ) - { - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 2; - renderer.uvRotateTop = 3; - renderer.uvRotateBottom = 3; - } - else - { - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 2; - } - } - - final BlockRenderInfo bri = imb.getRendererInstance(); - bri.setTemporaryRenderIcon( null ); - bri.setTemporaryRenderIcons( this.getBlockTextureFromSideOutside( imb, sp, displayBits, ori, ForgeDirection.UP ), this.getBlockTextureFromSideOutside( imb, sp, displayBits, ori, ForgeDirection.DOWN ), this.getBlockTextureFromSideOutside( imb, sp, displayBits, ori, ForgeDirection.SOUTH ), this.getBlockTextureFromSideOutside( imb, sp, displayBits, ori, ForgeDirection.NORTH ), this.getBlockTextureFromSideOutside( imb, sp, displayBits, ori, ForgeDirection.EAST ), this.getBlockTextureFromSideOutside( imb, sp, displayBits, ori, ForgeDirection.WEST ) ); - - final boolean r = renderer.renderStandardBlock( imb, x, y, z ); - - if( ( displayBits & TileSpatialPylon.DISPLAY_POWERED_ENABLED ) == TileSpatialPylon.DISPLAY_POWERED_ENABLED ) - { - final int bn = 15; - Tessellator.instance.setBrightness( bn << 20 | bn << 4 ); - Tessellator.instance.setColorOpaque_I( 0xffffff ); - - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - this.renderFace( x, y, z, imb, this.getBlockTextureFromSideInside( imb, sp, displayBits, ori, d ), renderer, d ); - } - } - else - { - bri.setTemporaryRenderIcon( null ); - bri.setTemporaryRenderIcons( this.getBlockTextureFromSideInside( imb, sp, displayBits, ori, ForgeDirection.UP ), this.getBlockTextureFromSideInside( imb, sp, displayBits, ori, ForgeDirection.DOWN ), this.getBlockTextureFromSideInside( imb, sp, displayBits, ori, ForgeDirection.SOUTH ), this.getBlockTextureFromSideInside( imb, sp, displayBits, ori, ForgeDirection.NORTH ), this.getBlockTextureFromSideInside( imb, sp, displayBits, ori, ForgeDirection.EAST ), this.getBlockTextureFromSideInside( imb, sp, displayBits, ori, ForgeDirection.WEST ) ); - - renderer.renderStandardBlock( imb, x, y, z ); - } - - bri.setTemporaryRenderIcon( null ); - renderer.uvRotateEast = renderer.uvRotateWest = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateBottom = 0; - - return r; - } - - renderer.overrideBlockTexture = imb.getIcon( 0, 0 ); - boolean result = renderer.renderStandardBlock( imb, x, y, z ); - - renderer.overrideBlockTexture = ExtraBlockTextures.BlockSpatialPylon_dim.getIcon(); - result = renderer.renderStandardBlock( imb, x, y, z ); - - renderer.overrideBlockTexture = null; - return result; - } - - private IIcon getBlockTextureFromSideOutside( final BlockSpatialPylon blk, final TileSpatialPylon sp, final int displayBits, final ForgeDirection ori, final ForgeDirection dir ) - { - - if( ori == dir || ori.getOpposite() == dir ) - { - return blk.getRendererInstance().getTexture( dir ); - } - - if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_MIDDLE ) - { - return ExtraBlockTextures.BlockSpatialPylonC.getIcon(); - } - else if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MIN ) - { - return ExtraBlockTextures.BlockSpatialPylonE.getIcon(); - } - else if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MAX ) - { - return ExtraBlockTextures.BlockSpatialPylonE.getIcon(); - } - - return blk.getIcon( 0, 0 ); - } - - private IIcon getBlockTextureFromSideInside( final BlockSpatialPylon blk, final TileSpatialPylon sp, final int displayBits, final ForgeDirection ori, final ForgeDirection dir ) - { - final boolean good = ( displayBits & TileSpatialPylon.DISPLAY_ENABLED ) == TileSpatialPylon.DISPLAY_ENABLED; - - if( ori == dir || ori.getOpposite() == dir ) - { - return good ? ExtraBlockTextures.BlockSpatialPylon_dim.getIcon() : ExtraBlockTextures.BlockSpatialPylon_red.getIcon(); - } - - if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_MIDDLE ) - { - return good ? ExtraBlockTextures.BlockSpatialPylonC_dim.getIcon() : ExtraBlockTextures.BlockSpatialPylonC_red.getIcon(); - } - else if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MIN ) - { - return good ? ExtraBlockTextures.BlockSpatialPylonE_dim.getIcon() : ExtraBlockTextures.BlockSpatialPylonE_red.getIcon(); - } - else if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MAX ) - { - return good ? ExtraBlockTextures.BlockSpatialPylonE_dim.getIcon() : ExtraBlockTextures.BlockSpatialPylonE_red.getIcon(); - } - - return blk.getIcon( 0, 0 ); - } +public class RenderSpatialPylon extends BaseBlockRender { + + public RenderSpatialPylon() { + super(false, 0); + } + + @Override + public void renderInventory( + final BlockSpatialPylon block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + renderer.overrideBlockTexture = ExtraBlockTextures.BlockSpatialPylon_dim.getIcon(); + super.renderInventory(block, is, renderer, type, obj); + renderer.overrideBlockTexture = null; + super.renderInventory(block, is, renderer, type, obj); + } + + @Override + public boolean renderInWorld( + final BlockSpatialPylon imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + renderer.setRenderBounds(0, 0, 0, 1, 1, 1); + + final TileSpatialPylon sp = imb.getTileEntity(world, x, y, z); + + final int displayBits = (sp == null) ? 0 : sp.getDisplayBits(); + + if (displayBits != 0) { + ForgeDirection ori = ForgeDirection.UNKNOWN; + if ((displayBits & TileSpatialPylon.DISPLAY_Z) == TileSpatialPylon.DISPLAY_X) { + ori = ForgeDirection.EAST; + + if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MAX) { + renderer.uvRotateEast = 1; + renderer.uvRotateWest = 2; + renderer.uvRotateTop = 2; + renderer.uvRotateBottom = 1; + } else if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MIN) { + renderer.uvRotateEast = 2; + renderer.uvRotateWest = 1; + renderer.uvRotateTop = 1; + renderer.uvRotateBottom = 2; + } else { + renderer.uvRotateEast = 1; + renderer.uvRotateWest = 1; + renderer.uvRotateTop = 1; + renderer.uvRotateBottom = 1; + } + } else if ((displayBits & TileSpatialPylon.DISPLAY_Z) == TileSpatialPylon.DISPLAY_Y) { + ori = ForgeDirection.UP; + if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MAX) { + renderer.uvRotateNorth = 3; + renderer.uvRotateSouth = 3; + renderer.uvRotateEast = 3; + renderer.uvRotateWest = 3; + } + } else if ((displayBits & TileSpatialPylon.DISPLAY_Z) == TileSpatialPylon.DISPLAY_Z) { + ori = ForgeDirection.NORTH; + if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MAX) { + renderer.uvRotateSouth = 1; + renderer.uvRotateNorth = 2; + } else if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MIN) { + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 2; + renderer.uvRotateTop = 3; + renderer.uvRotateBottom = 3; + } else { + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 2; + } + } + + final BlockRenderInfo bri = imb.getRendererInstance(); + bri.setTemporaryRenderIcon(null); + bri.setTemporaryRenderIcons( + this.getBlockTextureFromSideOutside(imb, sp, displayBits, ori, ForgeDirection.UP), + this.getBlockTextureFromSideOutside(imb, sp, displayBits, ori, ForgeDirection.DOWN), + this.getBlockTextureFromSideOutside(imb, sp, displayBits, ori, ForgeDirection.SOUTH), + this.getBlockTextureFromSideOutside(imb, sp, displayBits, ori, ForgeDirection.NORTH), + this.getBlockTextureFromSideOutside(imb, sp, displayBits, ori, ForgeDirection.EAST), + this.getBlockTextureFromSideOutside(imb, sp, displayBits, ori, ForgeDirection.WEST)); + + final boolean r = renderer.renderStandardBlock(imb, x, y, z); + + if ((displayBits & TileSpatialPylon.DISPLAY_POWERED_ENABLED) == TileSpatialPylon.DISPLAY_POWERED_ENABLED) { + final int bn = 15; + Tessellator.instance.setBrightness(bn << 20 | bn << 4); + Tessellator.instance.setColorOpaque_I(0xffffff); + + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + this.renderFace( + x, + y, + z, + imb, + this.getBlockTextureFromSideInside(imb, sp, displayBits, ori, d), + renderer, + d); + } + } else { + bri.setTemporaryRenderIcon(null); + bri.setTemporaryRenderIcons( + this.getBlockTextureFromSideInside(imb, sp, displayBits, ori, ForgeDirection.UP), + this.getBlockTextureFromSideInside(imb, sp, displayBits, ori, ForgeDirection.DOWN), + this.getBlockTextureFromSideInside(imb, sp, displayBits, ori, ForgeDirection.SOUTH), + this.getBlockTextureFromSideInside(imb, sp, displayBits, ori, ForgeDirection.NORTH), + this.getBlockTextureFromSideInside(imb, sp, displayBits, ori, ForgeDirection.EAST), + this.getBlockTextureFromSideInside(imb, sp, displayBits, ori, ForgeDirection.WEST)); + + renderer.renderStandardBlock(imb, x, y, z); + } + + bri.setTemporaryRenderIcon(null); + renderer.uvRotateEast = renderer.uvRotateWest = renderer.uvRotateNorth = + renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateBottom = 0; + + return r; + } + + renderer.overrideBlockTexture = imb.getIcon(0, 0); + boolean result = renderer.renderStandardBlock(imb, x, y, z); + + renderer.overrideBlockTexture = ExtraBlockTextures.BlockSpatialPylon_dim.getIcon(); + result = renderer.renderStandardBlock(imb, x, y, z); + + renderer.overrideBlockTexture = null; + return result; + } + + private IIcon getBlockTextureFromSideOutside( + final BlockSpatialPylon blk, + final TileSpatialPylon sp, + final int displayBits, + final ForgeDirection ori, + final ForgeDirection dir) { + + if (ori == dir || ori.getOpposite() == dir) { + return blk.getRendererInstance().getTexture(dir); + } + + if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_MIDDLE) { + return ExtraBlockTextures.BlockSpatialPylonC.getIcon(); + } else if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MIN) { + return ExtraBlockTextures.BlockSpatialPylonE.getIcon(); + } else if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MAX) { + return ExtraBlockTextures.BlockSpatialPylonE.getIcon(); + } + + return blk.getIcon(0, 0); + } + + private IIcon getBlockTextureFromSideInside( + final BlockSpatialPylon blk, + final TileSpatialPylon sp, + final int displayBits, + final ForgeDirection ori, + final ForgeDirection dir) { + final boolean good = (displayBits & TileSpatialPylon.DISPLAY_ENABLED) == TileSpatialPylon.DISPLAY_ENABLED; + + if (ori == dir || ori.getOpposite() == dir) { + return good + ? ExtraBlockTextures.BlockSpatialPylon_dim.getIcon() + : ExtraBlockTextures.BlockSpatialPylon_red.getIcon(); + } + + if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_MIDDLE) { + return good + ? ExtraBlockTextures.BlockSpatialPylonC_dim.getIcon() + : ExtraBlockTextures.BlockSpatialPylonC_red.getIcon(); + } else if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MIN) { + return good + ? ExtraBlockTextures.BlockSpatialPylonE_dim.getIcon() + : ExtraBlockTextures.BlockSpatialPylonE_red.getIcon(); + } else if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MAX) { + return good + ? ExtraBlockTextures.BlockSpatialPylonE_dim.getIcon() + : ExtraBlockTextures.BlockSpatialPylonE_red.getIcon(); + } + + return blk.getIcon(0, 0); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderTinyTNT.java b/src/main/java/appeng/client/render/blocks/RenderTinyTNT.java index c7b2e1f648e..1041872583f 100644 --- a/src/main/java/appeng/client/render/blocks/RenderTinyTNT.java +++ b/src/main/java/appeng/client/render/blocks/RenderTinyTNT.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.misc.BlockTinyTNT; import appeng.client.render.BaseBlockRender; import appeng.tile.AEBaseTile; @@ -27,29 +26,35 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; - -public class RenderTinyTNT extends BaseBlockRender -{ - - public RenderTinyTNT() - { - super( false, 0 ); - } - - @Override - public void renderInventory( final BlockTinyTNT block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - renderer.setRenderBounds( 0.25f, 0.0f, 0.25f, 0.75f, 0.5f, 0.75f ); - super.renderInventory( block, is, renderer, type, obj ); - } - - @Override - public boolean renderInWorld( final BlockTinyTNT imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - renderer.renderAllFaces = true; - renderer.setRenderBounds( 0.25f, 0.0f, 0.25f, 0.75f, 0.5f, 0.75f ); - final boolean out = super.renderInWorld( imb, world, x, y, z, renderer ); - renderer.renderAllFaces = false; - return out; - } +public class RenderTinyTNT extends BaseBlockRender { + + public RenderTinyTNT() { + super(false, 0); + } + + @Override + public void renderInventory( + final BlockTinyTNT block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + renderer.setRenderBounds(0.25f, 0.0f, 0.25f, 0.75f, 0.5f, 0.75f); + super.renderInventory(block, is, renderer, type, obj); + } + + @Override + public boolean renderInWorld( + final BlockTinyTNT imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + renderer.renderAllFaces = true; + renderer.setRenderBounds(0.25f, 0.0f, 0.25f, 0.75f, 0.5f, 0.75f); + final boolean out = super.renderInWorld(imb, world, x, y, z, renderer); + renderer.renderAllFaces = false; + return out; + } } diff --git a/src/main/java/appeng/client/render/blocks/RendererCableBus.java b/src/main/java/appeng/client/render/blocks/RendererCableBus.java index 21b3e24559d..4f19064aac6 100644 --- a/src/main/java/appeng/client/render/blocks/RendererCableBus.java +++ b/src/main/java/appeng/client/render/blocks/RendererCableBus.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.networking.BlockCableBus; import appeng.client.render.BaseBlockRender; import appeng.client.render.BusRenderHelper; @@ -31,45 +30,56 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; +public class RendererCableBus extends BaseBlockRender { -public class RendererCableBus extends BaseBlockRender -{ - - public RendererCableBus() - { - super( true, 30 ); - } + public RendererCableBus() { + super(true, 30); + } - @Override - public void renderInventory( final BlockCableBus blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - // nothing. - } + @Override + public void renderInventory( + final BlockCableBus blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + // nothing. + } - @Override - public boolean renderInWorld( final BlockCableBus block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final AEBaseTile t = block.getTileEntity( world, x, y, z ); + @Override + public boolean renderInWorld( + final BlockCableBus block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + final AEBaseTile t = block.getTileEntity(world, x, y, z); - if( t instanceof TileCableBus ) - { - BusRenderer.INSTANCE.getRenderer().renderAllFaces = true; - BusRenderer.INSTANCE.getRenderer().blockAccess = renderer.blockAccess; - BusRenderer.INSTANCE.getRenderer().overrideBlockTexture = renderer.overrideBlockTexture; - ( (TileCableBus) t ).getCableBus().renderStatic( x, y, z ); - BusRenderer.INSTANCE.getRenderer().renderAllFaces = false; - } + if (t instanceof TileCableBus) { + BusRenderer.INSTANCE.getRenderer().renderAllFaces = true; + BusRenderer.INSTANCE.getRenderer().blockAccess = renderer.blockAccess; + BusRenderer.INSTANCE.getRenderer().overrideBlockTexture = renderer.overrideBlockTexture; + ((TileCableBus) t).getCableBus().renderStatic(x, y, z); + BusRenderer.INSTANCE.getRenderer().renderAllFaces = false; + } - return BusRenderHelper.INSTANCE.getItemsRendered() > 0; - } + return BusRenderHelper.INSTANCE.getItemsRendered() > 0; + } - @Override - public void renderTile( final BlockCableBus block, final TileCableBus cableBus, final Tessellator tess, final double x, final double y, final double z, final float f, final RenderBlocks renderer ) - { - if( cableBus != null ) - { - BusRenderer.INSTANCE.getRenderer().overrideBlockTexture = null; - cableBus.getCableBus().renderDynamic( x, y, z ); - } - } + @Override + public void renderTile( + final BlockCableBus block, + final TileCableBus cableBus, + final Tessellator tess, + final double x, + final double y, + final double z, + final float f, + final RenderBlocks renderer) { + if (cableBus != null) { + BusRenderer.INSTANCE.getRenderer().overrideBlockTexture = null; + cableBus.getCableBus().renderDynamic(x, y, z); + } + } } diff --git a/src/main/java/appeng/client/render/blocks/RendererSecurity.java b/src/main/java/appeng/client/render/blocks/RendererSecurity.java index 8a7988c36fd..8f220ed7c83 100644 --- a/src/main/java/appeng/client/render/blocks/RendererSecurity.java +++ b/src/main/java/appeng/client/render/blocks/RendererSecurity.java @@ -18,12 +18,12 @@ package appeng.client.render.blocks; - import appeng.api.util.AEColor; import appeng.block.misc.BlockSecurity; import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; import appeng.tile.misc.TileSecurity; +import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.item.ItemStack; @@ -32,71 +32,85 @@ import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class RendererSecurity extends BaseBlockRender -{ - - public RendererSecurity() - { - super( false, 0 ); - } - - @Override - public void renderInventory( final BlockSecurity block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - renderer.overrideBlockTexture = ExtraBlockTextures.getMissing(); - this.renderInvBlock( EnumSet.of( ForgeDirection.SOUTH ), block, is, Tessellator.instance, 0x000000, renderer ); - - renderer.overrideBlockTexture = ExtraBlockTextures.MEChest.getIcon(); - this.renderInvBlock( EnumSet.of( ForgeDirection.UP ), block, is, Tessellator.instance, this.adjustBrightness( AEColor.Transparent.whiteVariant, 0.7 ), renderer ); - - renderer.overrideBlockTexture = null; - super.renderInventory( block, is, renderer, type, obj ); - } - - @Override - public boolean renderInWorld( final BlockSecurity imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TileSecurity sp = imb.getTileEntity( world, x, y, z ); - renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); - - final ForgeDirection up = sp.getUp(); - - this.preRenderInWorld( imb, world, x, y, z, renderer ); - - final boolean result = renderer.renderStandardBlock( imb, x, y, z ); - - int b = world.getLightBrightnessForSkyBlocks( x + up.offsetX, y + up.offsetY, z + up.offsetZ, 0 ); - - if( sp.isActive() ) - { - b = 15 << 20 | 15 << 4; - } - - Tessellator.instance.setBrightness( b ); - Tessellator.instance.setColorOpaque_I( 0xffffff ); - renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); - - Tessellator.instance.setColorOpaque_I( sp.getColor().whiteVariant ); - IIcon ico = sp.isActive() ? ExtraBlockTextures.BlockMESecurityOn_Light.getIcon() : ExtraBlockTextures.MEChest.getIcon(); - this.renderFace( x, y, z, imb, ico, renderer, up ); - - if( sp.isActive() ) - { - Tessellator.instance.setColorOpaque_I( sp.getColor().mediumVariant ); - ico = sp.isActive() ? ExtraBlockTextures.BlockMESecurityOn_Medium.getIcon() : ExtraBlockTextures.MEChest.getIcon(); - this.renderFace( x, y, z, imb, ico, renderer, up ); - - Tessellator.instance.setColorOpaque_I( sp.getColor().blackVariant ); - ico = sp.isActive() ? ExtraBlockTextures.BlockMESecurityOn_Dark.getIcon() : ExtraBlockTextures.MEChest.getIcon(); - this.renderFace( x, y, z, imb, ico, renderer, up ); - } - - renderer.overrideBlockTexture = null; - this.postRenderInWorld( renderer ); - - return result; - } +public class RendererSecurity extends BaseBlockRender { + + public RendererSecurity() { + super(false, 0); + } + + @Override + public void renderInventory( + final BlockSecurity block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj) { + renderer.overrideBlockTexture = ExtraBlockTextures.getMissing(); + this.renderInvBlock(EnumSet.of(ForgeDirection.SOUTH), block, is, Tessellator.instance, 0x000000, renderer); + + renderer.overrideBlockTexture = ExtraBlockTextures.MEChest.getIcon(); + this.renderInvBlock( + EnumSet.of(ForgeDirection.UP), + block, + is, + Tessellator.instance, + this.adjustBrightness(AEColor.Transparent.whiteVariant, 0.7), + renderer); + + renderer.overrideBlockTexture = null; + super.renderInventory(block, is, renderer, type, obj); + } + + @Override + public boolean renderInWorld( + final BlockSecurity imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer) { + final TileSecurity sp = imb.getTileEntity(world, x, y, z); + renderer.setRenderBounds(0, 0, 0, 1, 1, 1); + + final ForgeDirection up = sp.getUp(); + + this.preRenderInWorld(imb, world, x, y, z, renderer); + + final boolean result = renderer.renderStandardBlock(imb, x, y, z); + + int b = world.getLightBrightnessForSkyBlocks(x + up.offsetX, y + up.offsetY, z + up.offsetZ, 0); + + if (sp.isActive()) { + b = 15 << 20 | 15 << 4; + } + + Tessellator.instance.setBrightness(b); + Tessellator.instance.setColorOpaque_I(0xffffff); + renderer.setRenderBounds(0, 0, 0, 1, 1, 1); + + Tessellator.instance.setColorOpaque_I(sp.getColor().whiteVariant); + IIcon ico = sp.isActive() + ? ExtraBlockTextures.BlockMESecurityOn_Light.getIcon() + : ExtraBlockTextures.MEChest.getIcon(); + this.renderFace(x, y, z, imb, ico, renderer, up); + + if (sp.isActive()) { + Tessellator.instance.setColorOpaque_I(sp.getColor().mediumVariant); + ico = sp.isActive() + ? ExtraBlockTextures.BlockMESecurityOn_Medium.getIcon() + : ExtraBlockTextures.MEChest.getIcon(); + this.renderFace(x, y, z, imb, ico, renderer, up); + + Tessellator.instance.setColorOpaque_I(sp.getColor().blackVariant); + ico = sp.isActive() + ? ExtraBlockTextures.BlockMESecurityOn_Dark.getIcon() + : ExtraBlockTextures.MEChest.getIcon(); + this.renderFace(x, y, z, imb, ico, renderer, up); + } + + renderer.overrideBlockTexture = null; + this.postRenderInWorld(renderer); + + return result; + } } diff --git a/src/main/java/appeng/client/render/effects/AssemblerFX.java b/src/main/java/appeng/client/render/effects/AssemblerFX.java index 0c670b3d4ee..a07cbbbf8f4 100644 --- a/src/main/java/appeng/client/render/effects/AssemblerFX.java +++ b/src/main/java/appeng/client/render/effects/AssemblerFX.java @@ -18,7 +18,6 @@ package appeng.client.render.effects; - import appeng.api.storage.data.IAEItemStack; import appeng.client.EffectType; import appeng.core.CommonHelper; @@ -27,63 +26,69 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraft.world.World; +public class AssemblerFX extends EntityFX { -public class AssemblerFX extends EntityFX -{ - - private final EntityFloatingItem fi; - private final float speed; - private float time = 0; + private final EntityFloatingItem fi; + private final float speed; + private float time = 0; - public AssemblerFX( final World w, final double x, final double y, final double z, final double r, final double g, final double b, final float speed, final IAEItemStack is ) - { - super( w, x, y, z, r, g, b ); - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; - this.speed = speed; - this.fi = new EntityFloatingItem( this, w, x, y, z, is.getItemStack() ); - w.spawnEntityInWorld( this.fi ); - this.particleMaxAge = (int) Math.ceil( Math.max( 1, 100.0f / speed ) ) + 2; - this.noClip = true; - } + public AssemblerFX( + final World w, + final double x, + final double y, + final double z, + final double r, + final double g, + final double b, + final float speed, + final IAEItemStack is) { + super(w, x, y, z, r, g, b); + this.motionX = 0; + this.motionY = 0; + this.motionZ = 0; + this.speed = speed; + this.fi = new EntityFloatingItem(this, w, x, y, z, is.getItemStack()); + w.spawnEntityInWorld(this.fi); + this.particleMaxAge = (int) Math.ceil(Math.max(1, 100.0f / speed)) + 2; + this.noClip = true; + } - @Override - public int getBrightnessForRender( final float par1 ) - { - final int j1 = 13; - return j1 << 20 | j1 << 4; - } + @Override + public int getBrightnessForRender(final float par1) { + final int j1 = 13; + return j1 << 20 | j1 << 4; + } - @Override - public void onUpdate() - { - super.onUpdate(); + @Override + public void onUpdate() { + super.onUpdate(); - if( this.isDead ) - { - this.fi.setDead(); - } - else - { - final float lifeSpan = (float) this.particleAge / (float) this.particleMaxAge; - this.fi.setProgress( lifeSpan ); - } - } + if (this.isDead) { + this.fi.setDead(); + } else { + final float lifeSpan = (float) this.particleAge / (float) this.particleMaxAge; + this.fi.setProgress(lifeSpan); + } + } - @Override - public void renderParticle( final Tessellator tess, final float l, final float rX, final float rY, final float rZ, final float rYZ, final float rXY ) - { - this.time += l; + @Override + public void renderParticle( + final Tessellator tess, + final float l, + final float rX, + final float rY, + final float rZ, + final float rYZ, + final float rXY) { + this.time += l; - if( this.time > 4.0 ) - { - this.time -= 4.0; - // if ( CommonHelper.proxy.shouldAddParticles( r ) ) - for( int x = 0; x < (int) Math.ceil( this.speed / 5 ); x++ ) - { - CommonHelper.proxy.spawnEffect( EffectType.Crafting, this.worldObj, this.posX, this.posY, this.posZ, null ); - } - } - } + if (this.time > 4.0) { + this.time -= 4.0; + // if ( CommonHelper.proxy.shouldAddParticles( r ) ) + for (int x = 0; x < (int) Math.ceil(this.speed / 5); x++) { + CommonHelper.proxy.spawnEffect( + EffectType.Crafting, this.worldObj, this.posX, this.posY, this.posZ, null); + } + } + } } diff --git a/src/main/java/appeng/client/render/effects/ChargedOreFX.java b/src/main/java/appeng/client/render/effects/ChargedOreFX.java index bb60cdd70a2..7d0ddf30c8f 100644 --- a/src/main/java/appeng/client/render/effects/ChargedOreFX.java +++ b/src/main/java/appeng/client/render/effects/ChargedOreFX.java @@ -18,31 +18,32 @@ package appeng.client.render.effects; - import net.minecraft.client.particle.EntityReddustFX; import net.minecraft.world.World; - -public class ChargedOreFX extends EntityReddustFX -{ - - public ChargedOreFX( final World w, final double x, final double y, final double z, final float r, final float g, final float b ) - { - super( w, x, y, z, 0.21f, 0.61f, 1.0f ); - } - - @Override - public int getBrightnessForRender( final float par1 ) - { - int j1 = super.getBrightnessForRender( par1 ); - j1 = Math.max( j1 >> 20, j1 >> 4 ); - j1 += 3; - - if( j1 > 15 ) - { - j1 = 15; - } - - return j1 << 20 | j1 << 4; - } +public class ChargedOreFX extends EntityReddustFX { + + public ChargedOreFX( + final World w, + final double x, + final double y, + final double z, + final float r, + final float g, + final float b) { + super(w, x, y, z, 0.21f, 0.61f, 1.0f); + } + + @Override + public int getBrightnessForRender(final float par1) { + int j1 = super.getBrightnessForRender(par1); + j1 = Math.max(j1 >> 20, j1 >> 4); + j1 += 3; + + if (j1 > 15) { + j1 = 15; + } + + return j1 << 20 | j1 << 4; + } } diff --git a/src/main/java/appeng/client/render/effects/CraftingFx.java b/src/main/java/appeng/client/render/effects/CraftingFx.java index f77739fef7a..d5eec8cc66c 100644 --- a/src/main/java/appeng/client/render/effects/CraftingFx.java +++ b/src/main/java/appeng/client/render/effects/CraftingFx.java @@ -18,7 +18,6 @@ package appeng.client.render.effects; - import appeng.client.texture.ExtraBlockTextures; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -30,93 +29,97 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; - -@SideOnly( Side.CLIENT ) -public class CraftingFx extends EntityBreakingFX -{ - - private final IIcon particleTextureIndex; - - private final int startBlkX; - private final int startBlkY; - private final int startBlkZ; - - public CraftingFx( final World par1World, final double par2, final double par4, final double par6, final Item par8Item ) - { - super( par1World, par2, par4, par6, par8Item ); - this.particleGravity = 0; - this.particleBlue = 1; - this.particleGreen = 0.9f; - this.particleRed = 1; - this.particleAlpha = 1.3f; - this.particleScale = 1.5f; - this.particleTextureIndex = ExtraBlockTextures.BlockEnergyParticle.getIcon(); - this.particleMaxAge /= 1.2; - - this.startBlkX = MathHelper.floor_double( this.posX ); - this.startBlkY = MathHelper.floor_double( this.posY ); - this.startBlkZ = MathHelper.floor_double( this.posZ ); - - this.noClip = true; - } - - @Override - public int getFXLayer() - { - return 1; - } - - @Override - public void renderParticle( final Tessellator par1Tessellator, final float partialTick, final float x, final float y, final float z, final float rx, final float rz ) - { - if( partialTick < 0 || partialTick > 1 ) - { - return; - } - - final float f6 = this.particleTextureIndex.getMinU(); - final float f7 = this.particleTextureIndex.getMaxU(); - final float f8 = this.particleTextureIndex.getMinV(); - final float f9 = this.particleTextureIndex.getMaxV(); - final float scale = 0.1F * this.particleScale; - - float offX = (float) ( this.prevPosX + ( this.posX - this.prevPosX ) * partialTick ); - float offY = (float) ( this.prevPosY + ( this.posY - this.prevPosY ) * partialTick ); - float offZ = (float) ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * partialTick ); - - final int blkX = MathHelper.floor_double( offX ); - final int blkY = MathHelper.floor_double( offY ); - final int blkZ = MathHelper.floor_double( offZ ); - - if( blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ ) - { - offX -= interpPosX; - offY -= interpPosY; - offZ -= interpPosZ; - - // AELog.info( "" + partialTick ); - final float f14 = 1.0F; - par1Tessellator.setColorRGBA_F( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ); - par1Tessellator.addVertexWithUV( offX - x * scale - rx * scale, offY - y * scale, offZ - z * scale - rz * scale, f7, f9 ); - par1Tessellator.addVertexWithUV( offX - x * scale + rx * scale, offY + y * scale, offZ - z * scale + rz * scale, f7, f8 ); - par1Tessellator.addVertexWithUV( offX + x * scale + rx * scale, offY + y * scale, offZ + z * scale + rz * scale, f6, f8 ); - par1Tessellator.addVertexWithUV( offX + x * scale - rx * scale, offY - y * scale, offZ + z * scale - rz * scale, f6, f9 ); - } - } - - public void fromItem( final ForgeDirection d ) - { - this.posX += 0.2 * d.offsetX; - this.posY += 0.2 * d.offsetY; - this.posZ += 0.2 * d.offsetZ; - this.particleScale *= 0.8f; - } - - @Override - public void onUpdate() - { - super.onUpdate(); - this.particleScale *= 0.51f; - this.particleAlpha *= 0.51f; - } +@SideOnly(Side.CLIENT) +public class CraftingFx extends EntityBreakingFX { + + private final IIcon particleTextureIndex; + + private final int startBlkX; + private final int startBlkY; + private final int startBlkZ; + + public CraftingFx( + final World par1World, final double par2, final double par4, final double par6, final Item par8Item) { + super(par1World, par2, par4, par6, par8Item); + this.particleGravity = 0; + this.particleBlue = 1; + this.particleGreen = 0.9f; + this.particleRed = 1; + this.particleAlpha = 1.3f; + this.particleScale = 1.5f; + this.particleTextureIndex = ExtraBlockTextures.BlockEnergyParticle.getIcon(); + this.particleMaxAge /= 1.2; + + this.startBlkX = MathHelper.floor_double(this.posX); + this.startBlkY = MathHelper.floor_double(this.posY); + this.startBlkZ = MathHelper.floor_double(this.posZ); + + this.noClip = true; + } + + @Override + public int getFXLayer() { + return 1; + } + + @Override + public void renderParticle( + final Tessellator par1Tessellator, + final float partialTick, + final float x, + final float y, + final float z, + final float rx, + final float rz) { + if (partialTick < 0 || partialTick > 1) { + return; + } + + final float f6 = this.particleTextureIndex.getMinU(); + final float f7 = this.particleTextureIndex.getMaxU(); + final float f8 = this.particleTextureIndex.getMinV(); + final float f9 = this.particleTextureIndex.getMaxV(); + final float scale = 0.1F * this.particleScale; + + float offX = (float) (this.prevPosX + (this.posX - this.prevPosX) * partialTick); + float offY = (float) (this.prevPosY + (this.posY - this.prevPosY) * partialTick); + float offZ = (float) (this.prevPosZ + (this.posZ - this.prevPosZ) * partialTick); + + final int blkX = MathHelper.floor_double(offX); + final int blkY = MathHelper.floor_double(offY); + final int blkZ = MathHelper.floor_double(offZ); + + if (blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ) { + offX -= interpPosX; + offY -= interpPosY; + offZ -= interpPosZ; + + // AELog.info( "" + partialTick ); + final float f14 = 1.0F; + par1Tessellator.setColorRGBA_F( + this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha); + par1Tessellator.addVertexWithUV( + offX - x * scale - rx * scale, offY - y * scale, offZ - z * scale - rz * scale, f7, f9); + par1Tessellator.addVertexWithUV( + offX - x * scale + rx * scale, offY + y * scale, offZ - z * scale + rz * scale, f7, f8); + par1Tessellator.addVertexWithUV( + offX + x * scale + rx * scale, offY + y * scale, offZ + z * scale + rz * scale, f6, f8); + par1Tessellator.addVertexWithUV( + offX + x * scale - rx * scale, offY - y * scale, offZ + z * scale - rz * scale, f6, f9); + } + } + + public void fromItem(final ForgeDirection d) { + this.posX += 0.2 * d.offsetX; + this.posY += 0.2 * d.offsetY; + this.posZ += 0.2 * d.offsetZ; + this.particleScale *= 0.8f; + } + + @Override + public void onUpdate() { + super.onUpdate(); + this.particleScale *= 0.51f; + this.particleAlpha *= 0.51f; + } } diff --git a/src/main/java/appeng/client/render/effects/EnergyFx.java b/src/main/java/appeng/client/render/effects/EnergyFx.java index 1b533d722ff..7e8727ba593 100644 --- a/src/main/java/appeng/client/render/effects/EnergyFx.java +++ b/src/main/java/appeng/client/render/effects/EnergyFx.java @@ -18,7 +18,6 @@ package appeng.client.render.effects; - import appeng.client.texture.ExtraBlockTextures; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -30,82 +29,87 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; - -@SideOnly( Side.CLIENT ) -public class EnergyFx extends EntityBreakingFX -{ - - private final IIcon particleTextureIndex; - - private final int startBlkX; - private final int startBlkY; - private final int startBlkZ; - - public EnergyFx( final World par1World, final double par2, final double par4, final double par6, final Item par8Item ) - { - super( par1World, par2, par4, par6, par8Item ); - this.particleGravity = 0; - this.particleBlue = 255; - this.particleGreen = 255; - this.particleRed = 255; - this.particleAlpha = 1.4f; - this.particleScale = 3.5f; - this.particleTextureIndex = ExtraBlockTextures.BlockEnergyParticle.getIcon(); - - this.startBlkX = MathHelper.floor_double( this.posX ); - this.startBlkY = MathHelper.floor_double( this.posY ); - this.startBlkZ = MathHelper.floor_double( this.posZ ); - - this.noClip = true; - } - - @Override - public int getFXLayer() - { - return 1; - } - - @Override - public void renderParticle( final Tessellator par1Tessellator, final float par2, final float par3, final float par4, final float par5, final float par6, final float par7 ) - { - final float f6 = this.particleTextureIndex.getMinU(); - final float f7 = this.particleTextureIndex.getMaxU(); - final float f8 = this.particleTextureIndex.getMinV(); - final float f9 = this.particleTextureIndex.getMaxV(); - final float f10 = 0.1F * this.particleScale; - - final float f11 = (float) ( this.prevPosX + ( this.posX - this.prevPosX ) * par2 - interpPosX ); - final float f12 = (float) ( this.prevPosY + ( this.posY - this.prevPosY ) * par2 - interpPosY ); - final float f13 = (float) ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * par2 - interpPosZ ); - - final int blkX = MathHelper.floor_double( this.posX ); - final int blkY = MathHelper.floor_double( this.posY ); - final int blkZ = MathHelper.floor_double( this.posZ ); - - if( blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ ) - { - final float f14 = 1.0F; - par1Tessellator.setColorRGBA_F( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ); - par1Tessellator.addVertexWithUV( f11 - par3 * f10 - par6 * f10, f12 - par4 * f10, f13 - par5 * f10 - par7 * f10, f7, f9 ); - par1Tessellator.addVertexWithUV( f11 - par3 * f10 + par6 * f10, f12 + par4 * f10, f13 - par5 * f10 + par7 * f10, f7, f8 ); - par1Tessellator.addVertexWithUV( f11 + par3 * f10 + par6 * f10, f12 + par4 * f10, f13 + par5 * f10 + par7 * f10, f6, f8 ); - par1Tessellator.addVertexWithUV( f11 + par3 * f10 - par6 * f10, f12 - par4 * f10, f13 + par5 * f10 - par7 * f10, f6, f9 ); - } - } - - public void fromItem( final ForgeDirection d ) - { - this.posX += 0.2 * d.offsetX; - this.posY += 0.2 * d.offsetY; - this.posZ += 0.2 * d.offsetZ; - this.particleScale *= 0.8f; - } - - @Override - public void onUpdate() - { - super.onUpdate(); - this.particleScale *= 0.89f; - this.particleAlpha *= 0.89f; - } +@SideOnly(Side.CLIENT) +public class EnergyFx extends EntityBreakingFX { + + private final IIcon particleTextureIndex; + + private final int startBlkX; + private final int startBlkY; + private final int startBlkZ; + + public EnergyFx( + final World par1World, final double par2, final double par4, final double par6, final Item par8Item) { + super(par1World, par2, par4, par6, par8Item); + this.particleGravity = 0; + this.particleBlue = 255; + this.particleGreen = 255; + this.particleRed = 255; + this.particleAlpha = 1.4f; + this.particleScale = 3.5f; + this.particleTextureIndex = ExtraBlockTextures.BlockEnergyParticle.getIcon(); + + this.startBlkX = MathHelper.floor_double(this.posX); + this.startBlkY = MathHelper.floor_double(this.posY); + this.startBlkZ = MathHelper.floor_double(this.posZ); + + this.noClip = true; + } + + @Override + public int getFXLayer() { + return 1; + } + + @Override + public void renderParticle( + final Tessellator par1Tessellator, + final float par2, + final float par3, + final float par4, + final float par5, + final float par6, + final float par7) { + final float f6 = this.particleTextureIndex.getMinU(); + final float f7 = this.particleTextureIndex.getMaxU(); + final float f8 = this.particleTextureIndex.getMinV(); + final float f9 = this.particleTextureIndex.getMaxV(); + final float f10 = 0.1F * this.particleScale; + + final float f11 = (float) (this.prevPosX + (this.posX - this.prevPosX) * par2 - interpPosX); + final float f12 = (float) (this.prevPosY + (this.posY - this.prevPosY) * par2 - interpPosY); + final float f13 = (float) (this.prevPosZ + (this.posZ - this.prevPosZ) * par2 - interpPosZ); + + final int blkX = MathHelper.floor_double(this.posX); + final int blkY = MathHelper.floor_double(this.posY); + final int blkZ = MathHelper.floor_double(this.posZ); + + if (blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ) { + final float f14 = 1.0F; + par1Tessellator.setColorRGBA_F( + this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha); + par1Tessellator.addVertexWithUV( + f11 - par3 * f10 - par6 * f10, f12 - par4 * f10, f13 - par5 * f10 - par7 * f10, f7, f9); + par1Tessellator.addVertexWithUV( + f11 - par3 * f10 + par6 * f10, f12 + par4 * f10, f13 - par5 * f10 + par7 * f10, f7, f8); + par1Tessellator.addVertexWithUV( + f11 + par3 * f10 + par6 * f10, f12 + par4 * f10, f13 + par5 * f10 + par7 * f10, f6, f8); + par1Tessellator.addVertexWithUV( + f11 + par3 * f10 - par6 * f10, f12 - par4 * f10, f13 + par5 * f10 - par7 * f10, f6, f9); + } + } + + public void fromItem(final ForgeDirection d) { + this.posX += 0.2 * d.offsetX; + this.posY += 0.2 * d.offsetY; + this.posZ += 0.2 * d.offsetZ; + this.particleScale *= 0.8f; + } + + @Override + public void onUpdate() { + super.onUpdate(); + this.particleScale *= 0.89f; + this.particleAlpha *= 0.89f; + } } diff --git a/src/main/java/appeng/client/render/effects/LightningArcFX.java b/src/main/java/appeng/client/render/effects/LightningArcFX.java index bfbe92e2587..f064b8edabc 100644 --- a/src/main/java/appeng/client/render/effects/LightningArcFX.java +++ b/src/main/java/appeng/client/render/effects/LightningArcFX.java @@ -18,48 +18,52 @@ package appeng.client.render.effects; - -import net.minecraft.world.World; - import java.util.Random; +import net.minecraft.world.World; +public class LightningArcFX extends LightningFX { + private static final Random RANDOM_GENERATOR = new Random(); -public class LightningArcFX extends LightningFX -{ - private static final Random RANDOM_GENERATOR = new Random(); - - private final double rx; - private final double ry; - private final double rz; + private final double rx; + private final double ry; + private final double rz; - public LightningArcFX( final World w, final double x, final double y, final double z, final double ex, final double ey, final double ez, final double r, final double g, final double b ) - { - super( w, x, y, z, r, g, b, 6 ); - this.noClip = true; + public LightningArcFX( + final World w, + final double x, + final double y, + final double z, + final double ex, + final double ey, + final double ez, + final double r, + final double g, + final double b) { + super(w, x, y, z, r, g, b, 6); + this.noClip = true; - this.rx = ex - x; - this.ry = ey - y; - this.rz = ez - z; + this.rx = ex - x; + this.ry = ey - y; + this.rz = ez - z; - this.regen(); - } + this.regen(); + } - @Override - protected void regen() - { - final double i = 1.0 / ( this.getSteps() - 1 ); - final double lastDirectionX = this.rx * i; - final double lastDirectionY = this.ry * i; - final double lastDirectionZ = this.rz * i; - final double len = Math.sqrt( lastDirectionX * lastDirectionX + lastDirectionY * lastDirectionY + lastDirectionZ * lastDirectionZ ); + @Override + protected void regen() { + final double i = 1.0 / (this.getSteps() - 1); + final double lastDirectionX = this.rx * i; + final double lastDirectionY = this.ry * i; + final double lastDirectionZ = this.rz * i; + final double len = Math.sqrt( + lastDirectionX * lastDirectionX + lastDirectionY * lastDirectionY + lastDirectionZ * lastDirectionZ); - for( int s = 0; s < this.getSteps(); s++ ) - { - final double[][] localSteps = this.getPrecomputedSteps(); + for (int s = 0; s < this.getSteps(); s++) { + final double[][] localSteps = this.getPrecomputedSteps(); - localSteps[s][0] = ( lastDirectionX + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * len * 1.2 ) / 2.0; - localSteps[s][1] = ( lastDirectionY + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * len * 1.2 ) / 2.0; - localSteps[s][2] = ( lastDirectionZ + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * len * 1.2 ) / 2.0; - } - } + localSteps[s][0] = (lastDirectionX + (RANDOM_GENERATOR.nextDouble() - 0.5) * len * 1.2) / 2.0; + localSteps[s][1] = (lastDirectionY + (RANDOM_GENERATOR.nextDouble() - 0.5) * len * 1.2) / 2.0; + localSteps[s][2] = (lastDirectionZ + (RANDOM_GENERATOR.nextDouble() - 0.5) * len * 1.2) / 2.0; + } + } } diff --git a/src/main/java/appeng/client/render/effects/LightningFX.java b/src/main/java/appeng/client/render/effects/LightningFX.java index ba55b128dcb..4e93ee12a41 100644 --- a/src/main/java/appeng/client/render/effects/LightningFX.java +++ b/src/main/java/appeng/client/render/effects/LightningFX.java @@ -18,7 +18,7 @@ package appeng.client.render.effects; - +import java.util.Random; import net.minecraft.client.Minecraft; import net.minecraft.client.particle.EntityFX; import net.minecraft.client.renderer.Tessellator; @@ -26,200 +26,209 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.World; -import java.util.Random; - - -public class LightningFX extends EntityFX -{ - private static final Random RANDOM_GENERATOR = new Random(); - private static final int STEPS = 5; - - private final double[][] precomputedSteps; - private final double[] vertices = new double[3]; - private final double[] verticesWithUV = new double[3]; - private boolean hasData = false; - - public LightningFX( final World w, final double x, final double y, final double z, final double r, final double g, final double b ) - { - this( w, x, y, z, r, g, b, 6 ); - this.regen(); - } - - protected LightningFX( final World w, final double x, final double y, final double z, final double r, final double g, final double b, final int maxAge ) - { - super( w, x, y, z, r, g, b ); - this.precomputedSteps = new double[LightningFX.STEPS][3]; - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; - this.particleMaxAge = maxAge; - this.noClip = true; - } - - protected void regen() - { - double lastDirectionX = ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9; - double lastDirectionY = ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9; - double lastDirectionZ = ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9; - - for( int s = 0; s < LightningFX.STEPS; s++ ) - { - this.precomputedSteps[s][0] = lastDirectionX = ( lastDirectionX + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9 ) / 2.0; - this.precomputedSteps[s][1] = lastDirectionY = ( lastDirectionY + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9 ) / 2.0; - this.precomputedSteps[s][2] = lastDirectionZ = ( lastDirectionZ + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9 ) / 2.0; - } - } - - protected int getSteps() - { - return LightningFX.STEPS; - } - - @Override - public int getBrightnessForRender( final float par1 ) - { - final int j1 = 13; - return j1 << 20 | j1 << 4; - } - - @Override - public void renderParticle( final Tessellator tess, final float l, final float rX, final float rY, final float rZ, final float rYZ, final float rXY ) - { - final float j = 1.0f; - - tess.setColorRGBA_F( this.particleRed * j * 0.9f, this.particleGreen * j * 0.95f, this.particleBlue * j, this.particleAlpha ); - - if( this.particleAge == 3 ) - { - this.regen(); - } - double f6 = this.particleTextureIndexX / 16.0; - final double f7 = f6 + 0.0324375F; - double f8 = this.particleTextureIndexY / 16.0; - final double f9 = f8 + 0.0324375F; - - f6 = f7; - f8 = f9; - - double scale = 0.02;// 0.02F * this.particleScale; - - final double[] a = new double[3]; - final double[] b = new double[3]; - - double ox = 0; - double oy = 0; - double oz = 0; - - final EntityPlayer p = Minecraft.getMinecraft().thePlayer; - double offX = -rZ; - double offY = MathHelper.cos( (float) ( Math.PI / 2.0f + p.rotationPitch * 0.017453292F ) ); - double offZ = rX; - - for( int layer = 0; layer < 2; layer++ ) - { - if( layer == 0 ) - { - scale = 0.04; - offX *= 0.001; - offY *= 0.001; - offZ *= 0.001; - tess.setColorRGBA_F( this.particleRed * j * 0.4f, this.particleGreen * j * 0.25f, this.particleBlue * j * 0.45f, this.particleAlpha ); - } - else - { - offX = 0; - offY = 0; - offZ = 0; - scale = 0.02; - tess.setColorRGBA_F( this.particleRed * j * 0.9f, this.particleGreen * j * 0.65f, this.particleBlue * j * 0.85f, this.particleAlpha ); - } - - for( int cycle = 0; cycle < 3; cycle++ ) - { - this.clear(); - - double x = ( this.prevPosX + ( this.posX - this.prevPosX ) * l - interpPosX ) - offX; - double y = ( this.prevPosY + ( this.posY - this.prevPosY ) * l - interpPosY ) - offY; - double z = ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * l - interpPosZ ) - offZ; - - for( int s = 0; s < LightningFX.STEPS; s++ ) - { - final double xN = x + this.precomputedSteps[s][0]; - final double yN = y + this.precomputedSteps[s][1]; - final double zN = z + this.precomputedSteps[s][2]; - - final double xD = xN - x; - final double yD = yN - y; - final double zD = zN - z; - - if( cycle == 0 ) - { - ox = ( yD * 0 ) - ( 1 * zD ); - oy = ( zD * 0 ) - ( 0 * xD ); - oz = ( xD * 1 ) - ( 0 * yD ); - } - if( cycle == 1 ) - { - ox = ( yD * 1 ) - ( 0 * zD ); - oy = ( zD * 0 ) - ( 1 * xD ); - oz = ( xD * 0 ) - ( 0 * yD ); - } - if( cycle == 2 ) - { - ox = ( yD * 0 ) - ( 0 * zD ); - oy = ( zD * 1 ) - ( 0 * xD ); - oz = ( xD * 0 ) - ( 1 * yD ); - } - - final double ss = Math.sqrt( ox * ox + oy * oy + oz * oz ) / ( ( ( (double) LightningFX.STEPS - (double) s ) / LightningFX.STEPS ) * scale ); - ox /= ss; - oy /= ss; - oz /= ss; - - a[0] = x + ox; - a[1] = y + oy; - a[2] = z + oz; - - b[0] = x; - b[1] = y; - b[2] = z; - - this.draw( tess, a, b, f6, f8 ); - - x = xN; - y = yN; - z = zN; - } - } - } - } - - private void clear() - { - this.hasData = false; - } - - private void draw( final Tessellator tess, final double[] a, final double[] b, final double f6, final double f8 ) - { - if( this.hasData ) - { - tess.addVertexWithUV( a[0], a[1], a[2], f6, f8 ); - tess.addVertexWithUV( this.vertices[0], this.vertices[1], this.vertices[2], f6, f8 ); - tess.addVertexWithUV( this.verticesWithUV[0], this.verticesWithUV[1], this.verticesWithUV[2], f6, f8 ); - tess.addVertexWithUV( b[0], b[1], b[2], f6, f8 ); - } - - this.hasData = true; - - for( int x = 0; x < 3; x++ ) - { - this.vertices[x] = a[x]; - this.verticesWithUV[x] = b[x]; - } - } - - protected double[][] getPrecomputedSteps() - { - return this.precomputedSteps; - } +public class LightningFX extends EntityFX { + private static final Random RANDOM_GENERATOR = new Random(); + private static final int STEPS = 5; + + private final double[][] precomputedSteps; + private final double[] vertices = new double[3]; + private final double[] verticesWithUV = new double[3]; + private boolean hasData = false; + + public LightningFX( + final World w, + final double x, + final double y, + final double z, + final double r, + final double g, + final double b) { + this(w, x, y, z, r, g, b, 6); + this.regen(); + } + + protected LightningFX( + final World w, + final double x, + final double y, + final double z, + final double r, + final double g, + final double b, + final int maxAge) { + super(w, x, y, z, r, g, b); + this.precomputedSteps = new double[LightningFX.STEPS][3]; + this.motionX = 0; + this.motionY = 0; + this.motionZ = 0; + this.particleMaxAge = maxAge; + this.noClip = true; + } + + protected void regen() { + double lastDirectionX = (RANDOM_GENERATOR.nextDouble() - 0.5) * 0.9; + double lastDirectionY = (RANDOM_GENERATOR.nextDouble() - 0.5) * 0.9; + double lastDirectionZ = (RANDOM_GENERATOR.nextDouble() - 0.5) * 0.9; + + for (int s = 0; s < LightningFX.STEPS; s++) { + this.precomputedSteps[s][0] = + lastDirectionX = (lastDirectionX + (RANDOM_GENERATOR.nextDouble() - 0.5) * 0.9) / 2.0; + this.precomputedSteps[s][1] = + lastDirectionY = (lastDirectionY + (RANDOM_GENERATOR.nextDouble() - 0.5) * 0.9) / 2.0; + this.precomputedSteps[s][2] = + lastDirectionZ = (lastDirectionZ + (RANDOM_GENERATOR.nextDouble() - 0.5) * 0.9) / 2.0; + } + } + + protected int getSteps() { + return LightningFX.STEPS; + } + + @Override + public int getBrightnessForRender(final float par1) { + final int j1 = 13; + return j1 << 20 | j1 << 4; + } + + @Override + public void renderParticle( + final Tessellator tess, + final float l, + final float rX, + final float rY, + final float rZ, + final float rYZ, + final float rXY) { + final float j = 1.0f; + + tess.setColorRGBA_F( + this.particleRed * j * 0.9f, this.particleGreen * j * 0.95f, this.particleBlue * j, this.particleAlpha); + + if (this.particleAge == 3) { + this.regen(); + } + double f6 = this.particleTextureIndexX / 16.0; + final double f7 = f6 + 0.0324375F; + double f8 = this.particleTextureIndexY / 16.0; + final double f9 = f8 + 0.0324375F; + + f6 = f7; + f8 = f9; + + double scale = 0.02; // 0.02F * this.particleScale; + + final double[] a = new double[3]; + final double[] b = new double[3]; + + double ox = 0; + double oy = 0; + double oz = 0; + + final EntityPlayer p = Minecraft.getMinecraft().thePlayer; + double offX = -rZ; + double offY = MathHelper.cos((float) (Math.PI / 2.0f + p.rotationPitch * 0.017453292F)); + double offZ = rX; + + for (int layer = 0; layer < 2; layer++) { + if (layer == 0) { + scale = 0.04; + offX *= 0.001; + offY *= 0.001; + offZ *= 0.001; + tess.setColorRGBA_F( + this.particleRed * j * 0.4f, + this.particleGreen * j * 0.25f, + this.particleBlue * j * 0.45f, + this.particleAlpha); + } else { + offX = 0; + offY = 0; + offZ = 0; + scale = 0.02; + tess.setColorRGBA_F( + this.particleRed * j * 0.9f, + this.particleGreen * j * 0.65f, + this.particleBlue * j * 0.85f, + this.particleAlpha); + } + + for (int cycle = 0; cycle < 3; cycle++) { + this.clear(); + + double x = (this.prevPosX + (this.posX - this.prevPosX) * l - interpPosX) - offX; + double y = (this.prevPosY + (this.posY - this.prevPosY) * l - interpPosY) - offY; + double z = (this.prevPosZ + (this.posZ - this.prevPosZ) * l - interpPosZ) - offZ; + + for (int s = 0; s < LightningFX.STEPS; s++) { + final double xN = x + this.precomputedSteps[s][0]; + final double yN = y + this.precomputedSteps[s][1]; + final double zN = z + this.precomputedSteps[s][2]; + + final double xD = xN - x; + final double yD = yN - y; + final double zD = zN - z; + + if (cycle == 0) { + ox = (yD * 0) - (1 * zD); + oy = (zD * 0) - (0 * xD); + oz = (xD * 1) - (0 * yD); + } + if (cycle == 1) { + ox = (yD * 1) - (0 * zD); + oy = (zD * 0) - (1 * xD); + oz = (xD * 0) - (0 * yD); + } + if (cycle == 2) { + ox = (yD * 0) - (0 * zD); + oy = (zD * 1) - (0 * xD); + oz = (xD * 0) - (1 * yD); + } + + final double ss = Math.sqrt(ox * ox + oy * oy + oz * oz) + / ((((double) LightningFX.STEPS - (double) s) / LightningFX.STEPS) * scale); + ox /= ss; + oy /= ss; + oz /= ss; + + a[0] = x + ox; + a[1] = y + oy; + a[2] = z + oz; + + b[0] = x; + b[1] = y; + b[2] = z; + + this.draw(tess, a, b, f6, f8); + + x = xN; + y = yN; + z = zN; + } + } + } + } + + private void clear() { + this.hasData = false; + } + + private void draw(final Tessellator tess, final double[] a, final double[] b, final double f6, final double f8) { + if (this.hasData) { + tess.addVertexWithUV(a[0], a[1], a[2], f6, f8); + tess.addVertexWithUV(this.vertices[0], this.vertices[1], this.vertices[2], f6, f8); + tess.addVertexWithUV(this.verticesWithUV[0], this.verticesWithUV[1], this.verticesWithUV[2], f6, f8); + tess.addVertexWithUV(b[0], b[1], b[2], f6, f8); + } + + this.hasData = true; + + for (int x = 0; x < 3; x++) { + this.vertices[x] = a[x]; + this.verticesWithUV[x] = b[x]; + } + } + + protected double[][] getPrecomputedSteps() { + return this.precomputedSteps; + } } diff --git a/src/main/java/appeng/client/render/effects/MatterCannonFX.java b/src/main/java/appeng/client/render/effects/MatterCannonFX.java index b1045eb91e6..f17a4303643 100644 --- a/src/main/java/appeng/client/render/effects/MatterCannonFX.java +++ b/src/main/java/appeng/client/render/effects/MatterCannonFX.java @@ -18,7 +18,6 @@ package appeng.client.render.effects; - import appeng.client.texture.ExtraBlockTextures; import net.minecraft.client.particle.EntityBreakingFX; import net.minecraft.client.renderer.Tessellator; @@ -27,65 +26,71 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +public class MatterCannonFX extends EntityBreakingFX { -public class MatterCannonFX extends EntityBreakingFX -{ - - private final IIcon particleTextureIndex; + private final IIcon particleTextureIndex; - public MatterCannonFX( final World par1World, final double par2, final double par4, final double par6, final Item par8Item ) - { - super( par1World, par2, par4, par6, par8Item ); - this.particleGravity = 0; - this.particleBlue = 255; - this.particleGreen = 255; - this.particleRed = 255; - this.particleAlpha = 1.4f; - this.particleScale = 1.1f; - this.motionX = 0.0f; - this.motionY = 0.0f; - this.motionZ = 0.0f; - this.particleTextureIndex = ExtraBlockTextures.BlockMatterCannonParticle.getIcon(); - this.noClip = true; - } + public MatterCannonFX( + final World par1World, final double par2, final double par4, final double par6, final Item par8Item) { + super(par1World, par2, par4, par6, par8Item); + this.particleGravity = 0; + this.particleBlue = 255; + this.particleGreen = 255; + this.particleRed = 255; + this.particleAlpha = 1.4f; + this.particleScale = 1.1f; + this.motionX = 0.0f; + this.motionY = 0.0f; + this.motionZ = 0.0f; + this.particleTextureIndex = ExtraBlockTextures.BlockMatterCannonParticle.getIcon(); + this.noClip = true; + } - public void fromItem( final ForgeDirection d ) - { - this.particleScale *= 1.2f; - } + public void fromItem(final ForgeDirection d) { + this.particleScale *= 1.2f; + } - @Override - public void onUpdate() - { - super.onUpdate(); - this.particleScale *= 1.19f; - this.particleAlpha *= 0.59f; - } + @Override + public void onUpdate() { + super.onUpdate(); + this.particleScale *= 1.19f; + this.particleAlpha *= 0.59f; + } - @Override - public int getFXLayer() - { - return 1; - } + @Override + public int getFXLayer() { + return 1; + } - @Override - public void renderParticle( final Tessellator par1Tessellator, final float par2, final float par3, final float par4, final float par5, final float par6, final float par7 ) - { - final float f6 = this.particleTextureIndex.getMinU(); - final float f7 = this.particleTextureIndex.getMaxU(); - final float f8 = this.particleTextureIndex.getMinV(); - final float f9 = this.particleTextureIndex.getMaxV(); - final float f10 = 0.05F * this.particleScale; + @Override + public void renderParticle( + final Tessellator par1Tessellator, + final float par2, + final float par3, + final float par4, + final float par5, + final float par6, + final float par7) { + final float f6 = this.particleTextureIndex.getMinU(); + final float f7 = this.particleTextureIndex.getMaxU(); + final float f8 = this.particleTextureIndex.getMinV(); + final float f9 = this.particleTextureIndex.getMaxV(); + final float f10 = 0.05F * this.particleScale; - final float f11 = (float) ( this.prevPosX + ( this.posX - this.prevPosX ) * par2 - interpPosX ); - final float f12 = (float) ( this.prevPosY + ( this.posY - this.prevPosY ) * par2 - interpPosY ); - final float f13 = (float) ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * par2 - interpPosZ ); - final float f14 = 1.0F; + final float f11 = (float) (this.prevPosX + (this.posX - this.prevPosX) * par2 - interpPosX); + final float f12 = (float) (this.prevPosY + (this.posY - this.prevPosY) * par2 - interpPosY); + final float f13 = (float) (this.prevPosZ + (this.posZ - this.prevPosZ) * par2 - interpPosZ); + final float f14 = 1.0F; - par1Tessellator.setColorRGBA_F( this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha ); - par1Tessellator.addVertexWithUV( f11 - par3 * f10 - par6 * f10, f12 - par4 * f10, f13 - par5 * f10 - par7 * f10, f7, f9 ); - par1Tessellator.addVertexWithUV( f11 - par3 * f10 + par6 * f10, f12 + par4 * f10, f13 - par5 * f10 + par7 * f10, f7, f8 ); - par1Tessellator.addVertexWithUV( f11 + par3 * f10 + par6 * f10, f12 + par4 * f10, f13 + par5 * f10 + par7 * f10, f6, f8 ); - par1Tessellator.addVertexWithUV( f11 + par3 * f10 - par6 * f10, f12 - par4 * f10, f13 + par5 * f10 - par7 * f10, f6, f9 ); - } + par1Tessellator.setColorRGBA_F( + this.particleRed * f14, this.particleGreen * f14, this.particleBlue * f14, this.particleAlpha); + par1Tessellator.addVertexWithUV( + f11 - par3 * f10 - par6 * f10, f12 - par4 * f10, f13 - par5 * f10 - par7 * f10, f7, f9); + par1Tessellator.addVertexWithUV( + f11 - par3 * f10 + par6 * f10, f12 + par4 * f10, f13 - par5 * f10 + par7 * f10, f7, f8); + par1Tessellator.addVertexWithUV( + f11 + par3 * f10 + par6 * f10, f12 + par4 * f10, f13 + par5 * f10 + par7 * f10, f6, f8); + par1Tessellator.addVertexWithUV( + f11 + par3 * f10 - par6 * f10, f12 - par4 * f10, f13 + par5 * f10 - par7 * f10, f6, f9); + } } diff --git a/src/main/java/appeng/client/render/effects/VibrantFX.java b/src/main/java/appeng/client/render/effects/VibrantFX.java index 57b413f68df..41b80f80b21 100644 --- a/src/main/java/appeng/client/render/effects/VibrantFX.java +++ b/src/main/java/appeng/client/render/effects/VibrantFX.java @@ -18,59 +18,59 @@ package appeng.client.render.effects; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.particle.EntityFX; import net.minecraft.world.World; +@SideOnly(Side.CLIENT) +public class VibrantFX extends EntityFX { -@SideOnly( Side.CLIENT ) -public class VibrantFX extends EntityFX -{ - - public VibrantFX( final World par1World, final double x, final double y, final double z, final double par8, final double par10, final double par12 ) - { - super( par1World, x, y, z, par8, par10, par12 ); - final float f = this.rand.nextFloat() * 0.1F + 0.8F; - this.particleRed = f * 0.7f; - this.particleGreen = f * 0.89f; - this.particleBlue = f * 0.9f; - this.setParticleTextureIndex( 0 ); - this.setSize( 0.04F, 0.04F ); - this.particleScale *= this.rand.nextFloat() * 0.6F + 1.9F; - this.motionX = 0.0D; - this.motionY = 0.0D; - this.motionZ = 0.0D; - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - this.particleMaxAge = (int) ( 20.0D / ( Math.random() * 0.8D + 0.1D ) ); - this.noClip = true; - } + public VibrantFX( + final World par1World, + final double x, + final double y, + final double z, + final double par8, + final double par10, + final double par12) { + super(par1World, x, y, z, par8, par10, par12); + final float f = this.rand.nextFloat() * 0.1F + 0.8F; + this.particleRed = f * 0.7f; + this.particleGreen = f * 0.89f; + this.particleBlue = f * 0.9f; + this.setParticleTextureIndex(0); + this.setSize(0.04F, 0.04F); + this.particleScale *= this.rand.nextFloat() * 0.6F + 1.9F; + this.motionX = 0.0D; + this.motionY = 0.0D; + this.motionZ = 0.0D; + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + this.particleMaxAge = (int) (20.0D / (Math.random() * 0.8D + 0.1D)); + this.noClip = true; + } - @Override - public float getBrightness( final float par1 ) - { - return 1.0f; - } + @Override + public float getBrightness(final float par1) { + return 1.0f; + } - /** - * Called to update the entity's position/logic. - */ - @Override - public void onUpdate() - { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - // this.moveEntity(this.motionX, this.motionY, this.motionZ); - this.particleScale *= 0.95; + /** + * Called to update the entity's position/logic. + */ + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + // this.moveEntity(this.motionX, this.motionY, this.motionZ); + this.particleScale *= 0.95; - if( this.particleMaxAge <= 0 || this.particleScale < 0.1 ) - { - this.setDead(); - } - this.particleMaxAge--; - } + if (this.particleMaxAge <= 0 || this.particleScale < 0.1) { + this.setDead(); + } + this.particleMaxAge--; + } } diff --git a/src/main/java/appeng/client/render/items/ItemEncodedPatternRenderer.java b/src/main/java/appeng/client/render/items/ItemEncodedPatternRenderer.java index 7c268b6cfbe..cc8fd771cd8 100644 --- a/src/main/java/appeng/client/render/items/ItemEncodedPatternRenderer.java +++ b/src/main/java/appeng/client/render/items/ItemEncodedPatternRenderer.java @@ -18,7 +18,6 @@ package appeng.client.render.items; - import appeng.items.misc.ItemEncodedPattern; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderHelper; @@ -28,52 +27,46 @@ import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; +public class ItemEncodedPatternRenderer implements IItemRenderer { -public class ItemEncodedPatternRenderer implements IItemRenderer -{ - - private final RenderItem ri = new RenderItem(); - private boolean recursive = false; + private final RenderItem ri = new RenderItem(); + private boolean recursive = false; - @Override - public boolean handleRenderType( final ItemStack item, final ItemRenderType type ) - { - final boolean isShiftHeld = Keyboard.isKeyDown( Keyboard.KEY_LSHIFT ) || Keyboard.isKeyDown( Keyboard.KEY_RSHIFT ); + @Override + public boolean handleRenderType(final ItemStack item, final ItemRenderType type) { + final boolean isShiftHeld = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); - if( !this.recursive && type == IItemRenderer.ItemRenderType.INVENTORY && isShiftHeld ) - { - final ItemEncodedPattern iep = (ItemEncodedPattern) item.getItem(); + if (!this.recursive && type == IItemRenderer.ItemRenderType.INVENTORY && isShiftHeld) { + final ItemEncodedPattern iep = (ItemEncodedPattern) item.getItem(); - if( iep.getOutput( item ) != null ) - { - return true; - } - } + if (iep.getOutput(item) != null) { + return true; + } + } - return false; - } + return false; + } - @Override - public boolean shouldUseRenderHelper( final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper ) - { - return false; - } + @Override + public boolean shouldUseRenderHelper( + final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper) { + return false; + } - @Override - public void renderItem( final ItemRenderType type, final ItemStack item, final Object... data ) - { - this.recursive = true; + @Override + public void renderItem(final ItemRenderType type, final ItemStack item, final Object... data) { + this.recursive = true; - final ItemEncodedPattern iep = (ItemEncodedPattern) item.getItem(); - final ItemStack is = iep.getOutput( item ); - final Minecraft mc = Minecraft.getMinecraft(); + final ItemEncodedPattern iep = (ItemEncodedPattern) item.getItem(); + final ItemStack is = iep.getOutput(item); + final Minecraft mc = Minecraft.getMinecraft(); - GL11.glPushAttrib( GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT ); - RenderHelper.enableGUIStandardItemLighting(); - this.ri.renderItemAndEffectIntoGUI( mc.fontRenderer, mc.getTextureManager(), is, 0, 0 ); - RenderHelper.disableStandardItemLighting(); - GL11.glPopAttrib(); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT); + RenderHelper.enableGUIStandardItemLighting(); + this.ri.renderItemAndEffectIntoGUI(mc.fontRenderer, mc.getTextureManager(), is, 0, 0); + RenderHelper.disableStandardItemLighting(); + GL11.glPopAttrib(); - this.recursive = false; - } + this.recursive = false; + } } diff --git a/src/main/java/appeng/client/render/items/PaintBallRender.java b/src/main/java/appeng/client/render/items/PaintBallRender.java index eb2cc616692..4c98d0f9ffd 100644 --- a/src/main/java/appeng/client/render/items/PaintBallRender.java +++ b/src/main/java/appeng/client/render/items/PaintBallRender.java @@ -18,7 +18,6 @@ package appeng.client.render.items; - import appeng.api.util.AEColor; import appeng.client.texture.ExtraItemTextures; import appeng.items.misc.ItemPaintBall; @@ -29,111 +28,93 @@ import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; - -public class PaintBallRender implements IItemRenderer -{ - - @Override - public boolean handleRenderType( final ItemStack item, final ItemRenderType type ) - { - return true; - } - - @Override - public boolean shouldUseRenderHelper( final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper ) - { - return helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION; - } - - @Override - public void renderItem( final ItemRenderType type, final ItemStack item, final Object... data ) - { - final IIcon par2Icon; - - if( item.getItemDamage() < 20 ) - { - par2Icon = item.getIconIndex(); - } - else - { - par2Icon = ExtraItemTextures.ItemPaintBallShimmer.getIcon(); - } - - final float f4 = par2Icon.getMinU(); - final float f5 = par2Icon.getMaxU(); - final float f6 = par2Icon.getMinV(); - final float f7 = par2Icon.getMaxV(); - - final ItemPaintBall ipb = (ItemPaintBall) item.getItem(); - - final Tessellator tessellator = Tessellator.instance; - - GL11.glPushMatrix(); - - final AEColor col = ipb.getColor( item ); - - final int colorValue = item.getItemDamage() >= 20 ? col.mediumVariant : col.mediumVariant; - final int r = ( colorValue >> 16 ) & 0xff; - final int g = ( colorValue >> 8 ) & 0xff; - final int b = ( colorValue ) & 0xff; - - if( item.getItemDamage() >= 20 ) - { - final float fail = 0.7f; - final int full = (int) ( 255 * 0.3 ); - GL11.glColor4ub( (byte) ( full + r * fail ), (byte) ( full + g * fail ), (byte) ( full + b * fail ), (byte) 255 ); - } - else - { - GL11.glColor4ub( (byte) r, (byte) g, (byte) b, (byte) 255 ); - } - - if( type == ItemRenderType.INVENTORY ) - { - GL11.glScalef( 16F, 16F, 10F ); - GL11.glTranslatef( 0.0F, 1.0F, 0.0F ); - GL11.glRotatef( 180F, 1.0F, 0.0F, 0.0F ); - GL11.glEnable( GL11.GL_ALPHA_TEST ); - - tessellator.startDrawingQuads(); - tessellator.setNormal( 0.0F, 1.0F, 0.0F ); - tessellator.addVertexWithUV( 0, 0, 0, f4, f7 ); - tessellator.addVertexWithUV( 1, 0, 0, f5, f7 ); - tessellator.addVertexWithUV( 1, 1, 0, f5, f6 ); - tessellator.addVertexWithUV( 0, 1, 0, f4, f6 ); - tessellator.draw(); - } - else - { - if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) - { - GL11.glTranslatef( 0.0F, 0.0F, 0.0F ); - } - else - { - GL11.glTranslatef( -0.5F, -0.3F, 0.01F ); - } - final float f12 = 0.0625F; - ItemRenderer.renderItemIn2D( tessellator, f5, f6, f4, f7, par2Icon.getIconWidth(), par2Icon.getIconHeight(), f12 ); - - GL11.glDisable( GL11.GL_CULL_FACE ); - GL11.glColor4f( 1, 1, 1, 1.0F ); - GL11.glScalef( 1F, 1.1F, 1F ); - GL11.glTranslatef( 0.0F, 1.07F, f12 / -2.0f ); - GL11.glRotatef( 180F, 1.0F, 0.0F, 0.0F ); - } - - GL11.glColor4f( 1, 1, 1, 1.0F ); - - if( type == ItemRenderType.INVENTORY ) - { - GL11.glDisable( GL11.GL_ALPHA_TEST ); - } - else - { - GL11.glEnable( GL11.GL_CULL_FACE ); - } - - GL11.glPopMatrix(); - } +public class PaintBallRender implements IItemRenderer { + + @Override + public boolean handleRenderType(final ItemStack item, final ItemRenderType type) { + return true; + } + + @Override + public boolean shouldUseRenderHelper( + final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper) { + return helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION; + } + + @Override + public void renderItem(final ItemRenderType type, final ItemStack item, final Object... data) { + final IIcon par2Icon; + + if (item.getItemDamage() < 20) { + par2Icon = item.getIconIndex(); + } else { + par2Icon = ExtraItemTextures.ItemPaintBallShimmer.getIcon(); + } + + final float f4 = par2Icon.getMinU(); + final float f5 = par2Icon.getMaxU(); + final float f6 = par2Icon.getMinV(); + final float f7 = par2Icon.getMaxV(); + + final ItemPaintBall ipb = (ItemPaintBall) item.getItem(); + + final Tessellator tessellator = Tessellator.instance; + + GL11.glPushMatrix(); + + final AEColor col = ipb.getColor(item); + + final int colorValue = item.getItemDamage() >= 20 ? col.mediumVariant : col.mediumVariant; + final int r = (colorValue >> 16) & 0xff; + final int g = (colorValue >> 8) & 0xff; + final int b = (colorValue) & 0xff; + + if (item.getItemDamage() >= 20) { + final float fail = 0.7f; + final int full = (int) (255 * 0.3); + GL11.glColor4ub((byte) (full + r * fail), (byte) (full + g * fail), (byte) (full + b * fail), (byte) 255); + } else { + GL11.glColor4ub((byte) r, (byte) g, (byte) b, (byte) 255); + } + + if (type == ItemRenderType.INVENTORY) { + GL11.glScalef(16F, 16F, 10F); + GL11.glTranslatef(0.0F, 1.0F, 0.0F); + GL11.glRotatef(180F, 1.0F, 0.0F, 0.0F); + GL11.glEnable(GL11.GL_ALPHA_TEST); + + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 1.0F, 0.0F); + tessellator.addVertexWithUV(0, 0, 0, f4, f7); + tessellator.addVertexWithUV(1, 0, 0, f5, f7); + tessellator.addVertexWithUV(1, 1, 0, f5, f6); + tessellator.addVertexWithUV(0, 1, 0, f4, f6); + tessellator.draw(); + } else { + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + GL11.glTranslatef(0.0F, 0.0F, 0.0F); + } else { + GL11.glTranslatef(-0.5F, -0.3F, 0.01F); + } + final float f12 = 0.0625F; + ItemRenderer.renderItemIn2D( + tessellator, f5, f6, f4, f7, par2Icon.getIconWidth(), par2Icon.getIconHeight(), f12); + + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glColor4f(1, 1, 1, 1.0F); + GL11.glScalef(1F, 1.1F, 1F); + GL11.glTranslatef(0.0F, 1.07F, f12 / -2.0f); + GL11.glRotatef(180F, 1.0F, 0.0F, 0.0F); + } + + GL11.glColor4f(1, 1, 1, 1.0F); + + if (type == ItemRenderType.INVENTORY) { + GL11.glDisable(GL11.GL_ALPHA_TEST); + } else { + GL11.glEnable(GL11.GL_CULL_FACE); + } + + GL11.glPopMatrix(); + } } diff --git a/src/main/java/appeng/client/render/items/ToolBiometricCardRender.java b/src/main/java/appeng/client/render/items/ToolBiometricCardRender.java index 2cb818403f3..6b8cb7b9b06 100644 --- a/src/main/java/appeng/client/render/items/ToolBiometricCardRender.java +++ b/src/main/java/appeng/client/render/items/ToolBiometricCardRender.java @@ -18,7 +18,6 @@ package appeng.client.render.items; - import appeng.api.implementations.items.IBiometricCard; import appeng.api.util.AEColor; import appeng.client.texture.ExtraItemTextures; @@ -30,130 +29,118 @@ import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; - -public class ToolBiometricCardRender implements IItemRenderer -{ - - @Override - public boolean handleRenderType( final ItemStack item, final ItemRenderType type ) - { - return true; - } - - @Override - public boolean shouldUseRenderHelper( final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper ) - { - return helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION; - } - - @Override - public void renderItem( final ItemRenderType type, final ItemStack item, final Object... data ) - { - final IIcon par2Icon = item.getIconIndex(); - - final float f4 = par2Icon.getMinU(); - final float f5 = par2Icon.getMaxU(); - final float f6 = par2Icon.getMinV(); - final float f7 = par2Icon.getMaxV(); - - final Tessellator tessellator = Tessellator.instance; - - GL11.glPushMatrix(); - GL11.glPushAttrib( GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT ); - - if( type == ItemRenderType.INVENTORY ) - { - GL11.glColor4f( 1, 1, 1, 1.0F ); - GL11.glScalef( 16F, 16F, 10F ); - GL11.glTranslatef( 0.0F, 1.0F, 0.0F ); - GL11.glRotatef( 180F, 1.0F, 0.0F, 0.0F ); - GL11.glEnable( GL11.GL_ALPHA_TEST ); - - tessellator.startDrawingQuads(); - tessellator.setNormal( 0.0F, 1.0F, 0.0F ); - tessellator.addVertexWithUV( 0, 0, 0, f4, f7 ); - tessellator.addVertexWithUV( 1, 0, 0, f5, f7 ); - tessellator.addVertexWithUV( 1, 1, 0, f5, f6 ); - tessellator.addVertexWithUV( 0, 1, 0, f4, f6 ); - tessellator.draw(); - } - else - { - GL11.glTranslatef( -0.5F, -0.3F, 0.01F ); - final float f12 = 0.0625F; - ItemRenderer.renderItemIn2D( tessellator, f5, f6, f4, f7, par2Icon.getIconWidth(), par2Icon.getIconHeight(), f12 ); - - GL11.glDisable( GL11.GL_CULL_FACE ); - GL11.glColor4f( 1, 1, 1, 1.0F ); - GL11.glScalef( 1F, 1.1F, 1F ); - GL11.glTranslatef( 0.0F, 1.07F, f12 / -2.0f ); - GL11.glRotatef( 180F, 1.0F, 0.0F, 0.0F ); - } - - final float u = ExtraItemTextures.White.getIcon().getInterpolatedU( 8.1 ); - final float v = ExtraItemTextures.White.getIcon().getInterpolatedV( 8.1 ); - - String username = ""; - - if( item.getItem() instanceof IBiometricCard ) - { - final GameProfile gp = ( (IBiometricCard) item.getItem() ).getProfile( item ); - if( gp != null ) - { - username = gp.getName(); - } - } - final int hash = username.length() > 0 ? username.hashCode() : 0; - - GL11.glScalef( 1F / 16F, 1F / 16F, 1F ); - GL11.glTranslatef( 4, 6, 0 ); - GL11.glDisable( GL11.GL_LIGHTING ); - - tessellator.startDrawingQuads(); - - AEColor col = AEColor.values()[Math.abs( 3 + hash ) % AEColor.values().length]; - if( hash == 0 ) - { - col = AEColor.Black; - } - - final float z = 0; - - for( int x = 0; x < 8; x++ )// 8 - { - for( int y = 0; y < 6; y++ )// 6 - { - boolean isLit = false; - - if( x == 0 || y == 0 || x == 7 || y == 5 ) - { - isLit = false; - } - else - { - isLit = ( hash & ( 1 << x ) ) != 0 || ( hash & ( 1 << y ) ) != 0; - } - - if( isLit ) - { - tessellator.setColorOpaque_I( col.mediumVariant ); - } - else - { - final float scale = 0.3f / 255.0f; - tessellator.setColorOpaque_F( ( ( col.blackVariant >> 16 ) & 0xff ) * scale, ( ( col.blackVariant >> 8 ) & 0xff ) * scale, ( col.blackVariant & 0xff ) * scale ); - } - - tessellator.addVertexWithUV( x, y, z, u, v ); - tessellator.addVertexWithUV( x + 1, y, z, u, v ); - tessellator.addVertexWithUV( x + 1, y + 1, z, u, v ); - tessellator.addVertexWithUV( x, y + 1, z, u, v ); - } - } - - tessellator.draw(); - - GL11.glPopAttrib(); - GL11.glPopMatrix(); - } +public class ToolBiometricCardRender implements IItemRenderer { + + @Override + public boolean handleRenderType(final ItemStack item, final ItemRenderType type) { + return true; + } + + @Override + public boolean shouldUseRenderHelper( + final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper) { + return helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION; + } + + @Override + public void renderItem(final ItemRenderType type, final ItemStack item, final Object... data) { + final IIcon par2Icon = item.getIconIndex(); + + final float f4 = par2Icon.getMinU(); + final float f5 = par2Icon.getMaxU(); + final float f6 = par2Icon.getMinV(); + final float f7 = par2Icon.getMaxV(); + + final Tessellator tessellator = Tessellator.instance; + + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT); + + if (type == ItemRenderType.INVENTORY) { + GL11.glColor4f(1, 1, 1, 1.0F); + GL11.glScalef(16F, 16F, 10F); + GL11.glTranslatef(0.0F, 1.0F, 0.0F); + GL11.glRotatef(180F, 1.0F, 0.0F, 0.0F); + GL11.glEnable(GL11.GL_ALPHA_TEST); + + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 1.0F, 0.0F); + tessellator.addVertexWithUV(0, 0, 0, f4, f7); + tessellator.addVertexWithUV(1, 0, 0, f5, f7); + tessellator.addVertexWithUV(1, 1, 0, f5, f6); + tessellator.addVertexWithUV(0, 1, 0, f4, f6); + tessellator.draw(); + } else { + GL11.glTranslatef(-0.5F, -0.3F, 0.01F); + final float f12 = 0.0625F; + ItemRenderer.renderItemIn2D( + tessellator, f5, f6, f4, f7, par2Icon.getIconWidth(), par2Icon.getIconHeight(), f12); + + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glColor4f(1, 1, 1, 1.0F); + GL11.glScalef(1F, 1.1F, 1F); + GL11.glTranslatef(0.0F, 1.07F, f12 / -2.0f); + GL11.glRotatef(180F, 1.0F, 0.0F, 0.0F); + } + + final float u = ExtraItemTextures.White.getIcon().getInterpolatedU(8.1); + final float v = ExtraItemTextures.White.getIcon().getInterpolatedV(8.1); + + String username = ""; + + if (item.getItem() instanceof IBiometricCard) { + final GameProfile gp = ((IBiometricCard) item.getItem()).getProfile(item); + if (gp != null) { + username = gp.getName(); + } + } + final int hash = username.length() > 0 ? username.hashCode() : 0; + + GL11.glScalef(1F / 16F, 1F / 16F, 1F); + GL11.glTranslatef(4, 6, 0); + GL11.glDisable(GL11.GL_LIGHTING); + + tessellator.startDrawingQuads(); + + AEColor col = AEColor.values()[Math.abs(3 + hash) % AEColor.values().length]; + if (hash == 0) { + col = AEColor.Black; + } + + final float z = 0; + + for (int x = 0; x < 8; x++) // 8 + { + for (int y = 0; y < 6; y++) // 6 + { + boolean isLit = false; + + if (x == 0 || y == 0 || x == 7 || y == 5) { + isLit = false; + } else { + isLit = (hash & (1 << x)) != 0 || (hash & (1 << y)) != 0; + } + + if (isLit) { + tessellator.setColorOpaque_I(col.mediumVariant); + } else { + final float scale = 0.3f / 255.0f; + tessellator.setColorOpaque_F( + ((col.blackVariant >> 16) & 0xff) * scale, + ((col.blackVariant >> 8) & 0xff) * scale, + (col.blackVariant & 0xff) * scale); + } + + tessellator.addVertexWithUV(x, y, z, u, v); + tessellator.addVertexWithUV(x + 1, y, z, u, v); + tessellator.addVertexWithUV(x + 1, y + 1, z, u, v); + tessellator.addVertexWithUV(x, y + 1, z, u, v); + } + } + + tessellator.draw(); + + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } } diff --git a/src/main/java/appeng/client/render/items/ToolColorApplicatorRender.java b/src/main/java/appeng/client/render/items/ToolColorApplicatorRender.java index 4b845ccc7cd..fde89a2033e 100644 --- a/src/main/java/appeng/client/render/items/ToolColorApplicatorRender.java +++ b/src/main/java/appeng/client/render/items/ToolColorApplicatorRender.java @@ -18,7 +18,6 @@ package appeng.client.render.items; - import appeng.api.util.AEColor; import appeng.client.texture.ExtraItemTextures; import appeng.items.tools.powered.ToolColorApplicator; @@ -29,133 +28,120 @@ import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; - -public class ToolColorApplicatorRender implements IItemRenderer -{ - - @Override - public boolean handleRenderType( final ItemStack item, final ItemRenderType type ) - { - return true; - } - - @Override - public boolean shouldUseRenderHelper( final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper ) - { - return helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION; - } - - @Override - public void renderItem( final ItemRenderType type, final ItemStack item, final Object... data ) - { - final IIcon par2Icon = item.getIconIndex(); - - float f4 = par2Icon.getMinU(); - float f5 = par2Icon.getMaxU(); - float f6 = par2Icon.getMinV(); - float f7 = par2Icon.getMaxV(); - - final Tessellator tessellator = Tessellator.instance; - - GL11.glPushMatrix(); - GL11.glPushAttrib( GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT ); - - if( type == ItemRenderType.INVENTORY ) - { - GL11.glColor4f( 1, 1, 1, 1.0F ); - GL11.glScalef( 16F, 16F, 10F ); - GL11.glTranslatef( 0.0F, 1.0F, 0.0F ); - GL11.glRotatef( 180F, 1.0F, 0.0F, 0.0F ); - GL11.glEnable( GL11.GL_ALPHA_TEST ); - - tessellator.startDrawingQuads(); - tessellator.setNormal( 0.0F, 1.0F, 0.0F ); - tessellator.addVertexWithUV( 0, 0, 0, f4, f7 ); - tessellator.addVertexWithUV( 1, 0, 0, f5, f7 ); - tessellator.addVertexWithUV( 1, 1, 0, f5, f6 ); - tessellator.addVertexWithUV( 0, 1, 0, f4, f6 ); - tessellator.draw(); - } - else - { - if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) - { - GL11.glTranslatef( 0.0F, 0.0F, 0.0F ); - } - else if( type == ItemRenderType.EQUIPPED ) - { - GL11.glTranslatef( 0.0F, 0.0F, 0.0F ); - } - else - { - GL11.glTranslatef( -0.5F, -0.3F, 0.01F ); - } - final float f12 = 0.0625F; - ItemRenderer.renderItemIn2D( tessellator, f5, f6, f4, f7, par2Icon.getIconWidth(), par2Icon.getIconHeight(), f12 ); - - GL11.glDisable( GL11.GL_CULL_FACE ); - GL11.glColor4f( 1, 1, 1, 1.0F ); - GL11.glScalef( -1F, -1F, 1F ); - GL11.glTranslatef( -1.125F, 0.0f, f12 / -2.0f ); - GL11.glRotatef( 180F, 1.0F, 0.0F, 0.0F ); - } - - final IIcon dark = ExtraItemTextures.ToolColorApplicatorTip_Dark.getIcon(); - final IIcon med = ExtraItemTextures.ToolColorApplicatorTip_Medium.getIcon(); - final IIcon light = ExtraItemTextures.ToolColorApplicatorTip_Light.getIcon(); - - GL11.glScalef( 1F / 16F, 1F / 16F, 1F ); - - if( type != ItemRenderType.INVENTORY ) - { - GL11.glTranslatef( 2, 0, 0 ); - } - - GL11.glDisable( GL11.GL_LIGHTING ); - - final AEColor col = ( (ToolColorApplicator) item.getItem() ).getActiveColor( item ); - - if( col != null ) - { - tessellator.startDrawingQuads(); - - f4 = dark.getMinU(); - f5 = dark.getMaxU(); - f6 = dark.getMinV(); - f7 = dark.getMaxV(); - - tessellator.setColorOpaque_I( col.blackVariant ); - tessellator.addVertexWithUV( 0, 0, 0, f4, f7 ); - tessellator.addVertexWithUV( 16, 0, 0, f5, f7 ); - tessellator.addVertexWithUV( 16, 16, 0, f5, f6 ); - tessellator.addVertexWithUV( 0, 16, 0, f4, f6 ); - - f4 = light.getMinU(); - f5 = light.getMaxU(); - f6 = light.getMinV(); - f7 = light.getMaxV(); - - tessellator.setColorOpaque_I( col.whiteVariant ); - tessellator.addVertexWithUV( 0, 0, 0, f4, f7 ); - tessellator.addVertexWithUV( 16, 0, 0, f5, f7 ); - tessellator.addVertexWithUV( 16, 16, 0, f5, f6 ); - tessellator.addVertexWithUV( 0, 16, 0, f4, f6 ); - - f4 = med.getMinU(); - f5 = med.getMaxU(); - f6 = med.getMinV(); - f7 = med.getMaxV(); - - tessellator.setColorOpaque_I( col.mediumVariant ); - tessellator.addVertexWithUV( 0, 0, 0, f4, f7 ); - tessellator.addVertexWithUV( 16, 0, 0, f5, f7 ); - tessellator.addVertexWithUV( 16, 16, 0, f5, f6 ); - tessellator.addVertexWithUV( 0, 16, 0, f4, f6 ); - - tessellator.draw(); - } - - GL11.glPopAttrib(); - GL11.glPopMatrix(); - } +public class ToolColorApplicatorRender implements IItemRenderer { + + @Override + public boolean handleRenderType(final ItemStack item, final ItemRenderType type) { + return true; + } + + @Override + public boolean shouldUseRenderHelper( + final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper) { + return helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION; + } + + @Override + public void renderItem(final ItemRenderType type, final ItemStack item, final Object... data) { + final IIcon par2Icon = item.getIconIndex(); + + float f4 = par2Icon.getMinU(); + float f5 = par2Icon.getMaxU(); + float f6 = par2Icon.getMinV(); + float f7 = par2Icon.getMaxV(); + + final Tessellator tessellator = Tessellator.instance; + + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT); + + if (type == ItemRenderType.INVENTORY) { + GL11.glColor4f(1, 1, 1, 1.0F); + GL11.glScalef(16F, 16F, 10F); + GL11.glTranslatef(0.0F, 1.0F, 0.0F); + GL11.glRotatef(180F, 1.0F, 0.0F, 0.0F); + GL11.glEnable(GL11.GL_ALPHA_TEST); + + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 1.0F, 0.0F); + tessellator.addVertexWithUV(0, 0, 0, f4, f7); + tessellator.addVertexWithUV(1, 0, 0, f5, f7); + tessellator.addVertexWithUV(1, 1, 0, f5, f6); + tessellator.addVertexWithUV(0, 1, 0, f4, f6); + tessellator.draw(); + } else { + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + GL11.glTranslatef(0.0F, 0.0F, 0.0F); + } else if (type == ItemRenderType.EQUIPPED) { + GL11.glTranslatef(0.0F, 0.0F, 0.0F); + } else { + GL11.glTranslatef(-0.5F, -0.3F, 0.01F); + } + final float f12 = 0.0625F; + ItemRenderer.renderItemIn2D( + tessellator, f5, f6, f4, f7, par2Icon.getIconWidth(), par2Icon.getIconHeight(), f12); + + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glColor4f(1, 1, 1, 1.0F); + GL11.glScalef(-1F, -1F, 1F); + GL11.glTranslatef(-1.125F, 0.0f, f12 / -2.0f); + GL11.glRotatef(180F, 1.0F, 0.0F, 0.0F); + } + + final IIcon dark = ExtraItemTextures.ToolColorApplicatorTip_Dark.getIcon(); + final IIcon med = ExtraItemTextures.ToolColorApplicatorTip_Medium.getIcon(); + final IIcon light = ExtraItemTextures.ToolColorApplicatorTip_Light.getIcon(); + + GL11.glScalef(1F / 16F, 1F / 16F, 1F); + + if (type != ItemRenderType.INVENTORY) { + GL11.glTranslatef(2, 0, 0); + } + + GL11.glDisable(GL11.GL_LIGHTING); + + final AEColor col = ((ToolColorApplicator) item.getItem()).getActiveColor(item); + + if (col != null) { + tessellator.startDrawingQuads(); + + f4 = dark.getMinU(); + f5 = dark.getMaxU(); + f6 = dark.getMinV(); + f7 = dark.getMaxV(); + + tessellator.setColorOpaque_I(col.blackVariant); + tessellator.addVertexWithUV(0, 0, 0, f4, f7); + tessellator.addVertexWithUV(16, 0, 0, f5, f7); + tessellator.addVertexWithUV(16, 16, 0, f5, f6); + tessellator.addVertexWithUV(0, 16, 0, f4, f6); + + f4 = light.getMinU(); + f5 = light.getMaxU(); + f6 = light.getMinV(); + f7 = light.getMaxV(); + + tessellator.setColorOpaque_I(col.whiteVariant); + tessellator.addVertexWithUV(0, 0, 0, f4, f7); + tessellator.addVertexWithUV(16, 0, 0, f5, f7); + tessellator.addVertexWithUV(16, 16, 0, f5, f6); + tessellator.addVertexWithUV(0, 16, 0, f4, f6); + + f4 = med.getMinU(); + f5 = med.getMaxU(); + f6 = med.getMinV(); + f7 = med.getMaxV(); + + tessellator.setColorOpaque_I(col.mediumVariant); + tessellator.addVertexWithUV(0, 0, 0, f4, f7); + tessellator.addVertexWithUV(16, 0, 0, f5, f7); + tessellator.addVertexWithUV(16, 16, 0, f5, f6); + tessellator.addVertexWithUV(0, 16, 0, f4, f6); + + tessellator.draw(); + } + + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } } diff --git a/src/main/java/appeng/client/render/model/ModelCompass.java b/src/main/java/appeng/client/render/model/ModelCompass.java index 4c03c9d8aa8..179c5b3e720 100644 --- a/src/main/java/appeng/client/render/model/ModelCompass.java +++ b/src/main/java/appeng/client/render/model/ModelCompass.java @@ -18,102 +18,96 @@ package appeng.client.render.model; - import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; - -public class ModelCompass extends ModelBase -{ - - private final ModelRenderer Ring1; - private final ModelRenderer Ring2; - private final ModelRenderer Ring3; - private final ModelRenderer Ring4; - private final ModelRenderer Middle; - private final ModelRenderer Base; - - private final ModelRenderer Pointer; - - public ModelCompass() - { - this.textureWidth = 16; - this.textureHeight = 8; - - this.Ring1 = new ModelRenderer( this, 0, 0 ); - this.Ring1.addBox( 0F, 0F, 0F, 4, 1, 1 ); - this.Ring1.setRotationPoint( -2F, 22F, 2F ); - this.Ring1.setTextureSize( 16, 8 ); - this.Ring1.mirror = true; - this.setRotation( this.Ring1, 0F, 0F, 0F ); - - this.Ring2 = new ModelRenderer( this, 0, 0 ); - this.Ring2.addBox( 0F, 0F, 0F, 1, 1, 4 ); - this.Ring2.setRotationPoint( -3F, 22F, -2F ); - this.Ring2.setTextureSize( 16, 8 ); - this.Ring2.mirror = true; - this.setRotation( this.Ring2, 0F, 0F, 0F ); - - this.Ring3 = new ModelRenderer( this, 0, 0 ); - this.Ring3.addBox( 0F, 0F, 0F, 4, 1, 1 ); - this.Ring3.setRotationPoint( -2F, 22F, -3F ); - this.Ring3.setTextureSize( 16, 8 ); - this.Ring3.mirror = true; - this.setRotation( this.Ring3, 0F, 0F, 0F ); - - this.Ring4 = new ModelRenderer( this, 0, 0 ); - this.Ring4.addBox( 0F, 0F, 0F, 1, 1, 4 ); - this.Ring4.setRotationPoint( 2F, 22F, -2F ); - this.Ring4.setTextureSize( 16, 8 ); - this.Ring4.mirror = true; - this.setRotation( this.Ring4, 0F, 0F, 0F ); - - this.Middle = new ModelRenderer( this, 0, 0 ); - this.Middle.addBox( 0F, 0F, 0F, 1, 1, 1 ); - this.Middle.setRotationPoint( -0.5333334F, 22F, -0.5333334F ); - this.Middle.setTextureSize( 16, 8 ); - this.Middle.mirror = true; - this.setRotation( this.Middle, 0F, 0F, 0F ); - - this.Pointer = new ModelRenderer( this, 0, 0 ); - this.Pointer.setTextureOffset( 0, 5 ); - this.Pointer.addBox( -0.5F, 0F, 0F, 1, 1, 2 ); - this.Pointer.setRotationPoint( 0.5F, 22.5F, 0.5F ); - this.Pointer.setTextureSize( 16, 8 ); - this.Pointer.mirror = true; - this.Pointer.offsetZ = -0.034f; - this.Pointer.offsetX = -0.034f; - this.setRotation( this.Pointer, 0F, 0F, 0F ); - - this.Base = new ModelRenderer( this, 0, 0 ); - this.Base.addBox( 0F, 0F, 0F, 4, 1, 4 ); - this.Base.setRotationPoint( -2F, 23F, -2F ); - this.Base.setTextureSize( 16, 8 ); - this.Base.mirror = true; - this.setRotation( this.Base, 0F, 0F, 0F ); - } - - private void setRotation( final ModelRenderer model, final float x, final float y, final float z ) - { - model.rotateAngleX = x; - model.rotateAngleY = y; - model.rotateAngleZ = z; - } - - public void renderAll( final float rad ) - { - this.setRotation( this.Pointer, 0F, 0F, 0F ); - - this.Pointer.rotateAngleY = rad; - - this.Base.render( 0.0625F ); - this.Middle.render( 0.0625F ); - - this.Pointer.render( 0.0625F ); - - this.Ring1.render( 0.0625F ); - this.Ring2.render( 0.0625F ); - this.Ring3.render( 0.0625F ); - this.Ring4.render( 0.0625F ); - } +public class ModelCompass extends ModelBase { + + private final ModelRenderer Ring1; + private final ModelRenderer Ring2; + private final ModelRenderer Ring3; + private final ModelRenderer Ring4; + private final ModelRenderer Middle; + private final ModelRenderer Base; + + private final ModelRenderer Pointer; + + public ModelCompass() { + this.textureWidth = 16; + this.textureHeight = 8; + + this.Ring1 = new ModelRenderer(this, 0, 0); + this.Ring1.addBox(0F, 0F, 0F, 4, 1, 1); + this.Ring1.setRotationPoint(-2F, 22F, 2F); + this.Ring1.setTextureSize(16, 8); + this.Ring1.mirror = true; + this.setRotation(this.Ring1, 0F, 0F, 0F); + + this.Ring2 = new ModelRenderer(this, 0, 0); + this.Ring2.addBox(0F, 0F, 0F, 1, 1, 4); + this.Ring2.setRotationPoint(-3F, 22F, -2F); + this.Ring2.setTextureSize(16, 8); + this.Ring2.mirror = true; + this.setRotation(this.Ring2, 0F, 0F, 0F); + + this.Ring3 = new ModelRenderer(this, 0, 0); + this.Ring3.addBox(0F, 0F, 0F, 4, 1, 1); + this.Ring3.setRotationPoint(-2F, 22F, -3F); + this.Ring3.setTextureSize(16, 8); + this.Ring3.mirror = true; + this.setRotation(this.Ring3, 0F, 0F, 0F); + + this.Ring4 = new ModelRenderer(this, 0, 0); + this.Ring4.addBox(0F, 0F, 0F, 1, 1, 4); + this.Ring4.setRotationPoint(2F, 22F, -2F); + this.Ring4.setTextureSize(16, 8); + this.Ring4.mirror = true; + this.setRotation(this.Ring4, 0F, 0F, 0F); + + this.Middle = new ModelRenderer(this, 0, 0); + this.Middle.addBox(0F, 0F, 0F, 1, 1, 1); + this.Middle.setRotationPoint(-0.5333334F, 22F, -0.5333334F); + this.Middle.setTextureSize(16, 8); + this.Middle.mirror = true; + this.setRotation(this.Middle, 0F, 0F, 0F); + + this.Pointer = new ModelRenderer(this, 0, 0); + this.Pointer.setTextureOffset(0, 5); + this.Pointer.addBox(-0.5F, 0F, 0F, 1, 1, 2); + this.Pointer.setRotationPoint(0.5F, 22.5F, 0.5F); + this.Pointer.setTextureSize(16, 8); + this.Pointer.mirror = true; + this.Pointer.offsetZ = -0.034f; + this.Pointer.offsetX = -0.034f; + this.setRotation(this.Pointer, 0F, 0F, 0F); + + this.Base = new ModelRenderer(this, 0, 0); + this.Base.addBox(0F, 0F, 0F, 4, 1, 4); + this.Base.setRotationPoint(-2F, 23F, -2F); + this.Base.setTextureSize(16, 8); + this.Base.mirror = true; + this.setRotation(this.Base, 0F, 0F, 0F); + } + + private void setRotation(final ModelRenderer model, final float x, final float y, final float z) { + model.rotateAngleX = x; + model.rotateAngleY = y; + model.rotateAngleZ = z; + } + + public void renderAll(final float rad) { + this.setRotation(this.Pointer, 0F, 0F, 0F); + + this.Pointer.rotateAngleY = rad; + + this.Base.render(0.0625F); + this.Middle.render(0.0625F); + + this.Pointer.render(0.0625F); + + this.Ring1.render(0.0625F); + this.Ring2.render(0.0625F); + this.Ring3.render(0.0625F); + this.Ring4.render(0.0625F); + } } diff --git a/src/main/java/appeng/client/texture/CableBusTextures.java b/src/main/java/appeng/client/texture/CableBusTextures.java index 58683f0dd35..894edb67d4a 100644 --- a/src/main/java/appeng/client/texture/CableBusTextures.java +++ b/src/main/java/appeng/client/texture/CableBusTextures.java @@ -18,7 +18,6 @@ package appeng.client.texture; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; @@ -26,93 +25,225 @@ import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; - -public enum CableBusTextures -{ - - Channels00( "MECableSmart00" ), Channels01( "MECableSmart01" ), Channels02( "MECableSmart02" ), Channels03( "MECableSmart03" ), Channels10( "MECableSmart10" ), Channels11( "MECableSmart11" ), Channels12( "MECableSmart12" ), Channels13( "MECableSmart13" ), Channels14( "MECableSmart14" ), Channels04( "MECableSmart04" ), - - LevelEmitterTorchOn( "ItemPart.LevelEmitterOn" ), BlockWirelessOn( "BlockWirelessOn" ), - - BlockP2PTunnel2( "ItemPart.P2PTunnel2" ), BlockP2PTunnel3( "ItemPart.P2PTunnel3" ), - - // MEWaiting("MEWaiting"), - - PartMonitorSides( "PartMonitorSides" ), PartMonitorBack( "PartMonitorBack" ), - - Transparent( "Transparent" ), PartMonitorSidesStatus( "PartMonitorSidesStatus" ), PartMonitorSidesStatusLights( "PartMonitorSidesStatusLights" ), - - PartMonitor_Colored( "PartMonitor_Colored" ), PartMonitor_Bright( "PartMonitor_Bright" ), - - PartPatternTerm_Bright( "PartPatternTerm_Bright" ), PartPatternTerm_Colored( "PartPatternTerm_Colored" ), PartPatternTerm_Dark( "PartPatternTerm_Dark" ), - - PartConversionMonitor_Bright( "PartConversionMonitor_Bright" ), PartConversionMonitor_Colored( "PartConversionMonitor_Colored" ), PartConversionMonitor_Dark( "PartConversionMonitor_Dark" ), PartConversionMonitor_Dark_Locked( "PartConversionMonitor_Dark_Locked" ), - - PartInterfaceTerm_Bright( "PartInterfaceTerm_Bright" ), PartInterfaceTerm_Colored( "PartInterfaceTerm_Colored" ), PartInterfaceTerm_Dark( "PartInterfaceTerm_Dark" ), - - PartCraftingTerm_Bright( "PartCraftingTerm_Bright" ), PartCraftingTerm_Colored( "PartCraftingTerm_Colored" ), PartCraftingTerm_Dark( "PartCraftingTerm_Dark" ), // - - PartStorageMonitor_Bright( "PartStorageMonitor_Bright" ), PartStorageMonitor_Colored( "PartStorageMonitor_Colored" ), PartStorageMonitor_Dark( "PartStorageMonitor_Dark" ), PartStorageMonitor_Colored_Locked( "PartStorageMonitor_Colored_Locked" ), - - PartTerminal_Bright( "PartTerminal_Bright" ), PartTerminal_Colored( "PartTerminal_Colored" ), PartTerminal_Dark( "PartTerminal_Dark" ), - - MECable_Green( "MECable_Green" ), MECable_Grey( "MECable_Grey" ), MECable_LightBlue( "MECable_LightBlue" ), MECable_LightGrey( "MECable_LightGrey" ), MECable_Lime( "MECable_Lime" ), MECable_Magenta( "MECable_Magenta" ), MECable_Orange( "MECable_Orange" ), MECable_Pink( "MECable_Pink" ), MECable_Purple( "MECable_Purple" ), MECable_Red( "MECable_Red" ), MECable_White( "MECable_White" ), MECable_Yellow( "MECable_Yellow" ), MECable_Black( "MECable_Black" ), MECable_Blue( "MECable_Blue" ), MECable_Brown( "MECable_Brown" ), MECable_Cyan( "MECable_Cyan" ), - - MEDense_Black( "MEDense_Black" ), MEDense_Blue( "MEDense_Blue" ), MEDense_Brown( "MEDense_Brown" ), MEDense_Cyan( "MEDense_Cyan" ), MEDense_Gray( "MEDense_Gray" ), MEDense_Green( "MEDense_Green" ), MEDense_LightBlue( "MEDense_LightBlue" ), MEDense_LightGrey( "MEDense_LightGrey" ), MEDense_Lime( "MEDense_Lime" ), MEDense_Magenta( "MEDense_Magenta" ), MEDense_Orange( "MEDense_Orange" ), MEDense_Pink( "MEDense_Pink" ), MEDense_Purple( "MEDense_Purple" ), MEDense_Red( "MEDense_Red" ), MEDense_White( "MEDense_White" ), MEDense_Yellow( "MEDense_Yellow" ), - - MEDenseCovered_Black( "MEDenseCovered_Black" ), MEDenseCovered_Blue( "MEDenseCovered_Blue" ), MEDenseCovered_Brown( "MEDenseCovered_Brown" ), MEDenseCovered_Cyan( "MEDenseCovered_Cyan" ), MEDenseCovered_Gray( "MEDenseCovered_Gray" ), MEDenseCovered_Green( "MEDenseCovered_Green" ), MEDenseCovered_LightBlue( "MEDenseCovered_LightBlue" ), MEDenseCovered_LightGrey( "MEDenseCovered_LightGrey" ), MEDenseCovered_Lime( "MEDenseCovered_Lime" ), MEDenseCovered_Magenta( "MEDenseCovered_Magenta" ), MEDenseCovered_Orange( "MEDenseCovered_Orange" ), MEDenseCovered_Pink( "MEDenseCovered_Pink" ), MEDenseCovered_Purple( "MEDenseCovered_Purple" ), MEDenseCovered_Red( "MEDenseCovered_Red" ), MEDenseCovered_White( "MEDenseCovered_White" ), MEDenseCovered_Yellow( "MEDenseCovered_Yellow" ), - - MEUltraDense_Black( "MEUltraDense_Black" ), MEUltraDense_Blue( "MEUltraDense_Blue" ), MEUltraDense_Brown( "MEUltraDense_Brown" ), MEUltraDense_Cyan( "MEUltraDense_Cyan" ), MEUltraDense_Gray( "MEUltraDense_Gray" ), MEUltraDense_Green( "MEUltraDense_Green" ), MEUltraDense_LightBlue( "MEUltraDense_LightBlue" ), MEUltraDense_LightGrey( "MEUltraDense_LightGrey" ), MEUltraDense_Lime( "MEUltraDense_Lime" ), MEUltraDense_Magenta( "MEUltraDense_Magenta" ), MEUltraDense_Orange( "MEUltraDense_Orange" ), MEUltraDense_Pink( "MEUltraDense_Pink" ), MEUltraDense_Purple( "MEUltraDense_Purple" ), MEUltraDense_Red( "MEUltraDense_Red" ), MEUltraDense_White( "MEUltraDense_White" ), MEUltraDense_Yellow( "MEUltraDense_Yellow" ), - - MEUltraDenseCovered_Black( "MEUltraDenseCovered_Black" ), MEUltraDenseCovered_Blue( "MEUltraDenseCovered_Blue" ), MEUltraDenseCovered_Brown( "MEUltraDenseCovered_Brown" ), MEUltraDenseCovered_Cyan( "MEUltraDenseCovered_Cyan" ), MEUltraDenseCovered_Gray( "MEUltraDenseCovered_Gray" ), MEUltraDenseCovered_Green( "MEUltraDenseCovered_Green" ), MEUltraDenseCovered_LightBlue( "MEUltraDenseCovered_LightBlue" ), MEUltraDenseCovered_LightGrey( "MEUltraDenseCovered_LightGrey" ), MEUltraDenseCovered_Lime( "MEUltraDenseCovered_Lime" ), MEUltraDenseCovered_Magenta( "MEUltraDenseCovered_Magenta" ), MEUltraDenseCovered_Orange( "MEUltraDenseCovered_Orange" ), MEUltraDenseCovered_Pink( "MEUltraDenseCovered_Pink" ), MEUltraDenseCovered_Purple( "MEUltraDenseCovered_Purple" ), MEUltraDenseCovered_Red( "MEUltraDenseCovered_Red" ), MEUltraDenseCovered_White( "MEUltraDenseCovered_White" ), MEUltraDenseCovered_Yellow( "MEUltraDenseCovered_Yellow" ), - - MESmart_Black( "MESmart_Black" ), MESmart_Blue( "MESmart_Blue" ), MESmart_Brown( "MESmart_Brown" ), MESmart_Cyan( "MESmart_Cyan" ), MESmart_Gray( "MESmart_Gray" ), MESmart_Green( "MESmart_Green" ), MESmart_LightBlue( "MESmart_LightBlue" ), MESmart_LightGrey( "MESmart_LightGrey" ), MESmart_Lime( "MESmart_Lime" ), MESmart_Magenta( "MESmart_Magenta" ), MESmart_Orange( "MESmart_Orange" ), MESmart_Pink( "MESmart_Pink" ), MESmart_Purple( "MESmart_Purple" ), MESmart_Red( "MESmart_Red" ), MESmart_White( "MESmart_White" ), MESmart_Yellow( "MESmart_Yellow" ), - - MECovered_Black( "MECovered_Black" ), MECovered_Blue( "MECovered_Blue" ), MECovered_Brown( "MECovered_Brown" ), MECovered_Cyan( "MECovered_Cyan" ), MECovered_Gray( "MECovered_Gray" ), MECovered_Green( "MECovered_Green" ), MECovered_LightBlue( "MECovered_LightBlue" ), MECovered_LightGrey( "MECovered_LightGrey" ), MECovered_Lime( "MECovered_Lime" ), MECovered_Magenta( "MECovered_Magenta" ), MECovered_Orange( "MECovered_Orange" ), MECovered_Pink( "MECovered_Pink" ), MECovered_Purple( "MECovered_Purple" ), MECovered_Red( "MECovered_Red" ), MECovered_White( "MECovered_White" ), MECovered_Yellow( "MECovered_Yellow" ), - - BlockAnnihilationPlaneOn( "BlockAnnihilationPlaneOn" ), - - BlockFormPlaneOn( "BlockFormPlaneOn" ), - - BlockIdentityAnnihilationPlaneOn( "BlockIdentityAnnihilationPlaneOn" ), - - ItemPartLevelEmitterOn( "ItemPart.LevelEmitterOn" ), PartTransitionPlaneBack( "PartTransitionPlaneBack" ), - - PartTunnelSides( "PartTunnelSides" ), PartPlaneSides( "PartPlaneSides" ), PartExportSides( "PartExportSides" ), PartImportSides( "PartImportSides" ), - - PartWirelessSides( "PartWirelessSides" ), PartStorageSides( "PartStorageSides" ), PartStorageBack( "PartStorageBack" ); - - private final String name; - public IIcon IIcon; - - CableBusTextures( final String name ) - { - this.name = name; - } - - public static ResourceLocation GuiTexture( final String string ) - { - return null; - } - - @SideOnly( Side.CLIENT ) - public static IIcon getMissing() - { - return ( (TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( TextureMap.locationBlocksTexture ) ).getAtlasSprite( "missingno" ); - } - - public String getName() - { - return this.name; - } - - public IIcon getIcon() - { - return this.IIcon; - } - - public void registerIcon( final TextureMap map ) - { - this.IIcon = map.registerIcon( "appliedenergistics2:" + this.name ); - } +public enum CableBusTextures { + Channels00("MECableSmart00"), + Channels01("MECableSmart01"), + Channels02("MECableSmart02"), + Channels03("MECableSmart03"), + Channels10("MECableSmart10"), + Channels11("MECableSmart11"), + Channels12("MECableSmart12"), + Channels13("MECableSmart13"), + Channels14("MECableSmart14"), + Channels04("MECableSmart04"), + + LevelEmitterTorchOn("ItemPart.LevelEmitterOn"), + BlockWirelessOn("BlockWirelessOn"), + + BlockP2PTunnel2("ItemPart.P2PTunnel2"), + BlockP2PTunnel3("ItemPart.P2PTunnel3"), + + // MEWaiting("MEWaiting"), + + PartMonitorSides("PartMonitorSides"), + PartMonitorBack("PartMonitorBack"), + + Transparent("Transparent"), + PartMonitorSidesStatus("PartMonitorSidesStatus"), + PartMonitorSidesStatusLights("PartMonitorSidesStatusLights"), + + PartMonitor_Colored("PartMonitor_Colored"), + PartMonitor_Bright("PartMonitor_Bright"), + + PartPatternTerm_Bright("PartPatternTerm_Bright"), + PartPatternTerm_Colored("PartPatternTerm_Colored"), + PartPatternTerm_Dark("PartPatternTerm_Dark"), + + PartConversionMonitor_Bright("PartConversionMonitor_Bright"), + PartConversionMonitor_Colored("PartConversionMonitor_Colored"), + PartConversionMonitor_Dark("PartConversionMonitor_Dark"), + PartConversionMonitor_Dark_Locked("PartConversionMonitor_Dark_Locked"), + + PartInterfaceTerm_Bright("PartInterfaceTerm_Bright"), + PartInterfaceTerm_Colored("PartInterfaceTerm_Colored"), + PartInterfaceTerm_Dark("PartInterfaceTerm_Dark"), + + PartCraftingTerm_Bright("PartCraftingTerm_Bright"), + PartCraftingTerm_Colored("PartCraftingTerm_Colored"), + PartCraftingTerm_Dark("PartCraftingTerm_Dark"), // + + PartStorageMonitor_Bright("PartStorageMonitor_Bright"), + PartStorageMonitor_Colored("PartStorageMonitor_Colored"), + PartStorageMonitor_Dark("PartStorageMonitor_Dark"), + PartStorageMonitor_Colored_Locked("PartStorageMonitor_Colored_Locked"), + + PartTerminal_Bright("PartTerminal_Bright"), + PartTerminal_Colored("PartTerminal_Colored"), + PartTerminal_Dark("PartTerminal_Dark"), + + MECable_Green("MECable_Green"), + MECable_Grey("MECable_Grey"), + MECable_LightBlue("MECable_LightBlue"), + MECable_LightGrey("MECable_LightGrey"), + MECable_Lime("MECable_Lime"), + MECable_Magenta("MECable_Magenta"), + MECable_Orange("MECable_Orange"), + MECable_Pink("MECable_Pink"), + MECable_Purple("MECable_Purple"), + MECable_Red("MECable_Red"), + MECable_White("MECable_White"), + MECable_Yellow("MECable_Yellow"), + MECable_Black("MECable_Black"), + MECable_Blue("MECable_Blue"), + MECable_Brown("MECable_Brown"), + MECable_Cyan("MECable_Cyan"), + + MEDense_Black("MEDense_Black"), + MEDense_Blue("MEDense_Blue"), + MEDense_Brown("MEDense_Brown"), + MEDense_Cyan("MEDense_Cyan"), + MEDense_Gray("MEDense_Gray"), + MEDense_Green("MEDense_Green"), + MEDense_LightBlue("MEDense_LightBlue"), + MEDense_LightGrey("MEDense_LightGrey"), + MEDense_Lime("MEDense_Lime"), + MEDense_Magenta("MEDense_Magenta"), + MEDense_Orange("MEDense_Orange"), + MEDense_Pink("MEDense_Pink"), + MEDense_Purple("MEDense_Purple"), + MEDense_Red("MEDense_Red"), + MEDense_White("MEDense_White"), + MEDense_Yellow("MEDense_Yellow"), + + MEDenseCovered_Black("MEDenseCovered_Black"), + MEDenseCovered_Blue("MEDenseCovered_Blue"), + MEDenseCovered_Brown("MEDenseCovered_Brown"), + MEDenseCovered_Cyan("MEDenseCovered_Cyan"), + MEDenseCovered_Gray("MEDenseCovered_Gray"), + MEDenseCovered_Green("MEDenseCovered_Green"), + MEDenseCovered_LightBlue("MEDenseCovered_LightBlue"), + MEDenseCovered_LightGrey("MEDenseCovered_LightGrey"), + MEDenseCovered_Lime("MEDenseCovered_Lime"), + MEDenseCovered_Magenta("MEDenseCovered_Magenta"), + MEDenseCovered_Orange("MEDenseCovered_Orange"), + MEDenseCovered_Pink("MEDenseCovered_Pink"), + MEDenseCovered_Purple("MEDenseCovered_Purple"), + MEDenseCovered_Red("MEDenseCovered_Red"), + MEDenseCovered_White("MEDenseCovered_White"), + MEDenseCovered_Yellow("MEDenseCovered_Yellow"), + + MEUltraDense_Black("MEUltraDense_Black"), + MEUltraDense_Blue("MEUltraDense_Blue"), + MEUltraDense_Brown("MEUltraDense_Brown"), + MEUltraDense_Cyan("MEUltraDense_Cyan"), + MEUltraDense_Gray("MEUltraDense_Gray"), + MEUltraDense_Green("MEUltraDense_Green"), + MEUltraDense_LightBlue("MEUltraDense_LightBlue"), + MEUltraDense_LightGrey("MEUltraDense_LightGrey"), + MEUltraDense_Lime("MEUltraDense_Lime"), + MEUltraDense_Magenta("MEUltraDense_Magenta"), + MEUltraDense_Orange("MEUltraDense_Orange"), + MEUltraDense_Pink("MEUltraDense_Pink"), + MEUltraDense_Purple("MEUltraDense_Purple"), + MEUltraDense_Red("MEUltraDense_Red"), + MEUltraDense_White("MEUltraDense_White"), + MEUltraDense_Yellow("MEUltraDense_Yellow"), + + MEUltraDenseCovered_Black("MEUltraDenseCovered_Black"), + MEUltraDenseCovered_Blue("MEUltraDenseCovered_Blue"), + MEUltraDenseCovered_Brown("MEUltraDenseCovered_Brown"), + MEUltraDenseCovered_Cyan("MEUltraDenseCovered_Cyan"), + MEUltraDenseCovered_Gray("MEUltraDenseCovered_Gray"), + MEUltraDenseCovered_Green("MEUltraDenseCovered_Green"), + MEUltraDenseCovered_LightBlue("MEUltraDenseCovered_LightBlue"), + MEUltraDenseCovered_LightGrey("MEUltraDenseCovered_LightGrey"), + MEUltraDenseCovered_Lime("MEUltraDenseCovered_Lime"), + MEUltraDenseCovered_Magenta("MEUltraDenseCovered_Magenta"), + MEUltraDenseCovered_Orange("MEUltraDenseCovered_Orange"), + MEUltraDenseCovered_Pink("MEUltraDenseCovered_Pink"), + MEUltraDenseCovered_Purple("MEUltraDenseCovered_Purple"), + MEUltraDenseCovered_Red("MEUltraDenseCovered_Red"), + MEUltraDenseCovered_White("MEUltraDenseCovered_White"), + MEUltraDenseCovered_Yellow("MEUltraDenseCovered_Yellow"), + + MESmart_Black("MESmart_Black"), + MESmart_Blue("MESmart_Blue"), + MESmart_Brown("MESmart_Brown"), + MESmart_Cyan("MESmart_Cyan"), + MESmart_Gray("MESmart_Gray"), + MESmart_Green("MESmart_Green"), + MESmart_LightBlue("MESmart_LightBlue"), + MESmart_LightGrey("MESmart_LightGrey"), + MESmart_Lime("MESmart_Lime"), + MESmart_Magenta("MESmart_Magenta"), + MESmart_Orange("MESmart_Orange"), + MESmart_Pink("MESmart_Pink"), + MESmart_Purple("MESmart_Purple"), + MESmart_Red("MESmart_Red"), + MESmart_White("MESmart_White"), + MESmart_Yellow("MESmart_Yellow"), + + MECovered_Black("MECovered_Black"), + MECovered_Blue("MECovered_Blue"), + MECovered_Brown("MECovered_Brown"), + MECovered_Cyan("MECovered_Cyan"), + MECovered_Gray("MECovered_Gray"), + MECovered_Green("MECovered_Green"), + MECovered_LightBlue("MECovered_LightBlue"), + MECovered_LightGrey("MECovered_LightGrey"), + MECovered_Lime("MECovered_Lime"), + MECovered_Magenta("MECovered_Magenta"), + MECovered_Orange("MECovered_Orange"), + MECovered_Pink("MECovered_Pink"), + MECovered_Purple("MECovered_Purple"), + MECovered_Red("MECovered_Red"), + MECovered_White("MECovered_White"), + MECovered_Yellow("MECovered_Yellow"), + + BlockAnnihilationPlaneOn("BlockAnnihilationPlaneOn"), + + BlockFormPlaneOn("BlockFormPlaneOn"), + + BlockIdentityAnnihilationPlaneOn("BlockIdentityAnnihilationPlaneOn"), + + ItemPartLevelEmitterOn("ItemPart.LevelEmitterOn"), + PartTransitionPlaneBack("PartTransitionPlaneBack"), + + PartTunnelSides("PartTunnelSides"), + PartPlaneSides("PartPlaneSides"), + PartExportSides("PartExportSides"), + PartImportSides("PartImportSides"), + + PartWirelessSides("PartWirelessSides"), + PartStorageSides("PartStorageSides"), + PartStorageBack("PartStorageBack"); + + private final String name; + public IIcon IIcon; + + CableBusTextures(final String name) { + this.name = name; + } + + public static ResourceLocation GuiTexture(final String string) { + return null; + } + + @SideOnly(Side.CLIENT) + public static IIcon getMissing() { + return ((TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture(TextureMap.locationBlocksTexture)) + .getAtlasSprite("missingno"); + } + + public String getName() { + return this.name; + } + + public IIcon getIcon() { + return this.IIcon; + } + + public void registerIcon(final TextureMap map) { + this.IIcon = map.registerIcon("appliedenergistics2:" + this.name); + } } diff --git a/src/main/java/appeng/client/texture/ExtraBlockTextures.java b/src/main/java/appeng/client/texture/ExtraBlockTextures.java index 090182d8ed6..2b1186bc7a7 100644 --- a/src/main/java/appeng/client/texture/ExtraBlockTextures.java +++ b/src/main/java/appeng/client/texture/ExtraBlockTextures.java @@ -18,7 +18,6 @@ package appeng.client.texture; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; @@ -26,98 +25,148 @@ import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; +public enum ExtraBlockTextures { + BlockVibrationChamberFrontOn("BlockVibrationChamberFrontOn"), -public enum ExtraBlockTextures -{ - BlockVibrationChamberFrontOn( "BlockVibrationChamberFrontOn" ), - - OreQuartzStone( "OreQuartzStone" ), - - MEChest( "BlockMEChest" ), - - BlockMEChestItems_Light( "BlockMEChestItems_Light" ), BlockMEChestItems_Dark( "BlockMEChestItems_Dark" ), BlockMEChestItems_Medium( "BlockMEChestItems_Medium" ), - - BlockControllerPowered( "BlockControllerPowered" ), BlockControllerColumnPowered( "BlockControllerColumnPowered" ), BlockControllerColumn( "BlockControllerColumn" ), BlockControllerLights( "BlockControllerLights" ), BlockControllerColumnLights( "BlockControllerColumnLights" ), BlockControllerColumnConflict( "BlockControllerColumnConflict" ), BlockControllerConflict( "BlockControllerConflict" ), BlockControllerInsideA( "BlockControllerInsideA" ), BlockControllerInsideB( "BlockControllerInsideB" ), - - BlockMolecularAssemblerLights( "BlockMolecularAssemblerLights" ), - - BlockChargerInside( "BlockChargerInside" ), - - BlockInterfaceAlternate( "BlockInterfaceAlternate" ), BlockInterfaceAlternateArrow( "BlockInterfaceAlternateArrow" ), - - MEStorageCellTextures( "MEStorageCellTextures" ), White( "White" ), - - BlockMatterCannonParticle( "BlockMatterCannonParticle" ), BlockEnergyParticle( "BlockEnergyParticle" ), + OreQuartzStone("OreQuartzStone"), - GlassFrame( "BlockQuartzGlassFrame" ), + MEChest("BlockMEChest"), - BlockQRingCornerLight( "BlockQRingCornerLight" ), BlockQRingEdgeLight( "BlockQRingEdgeLight" ), + BlockMEChestItems_Light("BlockMEChestItems_Light"), + BlockMEChestItems_Dark("BlockMEChestItems_Dark"), + BlockMEChestItems_Medium("BlockMEChestItems_Medium"), - MEDenseEnergyCell0( "BlockDenseEnergyCell0" ), MEDenseEnergyCell1( "BlockDenseEnergyCell1" ), MEDenseEnergyCell2( "BlockDenseEnergyCell2" ), MEDenseEnergyCell3( "BlockDenseEnergyCell3" ), MEDenseEnergyCell4( "BlockDenseEnergyCell4" ), MEDenseEnergyCell5( "BlockDenseEnergyCell5" ), MEDenseEnergyCell6( "BlockDenseEnergyCell6" ), MEDenseEnergyCell7( "BlockDenseEnergyCell7" ), + BlockControllerPowered("BlockControllerPowered"), + BlockControllerColumnPowered("BlockControllerColumnPowered"), + BlockControllerColumn("BlockControllerColumn"), + BlockControllerLights("BlockControllerLights"), + BlockControllerColumnLights("BlockControllerColumnLights"), + BlockControllerColumnConflict("BlockControllerColumnConflict"), + BlockControllerConflict("BlockControllerConflict"), + BlockControllerInsideA("BlockControllerInsideA"), + BlockControllerInsideB("BlockControllerInsideB"), - MEEnergyCell0( "BlockEnergyCell0" ), MEEnergyCell1( "BlockEnergyCell1" ), MEEnergyCell2( "BlockEnergyCell2" ), MEEnergyCell3( "BlockEnergyCell3" ), MEEnergyCell4( "BlockEnergyCell4" ), MEEnergyCell5( "BlockEnergyCell5" ), MEEnergyCell6( "BlockEnergyCell6" ), MEEnergyCell7( "BlockEnergyCell7" ), + BlockMolecularAssemblerLights("BlockMolecularAssemblerLights"), - BlockSpatialPylon_dim( "BlockSpatialPylon_dim" ), BlockSpatialPylon_red( "BlockSpatialPylon_red" ), + BlockChargerInside("BlockChargerInside"), - BlockSpatialPylonC( "BlockSpatialPylon_spanned" ), BlockSpatialPylonC_dim( "BlockSpatialPylon_spanned_dim" ), BlockSpatialPylonC_red( "BlockSpatialPylon_spanned_red" ), + BlockInterfaceAlternate("BlockInterfaceAlternate"), + BlockInterfaceAlternateArrow("BlockInterfaceAlternateArrow"), - BlockQuartzGlassB( "BlockQuartzGlassB" ), BlockQuartzGlassC( "BlockQuartzGlassC" ), BlockQuartzGlassD( "BlockQuartzGlassD" ), + MEStorageCellTextures("MEStorageCellTextures"), + White("White"), - BlockSpatialPylonE( "BlockSpatialPylon_end" ), BlockSpatialPylonE_dim( "BlockSpatialPylon_end_dim" ), BlockSpatialPylonE_red( "BlockSpatialPylon_end_red" ), + BlockMatterCannonParticle("BlockMatterCannonParticle"), + BlockEnergyParticle("BlockEnergyParticle"), - BlockMESecurityOn_Light( "BlockMESecurityOn_Light" ), BlockMESecurityOn_Medium( "BlockMESecurityOn_Medium" ), BlockMESecurityOn_Dark( "BlockMESecurityOn_Dark" ), BlockInscriberInside( "BlockInscriberInside" ), + GlassFrame("BlockQuartzGlassFrame"), - BlockQuartzGrowthAcceleratorOn( "BlockQuartzGrowthAcceleratorOn" ), BlockQuartzGrowthAcceleratorSideOn( "BlockQuartzGrowthAcceleratorSideOn" ), + BlockQRingCornerLight("BlockQRingCornerLight"), + BlockQRingEdgeLight("BlockQRingEdgeLight"), - BlockWirelessInside( "BlockWirelessInside" ), + MEDenseEnergyCell0("BlockDenseEnergyCell0"), + MEDenseEnergyCell1("BlockDenseEnergyCell1"), + MEDenseEnergyCell2("BlockDenseEnergyCell2"), + MEDenseEnergyCell3("BlockDenseEnergyCell3"), + MEDenseEnergyCell4("BlockDenseEnergyCell4"), + MEDenseEnergyCell5("BlockDenseEnergyCell5"), + MEDenseEnergyCell6("BlockDenseEnergyCell6"), + MEDenseEnergyCell7("BlockDenseEnergyCell7"), - BlockCraftingAccelerator( "BlockCraftingAccelerator" ), BlockCraftingAccelerator4x( "BlockCraftingAccelerator4x" ), BlockCraftingAccelerator16x( "BlockCraftingAccelerator16x" ), BlockCraftingMonitor( "BlockCraftingMonitor" ), + MEEnergyCell0("BlockEnergyCell0"), + MEEnergyCell1("BlockEnergyCell1"), + MEEnergyCell2("BlockEnergyCell2"), + MEEnergyCell3("BlockEnergyCell3"), + MEEnergyCell4("BlockEnergyCell4"), + MEEnergyCell5("BlockEnergyCell5"), + MEEnergyCell6("BlockEnergyCell6"), + MEEnergyCell7("BlockEnergyCell7"), - BlockCraftingStorage1k( "BlockCraftingStorage" ), BlockCraftingStorage4k( "BlockCraftingStorage4k" ), BlockCraftingStorage16k( "BlockCraftingStorage16k" ), BlockCraftingStorage64k( "BlockCraftingStorage64k" ), + BlockSpatialPylon_dim("BlockSpatialPylon_dim"), + BlockSpatialPylon_red("BlockSpatialPylon_red"), - BlockCraftingAcceleratorFit( "BlockCraftingAcceleratorFit" ), BlockCraftingAccelerator4xFit( "BlockCraftingAccelerator4xFit" ), BlockCraftingAccelerator16xFit( "BlockCraftingAccelerator16xFit" ), + BlockSpatialPylonC("BlockSpatialPylon_spanned"), + BlockSpatialPylonC_dim("BlockSpatialPylon_spanned_dim"), + BlockSpatialPylonC_red("BlockSpatialPylon_spanned_red"), - BlockCraftingMonitorFit_Light( "BlockCraftingMonitorFit_Light" ), BlockCraftingMonitorFit_Dark( "BlockCraftingMonitorFit_Dark" ), BlockCraftingMonitorFit_Medium( "BlockCraftingMonitorFit_Medium" ), + BlockQuartzGlassB("BlockQuartzGlassB"), + BlockQuartzGlassC("BlockQuartzGlassC"), + BlockQuartzGlassD("BlockQuartzGlassD"), - BlockCraftingStorage1kFit( "BlockCraftingStorageFit" ), BlockCraftingStorage4kFit( "BlockCraftingStorage4kFit" ), BlockCraftingStorage16kFit( "BlockCraftingStorage16kFit" ), BlockCraftingStorage64kFit( "BlockCraftingStorage64kFit" ), + BlockSpatialPylonE("BlockSpatialPylon_end"), + BlockSpatialPylonE_dim("BlockSpatialPylon_end_dim"), + BlockSpatialPylonE_red("BlockSpatialPylon_end_red"), - BlockCraftingUnitRing( "BlockCraftingUnitRing" ), BlockCraftingUnitRingLongRotated( "BlockCraftingUnitRingLongRotated" ), BlockCraftingUnitRingLong( "BlockCraftingUnitRingLong" ), BlockCraftingUnitFit( "BlockCraftingUnitFit" ), + BlockMESecurityOn_Light("BlockMESecurityOn_Light"), + BlockMESecurityOn_Medium("BlockMESecurityOn_Medium"), + BlockMESecurityOn_Dark("BlockMESecurityOn_Dark"), + BlockInscriberInside("BlockInscriberInside"), - BlockCraftingMonitorOuter( "BlockCraftingMonitorOuter" ), BlockCraftingFitSolid( "BlockCraftingFitSolid" ), + BlockQuartzGrowthAcceleratorOn("BlockQuartzGrowthAcceleratorOn"), + BlockQuartzGrowthAcceleratorSideOn("BlockQuartzGrowthAcceleratorSideOn"), - BlockPaint2( "BlockPaint2" ), BlockPaint3( "BlockPaint3" ); + BlockWirelessInside("BlockWirelessInside"), - private final String name; - private IIcon IIcon; + BlockCraftingAccelerator("BlockCraftingAccelerator"), + BlockCraftingAccelerator4x("BlockCraftingAccelerator4x"), + BlockCraftingAccelerator16x("BlockCraftingAccelerator16x"), + BlockCraftingMonitor("BlockCraftingMonitor"), - ExtraBlockTextures( final String name ) - { - this.name = name; - } + BlockCraftingStorage1k("BlockCraftingStorage"), + BlockCraftingStorage4k("BlockCraftingStorage4k"), + BlockCraftingStorage16k("BlockCraftingStorage16k"), + BlockCraftingStorage64k("BlockCraftingStorage64k"), - public static ResourceLocation GuiTexture( final String string ) - { - return new ResourceLocation( "appliedenergistics2", "textures/" + string ); - } + BlockCraftingAcceleratorFit("BlockCraftingAcceleratorFit"), + BlockCraftingAccelerator4xFit("BlockCraftingAccelerator4xFit"), + BlockCraftingAccelerator16xFit("BlockCraftingAccelerator16xFit"), - @SideOnly( Side.CLIENT ) - public static IIcon getMissing() - { - return ( (TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( TextureMap.locationBlocksTexture ) ).getAtlasSprite( "missingno" ); - } + BlockCraftingMonitorFit_Light("BlockCraftingMonitorFit_Light"), + BlockCraftingMonitorFit_Dark("BlockCraftingMonitorFit_Dark"), + BlockCraftingMonitorFit_Medium("BlockCraftingMonitorFit_Medium"), - public String getName() - { - return this.name; - } + BlockCraftingStorage1kFit("BlockCraftingStorageFit"), + BlockCraftingStorage4kFit("BlockCraftingStorage4kFit"), + BlockCraftingStorage16kFit("BlockCraftingStorage16kFit"), + BlockCraftingStorage64kFit("BlockCraftingStorage64kFit"), + + BlockCraftingUnitRing("BlockCraftingUnitRing"), + BlockCraftingUnitRingLongRotated("BlockCraftingUnitRingLongRotated"), + BlockCraftingUnitRingLong("BlockCraftingUnitRingLong"), + BlockCraftingUnitFit("BlockCraftingUnitFit"), + + BlockCraftingMonitorOuter("BlockCraftingMonitorOuter"), + BlockCraftingFitSolid("BlockCraftingFitSolid"), + + BlockPaint2("BlockPaint2"), + BlockPaint3("BlockPaint3"); + + private final String name; + private IIcon IIcon; - public IIcon getIcon() - { - return this.IIcon; - } + ExtraBlockTextures(final String name) { + this.name = name; + } - public void registerIcon( final TextureMap map ) - { - this.IIcon = map.registerIcon( "appliedenergistics2:" + this.name ); - } + public static ResourceLocation GuiTexture(final String string) { + return new ResourceLocation("appliedenergistics2", "textures/" + string); + } + + @SideOnly(Side.CLIENT) + public static IIcon getMissing() { + return ((TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture(TextureMap.locationBlocksTexture)) + .getAtlasSprite("missingno"); + } + + public String getName() { + return this.name; + } + + public IIcon getIcon() { + return this.IIcon; + } + + public void registerIcon(final TextureMap map) { + this.IIcon = map.registerIcon("appliedenergistics2:" + this.name); + } } diff --git a/src/main/java/appeng/client/texture/ExtraItemTextures.java b/src/main/java/appeng/client/texture/ExtraItemTextures.java index 0940d1251f7..9c55ebd7d22 100644 --- a/src/main/java/appeng/client/texture/ExtraItemTextures.java +++ b/src/main/java/appeng/client/texture/ExtraItemTextures.java @@ -18,7 +18,6 @@ package appeng.client.texture; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; @@ -26,48 +25,42 @@ import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; +public enum ExtraItemTextures { + White("White"), + ItemPaintBallShimmer("ItemPaintBallShimmer"), -public enum ExtraItemTextures -{ - White( "White" ), ItemPaintBallShimmer( "ItemPaintBallShimmer" ), - - ToolColorApplicatorTip_Medium( "ToolColorApplicatorTip_Medium" ), + ToolColorApplicatorTip_Medium("ToolColorApplicatorTip_Medium"), - ToolColorApplicatorTip_Dark( "ToolColorApplicatorTip_Dark" ), + ToolColorApplicatorTip_Dark("ToolColorApplicatorTip_Dark"), - ToolColorApplicatorTip_Light( "ToolColorApplicatorTip_Light" ); + ToolColorApplicatorTip_Light("ToolColorApplicatorTip_Light"); - private final String name; - private IIcon IIcon; + private final String name; + private IIcon IIcon; - ExtraItemTextures( final String name ) - { - this.name = name; - } + ExtraItemTextures(final String name) { + this.name = name; + } - public static ResourceLocation GuiTexture( final String string ) - { - return new ResourceLocation( "appliedenergistics2", "textures/" + string ); - } + public static ResourceLocation GuiTexture(final String string) { + return new ResourceLocation("appliedenergistics2", "textures/" + string); + } - @SideOnly( Side.CLIENT ) - public static IIcon getMissing() - { - return ( (TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( TextureMap.locationItemsTexture ) ).getAtlasSprite( "missingno" ); - } + @SideOnly(Side.CLIENT) + public static IIcon getMissing() { + return ((TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture(TextureMap.locationItemsTexture)) + .getAtlasSprite("missingno"); + } - public String getName() - { - return this.name; - } + public String getName() { + return this.name; + } - public IIcon getIcon() - { - return this.IIcon; - } + public IIcon getIcon() { + return this.IIcon; + } - public void registerIcon( final TextureMap map ) - { - this.IIcon = map.registerIcon( "appliedenergistics2:" + this.name ); - } + public void registerIcon(final TextureMap map) { + this.IIcon = map.registerIcon("appliedenergistics2:" + this.name); + } } diff --git a/src/main/java/appeng/client/texture/FlippableIcon.java b/src/main/java/appeng/client/texture/FlippableIcon.java index 836bf8faea7..eea8fc569ad 100644 --- a/src/main/java/appeng/client/texture/FlippableIcon.java +++ b/src/main/java/appeng/client/texture/FlippableIcon.java @@ -18,149 +18,120 @@ package appeng.client.texture; - -import net.minecraft.util.IIcon; - import javax.annotation.Nonnull; +import net.minecraft.util.IIcon; - -public class FlippableIcon implements IIcon -{ - - private IIcon original; - private boolean flip_u; - private boolean flip_v; - - public FlippableIcon( final IIcon o ) - { - if( o == null ) - { - throw new IllegalArgumentException( "Cannot create a wrapper icon with a null icon." ); - } - - this.setOriginal( o ); - this.setFlipU( false ); - this.setFlipV( false ); - } - - @Override - public int getIconWidth() - { - return this.getOriginal().getIconWidth(); - } - - @Override - public int getIconHeight() - { - return this.getOriginal().getIconHeight(); - } - - @Override - public float getMinU() - { - if( this.isFlipU() ) - { - return this.getOriginal().getMaxU(); - } - return this.getOriginal().getMinU(); - } - - @Override - public float getMaxU() - { - if( this.isFlipU() ) - { - return this.getOriginal().getMinU(); - } - return this.getOriginal().getMaxU(); - } - - @Override - public float getInterpolatedU( final double px ) - { - if( this.isFlipU() ) - { - return this.getOriginal().getInterpolatedU( 16 - px ); - } - return this.getOriginal().getInterpolatedU( px ); - } - - @Override - public float getMinV() - { - if( this.isFlipV() ) - { - return this.getOriginal().getMaxV(); - } - return this.getOriginal().getMinV(); - } - - @Override - public float getMaxV() - { - if( this.isFlipV() ) - { - return this.getOriginal().getMinV(); - } - return this.getOriginal().getMaxV(); - } - - @Override - public float getInterpolatedV( final double px ) - { - if( this.isFlipV() ) - { - return this.getOriginal().getInterpolatedV( 16 - px ); - } - return this.getOriginal().getInterpolatedV( px ); - } - - @Override - public String getIconName() - { - return this.getOriginal().getIconName(); - } - - public IIcon getOriginal() - { - return this.original; - } - - public void setFlip( final boolean u, final boolean v ) - { - this.setFlipU( u ); - this.setFlipV( v ); - } - - public int setFlip( final int orientation ) - { - this.setFlipU( ( orientation & 8 ) == 8 ); - this.setFlipV( ( orientation & 16 ) == 16 ); - return orientation & 7; - } - - boolean isFlipU() - { - return this.flip_u; - } - - void setFlipU( final boolean flipU ) - { - this.flip_u = flipU; - } - - boolean isFlipV() - { - return this.flip_v; - } - - void setFlipV( final boolean flipV ) - { - this.flip_v = flipV; - } - - public void setOriginal( @Nonnull final IIcon original ) - { - this.original = original; - } +public class FlippableIcon implements IIcon { + + private IIcon original; + private boolean flip_u; + private boolean flip_v; + + public FlippableIcon(final IIcon o) { + if (o == null) { + throw new IllegalArgumentException("Cannot create a wrapper icon with a null icon."); + } + + this.setOriginal(o); + this.setFlipU(false); + this.setFlipV(false); + } + + @Override + public int getIconWidth() { + return this.getOriginal().getIconWidth(); + } + + @Override + public int getIconHeight() { + return this.getOriginal().getIconHeight(); + } + + @Override + public float getMinU() { + if (this.isFlipU()) { + return this.getOriginal().getMaxU(); + } + return this.getOriginal().getMinU(); + } + + @Override + public float getMaxU() { + if (this.isFlipU()) { + return this.getOriginal().getMinU(); + } + return this.getOriginal().getMaxU(); + } + + @Override + public float getInterpolatedU(final double px) { + if (this.isFlipU()) { + return this.getOriginal().getInterpolatedU(16 - px); + } + return this.getOriginal().getInterpolatedU(px); + } + + @Override + public float getMinV() { + if (this.isFlipV()) { + return this.getOriginal().getMaxV(); + } + return this.getOriginal().getMinV(); + } + + @Override + public float getMaxV() { + if (this.isFlipV()) { + return this.getOriginal().getMinV(); + } + return this.getOriginal().getMaxV(); + } + + @Override + public float getInterpolatedV(final double px) { + if (this.isFlipV()) { + return this.getOriginal().getInterpolatedV(16 - px); + } + return this.getOriginal().getInterpolatedV(px); + } + + @Override + public String getIconName() { + return this.getOriginal().getIconName(); + } + + public IIcon getOriginal() { + return this.original; + } + + public void setFlip(final boolean u, final boolean v) { + this.setFlipU(u); + this.setFlipV(v); + } + + public int setFlip(final int orientation) { + this.setFlipU((orientation & 8) == 8); + this.setFlipV((orientation & 16) == 16); + return orientation & 7; + } + + boolean isFlipU() { + return this.flip_u; + } + + void setFlipU(final boolean flipU) { + this.flip_u = flipU; + } + + boolean isFlipV() { + return this.flip_v; + } + + void setFlipV(final boolean flipV) { + this.flip_v = flipV; + } + + public void setOriginal(@Nonnull final IIcon original) { + this.original = original; + } } diff --git a/src/main/java/appeng/client/texture/FullIcon.java b/src/main/java/appeng/client/texture/FullIcon.java index 2cd2267af01..a372a31b084 100644 --- a/src/main/java/appeng/client/texture/FullIcon.java +++ b/src/main/java/appeng/client/texture/FullIcon.java @@ -18,93 +18,77 @@ package appeng.client.texture; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.util.IIcon; - -public class FullIcon implements IIcon -{ - - private final IIcon p; - - public FullIcon( final IIcon o ) - { - if( o == null ) - { - throw new IllegalArgumentException( "Cannot create a wrapper icon with a null icon." ); - } - - this.p = o; - } - - @Override - public int getIconWidth() - { - return this.p.getIconWidth(); - } - - @Override - public int getIconHeight() - { - return this.p.getIconHeight(); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getMinU() - { - return this.p.getMinU(); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getMaxU() - { - return this.p.getMaxU(); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getInterpolatedU( final double d0 ) - { - if( d0 > 8.0 ) - { - return this.p.getMaxU(); - } - return this.p.getMinU(); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getMinV() - { - return this.p.getMinV(); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getMaxV() - { - return this.p.getMaxV(); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getInterpolatedV( final double d0 ) - { - if( d0 > 8.0 ) - { - return this.p.getMaxV(); - } - return this.p.getMinV(); - } - - @Override - @SideOnly( Side.CLIENT ) - public String getIconName() - { - return this.p.getIconName(); - } +public class FullIcon implements IIcon { + + private final IIcon p; + + public FullIcon(final IIcon o) { + if (o == null) { + throw new IllegalArgumentException("Cannot create a wrapper icon with a null icon."); + } + + this.p = o; + } + + @Override + public int getIconWidth() { + return this.p.getIconWidth(); + } + + @Override + public int getIconHeight() { + return this.p.getIconHeight(); + } + + @Override + @SideOnly(Side.CLIENT) + public float getMinU() { + return this.p.getMinU(); + } + + @Override + @SideOnly(Side.CLIENT) + public float getMaxU() { + return this.p.getMaxU(); + } + + @Override + @SideOnly(Side.CLIENT) + public float getInterpolatedU(final double d0) { + if (d0 > 8.0) { + return this.p.getMaxU(); + } + return this.p.getMinU(); + } + + @Override + @SideOnly(Side.CLIENT) + public float getMinV() { + return this.p.getMinV(); + } + + @Override + @SideOnly(Side.CLIENT) + public float getMaxV() { + return this.p.getMaxV(); + } + + @Override + @SideOnly(Side.CLIENT) + public float getInterpolatedV(final double d0) { + if (d0 > 8.0) { + return this.p.getMaxV(); + } + return this.p.getMinV(); + } + + @Override + @SideOnly(Side.CLIENT) + public String getIconName() { + return this.p.getIconName(); + } } diff --git a/src/main/java/appeng/client/texture/MissingIcon.java b/src/main/java/appeng/client/texture/MissingIcon.java index 68f5eeb1cda..9d619f207f5 100644 --- a/src/main/java/appeng/client/texture/MissingIcon.java +++ b/src/main/java/appeng/client/texture/MissingIcon.java @@ -18,7 +18,6 @@ package appeng.client.texture; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; @@ -26,74 +25,64 @@ import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.IIcon; - -public class MissingIcon implements IIcon -{ - - private final boolean isBlock; - - public MissingIcon( final Object forWhat ) - { - this.isBlock = forWhat instanceof Block; - } - - @Override - public int getIconWidth() - { - return this.getMissing().getIconWidth(); - } - - @SideOnly( Side.CLIENT ) - private IIcon getMissing() - { - return ( (TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( this.isBlock ? TextureMap.locationBlocksTexture : TextureMap.locationItemsTexture ) ).getAtlasSprite( "missingno" ); - } - - @Override - public int getIconHeight() - { - return this.getMissing().getIconHeight(); - } - - @Override - public float getMinU() - { - return this.getMissing().getMinU(); - } - - @Override - public float getMaxU() - { - return this.getMissing().getMaxU(); - } - - @Override - public float getInterpolatedU( final double var1 ) - { - return this.getMissing().getInterpolatedU( var1 ); - } - - @Override - public float getMinV() - { - return this.getMissing().getMinV(); - } - - @Override - public float getMaxV() - { - return this.getMissing().getMaxV(); - } - - @Override - public float getInterpolatedV( final double var1 ) - { - return this.getMissing().getInterpolatedV( var1 ); - } - - @Override - public String getIconName() - { - return this.getMissing().getIconName(); - } +public class MissingIcon implements IIcon { + + private final boolean isBlock; + + public MissingIcon(final Object forWhat) { + this.isBlock = forWhat instanceof Block; + } + + @Override + public int getIconWidth() { + return this.getMissing().getIconWidth(); + } + + @SideOnly(Side.CLIENT) + private IIcon getMissing() { + return ((TextureMap) Minecraft.getMinecraft() + .getTextureManager() + .getTexture(this.isBlock ? TextureMap.locationBlocksTexture : TextureMap.locationItemsTexture)) + .getAtlasSprite("missingno"); + } + + @Override + public int getIconHeight() { + return this.getMissing().getIconHeight(); + } + + @Override + public float getMinU() { + return this.getMissing().getMinU(); + } + + @Override + public float getMaxU() { + return this.getMissing().getMaxU(); + } + + @Override + public float getInterpolatedU(final double var1) { + return this.getMissing().getInterpolatedU(var1); + } + + @Override + public float getMinV() { + return this.getMissing().getMinV(); + } + + @Override + public float getMaxV() { + return this.getMissing().getMaxV(); + } + + @Override + public float getInterpolatedV(final double var1) { + return this.getMissing().getInterpolatedV(var1); + } + + @Override + public String getIconName() { + return this.getMissing().getIconName(); + } } diff --git a/src/main/java/appeng/client/texture/OffsetIcon.java b/src/main/java/appeng/client/texture/OffsetIcon.java index 1f0fcd2a28a..6c384feb30c 100644 --- a/src/main/java/appeng/client/texture/OffsetIcon.java +++ b/src/main/java/appeng/client/texture/OffsetIcon.java @@ -18,100 +18,84 @@ package appeng.client.texture; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.util.IIcon; - -public class OffsetIcon implements IIcon -{ - - private final float offsetX; - private final float offsetY; - - private final IIcon p; - - public OffsetIcon( final IIcon o, final float x, final float y ) - { - if( o == null ) - { - throw new IllegalArgumentException( "Cannot create a wrapper icon with a null icon." ); - } - - this.p = o; - this.offsetX = x; - this.offsetY = y; - } - - @Override - public int getIconWidth() - { - return this.p.getIconWidth(); - } - - @Override - public int getIconHeight() - { - return this.p.getIconHeight(); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getMinU() - { - return this.u( 0 - this.offsetX ); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getMaxU() - { - return this.u( 16 - this.offsetX ); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getInterpolatedU( final double d0 ) - { - return this.u( d0 - this.offsetX ); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getMinV() - { - return this.v( 0 - this.offsetY ); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getMaxV() - { - return this.v( 16 - this.offsetY ); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getInterpolatedV( final double d0 ) - { - return this.v( d0 - this.offsetY ); - } - - @Override - @SideOnly( Side.CLIENT ) - public String getIconName() - { - return this.p.getIconName(); - } - - private float v( final double d ) - { - return this.p.getInterpolatedV( Math.min( 16.0, Math.max( 0.0, d ) ) ); - } - - private float u( final double d ) - { - return this.p.getInterpolatedU( Math.min( 16.0, Math.max( 0.0, d ) ) ); - } +public class OffsetIcon implements IIcon { + + private final float offsetX; + private final float offsetY; + + private final IIcon p; + + public OffsetIcon(final IIcon o, final float x, final float y) { + if (o == null) { + throw new IllegalArgumentException("Cannot create a wrapper icon with a null icon."); + } + + this.p = o; + this.offsetX = x; + this.offsetY = y; + } + + @Override + public int getIconWidth() { + return this.p.getIconWidth(); + } + + @Override + public int getIconHeight() { + return this.p.getIconHeight(); + } + + @Override + @SideOnly(Side.CLIENT) + public float getMinU() { + return this.u(0 - this.offsetX); + } + + @Override + @SideOnly(Side.CLIENT) + public float getMaxU() { + return this.u(16 - this.offsetX); + } + + @Override + @SideOnly(Side.CLIENT) + public float getInterpolatedU(final double d0) { + return this.u(d0 - this.offsetX); + } + + @Override + @SideOnly(Side.CLIENT) + public float getMinV() { + return this.v(0 - this.offsetY); + } + + @Override + @SideOnly(Side.CLIENT) + public float getMaxV() { + return this.v(16 - this.offsetY); + } + + @Override + @SideOnly(Side.CLIENT) + public float getInterpolatedV(final double d0) { + return this.v(d0 - this.offsetY); + } + + @Override + @SideOnly(Side.CLIENT) + public String getIconName() { + return this.p.getIconName(); + } + + private float v(final double d) { + return this.p.getInterpolatedV(Math.min(16.0, Math.max(0.0, d))); + } + + private float u(final double d) { + return this.p.getInterpolatedU(Math.min(16.0, Math.max(0.0, d))); + } } diff --git a/src/main/java/appeng/client/texture/TaughtIcon.java b/src/main/java/appeng/client/texture/TaughtIcon.java index f9d0c8e1492..4de9c80dd74 100644 --- a/src/main/java/appeng/client/texture/TaughtIcon.java +++ b/src/main/java/appeng/client/texture/TaughtIcon.java @@ -18,114 +18,94 @@ package appeng.client.texture; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.util.IIcon; - -public class TaughtIcon implements IIcon -{ - - private final float tightness; - - private final IIcon icon; - - public TaughtIcon( final IIcon icon, final float tightness ) - { - if( icon == null ) - { - throw new IllegalArgumentException( "Cannot create a wrapper icon with a null icon." ); - } - - this.icon = icon; - this.tightness = tightness * 0.4f; - } - - @Override - public int getIconWidth() - { - return this.icon.getIconWidth(); - } - - @Override - public int getIconHeight() - { - return this.icon.getIconHeight(); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getMinU() - { - return this.u( 0 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getMaxU() - { - return this.u( 16 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getInterpolatedU( final double d0 ) - { - return this.u( d0 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getMinV() - { - return this.v( 0 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getMaxV() - { - return this.v( 16 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getInterpolatedV( final double d0 ) - { - return this.v( d0 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public String getIconName() - { - return this.icon.getIconName(); - } - - private float v( double d ) - { - if( d < 8 ) - { - d -= this.tightness; - } - if( d > 8 ) - { - d += this.tightness; - } - return this.icon.getInterpolatedV( Math.min( 16.0, Math.max( 0.0, d ) ) ); - } - - private float u( double d ) - { - if( d < 8 ) - { - d -= this.tightness; - } - if( d > 8 ) - { - d += this.tightness; - } - return this.icon.getInterpolatedU( Math.min( 16.0, Math.max( 0.0, d ) ) ); - } +public class TaughtIcon implements IIcon { + + private final float tightness; + + private final IIcon icon; + + public TaughtIcon(final IIcon icon, final float tightness) { + if (icon == null) { + throw new IllegalArgumentException("Cannot create a wrapper icon with a null icon."); + } + + this.icon = icon; + this.tightness = tightness * 0.4f; + } + + @Override + public int getIconWidth() { + return this.icon.getIconWidth(); + } + + @Override + public int getIconHeight() { + return this.icon.getIconHeight(); + } + + @Override + @SideOnly(Side.CLIENT) + public float getMinU() { + return this.u(0); + } + + @Override + @SideOnly(Side.CLIENT) + public float getMaxU() { + return this.u(16); + } + + @Override + @SideOnly(Side.CLIENT) + public float getInterpolatedU(final double d0) { + return this.u(d0); + } + + @Override + @SideOnly(Side.CLIENT) + public float getMinV() { + return this.v(0); + } + + @Override + @SideOnly(Side.CLIENT) + public float getMaxV() { + return this.v(16); + } + + @Override + @SideOnly(Side.CLIENT) + public float getInterpolatedV(final double d0) { + return this.v(d0); + } + + @Override + @SideOnly(Side.CLIENT) + public String getIconName() { + return this.icon.getIconName(); + } + + private float v(double d) { + if (d < 8) { + d -= this.tightness; + } + if (d > 8) { + d += this.tightness; + } + return this.icon.getInterpolatedV(Math.min(16.0, Math.max(0.0, d))); + } + + private float u(double d) { + if (d < 8) { + d -= this.tightness; + } + if (d > 8) { + d += this.tightness; + } + return this.icon.getInterpolatedU(Math.min(16.0, Math.max(0.0, d))); + } } diff --git a/src/main/java/appeng/client/texture/TmpFlippableIcon.java b/src/main/java/appeng/client/texture/TmpFlippableIcon.java index 07789ffa743..bef860efad4 100644 --- a/src/main/java/appeng/client/texture/TmpFlippableIcon.java +++ b/src/main/java/appeng/client/texture/TmpFlippableIcon.java @@ -18,49 +18,38 @@ package appeng.client.texture; - import net.minecraft.init.Blocks; import net.minecraft.util.IIcon; +public class TmpFlippableIcon extends FlippableIcon { -public class TmpFlippableIcon extends FlippableIcon -{ - - private static final IIcon NULL_ICON = new MissingIcon( Blocks.diamond_block ); + private static final IIcon NULL_ICON = new MissingIcon(Blocks.diamond_block); - public TmpFlippableIcon() - { - super( NULL_ICON ); - } + public TmpFlippableIcon() { + super(NULL_ICON); + } - @Override - public void setOriginal( IIcon i ) - { - this.setFlip( false, false ); + @Override + public void setOriginal(IIcon i) { + this.setFlip(false, false); - while( i instanceof FlippableIcon ) - { - final FlippableIcon fi = (FlippableIcon) i; - if( fi.isFlipU() ) - { - this.setFlipU( !this.isFlipU() ); - } + while (i instanceof FlippableIcon) { + final FlippableIcon fi = (FlippableIcon) i; + if (fi.isFlipU()) { + this.setFlipU(!this.isFlipU()); + } - if( fi.isFlipV() ) - { - this.setFlipV( !this.isFlipV() ); - } + if (fi.isFlipV()) { + this.setFlipV(!this.isFlipV()); + } - i = fi.getOriginal(); - } + i = fi.getOriginal(); + } - if( i == null ) - { - super.setOriginal( NULL_ICON ); - } - else - { - super.setOriginal( i ); - } - } + if (i == null) { + super.setOriginal(NULL_ICON); + } else { + super.setOriginal(i); + } + } } diff --git a/src/main/java/appeng/container/AEBaseContainer.java b/src/main/java/appeng/container/AEBaseContainer.java index c69a74564f0..32c66d96d33 100644 --- a/src/main/java/appeng/container/AEBaseContainer.java +++ b/src/main/java/appeng/container/AEBaseContainer.java @@ -18,7 +18,6 @@ package appeng.container; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.SecurityPermissions; @@ -50,6 +49,11 @@ import appeng.util.Platform; import appeng.util.inv.AdaptorPlayerHand; import appeng.util.item.AEItemStack; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.*; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; @@ -64,1278 +68,1037 @@ import net.minecraftforge.common.util.ForgeDirection; import org.apache.commons.lang3.ArrayUtils; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.*; +public abstract class AEBaseContainer extends Container { + + private final InventoryPlayer invPlayer; + private final BaseActionSource mySrc; + private final HashSet locked = new HashSet(); + private final TileEntity tileEntity; + private final IPart part; + private final IGuiItemObject obj; + private final List dataChunks = new LinkedList(); + private final HashMap syncData = new HashMap(); + private boolean isContainerValid = true; + private String customName; + private ContainerOpenContext openContext; + private IMEInventoryHandler cellInv; + private IEnergySource powerSrc; + private boolean sentCustomName; + private int ticksSinceCheck = 900; + private IAEItemStack clientRequestedTargetItem = null; + + public AEBaseContainer(final InventoryPlayer ip, final TileEntity myTile, final IPart myPart) { + this(ip, myTile, myPart, null); + } + public AEBaseContainer( + final InventoryPlayer ip, final TileEntity myTile, final IPart myPart, final IGuiItemObject gio) { + this.invPlayer = ip; + this.tileEntity = myTile; + this.part = myPart; + this.obj = gio; + this.mySrc = new PlayerSource(ip.player, this.getActionHost()); + this.prepareSync(); + } -public abstract class AEBaseContainer extends Container -{ - - private final InventoryPlayer invPlayer; - private final BaseActionSource mySrc; - private final HashSet locked = new HashSet(); - private final TileEntity tileEntity; - private final IPart part; - private final IGuiItemObject obj; - private final List dataChunks = new LinkedList(); - private final HashMap syncData = new HashMap(); - private boolean isContainerValid = true; - private String customName; - private ContainerOpenContext openContext; - private IMEInventoryHandler cellInv; - private IEnergySource powerSrc; - private boolean sentCustomName; - private int ticksSinceCheck = 900; - private IAEItemStack clientRequestedTargetItem = null; - - public AEBaseContainer( final InventoryPlayer ip, final TileEntity myTile, final IPart myPart ) - { - this( ip, myTile, myPart, null ); - } - - public AEBaseContainer( final InventoryPlayer ip, final TileEntity myTile, final IPart myPart, final IGuiItemObject gio ) - { - this.invPlayer = ip; - this.tileEntity = myTile; - this.part = myPart; - this.obj = gio; - this.mySrc = new PlayerSource( ip.player, this.getActionHost() ); - this.prepareSync(); - } - - protected IActionHost getActionHost() - { - if( this.obj instanceof IActionHost ) - { - return (IActionHost) this.obj; - } - - if( this.tileEntity instanceof IActionHost ) - { - return (IActionHost) this.tileEntity; - } - - if( this.part instanceof IActionHost ) - { - return (IActionHost) this.part; - } - - return null; - } - - private void prepareSync() - { - walkSyncFields( 0, this.getClass().getFields(), new Field[0] ); - } + protected IActionHost getActionHost() { + if (this.obj instanceof IActionHost) { + return (IActionHost) this.obj; + } + + if (this.tileEntity instanceof IActionHost) { + return (IActionHost) this.tileEntity; + } + + if (this.part instanceof IActionHost) { + return (IActionHost) this.part; + } + + return null; + } + + private void prepareSync() { + walkSyncFields(0, this.getClass().getFields(), new Field[0]); + } private void walkSyncFields(int offset, final Field[] fields, final Field[] currentIndirections) { - for( final Field f : fields ) - { - if (f.isAnnotationPresent( GuiSync.Recurse.class )) - { - final GuiSync.Recurse annotation = f.getAnnotation( GuiSync.Recurse.class ); - walkSyncFields( offset + annotation.value(), f.getType().getFields(), ArrayUtils.add( currentIndirections, f ) ); + for (final Field f : fields) { + if (f.isAnnotationPresent(GuiSync.Recurse.class)) { + final GuiSync.Recurse annotation = f.getAnnotation(GuiSync.Recurse.class); + walkSyncFields( + offset + annotation.value(), f.getType().getFields(), ArrayUtils.add(currentIndirections, f)); } - if( f.isAnnotationPresent( GuiSync.class ) ) - { - final GuiSync annotation = f.getAnnotation( GuiSync.class ); + if (f.isAnnotationPresent(GuiSync.class)) { + final GuiSync annotation = f.getAnnotation(GuiSync.class); final int channel = offset + annotation.value(); - if( this.syncData.containsKey( channel ) ) - { - AELog.warn( "Channel already in use: " + channel + " for " + f.getName() ); + if (this.syncData.containsKey(channel)) { + AELog.warn("Channel already in use: " + channel + " for " + f.getName()); + } else { + this.syncData.put(channel, new SyncData(this, currentIndirections, f, channel)); + } + } + } + } + + public AEBaseContainer(final InventoryPlayer ip, final Object anchor) { + this.invPlayer = ip; + this.tileEntity = anchor instanceof TileEntity ? (TileEntity) anchor : null; + this.part = anchor instanceof IPart ? (IPart) anchor : null; + this.obj = anchor instanceof IGuiItemObject ? (IGuiItemObject) anchor : null; + + if (this.tileEntity == null && this.part == null && this.obj == null) { + throw new IllegalArgumentException("Must have a valid anchor, instead " + anchor + " in " + ip); + } + + this.mySrc = new PlayerSource(ip.player, this.getActionHost()); + + this.prepareSync(); + } + + public void postPartial(final PacketPartialItem packetPartialItem) { + this.dataChunks.add(packetPartialItem); + if (packetPartialItem.getPageCount() == this.dataChunks.size()) { + this.parsePartials(); + } + } + + private void parsePartials() { + int total = 0; + for (final PacketPartialItem ppi : this.dataChunks) { + total += ppi.getSize(); + } + + final byte[] buffer = new byte[total]; + int cursor = 0; + + for (final PacketPartialItem ppi : this.dataChunks) { + cursor = ppi.write(buffer, cursor); + } + + try { + final NBTTagCompound data = CompressedStreamTools.readCompressed(new ByteArrayInputStream(buffer)); + if (data != null) { + this.setTargetStack(AEApi.instance().storage().createItemStack(ItemStack.loadItemStackFromNBT(data))); + } + } catch (final IOException e) { + AELog.debug(e); + } + + this.dataChunks.clear(); + } + + public IAEItemStack getTargetStack() { + return this.clientRequestedTargetItem; + } + + public void setTargetStack(final IAEItemStack stack) { + // client doesn't need to re-send, makes for lower overhead rapid packets. + if (Platform.isClient()) { + final ItemStack a = stack == null ? null : stack.getItemStack(); + final ItemStack b = + this.clientRequestedTargetItem == null ? null : this.clientRequestedTargetItem.getItemStack(); + + if (Platform.isSameItemPrecise(a, b)) { + return; + } + + final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + final NBTTagCompound item = new NBTTagCompound(); + + if (stack != null) { + stack.writeToNBT(item); + } + + try { + CompressedStreamTools.writeCompressed(item, stream); + + final int maxChunkSize = 30000; + final List miniPackets = new LinkedList(); + + final byte[] data = stream.toByteArray(); + + final ByteArrayInputStream bis = new ByteArrayInputStream(data, 0, stream.size()); + while (bis.available() > 0) { + final int nextBLock = bis.available() > maxChunkSize ? maxChunkSize : bis.available(); + final byte[] nextSegment = new byte[nextBLock]; + bis.read(nextSegment); + miniPackets.add(nextSegment); } - else - { - this.syncData.put( channel, new SyncData( this, currentIndirections, f, channel ) ); + bis.close(); + stream.close(); + + int page = 0; + for (final byte[] packet : miniPackets) { + final PacketPartialItem ppi = new PacketPartialItem(page, miniPackets.size(), packet); + page++; + NetworkHandler.instance.sendToServer(ppi); } + } catch (final IOException e) { + AELog.debug(e); + return; } } + + this.clientRequestedTargetItem = stack == null ? null : stack.copy(); } - public AEBaseContainer( final InventoryPlayer ip, final Object anchor ) - { - this.invPlayer = ip; - this.tileEntity = anchor instanceof TileEntity ? (TileEntity) anchor : null; - this.part = anchor instanceof IPart ? (IPart) anchor : null; - this.obj = anchor instanceof IGuiItemObject ? (IGuiItemObject) anchor : null; - - if( this.tileEntity == null && this.part == null && this.obj == null ) - { - throw new IllegalArgumentException( "Must have a valid anchor, instead " + anchor + " in " + ip ); - } - - this.mySrc = new PlayerSource( ip.player, this.getActionHost() ); - - this.prepareSync(); - } - - public void postPartial( final PacketPartialItem packetPartialItem ) - { - this.dataChunks.add( packetPartialItem ); - if( packetPartialItem.getPageCount() == this.dataChunks.size() ) - { - this.parsePartials(); - } - } - - private void parsePartials() - { - int total = 0; - for( final PacketPartialItem ppi : this.dataChunks ) - { - total += ppi.getSize(); - } - - final byte[] buffer = new byte[total]; - int cursor = 0; - - for( final PacketPartialItem ppi : this.dataChunks ) - { - cursor = ppi.write( buffer, cursor ); - } - - try - { - final NBTTagCompound data = CompressedStreamTools.readCompressed( new ByteArrayInputStream( buffer ) ); - if( data != null ) - { - this.setTargetStack( AEApi.instance().storage().createItemStack( ItemStack.loadItemStackFromNBT( data ) ) ); - } - } - catch( final IOException e ) - { - AELog.debug( e ); - } - - this.dataChunks.clear(); - } - - public IAEItemStack getTargetStack() - { - return this.clientRequestedTargetItem; - } - - public void setTargetStack( final IAEItemStack stack ) - { - // client doesn't need to re-send, makes for lower overhead rapid packets. - if( Platform.isClient() ) - { - final ItemStack a = stack == null ? null : stack.getItemStack(); - final ItemStack b = this.clientRequestedTargetItem == null ? null : this.clientRequestedTargetItem.getItemStack(); - - if( Platform.isSameItemPrecise( a, b ) ) - { - return; - } - - final ByteArrayOutputStream stream = new ByteArrayOutputStream(); - final NBTTagCompound item = new NBTTagCompound(); - - if( stack != null ) - { - stack.writeToNBT( item ); - } - - try - { - CompressedStreamTools.writeCompressed( item, stream ); - - final int maxChunkSize = 30000; - final List miniPackets = new LinkedList(); - - final byte[] data = stream.toByteArray(); - - final ByteArrayInputStream bis = new ByteArrayInputStream( data, 0, stream.size() ); - while( bis.available() > 0 ) - { - final int nextBLock = bis.available() > maxChunkSize ? maxChunkSize : bis.available(); - final byte[] nextSegment = new byte[nextBLock]; - bis.read( nextSegment ); - miniPackets.add( nextSegment ); - } - bis.close(); - stream.close(); - - int page = 0; - for( final byte[] packet : miniPackets ) - { - final PacketPartialItem ppi = new PacketPartialItem( page, miniPackets.size(), packet ); - page++; - NetworkHandler.instance.sendToServer( ppi ); - } - } - catch( final IOException e ) - { - AELog.debug( e ); - return; - } - } - - this.clientRequestedTargetItem = stack == null ? null : stack.copy(); - } - - public BaseActionSource getActionSource() - { - return this.mySrc; - } - - public void verifyPermissions( final SecurityPermissions security, final boolean requirePower ) - { - if( Platform.isClient() ) - { - return; - } - - this.ticksSinceCheck++; - if( this.ticksSinceCheck < 20 ) - { - return; - } - - this.ticksSinceCheck = 0; - this.setValidContainer( this.isValidContainer() && this.hasAccess( security, requirePower ) ); - } - - protected boolean hasAccess( final SecurityPermissions perm, final boolean requirePower ) - { - final IActionHost host = this.getActionHost(); - - if( host != null ) - { - final IGridNode gn = host.getActionableNode(); - if( gn != null ) - { - final IGrid g = gn.getGrid(); - if( g != null ) - { - if( requirePower ) - { - final IEnergyGrid eg = g.getCache( IEnergyGrid.class ); - if( !eg.isNetworkPowered() ) - { - return false; - } - } - - final ISecurityGrid sg = g.getCache( ISecurityGrid.class ); - if( sg.hasPermission( this.getInventoryPlayer().player, perm ) ) - { - return true; - } - } - } - } - - return false; - } - - public void lockPlayerInventorySlot( final int idx ) - { - this.locked.add( idx ); - } - - public Object getTarget() - { - if( this.tileEntity != null ) - { - return this.tileEntity; - } - if( this.part != null ) - { - return this.part; - } - if( this.obj != null ) - { - return this.obj; - } - return null; - } - - public InventoryPlayer getPlayerInv() - { - return this.getInventoryPlayer(); - } - - public TileEntity getTileEntity() - { - return this.tileEntity; - } - - public final void updateFullProgressBar( final int idx, final long value ) - { - if( this.syncData.containsKey( idx ) ) - { - this.syncData.get( idx ).update( value ); - return; - } - - this.updateProgressBar( idx, (int) value ); - } - - public void stringSync( final int idx, final String value ) - { - if( this.syncData.containsKey( idx ) ) - { - this.syncData.get( idx ).update( value ); - } - } - - protected void bindPlayerInventory( final InventoryPlayer inventoryPlayer, final int offsetX, final int offsetY ) - { - // bind player inventory - for( int i = 0; i < 3; i++ ) - { - for( int j = 0; j < 9; j++ ) - { - if( this.locked.contains( j + i * 9 + 9 ) ) - { - this.addSlotToContainer( new SlotDisabled( inventoryPlayer, j + i * 9 + 9, 8 + j * 18 + offsetX, offsetY + i * 18 ) ); - } - else - { - this.addSlotToContainer( new SlotPlayerInv( inventoryPlayer, j + i * 9 + 9, 8 + j * 18 + offsetX, offsetY + i * 18 ) ); - } - } - } - - // bind player hotbar - for( int i = 0; i < 9; i++ ) - { - if( this.locked.contains( i ) ) - { - this.addSlotToContainer( new SlotDisabled( inventoryPlayer, i, 8 + i * 18 + offsetX, 58 + offsetY ) ); - } - else - { - this.addSlotToContainer( new SlotPlayerHotBar( inventoryPlayer, i, 8 + i * 18 + offsetX, 58 + offsetY ) ); - } - } - } - - @Override - protected Slot addSlotToContainer( final Slot newSlot ) - { - if( newSlot instanceof AppEngSlot ) - { - final AppEngSlot s = (AppEngSlot) newSlot; - s.setContainer( this ); - return super.addSlotToContainer( newSlot ); - } - else - { - throw new IllegalArgumentException( "Invalid Slot [" + newSlot + "]for AE Container instead of AppEngSlot." ); - } - } - - @Override - public void detectAndSendChanges() - { - this.sendCustomName(); - - if( Platform.isServer() ) - { - for( final Object crafter : this.crafters ) - { - final ICrafting icrafting = (ICrafting) crafter; - - for( final SyncData sd : this.syncData.values() ) - { - sd.tick( icrafting ); - } - } - } - - super.detectAndSendChanges(); - } - - @Override - public ItemStack transferStackInSlot( final EntityPlayer p, final int idx ) - { - if( Platform.isClient() ) - { - return null; - } - - boolean hasMETiles = false; - for( final Object is : this.inventorySlots ) - { - if( is instanceof InternalSlotME ) - { - hasMETiles = true; - break; - } - } - - if( hasMETiles && Platform.isClient() ) - { - return null; - } - - final AppEngSlot clickSlot = (AppEngSlot) this.inventorySlots.get( idx ); // require AE SLots! - - if( clickSlot instanceof SlotDisabled || clickSlot instanceof SlotInaccessible ) - { - return null; - } - if( clickSlot != null && clickSlot.getHasStack() ) - { - ItemStack tis = clickSlot.getStack(); - - if( tis == null ) - { - return null; - } - - final List selectedSlots = new ArrayList(); - - /** - * Gather a list of valid destinations. - */ - if( clickSlot.isPlayerSide() ) - { - tis = this.shiftStoreItem( tis ); - - // target slots in the container... - for( final Object inventorySlot : this.inventorySlots ) - { - final AppEngSlot cs = (AppEngSlot) inventorySlot; - - if( !( cs.isPlayerSide() ) && !( cs instanceof SlotFake ) && !( cs instanceof SlotCraftingMatrix ) ) - { - if( cs.isItemValid( tis ) ) - { - selectedSlots.add( cs ); - } - } - } - } - else - { - // target slots in the container... - for( final Object inventorySlot : this.inventorySlots ) - { - final AppEngSlot cs = (AppEngSlot) inventorySlot; - - if( ( cs.isPlayerSide() ) && !( cs instanceof SlotFake ) && !( cs instanceof SlotCraftingMatrix ) ) - { - if( cs.isItemValid( tis ) ) - { - selectedSlots.add( cs ); - } - } - } - } - - /** - * Handle Fake Slot Shift clicking. - */ - if( selectedSlots.isEmpty() && clickSlot.isPlayerSide() ) - { - if( tis != null ) - { - // target slots in the container... - for( final Object inventorySlot : this.inventorySlots ) - { - final AppEngSlot cs = (AppEngSlot) inventorySlot; - final ItemStack destination = cs.getStack(); - - if( !( cs.isPlayerSide() ) && cs instanceof SlotFake ) - { - if( Platform.isSameItemPrecise( destination, tis ) ) - { - break; - } - else if( destination == null ) - { - cs.putStack( tis.copy() ); - cs.onSlotChanged(); - this.updateSlot( cs ); - break; - } - } - } - } - } - - if( tis != null ) - { - // find partials.. - for( final Slot d : selectedSlots ) - { - if( d instanceof SlotDisabled || d instanceof SlotME ) - { - continue; - } - - if( d.isItemValid( tis ) ) - { - if( d.getHasStack() ) - { - final ItemStack t = d.getStack(); - - if( Platform.isSameItemPrecise( tis, t ) ) // t.isItemEqual(tis)) - { - int maxSize = t.getMaxStackSize(); - if( maxSize > d.getSlotStackLimit() ) - { - maxSize = d.getSlotStackLimit(); - } - - int placeAble = maxSize - t.stackSize; - - if( tis.stackSize < placeAble ) - { - placeAble = tis.stackSize; - } - - t.stackSize += placeAble; - tis.stackSize -= placeAble; - - if( tis.stackSize <= 0 ) - { - clickSlot.putStack( null ); - d.onSlotChanged(); - - // if ( hasMETiles ) updateClient(); - - this.updateSlot( clickSlot ); - this.updateSlot( d ); - return null; - } - else - { - this.updateSlot( d ); - } - } - } - } - } - - // any match.. - for( final Slot d : selectedSlots ) - { - if( d instanceof SlotDisabled || d instanceof SlotME ) - { - continue; - } - - if( d.isItemValid( tis ) ) - { - if( d.getHasStack() ) - { - final ItemStack t = d.getStack(); - - if( Platform.isSameItemPrecise( t, tis ) ) - { - int maxSize = t.getMaxStackSize(); - if( d.getSlotStackLimit() < maxSize ) - { - maxSize = d.getSlotStackLimit(); - } - - int placeAble = maxSize - t.stackSize; - - if( tis.stackSize < placeAble ) - { - placeAble = tis.stackSize; - } - - t.stackSize += placeAble; - tis.stackSize -= placeAble; - - if( tis.stackSize <= 0 ) - { - clickSlot.putStack( null ); - d.onSlotChanged(); - - // if ( worldEntity != null ) - // worldEntity.markDirty(); - // if ( hasMETiles ) updateClient(); - - this.updateSlot( clickSlot ); - this.updateSlot( d ); - return null; - } - else - { - this.updateSlot( d ); - } - } - } - else - { - int maxSize = tis.getMaxStackSize(); - if( maxSize > d.getSlotStackLimit() ) - { - maxSize = d.getSlotStackLimit(); - } - - final ItemStack tmp = tis.copy(); - if( tmp.stackSize > maxSize ) - { - tmp.stackSize = maxSize; - } - - tis.stackSize -= tmp.stackSize; - d.putStack( tmp ); - - if( tis.stackSize <= 0 ) - { - clickSlot.putStack( null ); - d.onSlotChanged(); - - // if ( worldEntity != null ) - // worldEntity.markDirty(); - // if ( hasMETiles ) updateClient(); - - this.updateSlot( clickSlot ); - this.updateSlot( d ); - return null; - } - else - { - this.updateSlot( d ); - } - } - } - } - } - - clickSlot.putStack( tis != null ? tis.copy() : null ); - } - - this.updateSlot( clickSlot ); - return null; - } - - @Override - public final void updateProgressBar( final int idx, final int value ) - { - if( this.syncData.containsKey( idx ) ) - { - this.syncData.get( idx ).update( (long) value ); - } - } - - @Override - public boolean canInteractWith( final EntityPlayer entityplayer ) - { - if( this.isValidContainer() ) - { - if( this.tileEntity instanceof IInventory ) - { - return ( (IInventory) this.tileEntity ).isUseableByPlayer( entityplayer ); - } - return true; - } - return false; - } - - @Override - public boolean canDragIntoSlot( final Slot s ) - { - return ( (AppEngSlot) s ).isDraggable(); - } - - public void doAction( final EntityPlayerMP player, final InventoryAction action, final int slot, final long id ) - { - if( slot >= 0 && slot < this.inventorySlots.size() ) - { - final Slot s = this.getSlot( slot ); - - if( s instanceof SlotCraftingTerm ) - { - switch( action ) - { - case CRAFT_SHIFT: - case CRAFT_ITEM: - case CRAFT_STACK: - ( (SlotCraftingTerm) s ).doClick( action, player ); - this.updateHeld( player ); - default: - } - } - - if( s instanceof SlotFake ) - { - final ItemStack hand = player.inventory.getItemStack(); - - switch( action ) - { - case PICKUP_OR_SET_DOWN: - - if( hand == null ) - { - s.putStack( null ); - } - else - { - s.putStack( hand.copy() ); - } - - break; - case PLACE_SINGLE: - - if( hand != null ) - { - final ItemStack is = hand.copy(); - is.stackSize = 1; - s.putStack( is ); - } - - break; - case SPLIT_OR_PLACE_SINGLE: - - ItemStack is = s.getStack(); - if( is != null ) - { - if( hand == null ) - { - is.stackSize--; - } - else if( hand.isItemEqual( is ) ) - { - is.stackSize = Math.min( is.getMaxStackSize(), is.stackSize + 1 ); - } - else - { - is = hand.copy(); - is.stackSize = 1; - } - - s.putStack( is ); - } - else if( hand != null ) - { - is = hand.copy(); - is.stackSize = 1; - s.putStack( is ); - } - - break; - case CREATIVE_DUPLICATE: - case MOVE_REGION: - case SHIFT_CLICK: - default: - break; - } - } - - if( action == InventoryAction.MOVE_REGION ) - { - if( s instanceof SlotPatternTerm ) - return; - //SlotPatternTerm should't transfer its ItemStack to the Player - - final List from = new LinkedList(); - - for( final Object j : this.inventorySlots ) - { - if( j instanceof Slot && j.getClass() == s.getClass() ) - { - from.add( (Slot) j ); - } - } - - for( final Slot fr : from ) - { - this.transferStackInSlot( player, fr.slotNumber ); - } - } - - return; - } - - // get target item. - final IAEItemStack slotItem = this.clientRequestedTargetItem; - - switch( action ) - { - case SHIFT_CLICK: - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - if( slotItem != null ) - { - IAEItemStack ais = slotItem.copy(); - ItemStack myItem = ais.getItemStack(); - - ais.setStackSize( myItem.getMaxStackSize() ); - - final InventoryAdaptor adp = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); - myItem.stackSize = (int) ais.getStackSize(); - myItem = adp.simulateAdd( myItem ); - - if( myItem != null ) - { - ais.setStackSize( ais.getStackSize() - myItem.stackSize ); - } - - ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais != null ) - { - adp.addItems( ais.getItemStack() ); - } - } - break; - case ROLL_DOWN: - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - final int releaseQty = 1; - final ItemStack isg = player.inventory.getItemStack(); - - if( isg != null && releaseQty > 0 ) - { - IAEItemStack ais = AEApi.instance().storage().createItemStack( isg ); - ais.setStackSize( 1 ); - final IAEItemStack extracted = ais.copy(); - - ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais == null ) - { - final InventoryAdaptor ia = new AdaptorPlayerHand( player ); - - final ItemStack fail = ia.removeItems( 1, extracted.getItemStack(), null ); - if( fail == null ) - { - this.getCellInventory().extractItems( extracted, Actionable.MODULATE, this.getActionSource() ); - } - - this.updateHeld( player ); - } - } - - break; - case ROLL_UP: - case PICKUP_SINGLE: - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - if( slotItem != null ) - { - int liftQty = 1; - final ItemStack item = player.inventory.getItemStack(); - - if( item != null ) - { - if( item.stackSize >= item.getMaxStackSize() ) - { - liftQty = 0; - } - if( !Platform.isSameItemPrecise( slotItem.getItemStack(), item ) ) - { - liftQty = 0; - } - } - - if( liftQty > 0 ) - { - IAEItemStack ais = slotItem.copy(); - ais.setStackSize( 1 ); - ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais != null ) - { - final InventoryAdaptor ia = new AdaptorPlayerHand( player ); - - final ItemStack fail = ia.addItems( ais.getItemStack() ); - if( fail != null ) - { - this.getCellInventory().injectItems( ais, Actionable.MODULATE, this.getActionSource() ); - } - - this.updateHeld( player ); - } - } - } - break; - case PICKUP_OR_SET_DOWN: - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - if( player.inventory.getItemStack() == null ) - { - if( slotItem != null ) - { - IAEItemStack ais = slotItem.copy(); - ais.setStackSize( ais.getItemStack().getMaxStackSize() ); - ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais != null ) - { - player.inventory.setItemStack( ais.getItemStack() ); - } - else - { - player.inventory.setItemStack( null ); - } - this.updateHeld( player ); - } - } - else - { - IAEItemStack ais = AEApi.instance().storage().createItemStack( player.inventory.getItemStack() ); - ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais != null ) - { - player.inventory.setItemStack( ais.getItemStack() ); - } - else - { - player.inventory.setItemStack( null ); - } - this.updateHeld( player ); - } - - break; - case SPLIT_OR_PLACE_SINGLE: - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - if( player.inventory.getItemStack() == null ) - { - if( slotItem != null ) - { - IAEItemStack ais = slotItem.copy(); - final long maxSize = ais.getItemStack().getMaxStackSize(); - ais.setStackSize( maxSize ); - ais = this.getCellInventory().extractItems( ais, Actionable.SIMULATE, this.getActionSource() ); - - if( ais != null ) - { - final long stackSize = Math.min( maxSize, ais.getStackSize() ); - ais.setStackSize( ( stackSize + 1 ) >> 1 ); - ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - } - - if( ais != null ) - { - player.inventory.setItemStack( ais.getItemStack() ); - } - else - { - player.inventory.setItemStack( null ); - } - this.updateHeld( player ); - } - } - else - { - IAEItemStack ais = AEApi.instance().storage().createItemStack( player.inventory.getItemStack() ); - ais.setStackSize( 1 ); - ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais == null ) - { - final ItemStack is = player.inventory.getItemStack(); - is.stackSize--; - if( is.stackSize <= 0 ) - { - player.inventory.setItemStack( null ); - } - this.updateHeld( player ); - } - } - - break; - case CREATIVE_DUPLICATE: - if( player.capabilities.isCreativeMode && slotItem != null ) - { - final ItemStack is = slotItem.getItemStack(); - is.stackSize = is.getMaxStackSize(); - player.inventory.setItemStack( is ); - this.updateHeld( player ); - } - break; - case MOVE_REGION: - - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - if( slotItem != null ) - { - final int playerInv = 9 * 4; - for( int slotNum = 0; slotNum < playerInv; slotNum++ ) - { - IAEItemStack ais = slotItem.copy(); - ItemStack myItem = ais.getItemStack(); - - ais.setStackSize( myItem.getMaxStackSize() ); - - final InventoryAdaptor adp = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); - myItem.stackSize = (int) ais.getStackSize(); - myItem = adp.simulateAdd( myItem ); - - if( myItem != null ) - { - ais.setStackSize( ais.getStackSize() - myItem.stackSize ); - } - - ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais != null ) - { - adp.addItems( ais.getItemStack() ); - } - else - { - return; - } - } - } - - break; - default: - break; - } - } - - protected void updateHeld( final EntityPlayerMP p ) - { - if( Platform.isServer() ) - { - try - { - NetworkHandler.instance.sendTo( new PacketInventoryAction( InventoryAction.UPDATE_HAND, 0, AEItemStack.create( p.inventory.getItemStack() ) ), p ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - - private ItemStack shiftStoreItem( final ItemStack input ) - { - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return input; - } - final IAEItemStack ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), AEApi.instance().storage().createItemStack( input ), this.getActionSource() ); - if( ais == null ) - { - return null; - } - return ais.getItemStack(); - } - - private void updateSlot( final Slot clickSlot ) - { - // ??? - this.detectAndSendChanges(); - } - - private void sendCustomName() - { - if( !this.sentCustomName ) - { - this.sentCustomName = true; - if( Platform.isServer() ) - { - ICustomNameObject name = null; - - if( this.part instanceof ICustomNameObject ) - { - name = (ICustomNameObject) this.part; - } - - if( this.tileEntity instanceof ICustomNameObject ) - { - name = (ICustomNameObject) this.tileEntity; - } - - if( this.obj instanceof ICustomNameObject ) - { - name = (ICustomNameObject) this.obj; - } - - if( this instanceof ICustomNameObject ) - { - name = (ICustomNameObject) this; - } - - if( name != null ) - { - if( name.hasCustomName() ) - { - this.setCustomName( name.getCustomName() ); - } - - if( this.getCustomName() != null ) - { - try - { - NetworkHandler.instance.sendTo( new PacketValueConfig( "CustomName", this.getCustomName() ), (EntityPlayerMP) this.getInventoryPlayer().player ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - } - } - } - - public void swapSlotContents( final int slotA, final int slotB ) - { - final Slot a = this.getSlot( slotA ); - final Slot b = this.getSlot( slotB ); - - // NPE protection... - if( a == null || b == null ) - { - return; - } - - final ItemStack isA = a.getStack(); - final ItemStack isB = b.getStack(); - - // something to do? - if( isA == null && isB == null ) - { - return; - } - - // can take? - - if( isA != null && !a.canTakeStack( this.getInventoryPlayer().player ) ) - { - return; - } - - if( isB != null && !b.canTakeStack( this.getInventoryPlayer().player ) ) - { - return; - } - - // swap valid? - - if( isB != null && !a.isItemValid( isB ) ) - { - return; - } - - if( isA != null && !b.isItemValid( isA ) ) - { - return; - } - - ItemStack testA = isB == null ? null : isB.copy(); - ItemStack testB = isA == null ? null : isA.copy(); - - // can put some back? - if( testA != null && testA.stackSize > a.getSlotStackLimit() ) - { - if( testB != null ) - { - return; - } - - final int totalA = testA.stackSize; - testA.stackSize = a.getSlotStackLimit(); - testB = testA.copy(); - - testB.stackSize = totalA - testA.stackSize; - } - - if( testB != null && testB.stackSize > b.getSlotStackLimit() ) - { - if( testA != null ) - { - return; - } - - final int totalB = testB.stackSize; - testB.stackSize = b.getSlotStackLimit(); - testA = testB.copy(); - - testA.stackSize = totalB - testA.stackSize; - } - - a.putStack( testA ); - b.putStack( testB ); - } - - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - - } - - public void onSlotChange( final Slot s ) - { - - } - - public boolean isValidForSlot( final Slot s, final ItemStack i ) - { - return true; - } - - public IMEInventoryHandler getCellInventory() - { - return this.cellInv; - } - - public void setCellInventory( final IMEInventoryHandler cellInv ) - { - this.cellInv = cellInv; - } - - public String getCustomName() - { - return this.customName; - } - - public void setCustomName( final String customName ) - { - this.customName = customName; - } - - public InventoryPlayer getInventoryPlayer() - { - return this.invPlayer; - } - - public boolean isValidContainer() - { - return this.isContainerValid; - } - - public void setValidContainer( final boolean isContainerValid ) - { - this.isContainerValid = isContainerValid; - } - - public ContainerOpenContext getOpenContext() - { - return this.openContext; - } - - public void setOpenContext( final ContainerOpenContext openContext ) - { - this.openContext = openContext; - } - - public IEnergySource getPowerSource() - { - return this.powerSrc; - } - - public void setPowerSource( final IEnergySource powerSrc ) - { - this.powerSrc = powerSrc; - } + public BaseActionSource getActionSource() { + return this.mySrc; + } + + public void verifyPermissions(final SecurityPermissions security, final boolean requirePower) { + if (Platform.isClient()) { + return; + } + + this.ticksSinceCheck++; + if (this.ticksSinceCheck < 20) { + return; + } + + this.ticksSinceCheck = 0; + this.setValidContainer(this.isValidContainer() && this.hasAccess(security, requirePower)); + } + + protected boolean hasAccess(final SecurityPermissions perm, final boolean requirePower) { + final IActionHost host = this.getActionHost(); + + if (host != null) { + final IGridNode gn = host.getActionableNode(); + if (gn != null) { + final IGrid g = gn.getGrid(); + if (g != null) { + if (requirePower) { + final IEnergyGrid eg = g.getCache(IEnergyGrid.class); + if (!eg.isNetworkPowered()) { + return false; + } + } + + final ISecurityGrid sg = g.getCache(ISecurityGrid.class); + if (sg.hasPermission(this.getInventoryPlayer().player, perm)) { + return true; + } + } + } + } + + return false; + } + + public void lockPlayerInventorySlot(final int idx) { + this.locked.add(idx); + } + + public Object getTarget() { + if (this.tileEntity != null) { + return this.tileEntity; + } + if (this.part != null) { + return this.part; + } + if (this.obj != null) { + return this.obj; + } + return null; + } + + public InventoryPlayer getPlayerInv() { + return this.getInventoryPlayer(); + } + + public TileEntity getTileEntity() { + return this.tileEntity; + } + + public final void updateFullProgressBar(final int idx, final long value) { + if (this.syncData.containsKey(idx)) { + this.syncData.get(idx).update(value); + return; + } + + this.updateProgressBar(idx, (int) value); + } + + public void stringSync(final int idx, final String value) { + if (this.syncData.containsKey(idx)) { + this.syncData.get(idx).update(value); + } + } + + protected void bindPlayerInventory(final InventoryPlayer inventoryPlayer, final int offsetX, final int offsetY) { + // bind player inventory + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + if (this.locked.contains(j + i * 9 + 9)) { + this.addSlotToContainer( + new SlotDisabled(inventoryPlayer, j + i * 9 + 9, 8 + j * 18 + offsetX, offsetY + i * 18)); + } else { + this.addSlotToContainer( + new SlotPlayerInv(inventoryPlayer, j + i * 9 + 9, 8 + j * 18 + offsetX, offsetY + i * 18)); + } + } + } + + // bind player hotbar + for (int i = 0; i < 9; i++) { + if (this.locked.contains(i)) { + this.addSlotToContainer(new SlotDisabled(inventoryPlayer, i, 8 + i * 18 + offsetX, 58 + offsetY)); + } else { + this.addSlotToContainer(new SlotPlayerHotBar(inventoryPlayer, i, 8 + i * 18 + offsetX, 58 + offsetY)); + } + } + } + + @Override + protected Slot addSlotToContainer(final Slot newSlot) { + if (newSlot instanceof AppEngSlot) { + final AppEngSlot s = (AppEngSlot) newSlot; + s.setContainer(this); + return super.addSlotToContainer(newSlot); + } else { + throw new IllegalArgumentException("Invalid Slot [" + newSlot + "]for AE Container instead of AppEngSlot."); + } + } + + @Override + public void detectAndSendChanges() { + this.sendCustomName(); + + if (Platform.isServer()) { + for (final Object crafter : this.crafters) { + final ICrafting icrafting = (ICrafting) crafter; + + for (final SyncData sd : this.syncData.values()) { + sd.tick(icrafting); + } + } + } + + super.detectAndSendChanges(); + } + + @Override + public ItemStack transferStackInSlot(final EntityPlayer p, final int idx) { + if (Platform.isClient()) { + return null; + } + + boolean hasMETiles = false; + for (final Object is : this.inventorySlots) { + if (is instanceof InternalSlotME) { + hasMETiles = true; + break; + } + } + + if (hasMETiles && Platform.isClient()) { + return null; + } + + final AppEngSlot clickSlot = (AppEngSlot) this.inventorySlots.get(idx); // require AE SLots! + + if (clickSlot instanceof SlotDisabled || clickSlot instanceof SlotInaccessible) { + return null; + } + if (clickSlot != null && clickSlot.getHasStack()) { + ItemStack tis = clickSlot.getStack(); + + if (tis == null) { + return null; + } + + final List selectedSlots = new ArrayList(); + + /** + * Gather a list of valid destinations. + */ + if (clickSlot.isPlayerSide()) { + tis = this.shiftStoreItem(tis); + + // target slots in the container... + for (final Object inventorySlot : this.inventorySlots) { + final AppEngSlot cs = (AppEngSlot) inventorySlot; + + if (!(cs.isPlayerSide()) && !(cs instanceof SlotFake) && !(cs instanceof SlotCraftingMatrix)) { + if (cs.isItemValid(tis)) { + selectedSlots.add(cs); + } + } + } + } else { + // target slots in the container... + for (final Object inventorySlot : this.inventorySlots) { + final AppEngSlot cs = (AppEngSlot) inventorySlot; + + if ((cs.isPlayerSide()) && !(cs instanceof SlotFake) && !(cs instanceof SlotCraftingMatrix)) { + if (cs.isItemValid(tis)) { + selectedSlots.add(cs); + } + } + } + } + + /** + * Handle Fake Slot Shift clicking. + */ + if (selectedSlots.isEmpty() && clickSlot.isPlayerSide()) { + if (tis != null) { + // target slots in the container... + for (final Object inventorySlot : this.inventorySlots) { + final AppEngSlot cs = (AppEngSlot) inventorySlot; + final ItemStack destination = cs.getStack(); + + if (!(cs.isPlayerSide()) && cs instanceof SlotFake) { + if (Platform.isSameItemPrecise(destination, tis)) { + break; + } else if (destination == null) { + cs.putStack(tis.copy()); + cs.onSlotChanged(); + this.updateSlot(cs); + break; + } + } + } + } + } + + if (tis != null) { + // find partials.. + for (final Slot d : selectedSlots) { + if (d instanceof SlotDisabled || d instanceof SlotME) { + continue; + } + + if (d.isItemValid(tis)) { + if (d.getHasStack()) { + final ItemStack t = d.getStack(); + + if (Platform.isSameItemPrecise(tis, t)) // t.isItemEqual(tis)) + { + int maxSize = t.getMaxStackSize(); + if (maxSize > d.getSlotStackLimit()) { + maxSize = d.getSlotStackLimit(); + } + + int placeAble = maxSize - t.stackSize; + + if (tis.stackSize < placeAble) { + placeAble = tis.stackSize; + } + + t.stackSize += placeAble; + tis.stackSize -= placeAble; + + if (tis.stackSize <= 0) { + clickSlot.putStack(null); + d.onSlotChanged(); + + // if ( hasMETiles ) updateClient(); + + this.updateSlot(clickSlot); + this.updateSlot(d); + return null; + } else { + this.updateSlot(d); + } + } + } + } + } + + // any match.. + for (final Slot d : selectedSlots) { + if (d instanceof SlotDisabled || d instanceof SlotME) { + continue; + } + + if (d.isItemValid(tis)) { + if (d.getHasStack()) { + final ItemStack t = d.getStack(); + + if (Platform.isSameItemPrecise(t, tis)) { + int maxSize = t.getMaxStackSize(); + if (d.getSlotStackLimit() < maxSize) { + maxSize = d.getSlotStackLimit(); + } + + int placeAble = maxSize - t.stackSize; + + if (tis.stackSize < placeAble) { + placeAble = tis.stackSize; + } + + t.stackSize += placeAble; + tis.stackSize -= placeAble; + + if (tis.stackSize <= 0) { + clickSlot.putStack(null); + d.onSlotChanged(); + + // if ( worldEntity != null ) + // worldEntity.markDirty(); + // if ( hasMETiles ) updateClient(); + + this.updateSlot(clickSlot); + this.updateSlot(d); + return null; + } else { + this.updateSlot(d); + } + } + } else { + int maxSize = tis.getMaxStackSize(); + if (maxSize > d.getSlotStackLimit()) { + maxSize = d.getSlotStackLimit(); + } + + final ItemStack tmp = tis.copy(); + if (tmp.stackSize > maxSize) { + tmp.stackSize = maxSize; + } + + tis.stackSize -= tmp.stackSize; + d.putStack(tmp); + + if (tis.stackSize <= 0) { + clickSlot.putStack(null); + d.onSlotChanged(); + + // if ( worldEntity != null ) + // worldEntity.markDirty(); + // if ( hasMETiles ) updateClient(); + + this.updateSlot(clickSlot); + this.updateSlot(d); + return null; + } else { + this.updateSlot(d); + } + } + } + } + } + + clickSlot.putStack(tis != null ? tis.copy() : null); + } + + this.updateSlot(clickSlot); + return null; + } + + @Override + public final void updateProgressBar(final int idx, final int value) { + if (this.syncData.containsKey(idx)) { + this.syncData.get(idx).update((long) value); + } + } + + @Override + public boolean canInteractWith(final EntityPlayer entityplayer) { + if (this.isValidContainer()) { + if (this.tileEntity instanceof IInventory) { + return ((IInventory) this.tileEntity).isUseableByPlayer(entityplayer); + } + return true; + } + return false; + } + + @Override + public boolean canDragIntoSlot(final Slot s) { + return ((AppEngSlot) s).isDraggable(); + } + + public void doAction(final EntityPlayerMP player, final InventoryAction action, final int slot, final long id) { + if (slot >= 0 && slot < this.inventorySlots.size()) { + final Slot s = this.getSlot(slot); + + if (s instanceof SlotCraftingTerm) { + switch (action) { + case CRAFT_SHIFT: + case CRAFT_ITEM: + case CRAFT_STACK: + ((SlotCraftingTerm) s).doClick(action, player); + this.updateHeld(player); + default: + } + } + + if (s instanceof SlotFake) { + final ItemStack hand = player.inventory.getItemStack(); + + switch (action) { + case PICKUP_OR_SET_DOWN: + if (hand == null) { + s.putStack(null); + } else { + s.putStack(hand.copy()); + } + + break; + case PLACE_SINGLE: + if (hand != null) { + final ItemStack is = hand.copy(); + is.stackSize = 1; + s.putStack(is); + } + + break; + case SPLIT_OR_PLACE_SINGLE: + ItemStack is = s.getStack(); + if (is != null) { + if (hand == null) { + is.stackSize--; + } else if (hand.isItemEqual(is)) { + is.stackSize = Math.min(is.getMaxStackSize(), is.stackSize + 1); + } else { + is = hand.copy(); + is.stackSize = 1; + } + + s.putStack(is); + } else if (hand != null) { + is = hand.copy(); + is.stackSize = 1; + s.putStack(is); + } + + break; + case CREATIVE_DUPLICATE: + case MOVE_REGION: + case SHIFT_CLICK: + default: + break; + } + } + + if (action == InventoryAction.MOVE_REGION) { + if (s instanceof SlotPatternTerm) return; + // SlotPatternTerm should't transfer its ItemStack to the Player + + final List from = new LinkedList(); + + for (final Object j : this.inventorySlots) { + if (j instanceof Slot && j.getClass() == s.getClass()) { + from.add((Slot) j); + } + } + + for (final Slot fr : from) { + this.transferStackInSlot(player, fr.slotNumber); + } + } + + return; + } + + // get target item. + final IAEItemStack slotItem = this.clientRequestedTargetItem; + + switch (action) { + case SHIFT_CLICK: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + if (slotItem != null) { + IAEItemStack ais = slotItem.copy(); + ItemStack myItem = ais.getItemStack(); + + ais.setStackSize(myItem.getMaxStackSize()); + + final InventoryAdaptor adp = InventoryAdaptor.getAdaptor(player, ForgeDirection.UNKNOWN); + myItem.stackSize = (int) ais.getStackSize(); + myItem = adp.simulateAdd(myItem); + + if (myItem != null) { + ais.setStackSize(ais.getStackSize() - myItem.stackSize); + } + + ais = Platform.poweredExtraction( + this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + if (ais != null) { + adp.addItems(ais.getItemStack()); + } + } + break; + case ROLL_DOWN: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + final int releaseQty = 1; + final ItemStack isg = player.inventory.getItemStack(); + + if (isg != null && releaseQty > 0) { + IAEItemStack ais = AEApi.instance().storage().createItemStack(isg); + ais.setStackSize(1); + final IAEItemStack extracted = ais.copy(); + + ais = Platform.poweredInsert( + this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + if (ais == null) { + final InventoryAdaptor ia = new AdaptorPlayerHand(player); + + final ItemStack fail = ia.removeItems(1, extracted.getItemStack(), null); + if (fail == null) { + this.getCellInventory() + .extractItems(extracted, Actionable.MODULATE, this.getActionSource()); + } + + this.updateHeld(player); + } + } + + break; + case ROLL_UP: + case PICKUP_SINGLE: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + if (slotItem != null) { + int liftQty = 1; + final ItemStack item = player.inventory.getItemStack(); + + if (item != null) { + if (item.stackSize >= item.getMaxStackSize()) { + liftQty = 0; + } + if (!Platform.isSameItemPrecise(slotItem.getItemStack(), item)) { + liftQty = 0; + } + } + + if (liftQty > 0) { + IAEItemStack ais = slotItem.copy(); + ais.setStackSize(1); + ais = Platform.poweredExtraction( + this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + if (ais != null) { + final InventoryAdaptor ia = new AdaptorPlayerHand(player); + + final ItemStack fail = ia.addItems(ais.getItemStack()); + if (fail != null) { + this.getCellInventory().injectItems(ais, Actionable.MODULATE, this.getActionSource()); + } + + this.updateHeld(player); + } + } + } + break; + case PICKUP_OR_SET_DOWN: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + if (player.inventory.getItemStack() == null) { + if (slotItem != null) { + IAEItemStack ais = slotItem.copy(); + ais.setStackSize(ais.getItemStack().getMaxStackSize()); + ais = Platform.poweredExtraction( + this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + if (ais != null) { + player.inventory.setItemStack(ais.getItemStack()); + } else { + player.inventory.setItemStack(null); + } + this.updateHeld(player); + } + } else { + IAEItemStack ais = AEApi.instance().storage().createItemStack(player.inventory.getItemStack()); + ais = Platform.poweredInsert( + this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + if (ais != null) { + player.inventory.setItemStack(ais.getItemStack()); + } else { + player.inventory.setItemStack(null); + } + this.updateHeld(player); + } + + break; + case SPLIT_OR_PLACE_SINGLE: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + if (player.inventory.getItemStack() == null) { + if (slotItem != null) { + IAEItemStack ais = slotItem.copy(); + final long maxSize = ais.getItemStack().getMaxStackSize(); + ais.setStackSize(maxSize); + ais = this.getCellInventory().extractItems(ais, Actionable.SIMULATE, this.getActionSource()); + + if (ais != null) { + final long stackSize = Math.min(maxSize, ais.getStackSize()); + ais.setStackSize((stackSize + 1) >> 1); + ais = Platform.poweredExtraction( + this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + } + + if (ais != null) { + player.inventory.setItemStack(ais.getItemStack()); + } else { + player.inventory.setItemStack(null); + } + this.updateHeld(player); + } + } else { + IAEItemStack ais = AEApi.instance().storage().createItemStack(player.inventory.getItemStack()); + ais.setStackSize(1); + ais = Platform.poweredInsert( + this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + if (ais == null) { + final ItemStack is = player.inventory.getItemStack(); + is.stackSize--; + if (is.stackSize <= 0) { + player.inventory.setItemStack(null); + } + this.updateHeld(player); + } + } + + break; + case CREATIVE_DUPLICATE: + if (player.capabilities.isCreativeMode && slotItem != null) { + final ItemStack is = slotItem.getItemStack(); + is.stackSize = is.getMaxStackSize(); + player.inventory.setItemStack(is); + this.updateHeld(player); + } + break; + case MOVE_REGION: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + if (slotItem != null) { + final int playerInv = 9 * 4; + for (int slotNum = 0; slotNum < playerInv; slotNum++) { + IAEItemStack ais = slotItem.copy(); + ItemStack myItem = ais.getItemStack(); + + ais.setStackSize(myItem.getMaxStackSize()); + + final InventoryAdaptor adp = InventoryAdaptor.getAdaptor(player, ForgeDirection.UNKNOWN); + myItem.stackSize = (int) ais.getStackSize(); + myItem = adp.simulateAdd(myItem); + + if (myItem != null) { + ais.setStackSize(ais.getStackSize() - myItem.stackSize); + } + + ais = Platform.poweredExtraction( + this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource()); + if (ais != null) { + adp.addItems(ais.getItemStack()); + } else { + return; + } + } + } + + break; + default: + break; + } + } + + protected void updateHeld(final EntityPlayerMP p) { + if (Platform.isServer()) { + try { + NetworkHandler.instance.sendTo( + new PacketInventoryAction( + InventoryAction.UPDATE_HAND, 0, AEItemStack.create(p.inventory.getItemStack())), + p); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + + private ItemStack shiftStoreItem(final ItemStack input) { + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return input; + } + final IAEItemStack ais = Platform.poweredInsert( + this.getPowerSource(), + this.getCellInventory(), + AEApi.instance().storage().createItemStack(input), + this.getActionSource()); + if (ais == null) { + return null; + } + return ais.getItemStack(); + } + + private void updateSlot(final Slot clickSlot) { + // ??? + this.detectAndSendChanges(); + } + + private void sendCustomName() { + if (!this.sentCustomName) { + this.sentCustomName = true; + if (Platform.isServer()) { + ICustomNameObject name = null; + + if (this.part instanceof ICustomNameObject) { + name = (ICustomNameObject) this.part; + } + + if (this.tileEntity instanceof ICustomNameObject) { + name = (ICustomNameObject) this.tileEntity; + } + + if (this.obj instanceof ICustomNameObject) { + name = (ICustomNameObject) this.obj; + } + + if (this instanceof ICustomNameObject) { + name = (ICustomNameObject) this; + } + + if (name != null) { + if (name.hasCustomName()) { + this.setCustomName(name.getCustomName()); + } + + if (this.getCustomName() != null) { + try { + NetworkHandler.instance.sendTo( + new PacketValueConfig("CustomName", this.getCustomName()), + (EntityPlayerMP) this.getInventoryPlayer().player); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + } + } + } + + public void swapSlotContents(final int slotA, final int slotB) { + final Slot a = this.getSlot(slotA); + final Slot b = this.getSlot(slotB); + + // NPE protection... + if (a == null || b == null) { + return; + } + + final ItemStack isA = a.getStack(); + final ItemStack isB = b.getStack(); + + // something to do? + if (isA == null && isB == null) { + return; + } + + // can take? + + if (isA != null && !a.canTakeStack(this.getInventoryPlayer().player)) { + return; + } + + if (isB != null && !b.canTakeStack(this.getInventoryPlayer().player)) { + return; + } + + // swap valid? + + if (isB != null && !a.isItemValid(isB)) { + return; + } + + if (isA != null && !b.isItemValid(isA)) { + return; + } + + ItemStack testA = isB == null ? null : isB.copy(); + ItemStack testB = isA == null ? null : isA.copy(); + + // can put some back? + if (testA != null && testA.stackSize > a.getSlotStackLimit()) { + if (testB != null) { + return; + } + + final int totalA = testA.stackSize; + testA.stackSize = a.getSlotStackLimit(); + testB = testA.copy(); + + testB.stackSize = totalA - testA.stackSize; + } + + if (testB != null && testB.stackSize > b.getSlotStackLimit()) { + if (testA != null) { + return; + } + + final int totalB = testB.stackSize; + testB.stackSize = b.getSlotStackLimit(); + testA = testB.copy(); + + testA.stackSize = totalB - testA.stackSize; + } + + a.putStack(testA); + b.putStack(testB); + } + + public void onUpdate(final String field, final Object oldValue, final Object newValue) {} + + public void onSlotChange(final Slot s) {} + + public boolean isValidForSlot(final Slot s, final ItemStack i) { + return true; + } + + public IMEInventoryHandler getCellInventory() { + return this.cellInv; + } + + public void setCellInventory(final IMEInventoryHandler cellInv) { + this.cellInv = cellInv; + } + + public String getCustomName() { + return this.customName; + } + + public void setCustomName(final String customName) { + this.customName = customName; + } + + public InventoryPlayer getInventoryPlayer() { + return this.invPlayer; + } + + public boolean isValidContainer() { + return this.isContainerValid; + } + + public void setValidContainer(final boolean isContainerValid) { + this.isContainerValid = isContainerValid; + } + + public ContainerOpenContext getOpenContext() { + return this.openContext; + } + + public void setOpenContext(final ContainerOpenContext openContext) { + this.openContext = openContext; + } + + public IEnergySource getPowerSource() { + return this.powerSrc; + } + + public void setPowerSource(final IEnergySource powerSrc) { + this.powerSrc = powerSrc; + } } diff --git a/src/main/java/appeng/container/ContainerNull.java b/src/main/java/appeng/container/ContainerNull.java index 8e94d3caf49..2f649f9f60c 100644 --- a/src/main/java/appeng/container/ContainerNull.java +++ b/src/main/java/appeng/container/ContainerNull.java @@ -18,20 +18,16 @@ package appeng.container; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; - /* * Totally useless container that does nothing. */ -public class ContainerNull extends Container -{ +public class ContainerNull extends Container { - @Override - public boolean canInteractWith( final EntityPlayer entityplayer ) - { - return false; - } + @Override + public boolean canInteractWith(final EntityPlayer entityplayer) { + return false; + } } diff --git a/src/main/java/appeng/container/ContainerOpenContext.java b/src/main/java/appeng/container/ContainerOpenContext.java index fb4017610a3..59e61497510 100644 --- a/src/main/java/appeng/container/ContainerOpenContext.java +++ b/src/main/java/appeng/container/ContainerOpenContext.java @@ -18,85 +18,69 @@ package appeng.container; - import appeng.api.parts.IPart; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; - -public class ContainerOpenContext -{ - - private final boolean isItem; - private World w; - private int x; - private int y; - private int z; - private ForgeDirection side; - - public ContainerOpenContext( final Object myItem ) - { - final boolean isWorld = myItem instanceof IPart || myItem instanceof TileEntity; - this.isItem = !isWorld; - } - - public TileEntity getTile() - { - if( this.isItem ) - { - return null; - } - return this.getWorld().getTileEntity( this.getX(), this.getY(), this.getZ() ); - } - - public ForgeDirection getSide() - { - return this.side; - } - - public void setSide( final ForgeDirection side ) - { - this.side = side; - } - - private int getZ() - { - return this.z; - } - - public void setZ( final int z ) - { - this.z = z; - } - - private int getY() - { - return this.y; - } - - public void setY( final int y ) - { - this.y = y; - } - - private int getX() - { - return this.x; - } - - public void setX( final int x ) - { - this.x = x; - } - - private World getWorld() - { - return this.w; - } - - public void setWorld( final World w ) - { - this.w = w; - } +public class ContainerOpenContext { + + private final boolean isItem; + private World w; + private int x; + private int y; + private int z; + private ForgeDirection side; + + public ContainerOpenContext(final Object myItem) { + final boolean isWorld = myItem instanceof IPart || myItem instanceof TileEntity; + this.isItem = !isWorld; + } + + public TileEntity getTile() { + if (this.isItem) { + return null; + } + return this.getWorld().getTileEntity(this.getX(), this.getY(), this.getZ()); + } + + public ForgeDirection getSide() { + return this.side; + } + + public void setSide(final ForgeDirection side) { + this.side = side; + } + + private int getZ() { + return this.z; + } + + public void setZ(final int z) { + this.z = z; + } + + private int getY() { + return this.y; + } + + public void setY(final int y) { + this.y = y; + } + + private int getX() { + return this.x; + } + + public void setX(final int x) { + this.x = x; + } + + private World getWorld() { + return this.w; + } + + public void setWorld(final World w) { + this.w = w; + } } diff --git a/src/main/java/appeng/container/guisync/GuiSync.java b/src/main/java/appeng/container/guisync/GuiSync.java index 50d70a74322..31c2ef27fd8 100644 --- a/src/main/java/appeng/container/guisync/GuiSync.java +++ b/src/main/java/appeng/container/guisync/GuiSync.java @@ -18,21 +18,18 @@ package appeng.container.guisync; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - /** * Annotates that this field should be synchronized between the server and client. * Requires the field to be public. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) -public @interface GuiSync -{ +public @interface GuiSync { int value(); @@ -41,8 +38,7 @@ */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) - public static @interface Recurse - { + public static @interface Recurse { int value(); } } diff --git a/src/main/java/appeng/container/guisync/SyncData.java b/src/main/java/appeng/container/guisync/SyncData.java index 9ddf6a3def4..cbda6d60b45 100644 --- a/src/main/java/appeng/container/guisync/SyncData.java +++ b/src/main/java/appeng/container/guisync/SyncData.java @@ -18,22 +18,18 @@ package appeng.container.guisync; - import appeng.container.AEBaseContainer; import appeng.core.AELog; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketProgressBar; import appeng.core.sync.packets.PacketValueConfig; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.inventory.ICrafting; - import java.io.IOException; import java.lang.reflect.Field; import java.util.EnumSet; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.ICrafting; - -public class SyncData -{ +public class SyncData { private final AEBaseContainer source; private final Field[] indirections; @@ -42,183 +38,138 @@ public class SyncData private final int channel; private Object clientVersion; - public SyncData( final AEBaseContainer container, final Field field, final GuiSync annotation ) - { - this( container, new Field[0], field, annotation.value() ); + public SyncData(final AEBaseContainer container, final Field field, final GuiSync annotation) { + this(container, new Field[0], field, annotation.value()); } - public SyncData( final AEBaseContainer container, final Field[] indirections, final Field field, final int channel ) - { + public SyncData(final AEBaseContainer container, final Field[] indirections, final Field field, final int channel) { this.clientVersion = null; this.source = container; this.indirections = indirections; this.field = field; this.channel = channel; StringBuilder nameBuilder = new StringBuilder(); - for( Field indirection : this.indirections ) - { - nameBuilder.append( indirection.getName() ); - nameBuilder.append( '.' ); + for (Field indirection : this.indirections) { + nameBuilder.append(indirection.getName()); + nameBuilder.append('.'); } - nameBuilder.append( this.field.getName() ); + nameBuilder.append(this.field.getName()); this.fieldName = nameBuilder.toString(); } - public int getChannel() - { + public int getChannel() { return this.channel; } - private Object getValue() throws IllegalAccessException - { + private Object getValue() throws IllegalAccessException { Object currentObject = source; - for( Field indirection : indirections ) - { - currentObject = indirection.get( currentObject ); + for (Field indirection : indirections) { + currentObject = indirection.get(currentObject); } - return field.get( currentObject ); + return field.get(currentObject); } - private void setValue( Object newVal ) throws IllegalAccessException - { + private void setValue(Object newVal) throws IllegalAccessException { Object currentObject = source; - for( Field indirection : indirections ) - { - currentObject = indirection.get( currentObject ); + for (Field indirection : indirections) { + currentObject = indirection.get(currentObject); } - field.set( currentObject, newVal ); + field.set(currentObject, newVal); } - public void tick( final ICrafting c ) - { - try - { + public void tick(final ICrafting c) { + try { final Object val = getValue(); - if( val != null && this.clientVersion == null ) - { - this.send( c, val ); - } else if( !val.equals( this.clientVersion ) ) - { - this.send( c, val ); + if (val != null && this.clientVersion == null) { + this.send(c, val); + } else if (!val.equals(this.clientVersion)) { + this.send(c, val); } - } catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } catch( final IllegalAccessException e ) - { - AELog.debug( e ); - } catch( final IOException e ) - { - AELog.debug( e ); + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); + } catch (final IOException e) { + AELog.debug(e); } } - private void send( final ICrafting o, final Object val ) throws IOException - { - if( val instanceof String ) - { - if( o instanceof EntityPlayerMP ) - { - NetworkHandler.instance.sendTo( new PacketValueConfig( "SyncDat." + this.channel, (String) val ), (EntityPlayerMP) o ); + private void send(final ICrafting o, final Object val) throws IOException { + if (val instanceof String) { + if (o instanceof EntityPlayerMP) { + NetworkHandler.instance.sendTo( + new PacketValueConfig("SyncDat." + this.channel, (String) val), (EntityPlayerMP) o); } - } else if( this.field.getType().isEnum() ) - { - o.sendProgressBarUpdate( this.source, this.channel, ( (Enum) val ).ordinal() ); - } else if( val instanceof Long || val.getClass() == long.class ) - { - NetworkHandler.instance.sendTo( new PacketProgressBar( this.channel, (Long) val ), (EntityPlayerMP) o ); - } else if( val instanceof Boolean || val.getClass() == boolean.class ) - { - o.sendProgressBarUpdate( this.source, this.channel, ( (Boolean) val ) ? 1 : 0 ); - } else - { - o.sendProgressBarUpdate( this.source, this.channel, (Integer) val ); + } else if (this.field.getType().isEnum()) { + o.sendProgressBarUpdate(this.source, this.channel, ((Enum) val).ordinal()); + } else if (val instanceof Long || val.getClass() == long.class) { + NetworkHandler.instance.sendTo(new PacketProgressBar(this.channel, (Long) val), (EntityPlayerMP) o); + } else if (val instanceof Boolean || val.getClass() == boolean.class) { + o.sendProgressBarUpdate(this.source, this.channel, ((Boolean) val) ? 1 : 0); + } else { + o.sendProgressBarUpdate(this.source, this.channel, (Integer) val); } this.clientVersion = val; } - public void update( final Object val ) - { - try - { + public void update(final Object val) { + try { final Object oldValue = this.getValue(); - if( val instanceof String ) - { - this.updateString( oldValue, (String) val ); - } else - { - this.updateValue( oldValue, (Long) val ); + if (val instanceof String) { + this.updateString(oldValue, (String) val); + } else { + this.updateValue(oldValue, (Long) val); } - } catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } catch( final IllegalAccessException e ) - { - AELog.debug( e ); + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); } } - private void updateString( final Object oldValue, final String val ) - { - try - { - this.setValue( val ); - this.source.onUpdate( this.fieldName, oldValue, this.getValue() ); - } catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } catch( final IllegalAccessException e ) - { - AELog.debug( e ); + private void updateString(final Object oldValue, final String val) { + try { + this.setValue(val); + this.source.onUpdate(this.fieldName, oldValue, this.getValue()); + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); } } - private void updateValue( final Object oldValue, final long val ) - { - try - { - if( this.field.getType().isEnum() ) - { - final EnumSet valList = EnumSet.allOf( (Class) this.field.getType() ); - for( final Enum e : valList ) - { - if( e.ordinal() == val ) - { - this.setValue( e ); + private void updateValue(final Object oldValue, final long val) { + try { + if (this.field.getType().isEnum()) { + final EnumSet valList = EnumSet.allOf((Class) this.field.getType()); + for (final Enum e : valList) { + if (e.ordinal() == val) { + this.setValue(e); break; } } - } else - { - if( this.field.getType().equals( int.class ) ) - { - this.setValue( (int) val ); - } else if( this.field.getType().equals( long.class ) ) - { - this.setValue( val ); - } else if( this.field.getType().equals( boolean.class ) ) - { - this.setValue( val == 1 ); - } else if( this.field.getType().equals( Integer.class ) ) - { - this.setValue( (int) val ); - } else if( this.field.getType().equals( Long.class ) ) - { - this.setValue( val ); - } else if( this.field.getType().equals( Boolean.class ) ) - { - this.setValue( val == 1 ); + } else { + if (this.field.getType().equals(int.class)) { + this.setValue((int) val); + } else if (this.field.getType().equals(long.class)) { + this.setValue(val); + } else if (this.field.getType().equals(boolean.class)) { + this.setValue(val == 1); + } else if (this.field.getType().equals(Integer.class)) { + this.setValue((int) val); + } else if (this.field.getType().equals(Long.class)) { + this.setValue(val); + } else if (this.field.getType().equals(Boolean.class)) { + this.setValue(val == 1); } } - this.source.onUpdate( this.fieldName, oldValue, this.getValue() ); - } catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } catch( final IllegalAccessException e ) - { - AELog.debug( e ); + this.source.onUpdate(this.fieldName, oldValue, this.getValue()); + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); } } } diff --git a/src/main/java/appeng/container/implementations/ContainerCPUTable.java b/src/main/java/appeng/container/implementations/ContainerCPUTable.java index 766408331e7..86aa06107da 100644 --- a/src/main/java/appeng/container/implementations/ContainerCPUTable.java +++ b/src/main/java/appeng/container/implementations/ContainerCPUTable.java @@ -11,15 +11,13 @@ import appeng.core.sync.packets.PacketCraftingCPUsUpdate; import appeng.util.Platform; import com.google.common.collect.ImmutableSet; -import net.minecraft.entity.player.EntityPlayerMP; - import java.io.IOException; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; +import net.minecraft.entity.player.EntityPlayerMP; -public class ContainerCPUTable implements ICraftingCPUSelectorContainer -{ +public class ContainerCPUTable implements ICraftingCPUSelectorContainer { private final AEBaseContainer parent; private ImmutableSet lastCpuSet = null; @@ -27,14 +25,16 @@ public class ContainerCPUTable implements ICraftingCPUSelectorContainer private final WeakHashMap cpuSerialMap = new WeakHashMap<>(); private int nextCpuSerial = 1; private int lastUpdate = 0; - @GuiSync( 0 ) + + @GuiSync(0) public int selectedCpuSerial = -1; + private final Consumer onCPUChange; private final boolean preferBusyCPUs; private final Predicate cpuFilter; - private static final Comparator CPU_COMPARATOR = Comparator - .comparing((CraftingCPUStatus e) -> e.getName() == null || e.getName().isEmpty()) + private static final Comparator CPU_COMPARATOR = Comparator.comparing( + (CraftingCPUStatus e) -> e.getName() == null || e.getName().isEmpty()) .thenComparing(e -> e.getName() != null ? e.getName() : "") .thenComparingInt(CraftingCPUStatus::getSerial); @@ -43,32 +43,32 @@ public class ContainerCPUTable implements ICraftingCPUSelectorContainer * @param onCPUChange Called whenever the current CPU is changed * @param preferBusyCPUs Whether busy CPUs should be picked first (e.g. crafting status vs. picking a CPU for a job) */ - public ContainerCPUTable(AEBaseContainer parent, Consumer onCPUChange, boolean preferBusyCPUs, Predicate cpuFilter) - { + public ContainerCPUTable( + AEBaseContainer parent, + Consumer onCPUChange, + boolean preferBusyCPUs, + Predicate cpuFilter) { this.parent = parent; this.onCPUChange = onCPUChange; this.preferBusyCPUs = preferBusyCPUs; this.cpuFilter = cpuFilter; } - public boolean isBusyCPUsPreferred() - { + public boolean isBusyCPUsPreferred() { return preferBusyCPUs; } - public Predicate getCpuFilter() - { + public Predicate getCpuFilter() { return cpuFilter; } - public void detectAndSendChanges( IGrid network, List crafters) { - if( Platform.isServer() && network != null ) - { - final ICraftingGrid cc = network.getCache( ICraftingGrid.class ); + public void detectAndSendChanges(IGrid network, List crafters) { + if (Platform.isServer() && network != null) { + final ICraftingGrid cc = network.getCache(ICraftingGrid.class); final ImmutableSet cpuSet = cc.getCpus(); // Update at least once a second ++lastUpdate; - if (!cpuSet.equals( lastCpuSet ) || lastUpdate > 20) { + if (!cpuSet.equals(lastCpuSet) || lastUpdate > 20) { lastUpdate = 0; lastCpuSet = cpuSet; updateCpuList(); @@ -87,7 +87,7 @@ public void detectAndSendChanges( IGrid network, List crafters) { if (selectedCpuSerial == -1) { // Try preferred CPUs first for (CraftingCPUStatus cpu : cpus) { - if ( preferBusyCPUs == cpu.isBusy() && cpuFilter.test(cpu) ) { + if (preferBusyCPUs == cpu.isBusy() && cpuFilter.test(cpu)) { selectCPU(cpu.getSerial()); break; } @@ -99,64 +99,48 @@ public void detectAndSendChanges( IGrid network, List crafters) { } } - private void updateCpuList() - { + private void updateCpuList() { this.cpus.clear(); - for (ICraftingCPU cpu : lastCpuSet) - { + for (ICraftingCPU cpu : lastCpuSet) { int serial = getOrAssignCpuSerial(cpu); - this.cpus.add( new CraftingCPUStatus( cpu, serial ) ); + this.cpus.add(new CraftingCPUStatus(cpu, serial)); } this.cpus.sort(CPU_COMPARATOR); } - private int getOrAssignCpuSerial( ICraftingCPU cpu ) - { - return cpuSerialMap.computeIfAbsent( cpu, unused -> nextCpuSerial++ ); + private int getOrAssignCpuSerial(ICraftingCPU cpu) { + return cpuSerialMap.computeIfAbsent(cpu, unused -> nextCpuSerial++); } - private void sendCPUs(List crafters) - { + private void sendCPUs(List crafters) { final PacketCraftingCPUsUpdate update; - for( final Object player : crafters ) - { - if( player instanceof EntityPlayerMP ) - { - try - { - NetworkHandler.instance.sendTo( new PacketCraftingCPUsUpdate( this.cpus ), (EntityPlayerMP) player ); - } - catch( IOException e ) - { - AELog.debug( e ); + for (final Object player : crafters) { + if (player instanceof EntityPlayerMP) { + try { + NetworkHandler.instance.sendTo(new PacketCraftingCPUsUpdate(this.cpus), (EntityPlayerMP) player); + } catch (IOException e) { + AELog.debug(e); } } } } @Override - public void selectCPU( int serial ) - { - if (Platform.isServer()) - { - if( serial < -1 ) - { + public void selectCPU(int serial) { + if (Platform.isServer()) { + if (serial < -1) { serial = -1; } final int searchedSerial = serial; - if( serial > -1 && cpus.stream().noneMatch(c -> c.getSerial() == searchedSerial) ) - { + if (serial > -1 && cpus.stream().noneMatch(c -> c.getSerial() == searchedSerial)) { serial = -1; } ICraftingCPU newSelectedCpu = null; - if( serial != -1 ) - { - for( ICraftingCPU cpu : lastCpuSet ) - { - if( cpuSerialMap.getOrDefault( cpu, -1 ) == serial ) - { + if (serial != -1) { + for (ICraftingCPU cpu : lastCpuSet) { + if (cpuSerialMap.getOrDefault(cpu, -1) == serial) { newSelectedCpu = cpu; break; } @@ -164,25 +148,24 @@ public void selectCPU( int serial ) } this.selectedCpuSerial = serial; - if (onCPUChange != null) - { - onCPUChange.accept( newSelectedCpu ); + if (onCPUChange != null) { + onCPUChange.accept(newSelectedCpu); } } } - public List getCPUs() - { - return Collections.unmodifiableList( cpus ); + public List getCPUs() { + return Collections.unmodifiableList(cpus); } - public CraftingCPUStatus getSelectedCPU() - { - return this.cpus.stream().filter(c -> c.getSerial() == selectedCpuSerial).findFirst().orElse(null); + public CraftingCPUStatus getSelectedCPU() { + return this.cpus.stream() + .filter(c -> c.getSerial() == selectedCpuSerial) + .findFirst() + .orElse(null); } - public void handleCPUUpdate( CraftingCPUStatus[] cpus ) - { - this.cpus = Arrays.asList( cpus ); + public void handleCPUUpdate(CraftingCPUStatus[] cpus) { + this.cpus = Arrays.asList(cpus); } } diff --git a/src/main/java/appeng/container/implementations/ContainerCellWorkbench.java b/src/main/java/appeng/container/implementations/ContainerCellWorkbench.java index 8d99d6bd6bf..beb057df0f1 100644 --- a/src/main/java/appeng/container/implementations/ContainerCellWorkbench.java +++ b/src/main/java/appeng/container/implementations/ContainerCellWorkbench.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.AEApi; import appeng.api.config.CopyMode; import appeng.api.config.FuzzyMode; @@ -36,6 +35,7 @@ import appeng.tile.misc.TileCellWorkbench; import appeng.util.Platform; import appeng.util.iterators.NullIterator; +import java.util.Iterator; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; @@ -43,308 +43,271 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.util.Iterator; - - -public class ContainerCellWorkbench extends ContainerUpgradeable -{ - private final TileCellWorkbench workBench; - private final AppEngNullInventory nullInventory = new AppEngNullInventory(); - @GuiSync( 2 ) - public CopyMode copyMode = CopyMode.CLEAR_ON_REMOVE; - private ItemStack prevStack = null; - private int lastUpgrades = 0; - - public ContainerCellWorkbench( final InventoryPlayer ip, final TileCellWorkbench te ) - { - super( ip, te ); - this.workBench = te; - } - - public void setFuzzy( final FuzzyMode valueOf ) - { - final ICellWorkbenchItem cwi = this.workBench.getCell(); - if( cwi != null ) - { - cwi.setFuzzyMode( this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ), valueOf ); - } - } - - public void nextWorkBenchCopyMode() - { - this.workBench.getConfigManager().putSetting( Settings.COPY_MODE, Platform.nextEnum( this.getWorkBenchCopyMode() ) ); - } - - private CopyMode getWorkBenchCopyMode() - { - return (CopyMode) this.workBench.getConfigManager().getSetting( Settings.COPY_MODE ); - } - - @Override - protected int getHeight() - { - return 251; - } - - @Override - protected void setupConfig() - { - final IInventory cell = this.getUpgradeable().getInventoryByName( "cell" ); - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.WORKBENCH_CELL, cell, 0, 152, 8, this.getInventoryPlayer() ) ); - - final IInventory inv = this.getUpgradeable().getInventoryByName( "config" ); - final IInventory upgradeInventory = new Upgrades(); - // null, 3 * 8 ); - - int offset = 0; - final int x = 8; - final int y = 29; - for( int w = 0; w < 7; w++ ) - { - for( int z = 0; z < 9; z++ ) - { - this.addSlotToContainer( new SlotFakeTypeOnly( inv, offset, x + z * 18, y + w * 18 ) ); - offset++; - } - } - - for( int zz = 0; zz < 3; zz++ ) - { - for( int z = 0; z < 8; z++ ) - { - final int iSLot = zz * 8 + z; - this.addSlotToContainer( new OptionalSlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgradeInventory, this, iSLot, 187 + zz * 18, 8 + 18 * z, iSLot, this.getInventoryPlayer() ) ); - } - } - /* - * if ( supportCapacity() ) { for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new - * OptionalSlotFakeTypeOnly( inv, this, offset++, x, y, z, w, 1 ) ); - * for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new OptionalSlotFakeTypeOnly( - * inv, this, offset++, x, y, z, w + 2, 2 ) ); - * for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new OptionalSlotFakeTypeOnly( - * inv, this, offset++, x, y, z, w + 4, 3 ) ); } - */ - } - - @Override - public int availableUpgrades() - { - final ItemStack is = this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ); - if( this.prevStack != is ) - { - this.prevStack = is; - this.lastUpgrades = this.getCellUpgradeInventory().getSizeInventory(); - } - return this.lastUpgrades; - } - - @Override - public void detectAndSendChanges() - { - final ItemStack is = this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ); - if( Platform.isServer() ) - { - if( this.workBench.getWorldObj().getTileEntity( this.workBench.xCoord, this.workBench.yCoord, this.workBench.zCoord ) != this.workBench ) - { - this.setValidContainer( false ); - } - - for( final Object crafter : this.crafters ) - { - final ICrafting icrafting = (ICrafting) crafter; - - if( this.prevStack != is ) - { - // if the bars changed an item was probably made, so just send shit! - for( final Object s : this.inventorySlots ) - { - if( s instanceof OptionalSlotRestrictedInput ) - { - final OptionalSlotRestrictedInput sri = (OptionalSlotRestrictedInput) s; - icrafting.sendSlotContents( this, sri.slotNumber, sri.getStack() ); - } - } - ( (EntityPlayerMP) icrafting ).isChangingQuantityOnly = false; - } - } - - this.setCopyMode( this.getWorkBenchCopyMode() ); - this.setFuzzyMode( this.getWorkBenchFuzzyMode() ); - } - - this.prevStack = is; - this.standardDetectAndSendChanges(); - } - - @Override - public boolean isSlotEnabled( final int idx ) - { - return idx < this.availableUpgrades(); - } - - public IInventory getCellUpgradeInventory() - { - final IInventory upgradeInventory = this.workBench.getCellUpgradeInventory(); - - return upgradeInventory == null ? this.nullInventory : upgradeInventory; - } - - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - if( field.equals( "copyMode" ) ) - { - this.workBench.getConfigManager().putSetting( Settings.COPY_MODE, this.getCopyMode() ); - } - - super.onUpdate( field, oldValue, newValue ); - } - - public void clear() - { - final IInventory inv = this.getUpgradeable().getInventoryByName( "config" ); - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - inv.setInventorySlotContents( x, null ); - } - this.detectAndSendChanges(); - } - - private FuzzyMode getWorkBenchFuzzyMode() - { - final ICellWorkbenchItem cwi = this.workBench.getCell(); - if( cwi != null ) - { - return cwi.getFuzzyMode( this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ) ); - } - return FuzzyMode.IGNORE_ALL; - } - - public void partition() - { - final IInventory inv = this.getUpgradeable().getInventoryByName( "config" ); - - final IMEInventory cellInv = AEApi.instance().registries().cell().getCellInventory( this.getUpgradeable().getInventoryByName( "cell" ).getStackInSlot( 0 ), null, StorageChannel.ITEMS ); - - Iterator i = new NullIterator(); - if( cellInv != null ) - { - final IItemList list = cellInv.getAvailableItems( AEApi.instance().storage().createItemList() ); - i = list.iterator(); - } - - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - if( i.hasNext() ) - { - final ItemStack g = i.next().getItemStack(); - g.stackSize = 1; - inv.setInventorySlotContents( x, g ); - } - else - { - inv.setInventorySlotContents( x, null ); - } - } - - this.detectAndSendChanges(); - } - - public CopyMode getCopyMode() - { - return this.copyMode; - } - - private void setCopyMode( final CopyMode copyMode ) - { - this.copyMode = copyMode; - } - - private class Upgrades implements IInventory - { - - @Override - public int getSizeInventory() - { - return ContainerCellWorkbench.this.getCellUpgradeInventory().getSizeInventory(); - } - - @Override - public ItemStack getStackInSlot( final int i ) - { - return ContainerCellWorkbench.this.getCellUpgradeInventory().getStackInSlot( i ); - } - - @Override - public ItemStack decrStackSize( final int i, final int j ) - { - final IInventory inv = ContainerCellWorkbench.this.getCellUpgradeInventory(); - final ItemStack is = inv.decrStackSize( i, j ); - inv.markDirty(); - return is; - } - - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - final IInventory inv = ContainerCellWorkbench.this.getCellUpgradeInventory(); - final ItemStack is = inv.getStackInSlotOnClosing( i ); - inv.markDirty(); - return is; - } - - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - final IInventory inv = ContainerCellWorkbench.this.getCellUpgradeInventory(); - inv.setInventorySlotContents( i, itemstack ); - inv.markDirty(); - } - - @Override - public String getInventoryName() - { - return "Upgrades"; - } - - @Override - public boolean hasCustomInventoryName() - { - return false; - } - - @Override - public int getInventoryStackLimit() - { - return 1; - } - - @Override - public void markDirty() - { - - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return false; - } - - @Override - public void openInventory() - { - } - - @Override - public void closeInventory() - { - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return ContainerCellWorkbench.this.getCellUpgradeInventory().isItemValidForSlot( i, itemstack ); - } - } +public class ContainerCellWorkbench extends ContainerUpgradeable { + private final TileCellWorkbench workBench; + private final AppEngNullInventory nullInventory = new AppEngNullInventory(); + + @GuiSync(2) + public CopyMode copyMode = CopyMode.CLEAR_ON_REMOVE; + + private ItemStack prevStack = null; + private int lastUpgrades = 0; + + public ContainerCellWorkbench(final InventoryPlayer ip, final TileCellWorkbench te) { + super(ip, te); + this.workBench = te; + } + + public void setFuzzy(final FuzzyMode valueOf) { + final ICellWorkbenchItem cwi = this.workBench.getCell(); + if (cwi != null) { + cwi.setFuzzyMode(this.workBench.getInventoryByName("cell").getStackInSlot(0), valueOf); + } + } + + public void nextWorkBenchCopyMode() { + this.workBench + .getConfigManager() + .putSetting(Settings.COPY_MODE, Platform.nextEnum(this.getWorkBenchCopyMode())); + } + + private CopyMode getWorkBenchCopyMode() { + return (CopyMode) this.workBench.getConfigManager().getSetting(Settings.COPY_MODE); + } + + @Override + protected int getHeight() { + return 251; + } + + @Override + protected void setupConfig() { + final IInventory cell = this.getUpgradeable().getInventoryByName("cell"); + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.WORKBENCH_CELL, cell, 0, 152, 8, this.getInventoryPlayer())); + + final IInventory inv = this.getUpgradeable().getInventoryByName("config"); + final IInventory upgradeInventory = new Upgrades(); + // null, 3 * 8 ); + + int offset = 0; + final int x = 8; + final int y = 29; + for (int w = 0; w < 7; w++) { + for (int z = 0; z < 9; z++) { + this.addSlotToContainer(new SlotFakeTypeOnly(inv, offset, x + z * 18, y + w * 18)); + offset++; + } + } + + for (int zz = 0; zz < 3; zz++) { + for (int z = 0; z < 8; z++) { + final int iSLot = zz * 8 + z; + this.addSlotToContainer(new OptionalSlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgradeInventory, + this, + iSLot, + 187 + zz * 18, + 8 + 18 * z, + iSLot, + this.getInventoryPlayer())); + } + } + /* + * if ( supportCapacity() ) { for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new + * OptionalSlotFakeTypeOnly( inv, this, offset++, x, y, z, w, 1 ) ); + * for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new OptionalSlotFakeTypeOnly( + * inv, this, offset++, x, y, z, w + 2, 2 ) ); + * for (int w = 0; w < 2; w++) for (int z = 0; z < 9; z++) addSlotToContainer( new OptionalSlotFakeTypeOnly( + * inv, this, offset++, x, y, z, w + 4, 3 ) ); } + */ + } + + @Override + public int availableUpgrades() { + final ItemStack is = this.workBench.getInventoryByName("cell").getStackInSlot(0); + if (this.prevStack != is) { + this.prevStack = is; + this.lastUpgrades = this.getCellUpgradeInventory().getSizeInventory(); + } + return this.lastUpgrades; + } + + @Override + public void detectAndSendChanges() { + final ItemStack is = this.workBench.getInventoryByName("cell").getStackInSlot(0); + if (Platform.isServer()) { + if (this.workBench + .getWorldObj() + .getTileEntity(this.workBench.xCoord, this.workBench.yCoord, this.workBench.zCoord) + != this.workBench) { + this.setValidContainer(false); + } + + for (final Object crafter : this.crafters) { + final ICrafting icrafting = (ICrafting) crafter; + + if (this.prevStack != is) { + // if the bars changed an item was probably made, so just send shit! + for (final Object s : this.inventorySlots) { + if (s instanceof OptionalSlotRestrictedInput) { + final OptionalSlotRestrictedInput sri = (OptionalSlotRestrictedInput) s; + icrafting.sendSlotContents(this, sri.slotNumber, sri.getStack()); + } + } + ((EntityPlayerMP) icrafting).isChangingQuantityOnly = false; + } + } + + this.setCopyMode(this.getWorkBenchCopyMode()); + this.setFuzzyMode(this.getWorkBenchFuzzyMode()); + } + + this.prevStack = is; + this.standardDetectAndSendChanges(); + } + + @Override + public boolean isSlotEnabled(final int idx) { + return idx < this.availableUpgrades(); + } + + public IInventory getCellUpgradeInventory() { + final IInventory upgradeInventory = this.workBench.getCellUpgradeInventory(); + + return upgradeInventory == null ? this.nullInventory : upgradeInventory; + } + + @Override + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + if (field.equals("copyMode")) { + this.workBench.getConfigManager().putSetting(Settings.COPY_MODE, this.getCopyMode()); + } + + super.onUpdate(field, oldValue, newValue); + } + + public void clear() { + final IInventory inv = this.getUpgradeable().getInventoryByName("config"); + for (int x = 0; x < inv.getSizeInventory(); x++) { + inv.setInventorySlotContents(x, null); + } + this.detectAndSendChanges(); + } + + private FuzzyMode getWorkBenchFuzzyMode() { + final ICellWorkbenchItem cwi = this.workBench.getCell(); + if (cwi != null) { + return cwi.getFuzzyMode(this.workBench.getInventoryByName("cell").getStackInSlot(0)); + } + return FuzzyMode.IGNORE_ALL; + } + + public void partition() { + final IInventory inv = this.getUpgradeable().getInventoryByName("config"); + + final IMEInventory cellInv = AEApi.instance() + .registries() + .cell() + .getCellInventory( + this.getUpgradeable().getInventoryByName("cell").getStackInSlot(0), null, StorageChannel.ITEMS); + + Iterator i = new NullIterator(); + if (cellInv != null) { + final IItemList list = + cellInv.getAvailableItems(AEApi.instance().storage().createItemList()); + i = list.iterator(); + } + + for (int x = 0; x < inv.getSizeInventory(); x++) { + if (i.hasNext()) { + final ItemStack g = i.next().getItemStack(); + g.stackSize = 1; + inv.setInventorySlotContents(x, g); + } else { + inv.setInventorySlotContents(x, null); + } + } + + this.detectAndSendChanges(); + } + + public CopyMode getCopyMode() { + return this.copyMode; + } + + private void setCopyMode(final CopyMode copyMode) { + this.copyMode = copyMode; + } + + private class Upgrades implements IInventory { + + @Override + public int getSizeInventory() { + return ContainerCellWorkbench.this.getCellUpgradeInventory().getSizeInventory(); + } + + @Override + public ItemStack getStackInSlot(final int i) { + return ContainerCellWorkbench.this.getCellUpgradeInventory().getStackInSlot(i); + } + + @Override + public ItemStack decrStackSize(final int i, final int j) { + final IInventory inv = ContainerCellWorkbench.this.getCellUpgradeInventory(); + final ItemStack is = inv.decrStackSize(i, j); + inv.markDirty(); + return is; + } + + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + final IInventory inv = ContainerCellWorkbench.this.getCellUpgradeInventory(); + final ItemStack is = inv.getStackInSlotOnClosing(i); + inv.markDirty(); + return is; + } + + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + final IInventory inv = ContainerCellWorkbench.this.getCellUpgradeInventory(); + inv.setInventorySlotContents(i, itemstack); + inv.markDirty(); + } + + @Override + public String getInventoryName() { + return "Upgrades"; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + @Override + public void markDirty() {} + + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return false; + } + + @Override + public void openInventory() {} + + @Override + public void closeInventory() {} + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return ContainerCellWorkbench.this.getCellUpgradeInventory().isItemValidForSlot(i, itemstack); + } + } } diff --git a/src/main/java/appeng/container/implementations/ContainerChest.java b/src/main/java/appeng/container/implementations/ContainerChest.java index b168f2f4068..b1aea0dff32 100644 --- a/src/main/java/appeng/container/implementations/ContainerChest.java +++ b/src/main/java/appeng/container/implementations/ContainerChest.java @@ -18,25 +18,22 @@ package appeng.container.implementations; - import appeng.container.AEBaseContainer; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.storage.TileChest; import net.minecraft.entity.player.InventoryPlayer; +public class ContainerChest extends AEBaseContainer { -public class ContainerChest extends AEBaseContainer -{ - - private final TileChest chest; + private final TileChest chest; - public ContainerChest( final InventoryPlayer ip, final TileChest chest ) - { - super( ip, chest, null ); - this.chest = chest; + public ContainerChest(final InventoryPlayer ip, final TileChest chest) { + super(ip, chest, null); + this.chest = chest; - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, this.chest, 1, 80, 37, this.getInventoryPlayer() ) ); + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, this.chest, 1, 80, 37, this.getInventoryPlayer())); - this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 166 - /* height of player inventory */ 82); + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCondenser.java b/src/main/java/appeng/container/implementations/ContainerCondenser.java index 9602710a930..6008a97dd06 100644 --- a/src/main/java/appeng/container/implementations/ContainerCondenser.java +++ b/src/main/java/appeng/container/implementations/ContainerCondenser.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.CondenserOutput; import appeng.api.config.Settings; import appeng.container.AEBaseContainer; @@ -30,65 +29,67 @@ import appeng.util.Platform; import net.minecraft.entity.player.InventoryPlayer; - -public class ContainerCondenser extends AEBaseContainer implements IProgressProvider -{ - - private final TileCondenser condenser; - @GuiSync( 0 ) - public long requiredEnergy = 0; - @GuiSync( 1 ) - public long storedPower = 0; - @GuiSync( 2 ) - public CondenserOutput output = CondenserOutput.TRASH; - - public ContainerCondenser( final InventoryPlayer ip, final TileCondenser condenser ) - { - super( ip, condenser, null ); - this.condenser = condenser; - - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.TRASH, condenser, 0, 51, 52, ip ) ); - this.addSlotToContainer( new SlotOutput( condenser, 1, 105, 52, -1 ) ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.STORAGE_COMPONENT, condenser.getInternalInventory(), 2, 101, 26, ip ) ).setStackLimit( 1 ) ); - - this.bindPlayerInventory( ip, 0, 197 - /* height of player inventory */82 ); - } - - @Override - public void detectAndSendChanges() - { - if( Platform.isServer() ) - { - final double maxStorage = this.condenser.getStorage(); - final double requiredEnergy = this.condenser.getRequiredPower(); - - this.requiredEnergy = requiredEnergy == 0 ? (int) maxStorage : (int) Math.min( requiredEnergy, maxStorage ); - this.storedPower = (int) this.condenser.getStoredPower(); - this.setOutput( (CondenserOutput) this.condenser.getConfigManager().getSetting( Settings.CONDENSER_OUTPUT ) ); - } - - super.detectAndSendChanges(); - } - - @Override - public int getCurrentProgress() - { - return (int) this.storedPower; - } - - @Override - public int getMaxProgress() - { - return (int) this.requiredEnergy; - } - - public CondenserOutput getOutput() - { - return this.output; - } - - private void setOutput( final CondenserOutput output ) - { - this.output = output; - } +public class ContainerCondenser extends AEBaseContainer implements IProgressProvider { + + private final TileCondenser condenser; + + @GuiSync(0) + public long requiredEnergy = 0; + + @GuiSync(1) + public long storedPower = 0; + + @GuiSync(2) + public CondenserOutput output = CondenserOutput.TRASH; + + public ContainerCondenser(final InventoryPlayer ip, final TileCondenser condenser) { + super(ip, condenser, null); + this.condenser = condenser; + + this.addSlotToContainer( + new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.TRASH, condenser, 0, 51, 52, ip)); + this.addSlotToContainer(new SlotOutput(condenser, 1, 105, 52, -1)); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.STORAGE_COMPONENT, + condenser.getInternalInventory(), + 2, + 101, + 26, + ip)) + .setStackLimit(1)); + + this.bindPlayerInventory(ip, 0, 197 - /* height of player inventory */ 82); + } + + @Override + public void detectAndSendChanges() { + if (Platform.isServer()) { + final double maxStorage = this.condenser.getStorage(); + final double requiredEnergy = this.condenser.getRequiredPower(); + + this.requiredEnergy = requiredEnergy == 0 ? (int) maxStorage : (int) Math.min(requiredEnergy, maxStorage); + this.storedPower = (int) this.condenser.getStoredPower(); + this.setOutput((CondenserOutput) this.condenser.getConfigManager().getSetting(Settings.CONDENSER_OUTPUT)); + } + + super.detectAndSendChanges(); + } + + @Override + public int getCurrentProgress() { + return (int) this.storedPower; + } + + @Override + public int getMaxProgress() { + return (int) this.requiredEnergy; + } + + public CondenserOutput getOutput() { + return this.output; + } + + private void setOutput(final CondenserOutput output) { + this.output = output; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftAmount.java b/src/main/java/appeng/container/implementations/ContainerCraftAmount.java index 4678181dcb4..09d9d4cb38f 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftAmount.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftAmount.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGrid; import appeng.api.networking.security.BaseActionSource; @@ -31,69 +30,57 @@ import appeng.core.sync.GuiBridge; import appeng.tile.inventory.AppEngInternalInventory; import appeng.util.Platform; +import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import javax.annotation.Nonnull; - +public class ContainerCraftAmount extends AEBaseContainer { -public class ContainerCraftAmount extends AEBaseContainer -{ + private final Slot craftingItem; + private IAEItemStack itemToCreate; - private final Slot craftingItem; - private IAEItemStack itemToCreate; + public ContainerCraftAmount(final InventoryPlayer ip, final ITerminalHost te) { + super(ip, te); - public ContainerCraftAmount( final InventoryPlayer ip, final ITerminalHost te ) - { - super( ip, te ); - - this.craftingItem = new SlotInaccessible( new AppEngInternalInventory( null, 1 ), 0, 34, 53 ); - this.addSlotToContainer( this.getCraftingItem() ); - } + this.craftingItem = new SlotInaccessible(new AppEngInternalInventory(null, 1), 0, 34, 53); + this.addSlotToContainer(this.getCraftingItem()); + } - @Override - public void detectAndSendChanges() - { - super.detectAndSendChanges(); - this.verifyPermissions( SecurityPermissions.CRAFT, false ); - } + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + this.verifyPermissions(SecurityPermissions.CRAFT, false); + } - public IGrid getGrid() - { - final IActionHost h = ( (IActionHost) this.getTarget() ); - return h.getActionableNode().getGrid(); - } + public IGrid getGrid() { + final IActionHost h = ((IActionHost) this.getTarget()); + return h.getActionableNode().getGrid(); + } - public World getWorld() - { - return this.getPlayerInv().player.worldObj; - } + public World getWorld() { + return this.getPlayerInv().player.worldObj; + } - public BaseActionSource getActionSrc() - { - return new PlayerSource( this.getPlayerInv().player, (IActionHost) this.getTarget() ); - } + public BaseActionSource getActionSrc() { + return new PlayerSource(this.getPlayerInv().player, (IActionHost) this.getTarget()); + } - public Slot getCraftingItem() - { - return this.craftingItem; - } + public Slot getCraftingItem() { + return this.craftingItem; + } - public IAEItemStack getItemToCraft() - { - return this.itemToCreate; - } + public IAEItemStack getItemToCraft() { + return this.itemToCreate; + } - public void setItemToCraft( @Nonnull final IAEItemStack itemToCreate ) - { - this.itemToCreate = itemToCreate; - } + public void setItemToCraft(@Nonnull final IAEItemStack itemToCreate) { + this.itemToCreate = itemToCreate; + } - public void openConfirmationGUI( EntityPlayer player, TileEntity te ) - { - Platform.openGUI( player, te, this.getOpenContext().getSide(), GuiBridge.GUI_CRAFTING_CONFIRM ); + public void openConfirmationGUI(EntityPlayer player, TileEntity te) { + Platform.openGUI(player, te, this.getOpenContext().getSide(), GuiBridge.GUI_CRAFTING_CONFIRM); } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java b/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java index 3b8c38b28c4..94f28da3300 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.SecurityPermissions; @@ -49,7 +48,9 @@ import appeng.parts.reporting.PartPatternTerminalEx; import appeng.parts.reporting.PartTerminal; import appeng.util.Platform; -import com.google.common.collect.ImmutableSet; +import java.io.IOException; +import java.util.concurrent.Future; +import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; @@ -58,368 +59,312 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.world.World; -import javax.annotation.Nonnull; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.concurrent.Future; +public class ContainerCraftConfirm extends AEBaseContainer implements ICraftingCPUSelectorContainer { + + private Future job; + private ICraftingJob result; + + @GuiSync(0) + public long bytesUsed; + + @GuiSync(1) + public long cpuBytesAvail; + @GuiSync(2) + public int cpuCoProcessors; -public class ContainerCraftConfirm extends AEBaseContainer implements ICraftingCPUSelectorContainer -{ - - private Future job; - private ICraftingJob result; - @GuiSync( 0 ) - public long bytesUsed; - @GuiSync( 1 ) - public long cpuBytesAvail; - @GuiSync( 2 ) - public int cpuCoProcessors; - @GuiSync( 3 ) - public boolean autoStart = false; - @GuiSync( 4 ) - public boolean simulation = true; - @GuiSync( 6 ) - public boolean noCPU = true; - @GuiSync( 7 ) - public String myName = ""; - @GuiSync.Recurse( 8 ) + @GuiSync(3) + public boolean autoStart = false; + + @GuiSync(4) + public boolean simulation = true; + + @GuiSync(6) + public boolean noCPU = true; + + @GuiSync(7) + public String myName = ""; + + @GuiSync.Recurse(8) public final ContainerCPUTable cpuTable; - public ContainerCraftConfirm( final InventoryPlayer ip, final ITerminalHost te ) - { - super( ip, te ); - this.cpuTable = new ContainerCPUTable( this, this::onCPUUpdate, false, this::cpuMatches ); - } + public ContainerCraftConfirm(final InventoryPlayer ip, final ITerminalHost te) { + super(ip, te); + this.cpuTable = new ContainerCPUTable(this, this::onCPUUpdate, false, this::cpuMatches); + } @Override - public void selectCPU( int cpu ) - { - this.cpuTable.selectCPU( cpu ); + public void selectCPU(int cpu) { + this.cpuTable.selectCPU(cpu); } - public void onCPUUpdate( ICraftingCPU cpu ) - { - if( cpu == null ) - { - this.setCpuAvailableBytes( 0 ); - this.setCpuCoProcessors( 0 ); - this.setName( "" ); - } - else - { - this.setName( cpu.getName() ); - this.setCpuAvailableBytes( cpu.getAvailableStorage() ); - this.setCpuCoProcessors( cpu.getCoProcessors() ); - } - } - - @Override - public void detectAndSendChanges() - { + public void onCPUUpdate(ICraftingCPU cpu) { + if (cpu == null) { + this.setCpuAvailableBytes(0); + this.setCpuCoProcessors(0); + this.setName(""); + } else { + this.setName(cpu.getName()); + this.setCpuAvailableBytes(cpu.getAvailableStorage()); + this.setCpuCoProcessors(cpu.getCoProcessors()); + } + } + + @Override + public void detectAndSendChanges() { // Wait with CPU selection until job bytes are retrieved - if (this.bytesUsed != 0) - { - cpuTable.detectAndSendChanges( getGrid(), crafters ); + if (this.bytesUsed != 0) { + cpuTable.detectAndSendChanges(getGrid(), crafters); } - if( Platform.isClient() ) - { - return; - } - - this.setNoCPU( this.cpuTable.getCPUs().isEmpty() ); - - super.detectAndSendChanges(); - - if( this.getJob() != null && this.getJob().isDone() ) - { - try - { - this.result = this.getJob().get(); - - if( !this.result.isSimulation() ) - { - this.setSimulation( false ); - if( this.isAutoStart() ) - { - this.startJob(); - return; - } - } - else - { - this.setSimulation( true ); - } - - try - { - final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate( (byte) 0 ); - final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate( (byte) 1 ); - final PacketMEInventoryUpdate c = this.result.isSimulation() ? new PacketMEInventoryUpdate( (byte) 2 ) : null; - - final IItemList plan = AEApi.instance().storage().createItemList(); - this.result.populatePlan( plan ); - - this.setUsedBytes( this.result.getByteTotal() ); - - for( final IAEItemStack out : plan ) - { - - IAEItemStack o = out.copy(); - o.reset(); - o.setStackSize( out.getStackSize() ); - - final IAEItemStack p = out.copy(); - p.reset(); - p.setStackSize( out.getCountRequestable() ); - - final IStorageGrid sg = this.getGrid().getCache( IStorageGrid.class ); - final IMEInventory items = sg.getItemInventory(); - - IAEItemStack m = null; - if( c != null && this.result.isSimulation() ) - { - m = o.copy(); - o = items.extractItems( o, Actionable.SIMULATE, this.getActionSource() ); - - if( o == null ) - { - o = m.copy(); - o.setStackSize( 0 ); - } - - m.setStackSize( m.getStackSize() - o.getStackSize() ); - } - - if( o.getStackSize() > 0 ) - { - a.appendItem( o ); - } - - if( p.getStackSize() > 0 ) - { - b.appendItem( p ); - } - - if( c != null && m != null && m.getStackSize() > 0 ) - { - c.appendItem( m ); - } - } - - for( final Object g : this.crafters ) - { - if( g instanceof EntityPlayer ) - { - NetworkHandler.instance.sendTo( a, (EntityPlayerMP) g ); - NetworkHandler.instance.sendTo( b, (EntityPlayerMP) g ); - if( c != null ) - { - NetworkHandler.instance.sendTo( c, (EntityPlayerMP) g ); - } - } - } - } - catch( final IOException e ) - { - // :P - } - } - catch( final Throwable e ) - { - this.getPlayerInv().player.addChatMessage( new ChatComponentText( "Error: " + e.toString() ) ); - AELog.debug( e ); - this.setValidContainer( false ); - this.result = null; - } - - this.setJob( null ); - } - this.verifyPermissions( SecurityPermissions.CRAFT, false ); - } - - private IGrid getGrid() - { - final IActionHost h = ( (IActionHost) this.getTarget() ); - if (h == null || h.getActionableNode() == null) - return null; - return h.getActionableNode().getGrid(); - } - - private boolean cpuMatches( final CraftingCPUStatus c ) - { - return c.getStorage() >= this.getUsedBytes() && !c.isBusy(); - } - - public void startJob() - { - if( this.result != null && !this.isSimulation() && getGrid() != null) - { - final ICraftingGrid cc = this.getGrid().getCache( ICraftingGrid.class ); + if (Platform.isClient()) { + return; + } + + this.setNoCPU(this.cpuTable.getCPUs().isEmpty()); + + super.detectAndSendChanges(); + + if (this.getJob() != null && this.getJob().isDone()) { + try { + this.result = this.getJob().get(); + + if (!this.result.isSimulation()) { + this.setSimulation(false); + if (this.isAutoStart()) { + this.startJob(); + return; + } + } else { + this.setSimulation(true); + } + + try { + final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate((byte) 0); + final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate((byte) 1); + final PacketMEInventoryUpdate c = + this.result.isSimulation() ? new PacketMEInventoryUpdate((byte) 2) : null; + + final IItemList plan = + AEApi.instance().storage().createItemList(); + this.result.populatePlan(plan); + + this.setUsedBytes(this.result.getByteTotal()); + + for (final IAEItemStack out : plan) { + + IAEItemStack o = out.copy(); + o.reset(); + o.setStackSize(out.getStackSize()); + + final IAEItemStack p = out.copy(); + p.reset(); + p.setStackSize(out.getCountRequestable()); + + final IStorageGrid sg = this.getGrid().getCache(IStorageGrid.class); + final IMEInventory items = sg.getItemInventory(); + + IAEItemStack m = null; + if (c != null && this.result.isSimulation()) { + m = o.copy(); + o = items.extractItems(o, Actionable.SIMULATE, this.getActionSource()); + + if (o == null) { + o = m.copy(); + o.setStackSize(0); + } + + m.setStackSize(m.getStackSize() - o.getStackSize()); + } + + if (o.getStackSize() > 0) { + a.appendItem(o); + } + + if (p.getStackSize() > 0) { + b.appendItem(p); + } + + if (c != null && m != null && m.getStackSize() > 0) { + c.appendItem(m); + } + } + + for (final Object g : this.crafters) { + if (g instanceof EntityPlayer) { + NetworkHandler.instance.sendTo(a, (EntityPlayerMP) g); + NetworkHandler.instance.sendTo(b, (EntityPlayerMP) g); + if (c != null) { + NetworkHandler.instance.sendTo(c, (EntityPlayerMP) g); + } + } + } + } catch (final IOException e) { + // :P + } + } catch (final Throwable e) { + this.getPlayerInv().player.addChatMessage(new ChatComponentText("Error: " + e.toString())); + AELog.debug(e); + this.setValidContainer(false); + this.result = null; + } + + this.setJob(null); + } + this.verifyPermissions(SecurityPermissions.CRAFT, false); + } + + private IGrid getGrid() { + final IActionHost h = ((IActionHost) this.getTarget()); + if (h == null || h.getActionableNode() == null) return null; + return h.getActionableNode().getGrid(); + } + + private boolean cpuMatches(final CraftingCPUStatus c) { + return c.getStorage() >= this.getUsedBytes() && !c.isBusy(); + } + + public void startJob() { + if (this.result != null && !this.isSimulation() && getGrid() != null) { + final ICraftingGrid cc = this.getGrid().getCache(ICraftingGrid.class); CraftingCPUStatus selected = this.cpuTable.getSelectedCPU(); - final ICraftingLink g = cc.submitJob( this.result, null, (selected == null) ? null : selected.getServerCluster(), true, this.getActionSrc() ); - this.setAutoStart( false ); - if( g != null ) - { - this.switchToOriginalGUI(); - } - } - } - - public void switchToOriginalGUI() - { + final ICraftingLink g = cc.submitJob( + this.result, + null, + (selected == null) ? null : selected.getServerCluster(), + true, + this.getActionSrc()); + this.setAutoStart(false); + if (g != null) { + this.switchToOriginalGUI(); + } + } + } + + public void switchToOriginalGUI() { GuiBridge originalGui = null; final IActionHost ah = this.getActionHost(); - if( ah instanceof WirelessTerminalGuiObject ) - { + if (ah instanceof WirelessTerminalGuiObject) { originalGui = GuiBridge.GUI_WIRELESS_TERM; } - if( ah instanceof PartTerminal ) - { + if (ah instanceof PartTerminal) { originalGui = GuiBridge.GUI_ME; } - if( ah instanceof PartCraftingTerminal ) - { + if (ah instanceof PartCraftingTerminal) { originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; } - if( ah instanceof PartPatternTerminal ) - { + if (ah instanceof PartPatternTerminal) { originalGui = GuiBridge.GUI_PATTERN_TERMINAL; } - if( ah instanceof PartPatternTerminalEx) - { + if (ah instanceof PartPatternTerminalEx) { originalGui = GuiBridge.GUI_PATTERN_TERMINAL_EX; } - if (originalGui != null && this.getOpenContext() != null) - { - NetworkHandler.instance.sendTo( new PacketSwitchGuis( originalGui ), (EntityPlayerMP) this.getInventoryPlayer().player ); + if (originalGui != null && this.getOpenContext() != null) { + NetworkHandler.instance.sendTo( + new PacketSwitchGuis(originalGui), (EntityPlayerMP) this.getInventoryPlayer().player); final TileEntity te = this.getOpenContext().getTile(); - Platform.openGUI( this.getInventoryPlayer().player, te, this.getOpenContext().getSide(), originalGui ); + Platform.openGUI( + this.getInventoryPlayer().player, te, this.getOpenContext().getSide(), originalGui); + } + } + + private BaseActionSource getActionSrc() { + return new PlayerSource(this.getPlayerInv().player, (IActionHost) this.getTarget()); + } + + @Override + public void removeCraftingFromCrafters(final ICrafting c) { + super.removeCraftingFromCrafters(c); + if (this.getJob() != null) { + this.getJob().cancel(true); + this.setJob(null); + } + } + + @Override + public void onContainerClosed(final EntityPlayer par1EntityPlayer) { + super.onContainerClosed(par1EntityPlayer); + if (this.getJob() != null) { + this.getJob().cancel(true); + this.setJob(null); } } - private BaseActionSource getActionSrc() - { - return new PlayerSource( this.getPlayerInv().player, (IActionHost) this.getTarget() ); - } - - @Override - public void removeCraftingFromCrafters( final ICrafting c ) - { - super.removeCraftingFromCrafters( c ); - if( this.getJob() != null ) - { - this.getJob().cancel( true ); - this.setJob( null ); - } - } - - @Override - public void onContainerClosed( final EntityPlayer par1EntityPlayer ) - { - super.onContainerClosed( par1EntityPlayer ); - if( this.getJob() != null ) - { - this.getJob().cancel( true ); - this.setJob( null ); - } - } - - public World getWorld() - { - return this.getPlayerInv().player.worldObj; - } - - public boolean isAutoStart() - { - return this.autoStart; - } - - public void setAutoStart( final boolean autoStart ) - { - this.autoStart = autoStart; - } - - public long getUsedBytes() - { - return this.bytesUsed; - } - - private void setUsedBytes( final long bytesUsed ) - { - this.bytesUsed = bytesUsed; - } - - public long getCpuAvailableBytes() - { - return this.cpuBytesAvail; - } - - private void setCpuAvailableBytes( final long cpuBytesAvail ) - { - this.cpuBytesAvail = cpuBytesAvail; - } - - public int getCpuCoProcessors() - { - return this.cpuCoProcessors; - } - - private void setCpuCoProcessors( final int cpuCoProcessors ) - { - this.cpuCoProcessors = cpuCoProcessors; - } - - public int getSelectedCpu() - { - return this.cpuTable.selectedCpuSerial; - } - - public String getName() - { - return this.myName; - } - - private void setName( @Nonnull final String myName ) - { - this.myName = myName; - } - - public boolean hasNoCPU() - { - return this.noCPU; - } - - private void setNoCPU( final boolean noCPU ) - { - this.noCPU = noCPU; - } - - public boolean isSimulation() - { - return this.simulation; - } - - private void setSimulation( final boolean simulation ) - { - this.simulation = simulation; - } - - private Future getJob() - { - return this.job; - } - - public void setJob( final Future job ) - { - this.job = job; - } + public World getWorld() { + return this.getPlayerInv().player.worldObj; + } + + public boolean isAutoStart() { + return this.autoStart; + } + + public void setAutoStart(final boolean autoStart) { + this.autoStart = autoStart; + } + + public long getUsedBytes() { + return this.bytesUsed; + } + + private void setUsedBytes(final long bytesUsed) { + this.bytesUsed = bytesUsed; + } + + public long getCpuAvailableBytes() { + return this.cpuBytesAvail; + } + + private void setCpuAvailableBytes(final long cpuBytesAvail) { + this.cpuBytesAvail = cpuBytesAvail; + } + + public int getCpuCoProcessors() { + return this.cpuCoProcessors; + } + + private void setCpuCoProcessors(final int cpuCoProcessors) { + this.cpuCoProcessors = cpuCoProcessors; + } + + public int getSelectedCpu() { + return this.cpuTable.selectedCpuSerial; + } + + public String getName() { + return this.myName; + } + + private void setName(@Nonnull final String myName) { + this.myName = myName; + } + + public boolean hasNoCPU() { + return this.noCPU; + } + + private void setNoCPU(final boolean noCPU) { + this.noCPU = noCPU; + } + + public boolean isSimulation() { + return this.simulation; + } + + private void setSimulation(final boolean simulation) { + this.simulation = simulation; + } + + private Future getJob() { + return this.job; + } + + public void setJob(final Future job) { + this.job = job; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftingCPU.java b/src/main/java/appeng/container/implementations/ContainerCraftingCPU.java index 320de674378..58e2c2ebece 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftingCPU.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftingCPU.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.AEApi; import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; @@ -30,7 +29,6 @@ import appeng.api.storage.IMEMonitorHandlerReceiver; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; -import appeng.api.util.WorldCoord; import appeng.container.AEBaseContainer; import appeng.container.guisync.GuiSync; import appeng.core.AELog; @@ -42,262 +40,214 @@ import appeng.me.cluster.implementations.CraftingCPUCluster; import appeng.tile.crafting.TileCraftingTile; import appeng.util.Platform; +import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ICrafting; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; - - -public class ContainerCraftingCPU extends AEBaseContainer implements IMEMonitorHandlerReceiver, ICustomNameObject -{ - - private final IItemList list = AEApi.instance().storage().createItemList(); - private IGrid network; - private CraftingCPUCluster monitor = null; - private String cpuName = null; - - @GuiSync( 0 ) - public long eta = -1; - - public ContainerCraftingCPU( final InventoryPlayer ip, final Object te ) - { - super( ip, te ); - final IGridHost host = (IGridHost) ( te instanceof IGridHost ? te : null ); - - if( host != null ) - { - this.findNode( host, ForgeDirection.UNKNOWN ); - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - this.findNode( host, d ); - } - } - - if( te instanceof TileCraftingTile ) - { - this.setCPU( (ICraftingCPU) ( (IAEMultiBlock) te ).getCluster() ); - } - - if( this.getNetwork() == null && Platform.isServer() ) - { - this.setValidContainer( false ); - } - } - - private void findNode( final IGridHost host, final ForgeDirection d ) - { - if( this.getNetwork() == null ) - { - final IGridNode node = host.getGridNode( d ); - if( node != null ) - { - this.setNetwork( node.getGrid() ); - } - } - } - - protected void setCPU( final ICraftingCPU c ) - { - if( c == this.getMonitor() ) - { - return; - } - - if( this.getMonitor() != null ) - { - this.getMonitor().removeListener( this ); - } - - for( final Object g : this.crafters ) - { - if( g instanceof EntityPlayer ) - { - try - { - NetworkHandler.instance.sendTo( new PacketValueConfig( "CraftingStatus", "Clear" ), (EntityPlayerMP) g ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - - if( c instanceof CraftingCPUCluster ) - { - this.cpuName = c.getName(); - this.setMonitor( (CraftingCPUCluster) c ); - this.list.resetStatus(); - this.getMonitor().getListOfItem( this.list, CraftingItemList.ALL ); - this.getMonitor().addListener( this, null ); - this.setEstimatedTime( 0 ); - } - else - { - this.setMonitor( null ); - this.cpuName = ""; - this.setEstimatedTime( -1 ); - } - } - - public void cancelCrafting() - { - if( this.getMonitor() != null ) - { - this.getMonitor().cancel(); - } - this.setEstimatedTime( -1 ); - } - - @Override - public void removeCraftingFromCrafters( final ICrafting c ) - { - super.removeCraftingFromCrafters( c ); - - if( this.crafters.isEmpty() && this.getMonitor() != null ) - { - this.getMonitor().removeListener( this ); - } - } - - @Override - public void onContainerClosed( final EntityPlayer player ) - { - super.onContainerClosed( player ); - if( this.getMonitor() != null ) - { - this.getMonitor().removeListener( this ); - } - } - - @Override - public void detectAndSendChanges() - { - if( Platform.isServer() && this.getMonitor() != null && !this.list.isEmpty() ) - { - try - { - if( this.getEstimatedTime() >= 0 ) - { - final long elapsedTime = this.getMonitor().getElapsedTime(); - final double remainingItems = this.getMonitor().getRemainingItemCount(); - final double startItems = this.getMonitor().getStartItemCount(); - final long eta = (long) ( elapsedTime / Math.max( 1d, ( startItems - remainingItems ) ) * remainingItems ); - this.setEstimatedTime( eta ); - } - - final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate( (byte) 0 ); - final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate( (byte) 1 ); - final PacketMEInventoryUpdate c = new PacketMEInventoryUpdate( (byte) 2 ); - - for( final IAEItemStack out : this.list ) - { - a.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.STORAGE ) ); - b.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.ACTIVE ) ); - c.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.PENDING ) ); - } - - this.list.resetStatus(); - - for( final Object g : this.crafters ) - { - if( g instanceof EntityPlayer ) - { - if( !a.isEmpty() ) - { - NetworkHandler.instance.sendTo( a, (EntityPlayerMP) g ); - } - - if( !b.isEmpty() ) - { - NetworkHandler.instance.sendTo( b, (EntityPlayerMP) g ); - } - - if( !c.isEmpty() ) - { - NetworkHandler.instance.sendTo( c, (EntityPlayerMP) g ); - } - } - } - } - catch( final IOException e ) - { - // :P - } - } - super.detectAndSendChanges(); - } - - @Override - public boolean isValid( final Object verificationToken ) - { - return true; - } - - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final BaseActionSource actionSource ) - { - for( IAEItemStack is : change ) - { - is = is.copy(); - is.setStackSize( 1 ); - this.list.add( is ); - } - } - - @Override - public void onListUpdate() - { - - } - - @Override - public String getCustomName() - { - return this.cpuName; - } - - @Override - public boolean hasCustomName() - { - return this.cpuName != null && this.cpuName.length() > 0; - } - - @Override - public void setCustomName(String name) { - this.cpuName = name; - } - - public long getEstimatedTime() - { - return this.eta; - } - - private void setEstimatedTime( final long eta ) - { - this.eta = eta; - } - - CraftingCPUCluster getMonitor() - { - return this.monitor; - } - - private void setMonitor( final CraftingCPUCluster monitor ) - { - this.monitor = monitor; - } - - IGrid getNetwork() - { - return this.network; - } - - private void setNetwork( final IGrid network ) - { - this.network = network; - } +public class ContainerCraftingCPU extends AEBaseContainer + implements IMEMonitorHandlerReceiver, ICustomNameObject { + + private final IItemList list = AEApi.instance().storage().createItemList(); + private IGrid network; + private CraftingCPUCluster monitor = null; + private String cpuName = null; + + @GuiSync(0) + public long eta = -1; + + public ContainerCraftingCPU(final InventoryPlayer ip, final Object te) { + super(ip, te); + final IGridHost host = (IGridHost) (te instanceof IGridHost ? te : null); + + if (host != null) { + this.findNode(host, ForgeDirection.UNKNOWN); + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + this.findNode(host, d); + } + } + + if (te instanceof TileCraftingTile) { + this.setCPU((ICraftingCPU) ((IAEMultiBlock) te).getCluster()); + } + + if (this.getNetwork() == null && Platform.isServer()) { + this.setValidContainer(false); + } + } + + private void findNode(final IGridHost host, final ForgeDirection d) { + if (this.getNetwork() == null) { + final IGridNode node = host.getGridNode(d); + if (node != null) { + this.setNetwork(node.getGrid()); + } + } + } + + protected void setCPU(final ICraftingCPU c) { + if (c == this.getMonitor()) { + return; + } + + if (this.getMonitor() != null) { + this.getMonitor().removeListener(this); + } + + for (final Object g : this.crafters) { + if (g instanceof EntityPlayer) { + try { + NetworkHandler.instance.sendTo( + new PacketValueConfig("CraftingStatus", "Clear"), (EntityPlayerMP) g); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + + if (c instanceof CraftingCPUCluster) { + this.cpuName = c.getName(); + this.setMonitor((CraftingCPUCluster) c); + this.list.resetStatus(); + this.getMonitor().getListOfItem(this.list, CraftingItemList.ALL); + this.getMonitor().addListener(this, null); + this.setEstimatedTime(0); + } else { + this.setMonitor(null); + this.cpuName = ""; + this.setEstimatedTime(-1); + } + } + + public void cancelCrafting() { + if (this.getMonitor() != null) { + this.getMonitor().cancel(); + } + this.setEstimatedTime(-1); + } + + @Override + public void removeCraftingFromCrafters(final ICrafting c) { + super.removeCraftingFromCrafters(c); + + if (this.crafters.isEmpty() && this.getMonitor() != null) { + this.getMonitor().removeListener(this); + } + } + + @Override + public void onContainerClosed(final EntityPlayer player) { + super.onContainerClosed(player); + if (this.getMonitor() != null) { + this.getMonitor().removeListener(this); + } + } + + @Override + public void detectAndSendChanges() { + if (Platform.isServer() && this.getMonitor() != null && !this.list.isEmpty()) { + try { + if (this.getEstimatedTime() >= 0) { + final long elapsedTime = this.getMonitor().getElapsedTime(); + final double remainingItems = this.getMonitor().getRemainingItemCount(); + final double startItems = this.getMonitor().getStartItemCount(); + final long eta = + (long) (elapsedTime / Math.max(1d, (startItems - remainingItems)) * remainingItems); + this.setEstimatedTime(eta); + } + + final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate((byte) 0); + final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate((byte) 1); + final PacketMEInventoryUpdate c = new PacketMEInventoryUpdate((byte) 2); + + for (final IAEItemStack out : this.list) { + a.appendItem(this.getMonitor().getItemStack(out, CraftingItemList.STORAGE)); + b.appendItem(this.getMonitor().getItemStack(out, CraftingItemList.ACTIVE)); + c.appendItem(this.getMonitor().getItemStack(out, CraftingItemList.PENDING)); + } + + this.list.resetStatus(); + + for (final Object g : this.crafters) { + if (g instanceof EntityPlayer) { + if (!a.isEmpty()) { + NetworkHandler.instance.sendTo(a, (EntityPlayerMP) g); + } + + if (!b.isEmpty()) { + NetworkHandler.instance.sendTo(b, (EntityPlayerMP) g); + } + + if (!c.isEmpty()) { + NetworkHandler.instance.sendTo(c, (EntityPlayerMP) g); + } + } + } + } catch (final IOException e) { + // :P + } + } + super.detectAndSendChanges(); + } + + @Override + public boolean isValid(final Object verificationToken) { + return true; + } + + @Override + public void postChange( + final IBaseMonitor monitor, + final Iterable change, + final BaseActionSource actionSource) { + for (IAEItemStack is : change) { + is = is.copy(); + is.setStackSize(1); + this.list.add(is); + } + } + + @Override + public void onListUpdate() {} + + @Override + public String getCustomName() { + return this.cpuName; + } + + @Override + public boolean hasCustomName() { + return this.cpuName != null && this.cpuName.length() > 0; + } + + @Override + public void setCustomName(String name) { + this.cpuName = name; + } + + public long getEstimatedTime() { + return this.eta; + } + + private void setEstimatedTime(final long eta) { + this.eta = eta; + } + + CraftingCPUCluster getMonitor() { + return this.monitor; + } + + private void setMonitor(final CraftingCPUCluster monitor) { + this.monitor = monitor; + } + + IGrid getNetwork() { + return this.network; + } + + private void setNetwork(final IGrid network) { + this.network = network; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java b/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java index f9976999b5b..42ec078ae3e 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java @@ -18,56 +18,37 @@ package appeng.container.implementations; - -import appeng.api.networking.IGrid; -import appeng.api.networking.crafting.ICraftingCPU; -import appeng.api.networking.crafting.ICraftingGrid; import appeng.api.storage.ITerminalHost; import appeng.container.guisync.GuiSync; import appeng.container.interfaces.ICraftingCPUSelectorContainer; -import appeng.core.AELog; -import appeng.core.sync.network.NetworkHandler; -import appeng.core.sync.packets.PacketCraftingCPUsUpdate; -import appeng.util.Platform; -import com.google.common.collect.ImmutableSet; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; - -import java.io.IOException; import java.util.*; +import net.minecraft.entity.player.InventoryPlayer; - -public class ContainerCraftingStatus extends ContainerCraftingCPU implements ICraftingCPUSelectorContainer -{ - @GuiSync.Recurse( 5 ) +public class ContainerCraftingStatus extends ContainerCraftingCPU implements ICraftingCPUSelectorContainer { + @GuiSync.Recurse(5) public ContainerCPUTable cpuTable; - public ContainerCraftingStatus( final InventoryPlayer ip, final ITerminalHost te ) - { - super( ip, te ); - cpuTable = new ContainerCPUTable( this, this::setCPU, true, c -> true ); - } + public ContainerCraftingStatus(final InventoryPlayer ip, final ITerminalHost te) { + super(ip, te); + cpuTable = new ContainerCPUTable(this, this::setCPU, true, c -> true); + } - public ContainerCPUTable getCPUTable() - { + public ContainerCPUTable getCPUTable() { return cpuTable; } @Override - public void detectAndSendChanges() - { + public void detectAndSendChanges() { cpuTable.detectAndSendChanges(getNetwork(), crafters); - super.detectAndSendChanges(); - } + super.detectAndSendChanges(); + } @Override - public void selectCPU( int serial ) - { - cpuTable.selectCPU( serial ); - } + public void selectCPU(int serial) { + cpuTable.selectCPU(serial); + } - public List getCPUs() - { + public List getCPUs() { return cpuTable.getCPUs(); } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java b/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java index 4ff9a2be3d1..1c8501d3f99 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.storage.ITerminalHost; import appeng.container.ContainerNull; import appeng.container.slot.SlotCraftingMatrix; @@ -34,79 +33,83 @@ import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; - -public class ContainerCraftingTerm extends ContainerMEMonitorable implements IAEAppEngInventory, IContainerCraftingPacket -{ - - private final PartCraftingTerminal ct; - private final AppEngInternalInventory output = new AppEngInternalInventory( this, 1 ); - private final SlotCraftingMatrix[] craftingSlots = new SlotCraftingMatrix[9]; - private final SlotCraftingTerm outputSlot; - - public ContainerCraftingTerm( final InventoryPlayer ip, final ITerminalHost monitorable ) - { - super( ip, monitorable, false ); - this.ct = (PartCraftingTerminal) monitorable; - - final IInventory crafting = this.ct.getInventoryByName( "crafting" ); - - for( int y = 0; y < 3; y++ ) - { - for( int x = 0; x < 3; x++ ) - { - this.addSlotToContainer( this.craftingSlots[x + y * 3] = new SlotCraftingMatrix( this, crafting, x + y * 3, 37 + x * 18, -72 + y * 18 ) ); - } - } - - this.addSlotToContainer( this.outputSlot = new SlotCraftingTerm( this.getPlayerInv().player, this.getActionSource(), this.getPowerSource(), monitorable, crafting, crafting, this.output, 131, -72 + 18, this ) ); - - this.bindPlayerInventory( ip, 0, 0 ); - - this.onCraftMatrixChanged( crafting ); - } - - /** - * Callback for when the crafting matrix is changed. - */ - @Override - public void onCraftMatrixChanged( final IInventory par1IInventory ) - { - final ContainerNull cn = new ContainerNull(); - final InventoryCrafting ic = new InventoryCrafting( cn, 3, 3 ); - - for( int x = 0; x < 9; x++ ) - { - ic.setInventorySlotContents( x, this.craftingSlots[x].getStack() ); - } - - this.outputSlot.putStack( CraftingManager.getInstance().findMatchingRecipe( ic, this.getPlayerInv().player.worldObj ) ); - } - - @Override - public void saveChanges() - { - - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "player" ) ) - { - return this.getInventoryPlayer(); - } - return this.ct.getInventoryByName( name ); - } - - @Override - public boolean useRealItems() - { - return true; - } +public class ContainerCraftingTerm extends ContainerMEMonitorable + implements IAEAppEngInventory, IContainerCraftingPacket { + + private final PartCraftingTerminal ct; + private final AppEngInternalInventory output = new AppEngInternalInventory(this, 1); + private final SlotCraftingMatrix[] craftingSlots = new SlotCraftingMatrix[9]; + private final SlotCraftingTerm outputSlot; + + public ContainerCraftingTerm(final InventoryPlayer ip, final ITerminalHost monitorable) { + super(ip, monitorable, false); + this.ct = (PartCraftingTerminal) monitorable; + + final IInventory crafting = this.ct.getInventoryByName("crafting"); + + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 3; x++) { + this.addSlotToContainer( + this.craftingSlots[x + y * 3] = + new SlotCraftingMatrix(this, crafting, x + y * 3, 37 + x * 18, -72 + y * 18)); + } + } + + this.addSlotToContainer( + this.outputSlot = new SlotCraftingTerm( + this.getPlayerInv().player, + this.getActionSource(), + this.getPowerSource(), + monitorable, + crafting, + crafting, + this.output, + 131, + -72 + 18, + this)); + + this.bindPlayerInventory(ip, 0, 0); + + this.onCraftMatrixChanged(crafting); + } + + /** + * Callback for when the crafting matrix is changed. + */ + @Override + public void onCraftMatrixChanged(final IInventory par1IInventory) { + final ContainerNull cn = new ContainerNull(); + final InventoryCrafting ic = new InventoryCrafting(cn, 3, 3); + + for (int x = 0; x < 9; x++) { + ic.setInventorySlotContents(x, this.craftingSlots[x].getStack()); + } + + this.outputSlot.putStack( + CraftingManager.getInstance().findMatchingRecipe(ic, this.getPlayerInv().player.worldObj)); + } + + @Override + public void saveChanges() {} + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) {} + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("player")) { + return this.getInventoryPlayer(); + } + return this.ct.getInventoryByName(name); + } + + @Override + public boolean useRealItems() { + return true; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerDrive.java b/src/main/java/appeng/container/implementations/ContainerDrive.java index 9e74837e124..eb86c7ce25f 100644 --- a/src/main/java/appeng/container/implementations/ContainerDrive.java +++ b/src/main/java/appeng/container/implementations/ContainerDrive.java @@ -18,28 +18,28 @@ package appeng.container.implementations; - import appeng.container.AEBaseContainer; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.storage.TileDrive; import net.minecraft.entity.player.InventoryPlayer; - -public class ContainerDrive extends AEBaseContainer -{ - - public ContainerDrive( final InventoryPlayer ip, final TileDrive drive ) - { - super( ip, drive, null ); - - for( int y = 0; y < 5; y++ ) - { - for( int x = 0; x < 2; x++ ) - { - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, drive, x + y * 2, 71 + x * 18, 14 + y * 18, this.getInventoryPlayer() ) ); - } - } - - this.bindPlayerInventory( ip, 0, 199 - /* height of player inventory */82 ); - } +public class ContainerDrive extends AEBaseContainer { + + public ContainerDrive(final InventoryPlayer ip, final TileDrive drive) { + super(ip, drive, null); + + for (int y = 0; y < 5; y++) { + for (int x = 0; x < 2; x++) { + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, + drive, + x + y * 2, + 71 + x * 18, + 14 + y * 18, + this.getInventoryPlayer())); + } + } + + this.bindPlayerInventory(ip, 0, 199 - /* height of player inventory */ 82); + } } diff --git a/src/main/java/appeng/container/implementations/ContainerFormationPlane.java b/src/main/java/appeng/container/implementations/ContainerFormationPlane.java index 8a2dd14b711..42e93ac4177 100644 --- a/src/main/java/appeng/container/implementations/ContainerFormationPlane.java +++ b/src/main/java/appeng/container/implementations/ContainerFormationPlane.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.*; import appeng.container.guisync.GuiSync; import appeng.container.slot.OptionalSlotFakeTypeOnly; @@ -29,95 +28,109 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; - -public class ContainerFormationPlane extends ContainerUpgradeable -{ - - @GuiSync( 6 ) - public YesNo placeMode; - - public ContainerFormationPlane( final InventoryPlayer ip, final PartFormationPlane te ) - { - super( ip, te ); - } - - @Override - protected int getHeight() - { - return 251; - } - - @Override - protected void setupConfig() - { - final int xo = 8; - final int yo = 23 + 6; - - final IInventory config = this.getUpgradeable().getInventoryByName( "config" ); - for( int y = 0; y < 7; y++ ) - { - for( int x = 0; x < 9; x++ ) - { - if( y < 2 ) - { - this.addSlotToContainer( new SlotFakeTypeOnly( config, y * 9 + x, xo + x * 18, yo + y * 18 ) ); - } - else - { - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( config, this, y * 9 + x, xo, yo, x, y, y - 2 ) ); - } - } - } - - final IInventory upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - - @Override - protected boolean supportCapacity() - { - return true; - } - - @Override - public int availableUpgrades() - { - return 5; - } - - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); - - if( Platform.isServer() ) - { - this.setFuzzyMode( (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting( Settings.FUZZY_MODE ) ); - this.setPlaceMode( (YesNo) this.getUpgradeable().getConfigManager().getSetting( Settings.PLACE_BLOCK ) ); - } - - this.standardDetectAndSendChanges(); - } - - @Override - public boolean isSlotEnabled( final int idx ) - { - final int upgrades = this.getUpgradeable().getInstalledUpgrades( Upgrades.CAPACITY ); - - return upgrades > idx; - } - - public YesNo getPlaceMode() - { - return this.placeMode; - } - - private void setPlaceMode( final YesNo placeMode ) - { - this.placeMode = placeMode; - } +public class ContainerFormationPlane extends ContainerUpgradeable { + + @GuiSync(6) + public YesNo placeMode; + + public ContainerFormationPlane(final InventoryPlayer ip, final PartFormationPlane te) { + super(ip, te); + } + + @Override + protected int getHeight() { + return 251; + } + + @Override + protected void setupConfig() { + final int xo = 8; + final int yo = 23 + 6; + + final IInventory config = this.getUpgradeable().getInventoryByName("config"); + for (int y = 0; y < 7; y++) { + for (int x = 0; x < 9; x++) { + if (y < 2) { + this.addSlotToContainer(new SlotFakeTypeOnly(config, y * 9 + x, xo + x * 18, yo + y * 18)); + } else { + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(config, this, y * 9 + x, xo, yo, x, y, y - 2)); + } + } + } + + final IInventory upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 1, + 187, + 8 + 18, + this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 2, + 187, + 8 + 18 * 2, + this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 3, + 187, + 8 + 18 * 3, + this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 4, + 187, + 8 + 18 * 4, + this.getInventoryPlayer())) + .setNotDraggable()); + } + + @Override + protected boolean supportCapacity() { + return true; + } + + @Override + public int availableUpgrades() { + return 5; + } + + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); + + if (Platform.isServer()) { + this.setFuzzyMode( + (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting(Settings.FUZZY_MODE)); + this.setPlaceMode((YesNo) this.getUpgradeable().getConfigManager().getSetting(Settings.PLACE_BLOCK)); + } + + this.standardDetectAndSendChanges(); + } + + @Override + public boolean isSlotEnabled(final int idx) { + final int upgrades = this.getUpgradeable().getInstalledUpgrades(Upgrades.CAPACITY); + + return upgrades > idx; + } + + public YesNo getPlaceMode() { + return this.placeMode; + } + + private void setPlaceMode(final YesNo placeMode) { + this.placeMode = placeMode; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerGrinder.java b/src/main/java/appeng/container/implementations/ContainerGrinder.java index e6963430704..cc8d3e6b068 100644 --- a/src/main/java/appeng/container/implementations/ContainerGrinder.java +++ b/src/main/java/appeng/container/implementations/ContainerGrinder.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.container.AEBaseContainer; import appeng.container.slot.SlotInaccessible; import appeng.container.slot.SlotOutput; @@ -26,24 +25,24 @@ import appeng.tile.grindstone.TileGrinder; import net.minecraft.entity.player.InventoryPlayer; +public class ContainerGrinder extends AEBaseContainer { -public class ContainerGrinder extends AEBaseContainer -{ - - public ContainerGrinder( final InventoryPlayer ip, final TileGrinder grinder ) - { - super( ip, grinder, null ); + public ContainerGrinder(final InventoryPlayer ip, final TileGrinder grinder) { + super(ip, grinder, null); - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ORE, grinder, 0, 12, 17, this.getInventoryPlayer() ) ); - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ORE, grinder, 1, 12 + 18, 17, this.getInventoryPlayer() ) ); - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ORE, grinder, 2, 12 + 36, 17, this.getInventoryPlayer() ) ); + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.ORE, grinder, 0, 12, 17, this.getInventoryPlayer())); + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.ORE, grinder, 1, 12 + 18, 17, this.getInventoryPlayer())); + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.ORE, grinder, 2, 12 + 36, 17, this.getInventoryPlayer())); - this.addSlotToContainer( new SlotInaccessible( grinder, 6, 80, 40 ) ); + this.addSlotToContainer(new SlotInaccessible(grinder, 6, 80, 40)); - this.addSlotToContainer( new SlotOutput( grinder, 3, 112, 63, 2 * 16 + 15 ) ); - this.addSlotToContainer( new SlotOutput( grinder, 4, 112 + 18, 63, 2 * 16 + 15 ) ); - this.addSlotToContainer( new SlotOutput( grinder, 5, 112 + 36, 63, 2 * 16 + 15 ) ); + this.addSlotToContainer(new SlotOutput(grinder, 3, 112, 63, 2 * 16 + 15)); + this.addSlotToContainer(new SlotOutput(grinder, 4, 112 + 18, 63, 2 * 16 + 15)); + this.addSlotToContainer(new SlotOutput(grinder, 5, 112 + 36, 63, 2 * 16 + 15)); - this.bindPlayerInventory( ip, 0, 176 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 176 - /* height of player inventory */ 82); + } } diff --git a/src/main/java/appeng/container/implementations/ContainerIOPort.java b/src/main/java/appeng/container/implementations/ContainerIOPort.java index 3ad1e6278de..39990b22493 100644 --- a/src/main/java/appeng/container/implementations/ContainerIOPort.java +++ b/src/main/java/appeng/container/implementations/ContainerIOPort.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.*; import appeng.container.guisync.GuiSync; import appeng.container.slot.SlotOutput; @@ -28,102 +27,116 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; - -public class ContainerIOPort extends ContainerUpgradeable -{ - - @GuiSync( 2 ) - public FullnessMode fMode = FullnessMode.EMPTY; - @GuiSync( 3 ) - public OperationMode opMode = OperationMode.EMPTY; - - public ContainerIOPort( final InventoryPlayer ip, final TileIOPort te ) - { - super( ip, te ); - } - - @Override - protected int getHeight() - { - return 166; - } - - @Override - protected void setupConfig() - { - int offX = 19; - int offY = 17; - - final IInventory cells = this.getUpgradeable().getInventoryByName( "cells" ); - - for( int y = 0; y < 3; y++ ) - { - for( int x = 0; x < 2; x++ ) - { - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, cells, x + y * 2, offX + x * 18, offY + y * 18, this.getInventoryPlayer() ) ); - } - } - - offX = 122; - offY = 17; - for( int y = 0; y < 3; y++ ) - { - for( int x = 0; x < 2; x++ ) - { - this.addSlotToContainer( new SlotOutput( cells, 6 + x + y * 2, offX + x * 18, offY + y * 18, SlotRestrictedInput.PlacableItemType.STORAGE_CELLS.IIcon ) ); - } - } - - final IInventory upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - - @Override - protected boolean supportCapacity() - { - return false; - } - - @Override - public int availableUpgrades() - { - return 3; - } - - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); - - if( Platform.isServer() ) - { - this.setOperationMode( (OperationMode) this.getUpgradeable().getConfigManager().getSetting( Settings.OPERATION_MODE ) ); - this.setFullMode( (FullnessMode) this.getUpgradeable().getConfigManager().getSetting( Settings.FULLNESS_MODE ) ); - this.setRedStoneMode( (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ) ); - } - - this.standardDetectAndSendChanges(); - } - - public FullnessMode getFullMode() - { - return this.fMode; - } - - private void setFullMode( final FullnessMode fMode ) - { - this.fMode = fMode; - } - - public OperationMode getOperationMode() - { - return this.opMode; - } - - private void setOperationMode( final OperationMode opMode ) - { - this.opMode = opMode; - } +public class ContainerIOPort extends ContainerUpgradeable { + + @GuiSync(2) + public FullnessMode fMode = FullnessMode.EMPTY; + + @GuiSync(3) + public OperationMode opMode = OperationMode.EMPTY; + + public ContainerIOPort(final InventoryPlayer ip, final TileIOPort te) { + super(ip, te); + } + + @Override + protected int getHeight() { + return 166; + } + + @Override + protected void setupConfig() { + int offX = 19; + int offY = 17; + + final IInventory cells = this.getUpgradeable().getInventoryByName("cells"); + + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 2; x++) { + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, + cells, + x + y * 2, + offX + x * 18, + offY + y * 18, + this.getInventoryPlayer())); + } + } + + offX = 122; + offY = 17; + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 2; x++) { + this.addSlotToContainer(new SlotOutput( + cells, + 6 + x + y * 2, + offX + x * 18, + offY + y * 18, + SlotRestrictedInput.PlacableItemType.STORAGE_CELLS.IIcon)); + } + } + + final IInventory upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 1, + 187, + 8 + 18, + this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 2, + 187, + 8 + 18 * 2, + this.getInventoryPlayer())) + .setNotDraggable()); + } + + @Override + protected boolean supportCapacity() { + return false; + } + + @Override + public int availableUpgrades() { + return 3; + } + + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); + + if (Platform.isServer()) { + this.setOperationMode( + (OperationMode) this.getUpgradeable().getConfigManager().getSetting(Settings.OPERATION_MODE)); + this.setFullMode( + (FullnessMode) this.getUpgradeable().getConfigManager().getSetting(Settings.FULLNESS_MODE)); + this.setRedStoneMode( + (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting(Settings.REDSTONE_CONTROLLED)); + } + + this.standardDetectAndSendChanges(); + } + + public FullnessMode getFullMode() { + return this.fMode; + } + + private void setFullMode(final FullnessMode fMode) { + this.fMode = fMode; + } + + public OperationMode getOperationMode() { + return this.opMode; + } + + private void setOperationMode(final OperationMode opMode) { + this.opMode = opMode; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerInscriber.java b/src/main/java/appeng/container/implementations/ContainerInscriber.java index 613fcb5d9c7..ef8e9794ea7 100644 --- a/src/main/java/appeng/container/implementations/ContainerInscriber.java +++ b/src/main/java/appeng/container/implementations/ContainerInscriber.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.AEApi; import appeng.api.definitions.IItemDefinition; import appeng.api.features.IInscriberRecipe; @@ -32,180 +31,187 @@ import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class ContainerInscriber extends ContainerUpgradeable implements IProgressProvider -{ - - private final TileInscriber ti; - - private final Slot top; - private final Slot middle; - private final Slot bottom; - - @GuiSync( 2 ) - public int maxProcessingTime = -1; - - @GuiSync( 3 ) - public int processingTime = -1; - - public ContainerInscriber( final InventoryPlayer ip, final TileInscriber te ) - { - super( ip, te ); - this.ti = te; - - this.addSlotToContainer( this.top = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.INSCRIBER_PLATE, this.ti, 0, 45, 16, this.getInventoryPlayer() ) ); - this.addSlotToContainer( this.bottom = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.INSCRIBER_PLATE, this.ti, 1, 45, 62, this.getInventoryPlayer() ) ); - this.addSlotToContainer( this.middle = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.INSCRIBER_INPUT, this.ti, 2, 63, 39, this.getInventoryPlayer() ) ); - - this.addSlotToContainer( new SlotOutput( this.ti, 3, 113, 40, -1 ) ); - } - - @Override - protected int getHeight() - { - return 176; - } - - @Override - /** - * Overridden super.setupConfig to prevent setting up the fake slots - */ protected void setupConfig() - { - this.setupUpgrades(); - } - - @Override - protected boolean supportCapacity() - { - return false; - } - - @Override - public int availableUpgrades() - { - return 3; - } - - @Override - public void detectAndSendChanges() - { - this.standardDetectAndSendChanges(); - - if( Platform.isServer() ) - { - this.maxProcessingTime = this.ti.getMaxProcessingTime(); - this.processingTime = this.ti.getProcessingTime(); - } - } - - @Override - public boolean isValidForSlot( final Slot s, final ItemStack is ) - { - final ItemStack top = this.ti.getStackInSlot( 0 ); - final ItemStack bot = this.ti.getStackInSlot( 1 ); - - if( s == this.middle ) - { - for( final ItemStack optional : AEApi.instance().registries().inscriber().getOptionals() ) - { - if( Platform.isSameItemPrecise( optional, is ) ) - { - return false; - } - } - - boolean matches = false; - boolean found = false; - - for( final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes() ) - { - final boolean matchA = ( top == null && !recipe.getTopOptional().isPresent() ) || ( Platform.isSameItemPrecise( top, recipe.getTopOptional().orNull() ) ) && // and... - ( bot == null && !recipe.getBottomOptional().isPresent() ) | ( Platform.isSameItemPrecise( bot, recipe.getBottomOptional().orNull() ) ); - - final boolean matchB = ( bot == null && !recipe.getTopOptional().isPresent() ) || ( Platform.isSameItemPrecise( bot, recipe.getTopOptional().orNull() ) ) && // and... - ( top == null && !recipe.getBottomOptional().isPresent() ) | ( Platform.isSameItemPrecise( top, recipe.getBottomOptional().orNull() ) ); - - if( matchA || matchB ) - { - matches = true; - for( final ItemStack option : recipe.getInputs() ) - { - if( Platform.isSameItemPrecise( is, option ) ) - { - found = true; - } - } - } - } - - if( matches && !found ) - { - return false; - } - } - - if( ( s == this.top && bot != null ) || ( s == this.bottom && top != null ) ) - { - ItemStack otherSlot = null; - if( s == this.top ) - { - otherSlot = this.bottom.getStack(); - } - else - { - otherSlot = this.top.getStack(); - } - - // name presses - final IItemDefinition namePress = AEApi.instance().definitions().materials().namePress(); - if( namePress.isSameAs( otherSlot ) ) - { - return namePress.isSameAs( is ); - } - - // everything else - boolean isValid = false; - for( final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes() ) - { - if( Platform.isSameItemPrecise( recipe.getTopOptional().orNull(), otherSlot ) ) - { - isValid = Platform.isSameItemPrecise( is, recipe.getBottomOptional().orNull() ); - } - else if( Platform.isSameItemPrecise( recipe.getBottomOptional().orNull(), otherSlot ) ) - { - isValid = Platform.isSameItemPrecise( is, recipe.getTopOptional().orNull() ); - } - - if( isValid ) - { - break; - } - } - - if( !isValid ) - { - return false; - } - } - - return true; - } - - @Override - public int getCurrentProgress() - { - return this.processingTime; - } - - @Override - public int getMaxProgress() - { - return this.maxProcessingTime; - } +public class ContainerInscriber extends ContainerUpgradeable implements IProgressProvider { + + private final TileInscriber ti; + + private final Slot top; + private final Slot middle; + private final Slot bottom; + + @GuiSync(2) + public int maxProcessingTime = -1; + + @GuiSync(3) + public int processingTime = -1; + + public ContainerInscriber(final InventoryPlayer ip, final TileInscriber te) { + super(ip, te); + this.ti = te; + + this.addSlotToContainer( + this.top = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.INSCRIBER_PLATE, + this.ti, + 0, + 45, + 16, + this.getInventoryPlayer())); + this.addSlotToContainer( + this.bottom = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.INSCRIBER_PLATE, + this.ti, + 1, + 45, + 62, + this.getInventoryPlayer())); + this.addSlotToContainer( + this.middle = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.INSCRIBER_INPUT, + this.ti, + 2, + 63, + 39, + this.getInventoryPlayer())); + + this.addSlotToContainer(new SlotOutput(this.ti, 3, 113, 40, -1)); + } + + @Override + protected int getHeight() { + return 176; + } + + @Override + /** + * Overridden super.setupConfig to prevent setting up the fake slots + */ + protected void setupConfig() { + this.setupUpgrades(); + } + + @Override + protected boolean supportCapacity() { + return false; + } + + @Override + public int availableUpgrades() { + return 3; + } + + @Override + public void detectAndSendChanges() { + this.standardDetectAndSendChanges(); + + if (Platform.isServer()) { + this.maxProcessingTime = this.ti.getMaxProcessingTime(); + this.processingTime = this.ti.getProcessingTime(); + } + } + + @Override + public boolean isValidForSlot(final Slot s, final ItemStack is) { + final ItemStack top = this.ti.getStackInSlot(0); + final ItemStack bot = this.ti.getStackInSlot(1); + + if (s == this.middle) { + for (final ItemStack optional : + AEApi.instance().registries().inscriber().getOptionals()) { + if (Platform.isSameItemPrecise(optional, is)) { + return false; + } + } + + boolean matches = false; + boolean found = false; + + for (final IInscriberRecipe recipe : + AEApi.instance().registries().inscriber().getRecipes()) { + final boolean matchA = (top == null && !recipe.getTopOptional().isPresent()) + || (Platform.isSameItemPrecise( + top, recipe.getTopOptional().orNull())) + && // and... + (bot == null && !recipe.getBottomOptional().isPresent()) + | (Platform.isSameItemPrecise( + bot, recipe.getBottomOptional().orNull())); + + final boolean matchB = (bot == null && !recipe.getTopOptional().isPresent()) + || (Platform.isSameItemPrecise( + bot, recipe.getTopOptional().orNull())) + && // and... + (top == null && !recipe.getBottomOptional().isPresent()) + | (Platform.isSameItemPrecise( + top, recipe.getBottomOptional().orNull())); + + if (matchA || matchB) { + matches = true; + for (final ItemStack option : recipe.getInputs()) { + if (Platform.isSameItemPrecise(is, option)) { + found = true; + } + } + } + } + + if (matches && !found) { + return false; + } + } + + if ((s == this.top && bot != null) || (s == this.bottom && top != null)) { + ItemStack otherSlot = null; + if (s == this.top) { + otherSlot = this.bottom.getStack(); + } else { + otherSlot = this.top.getStack(); + } + + // name presses + final IItemDefinition namePress = + AEApi.instance().definitions().materials().namePress(); + if (namePress.isSameAs(otherSlot)) { + return namePress.isSameAs(is); + } + + // everything else + boolean isValid = false; + for (final IInscriberRecipe recipe : + AEApi.instance().registries().inscriber().getRecipes()) { + if (Platform.isSameItemPrecise(recipe.getTopOptional().orNull(), otherSlot)) { + isValid = Platform.isSameItemPrecise( + is, recipe.getBottomOptional().orNull()); + } else if (Platform.isSameItemPrecise(recipe.getBottomOptional().orNull(), otherSlot)) { + isValid = Platform.isSameItemPrecise( + is, recipe.getTopOptional().orNull()); + } + + if (isValid) { + break; + } + } + + if (!isValid) { + return false; + } + } + + return true; + } + + @Override + public int getCurrentProgress() { + return this.processingTime; + } + + @Override + public int getMaxProgress() { + return this.maxProcessingTime; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerInterface.java b/src/main/java/appeng/container/implementations/ContainerInterface.java index fe9f8fc5629..88c36a7c6c2 100644 --- a/src/main/java/appeng/container/implementations/ContainerInterface.java +++ b/src/main/java/appeng/container/implementations/ContainerInterface.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.*; import appeng.api.util.IConfigManager; import appeng.container.guisync.GuiSync; @@ -26,161 +25,148 @@ import appeng.helpers.DualityInterface; import appeng.helpers.IInterfaceHost; import appeng.util.Platform; +import java.util.ArrayList; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -import java.util.ArrayList; - - -public class ContainerInterface extends ContainerUpgradeable implements IOptionalSlotHost -{ - - private final DualityInterface myDuality; - - @GuiSync(3) - public YesNo bMode = YesNo.NO; - - @GuiSync(4) - public YesNo iTermMode = YesNo.YES; - - @GuiSync(8) - public InsertionMode insertionMode = InsertionMode.DEFAULT; - - @GuiSync(7) - public int patternRows; - - public ContainerInterface( final InventoryPlayer ip, final IInterfaceHost te ) - { - super( ip, te.getInterfaceDuality().getHost() ); - - this.myDuality = te.getInterfaceDuality(); - patternRows = getPatternCapacityCardsInstalled(); - - for (int row = 0; row < 4; ++row) { - for (int x = 0; x < DualityInterface.NUMBER_OF_PATTERN_SLOTS; x++) { - this.addSlotToContainer(new OptionalSlotRestrictedInput( - SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, this.myDuality.getPatterns(), this, - x + row*DualityInterface.NUMBER_OF_PATTERN_SLOTS, 8 + 18 * x, 108 - row * 18, row, this.getInventoryPlayer()).setStackLimit( 1 ) ); - } - } - - for (int x = 0; x < DualityInterface.NUMBER_OF_CONFIG_SLOTS; x++) { - this.addSlotToContainer(new SlotFake(this.myDuality.getConfig(), x, 8 + 18 * x, 15)); - } - - for (int x = 0; x < DualityInterface.NUMBER_OF_STORAGE_SLOTS; x++) { - this.addSlotToContainer(new SlotNormal(this.myDuality.getStorage(), x, 8 + 18 * x, 15 + 18)); - } - } - - @Override - protected int getHeight() - { - return 211; - } - - @Override - protected void setupConfig() - { - this.setupUpgrades(); - } - - @Override - public int availableUpgrades() - { - return 4; - } - - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) { - super.onUpdate(field, oldValue, newValue); - if (Platform.isClient() && field.equals("patternRows")) - getRemovedPatterns(); - } - - @Override - public void detectAndSendChanges() { - this.verifyPermissions(SecurityPermissions.BUILD, false); - - if (patternRows != getPatternCapacityCardsInstalled()) - patternRows = getPatternCapacityCardsInstalled(); - - final ArrayList drops = getRemovedPatterns(); - if (!drops.isEmpty()) { - TileEntity te = myDuality.getHost().getTile(); - if (te != null) - Platform.spawnDrops(te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord, drops); - } - super.detectAndSendChanges(); - } - - private ArrayList getRemovedPatterns() { - final ArrayList drops = new ArrayList(); - for (final Object o : this.inventorySlots) { - if (o instanceof OptionalSlotRestrictedInput) { - final OptionalSlotRestrictedInput fs = (OptionalSlotRestrictedInput) o; - if (!fs.isEnabled()) { - ItemStack s = fs.inventory.getStackInSlot(fs.getSlotIndex()); - if (s != null) { - drops.add(s); - fs.inventory.setInventorySlotContents(fs.getSlotIndex(), null); - fs.clearStack(); - } - } - } - } - return drops; - } - - @Override - protected void loadSettingsFromHost( final IConfigManager cm ) - { - this.setBlockingMode( (YesNo) cm.getSetting( Settings.BLOCK ) ); - this.setInterfaceTerminalMode( (YesNo) cm.getSetting( Settings.INTERFACE_TERMINAL ) ); - this.setInsertionMode( (InsertionMode) cm.getSetting( Settings.INSERTION_MODE ) ); - } - - public YesNo getBlockingMode() - { - return this.bMode; - } - - private void setBlockingMode( final YesNo bMode ) - { - this.bMode = bMode; - } - - public YesNo getInterfaceTerminalMode() - { - return this.iTermMode; - } - - private void setInterfaceTerminalMode( final YesNo iTermMode ) - { - this.iTermMode = iTermMode; - } - - public InsertionMode getInsertionMode() - { - return this.insertionMode; - } - - private void setInsertionMode( final InsertionMode insertionMode ) - { - this.insertionMode = insertionMode; - } - - public int getPatternCapacityCardsInstalled() - { - if( myDuality == null ) - return 0; - return myDuality.getInstalledUpgrades( Upgrades.PATTERN_CAPACITY ); - } - - @Override - public boolean isSlotEnabled( final int idx ) - { - return myDuality.getInstalledUpgrades(Upgrades.PATTERN_CAPACITY) >= idx; - } +public class ContainerInterface extends ContainerUpgradeable implements IOptionalSlotHost { + + private final DualityInterface myDuality; + + @GuiSync(3) + public YesNo bMode = YesNo.NO; + + @GuiSync(4) + public YesNo iTermMode = YesNo.YES; + + @GuiSync(8) + public InsertionMode insertionMode = InsertionMode.DEFAULT; + + @GuiSync(7) + public int patternRows; + + public ContainerInterface(final InventoryPlayer ip, final IInterfaceHost te) { + super(ip, te.getInterfaceDuality().getHost()); + + this.myDuality = te.getInterfaceDuality(); + patternRows = getPatternCapacityCardsInstalled(); + + for (int row = 0; row < 4; ++row) { + for (int x = 0; x < DualityInterface.NUMBER_OF_PATTERN_SLOTS; x++) { + this.addSlotToContainer(new OptionalSlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, + this.myDuality.getPatterns(), + this, + x + row * DualityInterface.NUMBER_OF_PATTERN_SLOTS, + 8 + 18 * x, + 108 - row * 18, + row, + this.getInventoryPlayer()) + .setStackLimit(1)); + } + } + + for (int x = 0; x < DualityInterface.NUMBER_OF_CONFIG_SLOTS; x++) { + this.addSlotToContainer(new SlotFake(this.myDuality.getConfig(), x, 8 + 18 * x, 15)); + } + + for (int x = 0; x < DualityInterface.NUMBER_OF_STORAGE_SLOTS; x++) { + this.addSlotToContainer(new SlotNormal(this.myDuality.getStorage(), x, 8 + 18 * x, 15 + 18)); + } + } + + @Override + protected int getHeight() { + return 211; + } + + @Override + protected void setupConfig() { + this.setupUpgrades(); + } + + @Override + public int availableUpgrades() { + return 4; + } + + @Override + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + super.onUpdate(field, oldValue, newValue); + if (Platform.isClient() && field.equals("patternRows")) getRemovedPatterns(); + } + + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); + + if (patternRows != getPatternCapacityCardsInstalled()) patternRows = getPatternCapacityCardsInstalled(); + + final ArrayList drops = getRemovedPatterns(); + if (!drops.isEmpty()) { + TileEntity te = myDuality.getHost().getTile(); + if (te != null) Platform.spawnDrops(te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord, drops); + } + super.detectAndSendChanges(); + } + + private ArrayList getRemovedPatterns() { + final ArrayList drops = new ArrayList(); + for (final Object o : this.inventorySlots) { + if (o instanceof OptionalSlotRestrictedInput) { + final OptionalSlotRestrictedInput fs = (OptionalSlotRestrictedInput) o; + if (!fs.isEnabled()) { + ItemStack s = fs.inventory.getStackInSlot(fs.getSlotIndex()); + if (s != null) { + drops.add(s); + fs.inventory.setInventorySlotContents(fs.getSlotIndex(), null); + fs.clearStack(); + } + } + } + } + return drops; + } + + @Override + protected void loadSettingsFromHost(final IConfigManager cm) { + this.setBlockingMode((YesNo) cm.getSetting(Settings.BLOCK)); + this.setInterfaceTerminalMode((YesNo) cm.getSetting(Settings.INTERFACE_TERMINAL)); + this.setInsertionMode((InsertionMode) cm.getSetting(Settings.INSERTION_MODE)); + } + + public YesNo getBlockingMode() { + return this.bMode; + } + + private void setBlockingMode(final YesNo bMode) { + this.bMode = bMode; + } + + public YesNo getInterfaceTerminalMode() { + return this.iTermMode; + } + + private void setInterfaceTerminalMode(final YesNo iTermMode) { + this.iTermMode = iTermMode; + } + + public InsertionMode getInsertionMode() { + return this.insertionMode; + } + + private void setInsertionMode(final InsertionMode insertionMode) { + this.insertionMode = insertionMode; + } + + public int getPatternCapacityCardsInstalled() { + if (myDuality == null) return 0; + return myDuality.getInstalledUpgrades(Upgrades.PATTERN_CAPACITY); + } + + @Override + public boolean isSlotEnabled(final int idx) { + return myDuality.getInstalledUpgrades(Upgrades.PATTERN_CAPACITY) >= idx; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java b/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java index a904609c378..b5b02f0d51a 100644 --- a/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java +++ b/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.Settings; import appeng.api.config.Upgrades; import appeng.api.config.YesNo; @@ -43,6 +42,11 @@ import appeng.util.inv.ItemSlot; import appeng.util.inv.WrapperInvSlot; import com.google.common.collect.HashMultimap; +import com.google.common.collect.Multimap; +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; @@ -50,21 +54,15 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import com.google.common.collect.Multimap; - public final class ContainerInterfaceTerminal extends AEBaseContainer { - /** - * this stuff is all server side.. - */ + /** + * this stuff is all server side.. + */ private static long autoBase = Long.MIN_VALUE; + private final Multimap diList = HashMultimap.create(); - private final Map byId = new HashMap(); - //private final Map byId = new HashMap<>(); + private final Map byId = new HashMap(); + // private final Map byId = new HashMap<>(); private IGrid grid; private NBTTagCompound data = new NBTTagCompound(); @@ -98,15 +96,15 @@ public void detectAndSendChanges() { final IGridNode agn = host.getActionableNode(); if (agn != null && agn.isActive()) { for (final IGridNode gn : this.grid.getMachines(TileInterface.class)) { - InterfaceCheck interfaceCheck = new InterfaceCheck().invoke(gn); - total += interfaceCheck.getTotal(); - missing |= interfaceCheck.isMissing(); - } + InterfaceCheck interfaceCheck = new InterfaceCheck().invoke(gn); + total += interfaceCheck.getTotal(); + missing |= interfaceCheck.isMissing(); + } for (final IGridNode gn : this.grid.getMachines(PartInterface.class)) { - InterfaceCheck interfaceCheck = new InterfaceCheck().invoke(gn); - total += interfaceCheck.getTotal(); - missing |= interfaceCheck.isMissing(); + InterfaceCheck interfaceCheck = new InterfaceCheck().invoke(gn); + total += interfaceCheck.getTotal(); + missing |= interfaceCheck.isMissing(); } } } @@ -125,7 +123,8 @@ public void detectAndSendChanges() { if (!this.data.hasNoTags()) { try { - NetworkHandler.instance.sendTo(new PacketCompressedNBT(this.data), (EntityPlayerMP) this.getPlayerInv().player); + NetworkHandler.instance.sendTo( + new PacketCompressedNBT(this.data), (EntityPlayerMP) this.getPlayerInv().player); } catch (final IOException e) { // :P } @@ -134,7 +133,7 @@ public void detectAndSendChanges() { } } - @Override + @Override public void doAction(final EntityPlayerMP player, final InventoryAction action, final int slot, final long id) { final InvTracker inv = this.byId.get(id); if (inv != null) { @@ -153,25 +152,22 @@ public void doAction(final EntityPlayerMP player, final InventoryAction action, switch (action) { case PICKUP_OR_SET_DOWN: - - if (hasItemInHand) - { - for( int s = 0; s < interfaceHandler.getSizeInventory(); s++ ) - { - if( Platform.isSameItemPrecise( interfaceHandler.getStackInSlot( s ), player.inventory.getItemStack() ) ) - { + if (hasItemInHand) { + for (int s = 0; s < interfaceHandler.getSizeInventory(); s++) { + if (Platform.isSameItemPrecise( + interfaceHandler.getStackInSlot(s), player.inventory.getItemStack())) { canInsert = false; break; } } - if( canInsert ) - { + if (canInsert) { ItemStack inSlot = theSlot.getStackInSlot(0); if (inSlot == null) { player.inventory.setItemStack(interfaceSlot.addItems(player.inventory.getItemStack())); } else { inSlot = inSlot.copy(); - final ItemStack inHand = player.inventory.getItemStack().copy(); + final ItemStack inHand = + player.inventory.getItemStack().copy(); theSlot.setInventorySlotContents(0, null); player.inventory.setItemStack(null); @@ -193,17 +189,15 @@ public void doAction(final EntityPlayerMP player, final InventoryAction action, break; case SPLIT_OR_PLACE_SINGLE: - if (hasItemInHand) { - for( int s = 0; s < interfaceHandler.getSizeInventory(); s++ ) - { - if( Platform.isSameItemPrecise( interfaceHandler.getStackInSlot( s ), player.inventory.getItemStack() ) ) - { + for (int s = 0; s < interfaceHandler.getSizeInventory(); s++) { + if (Platform.isSameItemPrecise( + interfaceHandler.getStackInSlot(s), player.inventory.getItemStack())) { canInsert = false; break; } } - if( canInsert ) { + if (canInsert) { ItemStack extra = playerHand.removeItems(1, null, null); if (extra != null && !interfaceSlot.containsItems()) { extra = interfaceSlot.addItems(extra); @@ -224,22 +218,21 @@ public void doAction(final EntityPlayerMP player, final InventoryAction action, break; case SHIFT_CLICK: - final IInventory mySlot = slotInv.getWrapper(slot + inv.offset); final InventoryAdaptor playerInv = InventoryAdaptor.getAdaptor(player, ForgeDirection.UNKNOWN); mySlot.setInventorySlotContents(0, mergeToPlayerInventory(playerInv, mySlot.getStackInSlot(0))); break; case MOVE_REGION: - final InventoryAdaptor playerInvAd = InventoryAdaptor.getAdaptor(player, ForgeDirection.UNKNOWN); for (int x = 0; x < inv.client.getSizeInventory(); x++) { - inv.server.setInventorySlotContents(x + inv.offset, mergeToPlayerInventory(playerInvAd, inv.server.getStackInSlot(x + inv.offset))); + inv.server.setInventorySlotContents( + x + inv.offset, + mergeToPlayerInventory(playerInvAd, inv.server.getStackInSlot(x + inv.offset))); } break; case CREATIVE_DUPLICATE: - if (player.capabilities.isCreativeMode && !hasItemInHand) { player.inventory.setItemStack(is == null ? null : is.copy()); } @@ -252,11 +245,10 @@ public void doAction(final EntityPlayerMP player, final InventoryAction action, this.updateHeld(player); } } - private ItemStack mergeToPlayerInventory(InventoryAdaptor playerInv, ItemStack stack) - { - if (stack == null) - return null; - for (ItemSlot slot: playerInv) { + + private ItemStack mergeToPlayerInventory(InventoryAdaptor playerInv, ItemStack stack) { + if (stack == null) return null; + for (ItemSlot slot : playerInv) { if (Platform.isSameItemPrecise(slot.getItemStack(), stack)) { if (slot.getItemStack().stackSize < slot.getItemStack().getMaxStackSize()) { ++slot.getItemStack().stackSize; @@ -266,6 +258,7 @@ private ItemStack mergeToPlayerInventory(InventoryAdaptor playerInv, ItemStack s } return playerInv.addItems(stack); } + private void regenList(final NBTTagCompound data) { this.byId.clear(); this.diList.clear(); @@ -278,9 +271,9 @@ private void regenList(final NBTTagCompound data) { final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); final DualityInterface dual = ih.getInterfaceDuality(); if (gn.isActive() && dual.getConfigManager().getSetting(Settings.INTERFACE_TERMINAL) == YesNo.YES) { - for (int i = 0; i <= dual.getInstalledUpgrades(Upgrades.PATTERN_CAPACITY); ++i) { - this.diList.put(ih, new InvTracker(dual, dual.getPatterns(), dual.getTermName(), i * 9, 9)); - } + for (int i = 0; i <= dual.getInstalledUpgrades(Upgrades.PATTERN_CAPACITY); ++i) { + this.diList.put(ih, new InvTracker(dual, dual.getPatterns(), dual.getTermName(), i * 9, 9)); + } } } @@ -288,9 +281,9 @@ private void regenList(final NBTTagCompound data) { final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); final DualityInterface dual = ih.getInterfaceDuality(); if (gn.isActive() && dual.getConfigManager().getSetting(Settings.INTERFACE_TERMINAL) == YesNo.YES) { - for (int i = 0; i <= dual.getInstalledUpgrades(Upgrades.PATTERN_CAPACITY); ++i) { - this.diList.put(ih, new InvTracker(dual, dual.getPatterns(), dual.getTermName(), i * 9, 9)); - } + for (int i = 0; i <= dual.getInstalledUpgrades(Upgrades.PATTERN_CAPACITY); ++i) { + this.diList.put(ih, new InvTracker(dual, dual.getPatterns(), dual.getTermName(), i * 9, 9)); + } } } } @@ -360,7 +353,12 @@ private static class InvTracker { private final int Z; private final int dim; - public InvTracker(final DualityInterface dual, final IInventory patterns, final String unlocalizedName, int offset, int size) { + public InvTracker( + final DualityInterface dual, + final IInventory patterns, + final String unlocalizedName, + int offset, + int size) { this.server = patterns; this.client = new AppEngInternalInventory(null, size); this.unlocalizedName = unlocalizedName; @@ -373,7 +371,6 @@ public InvTracker(final DualityInterface dual, final IInventory patterns, final } } - private static class PatternInvSlot extends WrapperInvSlot { public PatternInvSlot(final IInventory inv) { @@ -386,44 +383,44 @@ public boolean isItemValid(final ItemStack itemstack) { } } - private class InterfaceCheck { - - int total = 0; - boolean missing = false; - public InterfaceCheck() { - } - - public int getTotal() { - return total; - } - - public boolean isMissing() { - return missing; - } - - public InterfaceCheck invoke(IGridNode gn) { - if (gn.isActive()) { - final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); - if (ih.getInterfaceDuality().getConfigManager().getSetting(Settings.INTERFACE_TERMINAL) == YesNo.NO) { - return this; - } - - final Collection t = ContainerInterfaceTerminal.this.diList.get(ih); - - if (t.isEmpty()) { - missing = true; - } else { - final DualityInterface dual = ih.getInterfaceDuality(); - for (InvTracker it : t) { - if (!it.unlocalizedName.equals(dual.getTermName())) { - missing = true; - } - } - } - - total += (ih.getInterfaceDuality().getInstalledUpgrades(Upgrades.PATTERN_CAPACITY) + 1); - } - return this; - } - } + private class InterfaceCheck { + + int total = 0; + boolean missing = false; + + public InterfaceCheck() {} + + public int getTotal() { + return total; + } + + public boolean isMissing() { + return missing; + } + + public InterfaceCheck invoke(IGridNode gn) { + if (gn.isActive()) { + final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); + if (ih.getInterfaceDuality().getConfigManager().getSetting(Settings.INTERFACE_TERMINAL) == YesNo.NO) { + return this; + } + + final Collection t = ContainerInterfaceTerminal.this.diList.get(ih); + + if (t.isEmpty()) { + missing = true; + } else { + final DualityInterface dual = ih.getInterfaceDuality(); + for (InvTracker it : t) { + if (!it.unlocalizedName.equals(dual.getTermName())) { + missing = true; + } + } + } + + total += (ih.getInterfaceDuality().getInstalledUpgrades(Upgrades.PATTERN_CAPACITY) + 1); + } + return this; + } + } } diff --git a/src/main/java/appeng/container/implementations/ContainerLevelEmitter.java b/src/main/java/appeng/container/implementations/ContainerLevelEmitter.java index c51f4d19b77..5fa687b247e 100644 --- a/src/main/java/appeng/container/implementations/ContainerLevelEmitter.java +++ b/src/main/java/appeng/container/implementations/ContainerLevelEmitter.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.*; import appeng.container.guisync.GuiSync; import appeng.container.slot.SlotFakeTypeOnly; @@ -32,129 +31,143 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; - -public class ContainerLevelEmitter extends ContainerUpgradeable -{ - - private final PartLevelEmitter lvlEmitter; - - @SideOnly( Side.CLIENT ) - private GuiTextField textField; - @GuiSync( 2 ) - public LevelType lvType; - @GuiSync( 3 ) - public long EmitterValue = -1; - @GuiSync( 4 ) - public YesNo cmType; - - public ContainerLevelEmitter( final InventoryPlayer ip, final PartLevelEmitter te ) - { - super( ip, te ); - this.lvlEmitter = te; - } - - @SideOnly( Side.CLIENT ) - public void setTextField( final GuiTextField level ) - { - this.textField = level; - this.textField.setText( String.valueOf( this.EmitterValue ) ); - } - - public void setLevel( final long l, final EntityPlayer player ) - { - this.lvlEmitter.setReportingValue( l ); - this.EmitterValue = l; - } - - @Override - protected void setupConfig() - { - final IInventory upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - if( this.availableUpgrades() > 0 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - if( this.availableUpgrades() > 1 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - if( this.availableUpgrades() > 2 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - if( this.availableUpgrades() > 3 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - - final IInventory inv = this.getUpgradeable().getInventoryByName( "config" ); - final int y = 40; - final int x = 80 + 44; - - this.addSlotToContainer( new SlotFakeTypeOnly( inv, 0, x, y ) ); - } - - @Override - protected boolean supportCapacity() - { - return false; - } - - @Override - public int availableUpgrades() - { - - return 1; - } - - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); - - if( Platform.isServer() ) - { - this.EmitterValue = this.lvlEmitter.getReportingValue(); - this.setCraftingMode( (YesNo) this.getUpgradeable().getConfigManager().getSetting( Settings.CRAFT_VIA_REDSTONE ) ); - this.setLevelMode( (LevelType) this.getUpgradeable().getConfigManager().getSetting( Settings.LEVEL_TYPE ) ); - this.setFuzzyMode( (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting( Settings.FUZZY_MODE ) ); - this.setRedStoneMode( (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting( Settings.REDSTONE_EMITTER ) ); - } - - this.standardDetectAndSendChanges(); - } - - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - if( field.equals( "EmitterValue" ) ) - { - if( this.textField != null ) - { - this.textField.setText( String.valueOf( this.EmitterValue ) ); - } - } - } - - @Override - public YesNo getCraftingMode() - { - return this.cmType; - } - - @Override - public void setCraftingMode( final YesNo cmType ) - { - this.cmType = cmType; - } - - public LevelType getLevelMode() - { - return this.lvType; - } - - private void setLevelMode( final LevelType lvType ) - { - this.lvType = lvType; - } +public class ContainerLevelEmitter extends ContainerUpgradeable { + + private final PartLevelEmitter lvlEmitter; + + @SideOnly(Side.CLIENT) + private GuiTextField textField; + + @GuiSync(2) + public LevelType lvType; + + @GuiSync(3) + public long EmitterValue = -1; + + @GuiSync(4) + public YesNo cmType; + + public ContainerLevelEmitter(final InventoryPlayer ip, final PartLevelEmitter te) { + super(ip, te); + this.lvlEmitter = te; + } + + @SideOnly(Side.CLIENT) + public void setTextField(final GuiTextField level) { + this.textField = level; + this.textField.setText(String.valueOf(this.EmitterValue)); + } + + public void setLevel(final long l, final EntityPlayer player) { + this.lvlEmitter.setReportingValue(l); + this.EmitterValue = l; + } + + @Override + protected void setupConfig() { + final IInventory upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + if (this.availableUpgrades() > 0) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 0, + 187, + 8, + this.getInventoryPlayer())) + .setNotDraggable()); + } + if (this.availableUpgrades() > 1) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 1, + 187, + 8 + 18, + this.getInventoryPlayer())) + .setNotDraggable()); + } + if (this.availableUpgrades() > 2) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 2, + 187, + 8 + 18 * 2, + this.getInventoryPlayer())) + .setNotDraggable()); + } + if (this.availableUpgrades() > 3) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 3, + 187, + 8 + 18 * 3, + this.getInventoryPlayer())) + .setNotDraggable()); + } + + final IInventory inv = this.getUpgradeable().getInventoryByName("config"); + final int y = 40; + final int x = 80 + 44; + + this.addSlotToContainer(new SlotFakeTypeOnly(inv, 0, x, y)); + } + + @Override + protected boolean supportCapacity() { + return false; + } + + @Override + public int availableUpgrades() { + + return 1; + } + + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); + + if (Platform.isServer()) { + this.EmitterValue = this.lvlEmitter.getReportingValue(); + this.setCraftingMode( + (YesNo) this.getUpgradeable().getConfigManager().getSetting(Settings.CRAFT_VIA_REDSTONE)); + this.setLevelMode( + (LevelType) this.getUpgradeable().getConfigManager().getSetting(Settings.LEVEL_TYPE)); + this.setFuzzyMode( + (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting(Settings.FUZZY_MODE)); + this.setRedStoneMode( + (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting(Settings.REDSTONE_EMITTER)); + } + + this.standardDetectAndSendChanges(); + } + + @Override + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + if (field.equals("EmitterValue")) { + if (this.textField != null) { + this.textField.setText(String.valueOf(this.EmitterValue)); + } + } + } + + @Override + public YesNo getCraftingMode() { + return this.cmType; + } + + @Override + public void setCraftingMode(final YesNo cmType) { + this.cmType = cmType; + } + + public LevelType getLevelMode() { + return this.lvType; + } + + private void setLevelMode(final LevelType lvType) { + this.lvType = lvType; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerMAC.java b/src/main/java/appeng/container/implementations/ContainerMAC.java index c4c0124ebcd..6f7180d6938 100644 --- a/src/main/java/appeng/container/implementations/ContainerMAC.java +++ b/src/main/java/appeng/container/implementations/ContainerMAC.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.RedstoneMode; import appeng.api.config.SecurityPermissions; import appeng.api.config.Settings; @@ -36,121 +35,142 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.World; - -public class ContainerMAC extends ContainerUpgradeable implements IProgressProvider -{ - - private static final int MAX_CRAFT_PROGRESS = 100; - private final TileMolecularAssembler tma; - @GuiSync( 4 ) - public int craftProgress = 0; - - public ContainerMAC( final InventoryPlayer ip, final TileMolecularAssembler te ) - { - super( ip, te ); - this.tma = te; - } - - public boolean isValidItemForSlot( final int slotIndex, final ItemStack i ) - { - final IInventory mac = this.getUpgradeable().getInventoryByName( "mac" ); - - final ItemStack is = mac.getStackInSlot( 10 ); - if( is == null ) - { - return false; - } - - if( is.getItem() instanceof ItemEncodedPattern ) - { - final World w = this.getTileEntity().getWorldObj(); - final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); - final ICraftingPatternDetails ph = iep.getPatternForItem( is, w ); - if( ph.isCraftable() ) - { - return ph.isValidItemForSlot( slotIndex, i, w ); - } - } - - return false; - } - - @Override - protected int getHeight() - { - return 197; - } - - @Override - protected void setupConfig() - { - int offX = 29; - int offY = 30; - - final IInventory mac = this.getUpgradeable().getInventoryByName( "mac" ); - - for( int y = 0; y < 3; y++ ) - { - for( int x = 0; x < 3; x++ ) - { - final SlotMACPattern s = new SlotMACPattern( this, mac, x + y * 3, offX + x * 18, offY + y * 18 ); - this.addSlotToContainer( s ); - } - } - - offX = 126; - offY = 16; - - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODED_CRAFTING_PATTERN, mac, 10, offX, offY, this.getInventoryPlayer() ) ); - this.addSlotToContainer( new SlotOutput( mac, 9, offX, offY + 32, -1 ) ); - - offX = 122; - offY = 17; - - final IInventory upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - - @Override - protected boolean supportCapacity() - { - return false; - } - - @Override - public int availableUpgrades() - { - return 5; - } - - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); - - if( Platform.isServer() ) - { - this.setRedStoneMode( (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ) ); - } - - this.craftProgress = this.tma.getCraftingProgress(); - - this.standardDetectAndSendChanges(); - } - - @Override - public int getCurrentProgress() - { - return this.craftProgress; - } - - @Override - public int getMaxProgress() - { - return MAX_CRAFT_PROGRESS; - } +public class ContainerMAC extends ContainerUpgradeable implements IProgressProvider { + + private static final int MAX_CRAFT_PROGRESS = 100; + private final TileMolecularAssembler tma; + + @GuiSync(4) + public int craftProgress = 0; + + public ContainerMAC(final InventoryPlayer ip, final TileMolecularAssembler te) { + super(ip, te); + this.tma = te; + } + + public boolean isValidItemForSlot(final int slotIndex, final ItemStack i) { + final IInventory mac = this.getUpgradeable().getInventoryByName("mac"); + + final ItemStack is = mac.getStackInSlot(10); + if (is == null) { + return false; + } + + if (is.getItem() instanceof ItemEncodedPattern) { + final World w = this.getTileEntity().getWorldObj(); + final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); + final ICraftingPatternDetails ph = iep.getPatternForItem(is, w); + if (ph.isCraftable()) { + return ph.isValidItemForSlot(slotIndex, i, w); + } + } + + return false; + } + + @Override + protected int getHeight() { + return 197; + } + + @Override + protected void setupConfig() { + int offX = 29; + int offY = 30; + + final IInventory mac = this.getUpgradeable().getInventoryByName("mac"); + + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 3; x++) { + final SlotMACPattern s = new SlotMACPattern(this, mac, x + y * 3, offX + x * 18, offY + y * 18); + this.addSlotToContainer(s); + } + } + + offX = 126; + offY = 16; + + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.ENCODED_CRAFTING_PATTERN, + mac, + 10, + offX, + offY, + this.getInventoryPlayer())); + this.addSlotToContainer(new SlotOutput(mac, 9, offX, offY + 32, -1)); + + offX = 122; + offY = 17; + + final IInventory upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 1, + 187, + 8 + 18, + this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 2, + 187, + 8 + 18 * 2, + this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 3, + 187, + 8 + 18 * 3, + this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 4, + 187, + 8 + 18 * 4, + this.getInventoryPlayer())) + .setNotDraggable()); + } + + @Override + protected boolean supportCapacity() { + return false; + } + + @Override + public int availableUpgrades() { + return 5; + } + + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); + + if (Platform.isServer()) { + this.setRedStoneMode( + (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting(Settings.REDSTONE_CONTROLLED)); + } + + this.craftProgress = this.tma.getCraftingProgress(); + + this.standardDetectAndSendChanges(); + } + + @Override + public int getCurrentProgress() { + return this.craftProgress; + } + + @Override + public int getMaxProgress() { + return MAX_CRAFT_PROGRESS; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerMEMonitorable.java b/src/main/java/appeng/container/implementations/ContainerMEMonitorable.java index d354636ffd0..f665ced0193 100644 --- a/src/main/java/appeng/container/implementations/ContainerMEMonitorable.java +++ b/src/main/java/appeng/container/implementations/ContainerMEMonitorable.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.AEApi; import appeng.api.config.*; import appeng.api.implementations.guiobjects.IPortableCell; @@ -51,6 +50,9 @@ import appeng.util.ConfigManager; import appeng.util.IConfigManagerHost; import appeng.util.Platform; +import java.io.IOException; +import java.nio.BufferOverflowException; +import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; @@ -59,384 +61,311 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nonnull; -import java.io.IOException; -import java.nio.BufferOverflowException; - - -public class ContainerMEMonitorable extends AEBaseContainer implements IConfigManagerHost, IConfigurableObject, IMEMonitorHandlerReceiver -{ - - private final SlotRestrictedInput[] cellView = new SlotRestrictedInput[5]; - private final IMEMonitor monitor; - private final IItemList items = AEApi.instance().storage().createItemList(); - private final IConfigManager clientCM; - private final ITerminalHost host; - @GuiSync( 99 ) - public boolean canAccessViewCells = false; - @GuiSync( 98 ) - public boolean hasPower = false; - private IConfigManagerHost gui; - private IConfigManager serverCM; - private IGridNode networkNode; - - public ContainerMEMonitorable( final InventoryPlayer ip, final ITerminalHost monitorable ) - { - this( ip, monitorable, true ); - } - - protected ContainerMEMonitorable( final InventoryPlayer ip, final ITerminalHost monitorable, final boolean bindInventory ) - { - super( ip, monitorable instanceof TileEntity ? (TileEntity) monitorable : null, monitorable instanceof IPart ? (IPart) monitorable : null ); - - this.host = monitorable; - this.clientCM = new ConfigManager( this ); - - this.clientCM.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - this.clientCM.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - this.clientCM.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); - - if( Platform.isServer() ) - { - this.serverCM = monitorable.getConfigManager(); - - this.monitor = monitorable.getItemInventory(); - if( this.monitor != null ) - { - this.monitor.addListener( this, null ); - - this.setCellInventory( this.monitor ); - - if( monitorable instanceof IPortableCell ) - { - this.setPowerSource( (IEnergySource) monitorable ); - } - else if( monitorable instanceof IMEChest ) - { - this.setPowerSource( (IEnergySource) monitorable ); - } - else if( monitorable instanceof IGridHost ) - { - final IGridNode node = ( (IGridHost) monitorable ).getGridNode( ForgeDirection.UNKNOWN ); - if( node != null ) - { - this.networkNode = node; - final IGrid g = node.getGrid(); - if( g != null ) - { - this.setPowerSource( new ChannelPowerSrc( this.networkNode, (IEnergySource) g.getCache( IEnergyGrid.class ) ) ); - } - } - } - } - else - { - this.setValidContainer( false ); - } - } - else - { - this.monitor = null; - } - - this.canAccessViewCells = false; - if( monitorable instanceof IViewCellStorage ) - { - for( int y = 0; y < 5; y++ ) - { - this.cellView[y] = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.VIEW_CELL, ( (IViewCellStorage) monitorable ).getViewCellStorage(), y, 206, y * 18 + 8, this.getInventoryPlayer() ); - this.cellView[y].setAllowEdit( this.canAccessViewCells ); - this.addSlotToContainer( this.cellView[y] ); - } - } - - if( bindInventory ) - { - this.bindPlayerInventory( ip, 0, 0 ); - } - } - - public IGridNode getNetworkNode() - { - return this.networkNode; - } - - @Override - public void detectAndSendChanges() - { - if( Platform.isServer() ) - { - if( this.monitor != this.host.getItemInventory() ) - { - this.setValidContainer( false ); - } - - for( final Settings set : this.serverCM.getSettings() ) - { - final Enum sideLocal = this.serverCM.getSetting( set ); - final Enum sideRemote = this.clientCM.getSetting( set ); - - if( sideLocal != sideRemote ) - { - this.clientCM.putSetting( set, sideLocal ); - for( final Object crafter : this.crafters ) - { - try - { - NetworkHandler.instance.sendTo( new PacketValueConfig( set.name(), sideLocal.name() ), (EntityPlayerMP) crafter ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - } - - if( !this.items.isEmpty() ) - { - try - { - final IItemList monitorCache = this.monitor.getStorageList(); - - final PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); - - for( final IAEItemStack is : this.items ) - { - final IAEItemStack send = monitorCache.findPrecise( is ); - if( send == null ) - { - is.setStackSize( 0 ); - piu.appendItem( is ); - } - else - { - piu.appendItem( send ); - } - } - - if( !piu.isEmpty() ) - { - this.items.resetStatus(); - - for( final Object c : this.crafters ) - { - if( c instanceof EntityPlayer ) - { - NetworkHandler.instance.sendTo( piu, (EntityPlayerMP) c ); - } - } - } - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - - this.updatePowerStatus(); - - final boolean oldAccessible = this.canAccessViewCells; - this.canAccessViewCells = - this.host instanceof WirelessTerminalGuiObject - || this.hasAccess( SecurityPermissions.BUILD, false ); - if( this.canAccessViewCells != oldAccessible ) - { - for( int y = 0; y < 5; y++ ) - { - if( this.cellView[y] != null ) - { - this.cellView[y].setAllowEdit( this.canAccessViewCells ); - } - } - } - - super.detectAndSendChanges(); - } - } - - protected void updatePowerStatus() - { - try - { - if( this.networkNode != null ) - { - this.setPowered( this.networkNode.isActive() ); - } - else if( this.getPowerSource() instanceof IEnergyGrid ) - { - this.setPowered( ( (IEnergyGrid) this.getPowerSource() ).isNetworkPowered() ); - } - else - { - this.setPowered( this.getPowerSource().extractAEPower( 1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0.8 ); - } - } - catch( final Throwable t ) - { - // :P - } - } - - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - if( field.equals( "canAccessViewCells" ) ) - { - for( int y = 0; y < 5; y++ ) - { - if( this.cellView[y] != null ) - { - this.cellView[y].setAllowEdit( this.canAccessViewCells ); - } - } - } - - super.onUpdate( field, oldValue, newValue ); - } - - @Override - public void addCraftingToCrafters( final ICrafting c ) - { - super.addCraftingToCrafters( c ); - this.queueInventory( c ); - } - - private void queueInventory( final ICrafting c ) - { - if( Platform.isServer() && c instanceof EntityPlayer && this.monitor != null ) - { - try - { - PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); - final IItemList monitorCache = this.monitor.getStorageList(); - - for( final IAEItemStack send : monitorCache ) - { - try - { - piu.appendItem( send ); - } - catch( final BufferOverflowException boe ) - { - NetworkHandler.instance.sendTo( piu, (EntityPlayerMP) c ); - - piu = new PacketMEInventoryUpdate(); - piu.appendItem( send ); - } - } - - NetworkHandler.instance.sendTo( piu, (EntityPlayerMP) c ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - - @Override - public void removeCraftingFromCrafters( final ICrafting c ) - { - super.removeCraftingFromCrafters( c ); - - if( this.crafters.isEmpty() && this.monitor != null ) - { - this.monitor.removeListener( this ); - } - } - - @Override - public void onContainerClosed( final EntityPlayer player ) - { - super.onContainerClosed( player ); - if( this.monitor != null ) - { - this.monitor.removeListener( this ); - } - } - - @Override - public boolean isValid( final Object verificationToken ) - { - return true; - } - - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final BaseActionSource source ) - { - for( final IAEItemStack is : change ) - { - this.items.add( is ); - } - } - - @Override - public void onListUpdate() - { - for( final Object c : this.crafters ) - { - if( c instanceof ICrafting ) - { - final ICrafting cr = (ICrafting) c; - this.queueInventory( cr ); - } - } - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - if( this.getGui() != null ) - { - this.getGui().updateSetting( manager, settingName, newValue ); - } - } - - @Override - public IConfigManager getConfigManager() - { - if( Platform.isServer() ) - { - return this.serverCM; - } - return this.clientCM; - } - - public ItemStack[] getViewCells() - { - final ItemStack[] list = new ItemStack[this.cellView.length]; - - for( int x = 0; x < this.cellView.length; x++ ) - { - list[x] = this.cellView[x].getStack(); - } - - return list; - } - - public SlotRestrictedInput getCellViewSlot( final int index ) - { - return this.cellView[index]; - } - - public boolean isPowered() - { - return this.hasPower; - } - - private void setPowered( final boolean isPowered ) - { - this.hasPower = isPowered; - } - - private IConfigManagerHost getGui() - { - return this.gui; - } - - public void setGui( @Nonnull final IConfigManagerHost gui ) - { - this.gui = gui; - } +public class ContainerMEMonitorable extends AEBaseContainer + implements IConfigManagerHost, IConfigurableObject, IMEMonitorHandlerReceiver { + + private final SlotRestrictedInput[] cellView = new SlotRestrictedInput[5]; + private final IMEMonitor monitor; + private final IItemList items = AEApi.instance().storage().createItemList(); + private final IConfigManager clientCM; + private final ITerminalHost host; + + @GuiSync(99) + public boolean canAccessViewCells = false; + + @GuiSync(98) + public boolean hasPower = false; + + private IConfigManagerHost gui; + private IConfigManager serverCM; + private IGridNode networkNode; + + public ContainerMEMonitorable(final InventoryPlayer ip, final ITerminalHost monitorable) { + this(ip, monitorable, true); + } + + protected ContainerMEMonitorable( + final InventoryPlayer ip, final ITerminalHost monitorable, final boolean bindInventory) { + super( + ip, + monitorable instanceof TileEntity ? (TileEntity) monitorable : null, + monitorable instanceof IPart ? (IPart) monitorable : null); + + this.host = monitorable; + this.clientCM = new ConfigManager(this); + + this.clientCM.registerSetting(Settings.SORT_BY, SortOrder.NAME); + this.clientCM.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + this.clientCM.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); + + if (Platform.isServer()) { + this.serverCM = monitorable.getConfigManager(); + + this.monitor = monitorable.getItemInventory(); + if (this.monitor != null) { + this.monitor.addListener(this, null); + + this.setCellInventory(this.monitor); + + if (monitorable instanceof IPortableCell) { + this.setPowerSource((IEnergySource) monitorable); + } else if (monitorable instanceof IMEChest) { + this.setPowerSource((IEnergySource) monitorable); + } else if (monitorable instanceof IGridHost) { + final IGridNode node = ((IGridHost) monitorable).getGridNode(ForgeDirection.UNKNOWN); + if (node != null) { + this.networkNode = node; + final IGrid g = node.getGrid(); + if (g != null) { + this.setPowerSource(new ChannelPowerSrc( + this.networkNode, (IEnergySource) g.getCache(IEnergyGrid.class))); + } + } + } + } else { + this.setValidContainer(false); + } + } else { + this.monitor = null; + } + + this.canAccessViewCells = false; + if (monitorable instanceof IViewCellStorage) { + for (int y = 0; y < 5; y++) { + this.cellView[y] = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.VIEW_CELL, + ((IViewCellStorage) monitorable).getViewCellStorage(), + y, + 206, + y * 18 + 8, + this.getInventoryPlayer()); + this.cellView[y].setAllowEdit(this.canAccessViewCells); + this.addSlotToContainer(this.cellView[y]); + } + } + + if (bindInventory) { + this.bindPlayerInventory(ip, 0, 0); + } + } + + public IGridNode getNetworkNode() { + return this.networkNode; + } + + @Override + public void detectAndSendChanges() { + if (Platform.isServer()) { + if (this.monitor != this.host.getItemInventory()) { + this.setValidContainer(false); + } + + for (final Settings set : this.serverCM.getSettings()) { + final Enum sideLocal = this.serverCM.getSetting(set); + final Enum sideRemote = this.clientCM.getSetting(set); + + if (sideLocal != sideRemote) { + this.clientCM.putSetting(set, sideLocal); + for (final Object crafter : this.crafters) { + try { + NetworkHandler.instance.sendTo( + new PacketValueConfig(set.name(), sideLocal.name()), (EntityPlayerMP) crafter); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + } + + if (!this.items.isEmpty()) { + try { + final IItemList monitorCache = this.monitor.getStorageList(); + + final PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); + + for (final IAEItemStack is : this.items) { + final IAEItemStack send = monitorCache.findPrecise(is); + if (send == null) { + is.setStackSize(0); + piu.appendItem(is); + } else { + piu.appendItem(send); + } + } + + if (!piu.isEmpty()) { + this.items.resetStatus(); + + for (final Object c : this.crafters) { + if (c instanceof EntityPlayer) { + NetworkHandler.instance.sendTo(piu, (EntityPlayerMP) c); + } + } + } + } catch (final IOException e) { + AELog.debug(e); + } + } + + this.updatePowerStatus(); + + final boolean oldAccessible = this.canAccessViewCells; + this.canAccessViewCells = + this.host instanceof WirelessTerminalGuiObject || this.hasAccess(SecurityPermissions.BUILD, false); + if (this.canAccessViewCells != oldAccessible) { + for (int y = 0; y < 5; y++) { + if (this.cellView[y] != null) { + this.cellView[y].setAllowEdit(this.canAccessViewCells); + } + } + } + + super.detectAndSendChanges(); + } + } + + protected void updatePowerStatus() { + try { + if (this.networkNode != null) { + this.setPowered(this.networkNode.isActive()); + } else if (this.getPowerSource() instanceof IEnergyGrid) { + this.setPowered(((IEnergyGrid) this.getPowerSource()).isNetworkPowered()); + } else { + this.setPowered( + this.getPowerSource().extractAEPower(1, Actionable.SIMULATE, PowerMultiplier.CONFIG) > 0.8); + } + } catch (final Throwable t) { + // :P + } + } + + @Override + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + if (field.equals("canAccessViewCells")) { + for (int y = 0; y < 5; y++) { + if (this.cellView[y] != null) { + this.cellView[y].setAllowEdit(this.canAccessViewCells); + } + } + } + + super.onUpdate(field, oldValue, newValue); + } + + @Override + public void addCraftingToCrafters(final ICrafting c) { + super.addCraftingToCrafters(c); + this.queueInventory(c); + } + + private void queueInventory(final ICrafting c) { + if (Platform.isServer() && c instanceof EntityPlayer && this.monitor != null) { + try { + PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); + final IItemList monitorCache = this.monitor.getStorageList(); + + for (final IAEItemStack send : monitorCache) { + try { + piu.appendItem(send); + } catch (final BufferOverflowException boe) { + NetworkHandler.instance.sendTo(piu, (EntityPlayerMP) c); + + piu = new PacketMEInventoryUpdate(); + piu.appendItem(send); + } + } + + NetworkHandler.instance.sendTo(piu, (EntityPlayerMP) c); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + + @Override + public void removeCraftingFromCrafters(final ICrafting c) { + super.removeCraftingFromCrafters(c); + + if (this.crafters.isEmpty() && this.monitor != null) { + this.monitor.removeListener(this); + } + } + + @Override + public void onContainerClosed(final EntityPlayer player) { + super.onContainerClosed(player); + if (this.monitor != null) { + this.monitor.removeListener(this); + } + } + + @Override + public boolean isValid(final Object verificationToken) { + return true; + } + + @Override + public void postChange( + final IBaseMonitor monitor, + final Iterable change, + final BaseActionSource source) { + for (final IAEItemStack is : change) { + this.items.add(is); + } + } + + @Override + public void onListUpdate() { + for (final Object c : this.crafters) { + if (c instanceof ICrafting) { + final ICrafting cr = (ICrafting) c; + this.queueInventory(cr); + } + } + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + if (this.getGui() != null) { + this.getGui().updateSetting(manager, settingName, newValue); + } + } + + @Override + public IConfigManager getConfigManager() { + if (Platform.isServer()) { + return this.serverCM; + } + return this.clientCM; + } + + public ItemStack[] getViewCells() { + final ItemStack[] list = new ItemStack[this.cellView.length]; + + for (int x = 0; x < this.cellView.length; x++) { + list[x] = this.cellView[x].getStack(); + } + + return list; + } + + public SlotRestrictedInput getCellViewSlot(final int index) { + return this.cellView[index]; + } + + public boolean isPowered() { + return this.hasPower; + } + + private void setPowered(final boolean isPowered) { + this.hasPower = isPowered; + } + + private IConfigManagerHost getGui() { + return this.gui; + } + + public void setGui(@Nonnull final IConfigManagerHost gui) { + this.gui = gui; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java b/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java index 4edea58213a..5e1cc46aec6 100644 --- a/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java +++ b/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; import appeng.api.implementations.guiobjects.IPortableCell; @@ -27,82 +26,66 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; +public class ContainerMEPortableCell extends ContainerMEMonitorable { -public class ContainerMEPortableCell extends ContainerMEMonitorable -{ - - private double powerMultiplier = 0.5; + private double powerMultiplier = 0.5; - private final IPortableCell civ; - private int ticks = 0; - private final int slot; + private final IPortableCell civ; + private int ticks = 0; + private final int slot; - public ContainerMEPortableCell( final InventoryPlayer ip, final IPortableCell monitorable ) - { - super( ip, monitorable, false ); - if( monitorable instanceof IInventorySlotAware ) - { - final int slotIndex = ( (IInventorySlotAware) monitorable ).getInventorySlot(); - this.lockPlayerInventorySlot( slotIndex ); - this.slot = slotIndex; - } - else - { - this.slot = -1; - this.lockPlayerInventorySlot( ip.currentItem ); - } - this.civ = monitorable; - this.bindPlayerInventory( ip, 0, 0 ); - } + public ContainerMEPortableCell(final InventoryPlayer ip, final IPortableCell monitorable) { + super(ip, monitorable, false); + if (monitorable instanceof IInventorySlotAware) { + final int slotIndex = ((IInventorySlotAware) monitorable).getInventorySlot(); + this.lockPlayerInventorySlot(slotIndex); + this.slot = slotIndex; + } else { + this.slot = -1; + this.lockPlayerInventorySlot(ip.currentItem); + } + this.civ = monitorable; + this.bindPlayerInventory(ip, 0, 0); + } - @Override - public void detectAndSendChanges() - { - final ItemStack currentItem = this.slot < 0 ? this.getPlayerInv().getCurrentItem() : this.getPlayerInv().getStackInSlot( this.slot ); + @Override + public void detectAndSendChanges() { + final ItemStack currentItem = this.slot < 0 + ? this.getPlayerInv().getCurrentItem() + : this.getPlayerInv().getStackInSlot(this.slot); - if( this.civ != null ) - { - if( currentItem != this.civ.getItemStack() ) - { - if( currentItem != null ) - { - if( Platform.isSameItem( this.civ.getItemStack(), currentItem ) ) - { - this.getPlayerInv().setInventorySlotContents( this.getPlayerInv().currentItem, this.civ.getItemStack() ); - } - else - { - this.setValidContainer( false ); - } - } - else - { - this.setValidContainer( false ); - } - } - } - else - { - this.setValidContainer( false ); - } + if (this.civ != null) { + if (currentItem != this.civ.getItemStack()) { + if (currentItem != null) { + if (Platform.isSameItem(this.civ.getItemStack(), currentItem)) { + this.getPlayerInv() + .setInventorySlotContents(this.getPlayerInv().currentItem, this.civ.getItemStack()); + } else { + this.setValidContainer(false); + } + } else { + this.setValidContainer(false); + } + } + } else { + this.setValidContainer(false); + } - // drain 1 ae t - this.ticks++; - if( this.ticks > 10 ) - { - this.civ.extractAEPower( this.getPowerMultiplier() * this.ticks, Actionable.MODULATE, PowerMultiplier.CONFIG ); - this.ticks = 0; - } - super.detectAndSendChanges(); - } + // drain 1 ae t + this.ticks++; + if (this.ticks > 10) { + this.civ.extractAEPower( + this.getPowerMultiplier() * this.ticks, Actionable.MODULATE, PowerMultiplier.CONFIG); + this.ticks = 0; + } + super.detectAndSendChanges(); + } - private double getPowerMultiplier() - { - return this.powerMultiplier; - } + private double getPowerMultiplier() { + return this.powerMultiplier; + } - void setPowerMultiplier( final double powerMultiplier ) - { - this.powerMultiplier = powerMultiplier; - } + void setPowerMultiplier(final double powerMultiplier) { + this.powerMultiplier = powerMultiplier; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerNetworkStatus.java b/src/main/java/appeng/container/implementations/ContainerNetworkStatus.java index 87a2604a318..92645826c15 100644 --- a/src/main/java/appeng/container/implementations/ContainerNetworkStatus.java +++ b/src/main/java/appeng/container/implementations/ContainerNetworkStatus.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.AEApi; import appeng.api.config.PowerMultiplier; import appeng.api.implementations.guiobjects.INetworkTool; @@ -35,157 +34,133 @@ import appeng.core.sync.packets.PacketMEInventoryUpdate; import appeng.util.Platform; import appeng.util.item.AEItemStack; +import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; - - -public class ContainerNetworkStatus extends AEBaseContainer -{ - - @GuiSync( 0 ) - public long avgAddition; - @GuiSync( 1 ) - public long powerUsage; - @GuiSync( 2 ) - public long currentPower; - @GuiSync( 3 ) - public long maxPower; - private IGrid network; - private int delay = 40; - - public ContainerNetworkStatus( final InventoryPlayer ip, final INetworkTool te ) - { - super( ip, null, null ); - final IGridHost host = te.getGridHost(); - - if( host != null ) - { - this.findNode( host, ForgeDirection.UNKNOWN ); - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - this.findNode( host, d ); - } - } - - if( this.network == null && Platform.isServer() ) - { - this.setValidContainer( false ); - } - } - - private void findNode( final IGridHost host, final ForgeDirection d ) - { - if( this.network == null ) - { - final IGridNode node = host.getGridNode( d ); - if( node != null ) - { - this.network = node.getGrid(); - } - } - } - - @Override - public void detectAndSendChanges() - { - this.delay++; - if( Platform.isServer() && this.delay > 15 && this.network != null ) - { - this.delay = 0; - - final IEnergyGrid eg = this.network.getCache( IEnergyGrid.class ); - if( eg != null ) - { - this.setAverageAddition( (long) ( 100.0 * eg.getAvgPowerInjection() ) ); - this.setPowerUsage( (long) ( 100.0 * eg.getAvgPowerUsage() ) ); - this.setCurrentPower( (long) ( 100.0 * eg.getStoredPower() ) ); - this.setMaxPower( (long) ( 100.0 * eg.getMaxStoredPower() ) ); - } - - try - { - final PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); - - for( final Class machineClass : this.network.getMachinesClasses() ) - { - final IItemList list = AEApi.instance().storage().createItemList(); - for( final IGridNode machine : this.network.getMachines( machineClass ) ) - { - final IGridBlock blk = machine.getGridBlock(); - final ItemStack is = blk.getMachineRepresentation(); - if( is != null && is.getItem() != null ) - { - final IAEItemStack ais = AEItemStack.create( is ); - ais.setStackSize( 1 ); - ais.setCountRequestable( (long) PowerMultiplier.CONFIG.multiply ( blk.getIdlePowerUsage() * 100.0 ) ); - list.add( ais ); - } - } - - for( final IAEItemStack ais : list ) - { - piu.appendItem( ais ); - } - } - - for( final Object c : this.crafters ) - { - if( c instanceof EntityPlayer ) - { - NetworkHandler.instance.sendTo( piu, (EntityPlayerMP) c ); - } - } - } - catch( final IOException e ) - { - // :P - } - } - super.detectAndSendChanges(); - } - - public long getCurrentPower() - { - return this.currentPower; - } - - private void setCurrentPower( final long currentPower ) - { - this.currentPower = currentPower; - } - - public long getMaxPower() - { - return this.maxPower; - } - - private void setMaxPower( final long maxPower ) - { - this.maxPower = maxPower; - } - - public long getAverageAddition() - { - return this.avgAddition; - } - - private void setAverageAddition( final long avgAddition ) - { - this.avgAddition = avgAddition; - } - - public long getPowerUsage() - { - return this.powerUsage; - } - - private void setPowerUsage( final long powerUsage ) - { - this.powerUsage = powerUsage; - } +public class ContainerNetworkStatus extends AEBaseContainer { + + @GuiSync(0) + public long avgAddition; + + @GuiSync(1) + public long powerUsage; + + @GuiSync(2) + public long currentPower; + + @GuiSync(3) + public long maxPower; + + private IGrid network; + private int delay = 40; + + public ContainerNetworkStatus(final InventoryPlayer ip, final INetworkTool te) { + super(ip, null, null); + final IGridHost host = te.getGridHost(); + + if (host != null) { + this.findNode(host, ForgeDirection.UNKNOWN); + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + this.findNode(host, d); + } + } + + if (this.network == null && Platform.isServer()) { + this.setValidContainer(false); + } + } + + private void findNode(final IGridHost host, final ForgeDirection d) { + if (this.network == null) { + final IGridNode node = host.getGridNode(d); + if (node != null) { + this.network = node.getGrid(); + } + } + } + + @Override + public void detectAndSendChanges() { + this.delay++; + if (Platform.isServer() && this.delay > 15 && this.network != null) { + this.delay = 0; + + final IEnergyGrid eg = this.network.getCache(IEnergyGrid.class); + if (eg != null) { + this.setAverageAddition((long) (100.0 * eg.getAvgPowerInjection())); + this.setPowerUsage((long) (100.0 * eg.getAvgPowerUsage())); + this.setCurrentPower((long) (100.0 * eg.getStoredPower())); + this.setMaxPower((long) (100.0 * eg.getMaxStoredPower())); + } + + try { + final PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); + + for (final Class machineClass : this.network.getMachinesClasses()) { + final IItemList list = + AEApi.instance().storage().createItemList(); + for (final IGridNode machine : this.network.getMachines(machineClass)) { + final IGridBlock blk = machine.getGridBlock(); + final ItemStack is = blk.getMachineRepresentation(); + if (is != null && is.getItem() != null) { + final IAEItemStack ais = AEItemStack.create(is); + ais.setStackSize(1); + ais.setCountRequestable( + (long) PowerMultiplier.CONFIG.multiply(blk.getIdlePowerUsage() * 100.0)); + list.add(ais); + } + } + + for (final IAEItemStack ais : list) { + piu.appendItem(ais); + } + } + + for (final Object c : this.crafters) { + if (c instanceof EntityPlayer) { + NetworkHandler.instance.sendTo(piu, (EntityPlayerMP) c); + } + } + } catch (final IOException e) { + // :P + } + } + super.detectAndSendChanges(); + } + + public long getCurrentPower() { + return this.currentPower; + } + + private void setCurrentPower(final long currentPower) { + this.currentPower = currentPower; + } + + public long getMaxPower() { + return this.maxPower; + } + + private void setMaxPower(final long maxPower) { + this.maxPower = maxPower; + } + + public long getAverageAddition() { + return this.avgAddition; + } + + private void setAverageAddition(final long avgAddition) { + this.avgAddition = avgAddition; + } + + public long getPowerUsage() { + return this.powerUsage; + } + + private void setPowerUsage(final long powerUsage) { + this.powerUsage = powerUsage; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerNetworkTool.java b/src/main/java/appeng/container/implementations/ContainerNetworkTool.java index 75e75323746..8eaf77d60a0 100644 --- a/src/main/java/appeng/container/implementations/ContainerNetworkTool.java +++ b/src/main/java/appeng/container/implementations/ContainerNetworkTool.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.implementations.guiobjects.INetworkTool; import appeng.container.AEBaseContainer; import appeng.container.guisync.GuiSync; @@ -28,80 +27,70 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; - -public class ContainerNetworkTool extends AEBaseContainer -{ - - private final INetworkTool toolInv; - - @GuiSync( 1 ) - public boolean facadeMode; - - public ContainerNetworkTool( final InventoryPlayer ip, final INetworkTool te ) - { - super( ip, null, null ); - this.toolInv = te; - - this.lockPlayerInventorySlot( ip.currentItem ); - - for( int y = 0; y < 3; y++ ) - { - for( int x = 0; x < 3; x++ ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, te, y * 3 + x, 80 - 18 + x * 18, 37 - 18 + y * 18, this.getInventoryPlayer() ) ) ); - } - } - - this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); - } - - public void toggleFacadeMode() - { - final NBTTagCompound data = Platform.openNbtData( this.toolInv.getItemStack() ); - data.setBoolean( "hideFacades", !data.getBoolean( "hideFacades" ) ); - this.detectAndSendChanges(); - } - - @Override - public void detectAndSendChanges() - { - final ItemStack currentItem = this.getPlayerInv().getCurrentItem(); - - if( currentItem != this.toolInv.getItemStack() ) - { - if( currentItem != null ) - { - if( Platform.isSameItem( this.toolInv.getItemStack(), currentItem ) ) - { - this.getPlayerInv().setInventorySlotContents( this.getPlayerInv().currentItem, this.toolInv.getItemStack() ); - } - else - { - this.setValidContainer( false ); - } - } - else - { - this.setValidContainer( false ); - } - } - - if( this.isValidContainer() ) - { - final NBTTagCompound data = Platform.openNbtData( currentItem ); - this.setFacadeMode( data.getBoolean( "hideFacades" ) ); - } - - super.detectAndSendChanges(); - } - - public boolean isFacadeMode() - { - return this.facadeMode; - } - - private void setFacadeMode( final boolean facadeMode ) - { - this.facadeMode = facadeMode; - } +public class ContainerNetworkTool extends AEBaseContainer { + + private final INetworkTool toolInv; + + @GuiSync(1) + public boolean facadeMode; + + public ContainerNetworkTool(final InventoryPlayer ip, final INetworkTool te) { + super(ip, null, null); + this.toolInv = te; + + this.lockPlayerInventorySlot(ip.currentItem); + + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 3; x++) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + te, + y * 3 + x, + 80 - 18 + x * 18, + 37 - 18 + y * 18, + this.getInventoryPlayer()))); + } + } + + this.bindPlayerInventory(ip, 0, 166 - /* height of player inventory */ 82); + } + + public void toggleFacadeMode() { + final NBTTagCompound data = Platform.openNbtData(this.toolInv.getItemStack()); + data.setBoolean("hideFacades", !data.getBoolean("hideFacades")); + this.detectAndSendChanges(); + } + + @Override + public void detectAndSendChanges() { + final ItemStack currentItem = this.getPlayerInv().getCurrentItem(); + + if (currentItem != this.toolInv.getItemStack()) { + if (currentItem != null) { + if (Platform.isSameItem(this.toolInv.getItemStack(), currentItem)) { + this.getPlayerInv() + .setInventorySlotContents(this.getPlayerInv().currentItem, this.toolInv.getItemStack()); + } else { + this.setValidContainer(false); + } + } else { + this.setValidContainer(false); + } + } + + if (this.isValidContainer()) { + final NBTTagCompound data = Platform.openNbtData(currentItem); + this.setFacadeMode(data.getBoolean("hideFacades")); + } + + super.detectAndSendChanges(); + } + + public boolean isFacadeMode() { + return this.facadeMode; + } + + private void setFacadeMode(final boolean facadeMode) { + this.facadeMode = facadeMode; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerOreFilter.java b/src/main/java/appeng/container/implementations/ContainerOreFilter.java index 9ce8c2a6aaa..2c21101b288 100644 --- a/src/main/java/appeng/container/implementations/ContainerOreFilter.java +++ b/src/main/java/appeng/container/implementations/ContainerOreFilter.java @@ -11,46 +11,41 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.tileentity.TileEntity; -public class ContainerOreFilter extends AEBaseContainer -{ +public class ContainerOreFilter extends AEBaseContainer { private final IOreFilterable filterHost; - @SideOnly( Side.CLIENT ) + + @SideOnly(Side.CLIENT) private MEGuiTextField textField; - @GuiSync( 2 ) + + @GuiSync(2) public String filter = ""; - public ContainerOreFilter( final InventoryPlayer ip, final IOreFilterable te) - { - super( ip, (TileEntity) ( te instanceof TileEntity ? te : null ), (IPart) ( te instanceof IPart ? te : null ) ); + public ContainerOreFilter(final InventoryPlayer ip, final IOreFilterable te) { + super(ip, (TileEntity) (te instanceof TileEntity ? te : null), (IPart) (te instanceof IPart ? te : null)); this.filterHost = te; } - @SideOnly( Side.CLIENT ) - public void setTextField( final MEGuiTextField f ) - { + @SideOnly(Side.CLIENT) + public void setTextField(final MEGuiTextField f) { this.textField = f; this.textField.setText(filter); } - public void setFilter( final String newValue) - { + public void setFilter(final String newValue) { this.filterHost.setFilter(newValue); this.filter = newValue; } @Override - public void detectAndSendChanges() - { - if (Platform.isServer()) - this.filter = this.filterHost.getFilter(); + public void detectAndSendChanges() { + if (Platform.isServer()) this.filter = this.filterHost.getFilter(); super.detectAndSendChanges(); } + @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - if (field.equals("filter") && this.textField != null) - this.textField.setText(filter); + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + if (field.equals("filter") && this.textField != null) this.textField.setText(filter); - super.onUpdate( field, oldValue, newValue ); + super.onUpdate(field, oldValue, newValue); } } diff --git a/src/main/java/appeng/container/implementations/ContainerPatternTerm.java b/src/main/java/appeng/container/implementations/ContainerPatternTerm.java index ee33759fc9a..394f3673b50 100644 --- a/src/main/java/appeng/container/implementations/ContainerPatternTerm.java +++ b/src/main/java/appeng/container/implementations/ContainerPatternTerm.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.definitions.IDefinitions; @@ -41,6 +40,11 @@ import appeng.util.Platform; import appeng.util.inv.AdaptorPlayerHand; import appeng.util.item.AEItemStack; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collectors; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; @@ -53,584 +57,534 @@ import net.minecraft.nbt.NBTTagList; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.stream.Collectors; - - -public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEAppEngInventory, IOptionalSlotHost, IContainerCraftingPacket -{ - - private final PartPatternTerminal patternTerminal; - private final AppEngInternalInventory cOut = new AppEngInternalInventory( null, 1 ); - private final IInventory crafting; - private final SlotFakeCraftingMatrix[] craftingSlots = new SlotFakeCraftingMatrix[9]; - private final OptionalSlotFake[] outputSlots = new OptionalSlotFake[3]; - private final SlotPatternTerm craftSlot; - private final SlotRestrictedInput patternSlotIN; - private final SlotRestrictedInput patternSlotOUT; - @GuiSync( 97 ) - public boolean craftingMode = true; - @GuiSync( 96 ) - public boolean substitute = false; - - public ContainerPatternTerm( final InventoryPlayer ip, final ITerminalHost monitorable ) - { - super( ip, monitorable, false ); - this.patternTerminal = (PartPatternTerminal) monitorable; - - final IInventory patternInv = this.getPatternTerminal().getInventoryByName( "pattern" ); - final IInventory output = this.getPatternTerminal().getInventoryByName( "output" ); - - this.crafting = this.getPatternTerminal().getInventoryByName( "crafting" ); - - for( int y = 0; y < 3; y++ ) - { - for( int x = 0; x < 3; x++ ) - { - this.addSlotToContainer( this.craftingSlots[x + y * 3] = new SlotFakeCraftingMatrix( this.crafting, x + y * 3, 18 + x * 18, -76 + y * 18 ) ); - } - } - - this.addSlotToContainer( this.craftSlot = new SlotPatternTerm( ip.player, this.getActionSource(), this.getPowerSource(), monitorable, this.crafting, patternInv, this.cOut, 110, -76 + 18, this, 2, this ) ); - this.craftSlot.setIIcon( -1 ); - - for( int y = 0; y < 3; y++ ) - { - this.addSlotToContainer( this.outputSlots[y] = new SlotPatternOutputs( output, this, y, 110, -76 + y * 18, 0, 0, 1 ) ); - this.outputSlots[y].setRenderDisabled( false ); - } - - this.addSlotToContainer( this.patternSlotIN = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.BLANK_PATTERN, patternInv, 0, 147, -72 - 9, this.getInventoryPlayer() ) ); - this.addSlotToContainer( this.patternSlotOUT = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, patternInv, 1, 147, -72 + 34, this.getInventoryPlayer() ) ); - - this.patternSlotOUT.setStackLimit( 1 ); - - this.bindPlayerInventory( ip, 0, 0 ); - this.updateOrderOfOutputSlots(); - } - - private void updateOrderOfOutputSlots() - { - if( !this.isCraftingMode() ) - { - this.craftSlot.xDisplayPosition = -9000; - - for( int y = 0; y < 3; y++ ) - { - this.outputSlots[y].xDisplayPosition = this.outputSlots[y].getX(); - } - } - else - { - this.craftSlot.xDisplayPosition = this.craftSlot.getX(); - - for( int y = 0; y < 3; y++ ) - { - this.outputSlots[y].xDisplayPosition = -9000; - } - } - } - - @Override - public void putStackInSlot( final int par1, final ItemStack par2ItemStack ) - { - super.putStackInSlot( par1, par2ItemStack ); - this.getAndUpdateOutput(); - } - - @Override - public void putStacksInSlots( final ItemStack[] par1ArrayOfItemStack ) - { - super.putStacksInSlots( par1ArrayOfItemStack ); - this.getAndUpdateOutput(); - } - - private ItemStack getAndUpdateOutput() - { - final InventoryCrafting ic = new InventoryCrafting( this, 3, 3 ); - - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - ic.setInventorySlotContents( x, this.crafting.getStackInSlot( x ) ); - } - - final ItemStack is = CraftingManager.getInstance().findMatchingRecipe( ic, this.getPlayerInv().player.worldObj ); - this.cOut.setInventorySlotContents( 0, is ); - return is; - } - - @Override - public void saveChanges() - { - - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - - } - - public void encodeAndMoveToInventory(boolean encodeWholeStack) - { - encode(); - ItemStack output = this.patternSlotOUT.getStack(); - if ( output != null ) - { - if (encodeWholeStack) - { - ItemStack blanks = this.patternSlotIN.getStack(); - this.patternSlotIN.putStack(null); - if (blanks != null) - output.stackSize += blanks.stackSize; - } - if (!getPlayerInv().addItemStackToInventory( output )) - { - getPlayerInv().player.entityDropItem(output, 0); - } - this.patternSlotOUT.putStack( null ); - } - } - - public void encode() - { - ItemStack output = this.patternSlotOUT.getStack(); - - final ItemStack[] in = this.getInputs(); - final ItemStack[] out = this.getOutputs(); - - // if there is no input, this would be silly. - if( in == null || out == null ) - { - return; - } - - // first check the output slots, should either be null, or a pattern - if( output != null && !this.isPattern( output ) ) - { - return; - }// if nothing is there we should snag a new pattern. - else if( output == null ) - { - output = this.patternSlotIN.getStack(); - if (!this.isPattern( output )) - { - return; // no blanks. - } - - // remove one, and clear the input slot. - output.stackSize--; - if( output.stackSize == 0 ) - { - this.patternSlotIN.putStack( null ); - } - - // add a new encoded pattern. - for( final ItemStack encodedPatternStack : AEApi.instance().definitions().items().encodedPattern().maybeStack( 1 ).asSet() ) - { - output = encodedPatternStack; - this.patternSlotOUT.putStack( output ); - } - } - - // encode the slot. - final NBTTagCompound encodedValue = new NBTTagCompound(); - - final NBTTagList tagIn = new NBTTagList(); - final NBTTagList tagOut = new NBTTagList(); - - for( final ItemStack i : in ) - { - tagIn.appendTag( this.createItemTag( i ) ); - } - - for( final ItemStack i : out ) - { - tagOut.appendTag( this.createItemTag( i ) ); - } - - encodedValue.setTag( "in", tagIn ); - encodedValue.setTag( "out", tagOut ); - encodedValue.setBoolean( "crafting", this.isCraftingMode() ); - encodedValue.setBoolean( "substitute", this.isSubstitute() ); - - output.setTagCompound( encodedValue ); - } - - private ItemStack[] getInputs() - { - final ItemStack[] input = new ItemStack[9]; - boolean hasValue = false; - - for( int x = 0; x < this.craftingSlots.length; x++ ) - { - input[x] = this.craftingSlots[x].getStack(); - if( input[x] != null ) - { - hasValue = true; - } - } - - if( hasValue ) - { - return input; - } - - return null; - } - - private ItemStack[] getOutputs() - { - if( this.isCraftingMode() ) - { - final ItemStack out = this.getAndUpdateOutput(); - - if( out != null && out.stackSize > 0 ) - { - return new ItemStack[] { out }; - } - } - else - { - final List list = new ArrayList<>( 3 ); - boolean hasValue = false; - - for( final OptionalSlotFake outputSlot : this.outputSlots ) - { - final ItemStack out = outputSlot.getStack(); - - if( out != null && out.stackSize > 0 ) - { - list.add( out ); - hasValue = true; - } - } - - if( hasValue ) - { - return list.toArray( new ItemStack[list.size()] ); - } - } - - return null; - } - - private boolean isPattern( final ItemStack output ) - { - if( output == null ) - { - return false; - } - - final IDefinitions definitions = AEApi.instance().definitions(); - - boolean isPattern = definitions.items().encodedPattern().isSameAs( output ); - isPattern |= definitions.materials().blankPattern().isSameAs( output ); - - return isPattern; - } - - private NBTBase createItemTag( final ItemStack i ) - { - final NBTTagCompound c = new NBTTagCompound(); - - if( i != null ) - { - i.writeToNBT( c ); - c.setInteger( "Count", i.stackSize ); - } - - return c; - } - - @Override - public boolean isSlotEnabled( final int idx ) - { - if( idx == 1 ) - { - return Platform.isServer() ? !this.getPatternTerminal().isCraftingRecipe() : !this.isCraftingMode(); - } - else if( idx == 2 ) - { - return Platform.isServer() ? this.getPatternTerminal().isCraftingRecipe() : this.isCraftingMode(); - } - else - { - return false; - } - } - - public void craftOrGetItem( final PacketPatternSlot packetPatternSlot ) - { - if( packetPatternSlot.slotItem != null && this.getCellInventory() != null ) - { - final IAEItemStack out = packetPatternSlot.slotItem.copy(); - InventoryAdaptor inv = new AdaptorPlayerHand( this.getPlayerInv().player ); - final InventoryAdaptor playerInv = InventoryAdaptor.getAdaptor( this.getPlayerInv().player, ForgeDirection.UNKNOWN ); - - if( packetPatternSlot.shift ) - { - inv = playerInv; - } - - if( inv.simulateAdd( out.getItemStack() ) != null ) - { - return; - } - - final IAEItemStack extracted = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), out, this.getActionSource() ); - final EntityPlayer p = this.getPlayerInv().player; - - if( extracted != null ) - { - inv.addItems( extracted.getItemStack() ); - if( p instanceof EntityPlayerMP ) - { - this.updateHeld( (EntityPlayerMP) p ); - } - this.detectAndSendChanges(); - return; - } - - final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); - final InventoryCrafting real = new InventoryCrafting( new ContainerNull(), 3, 3 ); - - for( int x = 0; x < 9; x++ ) - { - ic.setInventorySlotContents( x, packetPatternSlot.pattern[x] == null ? null : packetPatternSlot.pattern[x].getItemStack() ); - } - - final IRecipe r = Platform.findMatchingRecipe( ic, p.worldObj ); - - if( r == null ) - { - return; - } - - final IMEMonitor storage = this.getPatternTerminal().getItemInventory(); - final IItemList all = storage.getStorageList(); - - final ItemStack is = r.getCraftingResult( ic ); - - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - if( ic.getStackInSlot( x ) != null ) - { - final ItemStack pulled = Platform.extractItemsByRecipe( this.getPowerSource(), this.getActionSource(), storage, p.worldObj, r, is, ic, ic.getStackInSlot( x ), x, all, Actionable.MODULATE, ItemViewCell.createFilter( this.getViewCells() ) ); - real.setInventorySlotContents( x, pulled ); - } - } - - final IRecipe rr = Platform.findMatchingRecipe( real, p.worldObj ); - - if( rr == r && Platform.isSameItemPrecise( rr.getCraftingResult( real ), is ) ) - { - final SlotCrafting sc = new SlotCrafting( p, real, this.cOut, 0, 0, 0 ); - sc.onPickupFromSlot( p, is ); - - for( int x = 0; x < real.getSizeInventory(); x++ ) - { - final ItemStack failed = playerInv.addItems( real.getStackInSlot( x ) ); - - if( failed != null ) - { - p.dropPlayerItemWithRandomChoice( failed, false ); - } - } - - inv.addItems( is ); - if( p instanceof EntityPlayerMP ) - { - this.updateHeld( (EntityPlayerMP) p ); - } - this.detectAndSendChanges(); - } - else - { - for( int x = 0; x < real.getSizeInventory(); x++ ) - { - final ItemStack failed = real.getStackInSlot( x ); - if( failed != null ) - { - this.getCellInventory().injectItems( AEItemStack.create( failed ), Actionable.MODULATE, new MachineSource( this.getPatternTerminal() ) ); - } - } - } - } - } - - @Override - public void detectAndSendChanges() - { - super.detectAndSendChanges(); - if( Platform.isServer() ) - { - if( this.isCraftingMode() != this.getPatternTerminal().isCraftingRecipe() ) - { - this.setCraftingMode( this.getPatternTerminal().isCraftingRecipe() ); - this.updateOrderOfOutputSlots(); - } - - this.substitute = this.patternTerminal.isSubstitution(); - } - } - - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - super.onUpdate( field, oldValue, newValue ); - - if( field.equals( "craftingMode" ) ) - { - this.getAndUpdateOutput(); - this.updateOrderOfOutputSlots(); - } - } - - @Override - public void onSlotChange( final Slot s ) - { - if( s == this.patternSlotOUT && Platform.isServer() ) - { - for( final Object crafter : this.crafters ) - { - final ICrafting icrafting = (ICrafting) crafter; - - for( final Object g : this.inventorySlots ) - { - if( g instanceof OptionalSlotFake || g instanceof SlotFakeCraftingMatrix ) - { - final Slot sri = (Slot) g; - icrafting.sendSlotContents( this, sri.slotNumber, sri.getStack() ); - } - } - ( (EntityPlayerMP) icrafting ).isChangingQuantityOnly = false; - } - this.detectAndSendChanges(); - } - } - - public void clear() - { - for( final Slot s : this.craftingSlots ) - { - s.putStack( null ); - } - - for( final Slot s : this.outputSlots ) - { - s.putStack( null ); - } - - this.detectAndSendChanges(); - this.getAndUpdateOutput(); - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "player" ) ) - { - return this.getInventoryPlayer(); - } - return this.getPatternTerminal().getInventoryByName( name ); - } - - @Override - public boolean useRealItems() - { - return false; - } - - public void toggleSubstitute() - { - this.substitute = !this.substitute; - - this.detectAndSendChanges(); - this.getAndUpdateOutput(); - } - - public boolean isCraftingMode() - { - return this.craftingMode; - } - - private void setCraftingMode( final boolean craftingMode ) - { - this.craftingMode = craftingMode; - } - - public PartPatternTerminal getPatternTerminal() - { - return this.patternTerminal; - } - - private boolean isSubstitute() - { - return this.substitute; - } - - public void setSubstitute( final boolean substitute ) - { - this.substitute = substitute; - } - - static boolean canDoubleStacks(SlotFake[] slots) - { - List enabledSlots = Arrays.stream(slots).filter(SlotFake::isEnabled).collect(Collectors.toList()); - long emptyStots = enabledSlots.stream().filter(s -> s.getStack() == null).count(); - long fullSlots = enabledSlots.stream().filter(s-> s.getStack() != null && s.getStack().stackSize * 2 > 127).count(); - return fullSlots <= emptyStots && emptyStots < enabledSlots.size(); - } - - static void doubleStacksInternal(SlotFake[] slots) - { - List overFlowStacks = new ArrayList<>(); - List enabledSlots = Arrays.stream(slots).filter(SlotFake::isEnabled).collect(Collectors.toList()); - for (final Slot s : enabledSlots) - { - ItemStack st = s.getStack(); - if (st == null) - continue; - if (st.stackSize * 2 > 127) - { - overFlowStacks.add(st.copy()); - } - else - { - st.stackSize *= 2; - s.putStack(st); - } - } - Iterator ow = overFlowStacks.iterator(); - for (final Slot s : enabledSlots) { - if (!ow.hasNext()) - break; - if (s.getStack() != null) - continue; - s.putStack(ow.next()); - } - assert !ow.hasNext(); - } - - public void doubleStacks(boolean isShift) - { - if (!isCraftingMode() && canDoubleStacks(craftingSlots) && canDoubleStacks(outputSlots)) - { - doubleStacksInternal(this.craftingSlots); - doubleStacksInternal(this.outputSlots); - if (isShift) - { - while (canDoubleStacks(craftingSlots) && canDoubleStacks(outputSlots)) - { - doubleStacksInternal(this.craftingSlots); - doubleStacksInternal(this.outputSlots); - } - } - this.detectAndSendChanges(); - } - } +public class ContainerPatternTerm extends ContainerMEMonitorable + implements IAEAppEngInventory, IOptionalSlotHost, IContainerCraftingPacket { + + private final PartPatternTerminal patternTerminal; + private final AppEngInternalInventory cOut = new AppEngInternalInventory(null, 1); + private final IInventory crafting; + private final SlotFakeCraftingMatrix[] craftingSlots = new SlotFakeCraftingMatrix[9]; + private final OptionalSlotFake[] outputSlots = new OptionalSlotFake[3]; + private final SlotPatternTerm craftSlot; + private final SlotRestrictedInput patternSlotIN; + private final SlotRestrictedInput patternSlotOUT; + + @GuiSync(97) + public boolean craftingMode = true; + + @GuiSync(96) + public boolean substitute = false; + + public ContainerPatternTerm(final InventoryPlayer ip, final ITerminalHost monitorable) { + super(ip, monitorable, false); + this.patternTerminal = (PartPatternTerminal) monitorable; + + final IInventory patternInv = this.getPatternTerminal().getInventoryByName("pattern"); + final IInventory output = this.getPatternTerminal().getInventoryByName("output"); + + this.crafting = this.getPatternTerminal().getInventoryByName("crafting"); + + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 3; x++) { + this.addSlotToContainer( + this.craftingSlots[x + y * 3] = + new SlotFakeCraftingMatrix(this.crafting, x + y * 3, 18 + x * 18, -76 + y * 18)); + } + } + + this.addSlotToContainer( + this.craftSlot = new SlotPatternTerm( + ip.player, + this.getActionSource(), + this.getPowerSource(), + monitorable, + this.crafting, + patternInv, + this.cOut, + 110, + -76 + 18, + this, + 2, + this)); + this.craftSlot.setIIcon(-1); + + for (int y = 0; y < 3; y++) { + this.addSlotToContainer( + this.outputSlots[y] = new SlotPatternOutputs(output, this, y, 110, -76 + y * 18, 0, 0, 1)); + this.outputSlots[y].setRenderDisabled(false); + } + + this.addSlotToContainer( + this.patternSlotIN = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.BLANK_PATTERN, + patternInv, + 0, + 147, + -72 - 9, + this.getInventoryPlayer())); + this.addSlotToContainer( + this.patternSlotOUT = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, + patternInv, + 1, + 147, + -72 + 34, + this.getInventoryPlayer())); + + this.patternSlotOUT.setStackLimit(1); + + this.bindPlayerInventory(ip, 0, 0); + this.updateOrderOfOutputSlots(); + } + + private void updateOrderOfOutputSlots() { + if (!this.isCraftingMode()) { + this.craftSlot.xDisplayPosition = -9000; + + for (int y = 0; y < 3; y++) { + this.outputSlots[y].xDisplayPosition = this.outputSlots[y].getX(); + } + } else { + this.craftSlot.xDisplayPosition = this.craftSlot.getX(); + + for (int y = 0; y < 3; y++) { + this.outputSlots[y].xDisplayPosition = -9000; + } + } + } + + @Override + public void putStackInSlot(final int par1, final ItemStack par2ItemStack) { + super.putStackInSlot(par1, par2ItemStack); + this.getAndUpdateOutput(); + } + + @Override + public void putStacksInSlots(final ItemStack[] par1ArrayOfItemStack) { + super.putStacksInSlots(par1ArrayOfItemStack); + this.getAndUpdateOutput(); + } + + private ItemStack getAndUpdateOutput() { + final InventoryCrafting ic = new InventoryCrafting(this, 3, 3); + + for (int x = 0; x < ic.getSizeInventory(); x++) { + ic.setInventorySlotContents(x, this.crafting.getStackInSlot(x)); + } + + final ItemStack is = CraftingManager.getInstance().findMatchingRecipe(ic, this.getPlayerInv().player.worldObj); + this.cOut.setInventorySlotContents(0, is); + return is; + } + + @Override + public void saveChanges() {} + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) {} + + public void encodeAndMoveToInventory(boolean encodeWholeStack) { + encode(); + ItemStack output = this.patternSlotOUT.getStack(); + if (output != null) { + if (encodeWholeStack) { + ItemStack blanks = this.patternSlotIN.getStack(); + this.patternSlotIN.putStack(null); + if (blanks != null) output.stackSize += blanks.stackSize; + } + if (!getPlayerInv().addItemStackToInventory(output)) { + getPlayerInv().player.entityDropItem(output, 0); + } + this.patternSlotOUT.putStack(null); + } + } + + public void encode() { + ItemStack output = this.patternSlotOUT.getStack(); + + final ItemStack[] in = this.getInputs(); + final ItemStack[] out = this.getOutputs(); + + // if there is no input, this would be silly. + if (in == null || out == null) { + return; + } + + // first check the output slots, should either be null, or a pattern + if (output != null && !this.isPattern(output)) { + return; + } // if nothing is there we should snag a new pattern. + else if (output == null) { + output = this.patternSlotIN.getStack(); + if (!this.isPattern(output)) { + return; // no blanks. + } + + // remove one, and clear the input slot. + output.stackSize--; + if (output.stackSize == 0) { + this.patternSlotIN.putStack(null); + } + + // add a new encoded pattern. + for (final ItemStack encodedPatternStack : AEApi.instance() + .definitions() + .items() + .encodedPattern() + .maybeStack(1) + .asSet()) { + output = encodedPatternStack; + this.patternSlotOUT.putStack(output); + } + } + + // encode the slot. + final NBTTagCompound encodedValue = new NBTTagCompound(); + + final NBTTagList tagIn = new NBTTagList(); + final NBTTagList tagOut = new NBTTagList(); + + for (final ItemStack i : in) { + tagIn.appendTag(this.createItemTag(i)); + } + + for (final ItemStack i : out) { + tagOut.appendTag(this.createItemTag(i)); + } + + encodedValue.setTag("in", tagIn); + encodedValue.setTag("out", tagOut); + encodedValue.setBoolean("crafting", this.isCraftingMode()); + encodedValue.setBoolean("substitute", this.isSubstitute()); + + output.setTagCompound(encodedValue); + } + + private ItemStack[] getInputs() { + final ItemStack[] input = new ItemStack[9]; + boolean hasValue = false; + + for (int x = 0; x < this.craftingSlots.length; x++) { + input[x] = this.craftingSlots[x].getStack(); + if (input[x] != null) { + hasValue = true; + } + } + + if (hasValue) { + return input; + } + + return null; + } + + private ItemStack[] getOutputs() { + if (this.isCraftingMode()) { + final ItemStack out = this.getAndUpdateOutput(); + + if (out != null && out.stackSize > 0) { + return new ItemStack[] {out}; + } + } else { + final List list = new ArrayList<>(3); + boolean hasValue = false; + + for (final OptionalSlotFake outputSlot : this.outputSlots) { + final ItemStack out = outputSlot.getStack(); + + if (out != null && out.stackSize > 0) { + list.add(out); + hasValue = true; + } + } + + if (hasValue) { + return list.toArray(new ItemStack[list.size()]); + } + } + + return null; + } + + private boolean isPattern(final ItemStack output) { + if (output == null) { + return false; + } + + final IDefinitions definitions = AEApi.instance().definitions(); + + boolean isPattern = definitions.items().encodedPattern().isSameAs(output); + isPattern |= definitions.materials().blankPattern().isSameAs(output); + + return isPattern; + } + + private NBTBase createItemTag(final ItemStack i) { + final NBTTagCompound c = new NBTTagCompound(); + + if (i != null) { + i.writeToNBT(c); + c.setInteger("Count", i.stackSize); + } + + return c; + } + + @Override + public boolean isSlotEnabled(final int idx) { + if (idx == 1) { + return Platform.isServer() ? !this.getPatternTerminal().isCraftingRecipe() : !this.isCraftingMode(); + } else if (idx == 2) { + return Platform.isServer() ? this.getPatternTerminal().isCraftingRecipe() : this.isCraftingMode(); + } else { + return false; + } + } + + public void craftOrGetItem(final PacketPatternSlot packetPatternSlot) { + if (packetPatternSlot.slotItem != null && this.getCellInventory() != null) { + final IAEItemStack out = packetPatternSlot.slotItem.copy(); + InventoryAdaptor inv = new AdaptorPlayerHand(this.getPlayerInv().player); + final InventoryAdaptor playerInv = + InventoryAdaptor.getAdaptor(this.getPlayerInv().player, ForgeDirection.UNKNOWN); + + if (packetPatternSlot.shift) { + inv = playerInv; + } + + if (inv.simulateAdd(out.getItemStack()) != null) { + return; + } + + final IAEItemStack extracted = Platform.poweredExtraction( + this.getPowerSource(), this.getCellInventory(), out, this.getActionSource()); + final EntityPlayer p = this.getPlayerInv().player; + + if (extracted != null) { + inv.addItems(extracted.getItemStack()); + if (p instanceof EntityPlayerMP) { + this.updateHeld((EntityPlayerMP) p); + } + this.detectAndSendChanges(); + return; + } + + final InventoryCrafting ic = new InventoryCrafting(new ContainerNull(), 3, 3); + final InventoryCrafting real = new InventoryCrafting(new ContainerNull(), 3, 3); + + for (int x = 0; x < 9; x++) { + ic.setInventorySlotContents( + x, packetPatternSlot.pattern[x] == null ? null : packetPatternSlot.pattern[x].getItemStack()); + } + + final IRecipe r = Platform.findMatchingRecipe(ic, p.worldObj); + + if (r == null) { + return; + } + + final IMEMonitor storage = this.getPatternTerminal().getItemInventory(); + final IItemList all = storage.getStorageList(); + + final ItemStack is = r.getCraftingResult(ic); + + for (int x = 0; x < ic.getSizeInventory(); x++) { + if (ic.getStackInSlot(x) != null) { + final ItemStack pulled = Platform.extractItemsByRecipe( + this.getPowerSource(), + this.getActionSource(), + storage, + p.worldObj, + r, + is, + ic, + ic.getStackInSlot(x), + x, + all, + Actionable.MODULATE, + ItemViewCell.createFilter(this.getViewCells())); + real.setInventorySlotContents(x, pulled); + } + } + + final IRecipe rr = Platform.findMatchingRecipe(real, p.worldObj); + + if (rr == r && Platform.isSameItemPrecise(rr.getCraftingResult(real), is)) { + final SlotCrafting sc = new SlotCrafting(p, real, this.cOut, 0, 0, 0); + sc.onPickupFromSlot(p, is); + + for (int x = 0; x < real.getSizeInventory(); x++) { + final ItemStack failed = playerInv.addItems(real.getStackInSlot(x)); + + if (failed != null) { + p.dropPlayerItemWithRandomChoice(failed, false); + } + } + + inv.addItems(is); + if (p instanceof EntityPlayerMP) { + this.updateHeld((EntityPlayerMP) p); + } + this.detectAndSendChanges(); + } else { + for (int x = 0; x < real.getSizeInventory(); x++) { + final ItemStack failed = real.getStackInSlot(x); + if (failed != null) { + this.getCellInventory() + .injectItems( + AEItemStack.create(failed), + Actionable.MODULATE, + new MachineSource(this.getPatternTerminal())); + } + } + } + } + } + + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + if (Platform.isServer()) { + if (this.isCraftingMode() != this.getPatternTerminal().isCraftingRecipe()) { + this.setCraftingMode(this.getPatternTerminal().isCraftingRecipe()); + this.updateOrderOfOutputSlots(); + } + + this.substitute = this.patternTerminal.isSubstitution(); + } + } + + @Override + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + super.onUpdate(field, oldValue, newValue); + + if (field.equals("craftingMode")) { + this.getAndUpdateOutput(); + this.updateOrderOfOutputSlots(); + } + } + + @Override + public void onSlotChange(final Slot s) { + if (s == this.patternSlotOUT && Platform.isServer()) { + for (final Object crafter : this.crafters) { + final ICrafting icrafting = (ICrafting) crafter; + + for (final Object g : this.inventorySlots) { + if (g instanceof OptionalSlotFake || g instanceof SlotFakeCraftingMatrix) { + final Slot sri = (Slot) g; + icrafting.sendSlotContents(this, sri.slotNumber, sri.getStack()); + } + } + ((EntityPlayerMP) icrafting).isChangingQuantityOnly = false; + } + this.detectAndSendChanges(); + } + } + + public void clear() { + for (final Slot s : this.craftingSlots) { + s.putStack(null); + } + + for (final Slot s : this.outputSlots) { + s.putStack(null); + } + + this.detectAndSendChanges(); + this.getAndUpdateOutput(); + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("player")) { + return this.getInventoryPlayer(); + } + return this.getPatternTerminal().getInventoryByName(name); + } + + @Override + public boolean useRealItems() { + return false; + } + + public void toggleSubstitute() { + this.substitute = !this.substitute; + + this.detectAndSendChanges(); + this.getAndUpdateOutput(); + } + + public boolean isCraftingMode() { + return this.craftingMode; + } + + private void setCraftingMode(final boolean craftingMode) { + this.craftingMode = craftingMode; + } + + public PartPatternTerminal getPatternTerminal() { + return this.patternTerminal; + } + + private boolean isSubstitute() { + return this.substitute; + } + + public void setSubstitute(final boolean substitute) { + this.substitute = substitute; + } + + static boolean canDoubleStacks(SlotFake[] slots) { + List enabledSlots = + Arrays.stream(slots).filter(SlotFake::isEnabled).collect(Collectors.toList()); + long emptyStots = + enabledSlots.stream().filter(s -> s.getStack() == null).count(); + long fullSlots = enabledSlots.stream() + .filter(s -> s.getStack() != null && s.getStack().stackSize * 2 > 127) + .count(); + return fullSlots <= emptyStots && emptyStots < enabledSlots.size(); + } + + static void doubleStacksInternal(SlotFake[] slots) { + List overFlowStacks = new ArrayList<>(); + List enabledSlots = + Arrays.stream(slots).filter(SlotFake::isEnabled).collect(Collectors.toList()); + for (final Slot s : enabledSlots) { + ItemStack st = s.getStack(); + if (st == null) continue; + if (st.stackSize * 2 > 127) { + overFlowStacks.add(st.copy()); + } else { + st.stackSize *= 2; + s.putStack(st); + } + } + Iterator ow = overFlowStacks.iterator(); + for (final Slot s : enabledSlots) { + if (!ow.hasNext()) break; + if (s.getStack() != null) continue; + s.putStack(ow.next()); + } + assert !ow.hasNext(); + } + + public void doubleStacks(boolean isShift) { + if (!isCraftingMode() && canDoubleStacks(craftingSlots) && canDoubleStacks(outputSlots)) { + doubleStacksInternal(this.craftingSlots); + doubleStacksInternal(this.outputSlots); + if (isShift) { + while (canDoubleStacks(craftingSlots) && canDoubleStacks(outputSlots)) { + doubleStacksInternal(this.craftingSlots); + doubleStacksInternal(this.outputSlots); + } + } + this.detectAndSendChanges(); + } + } } diff --git a/src/main/java/appeng/container/implementations/ContainerPatternTermEx.java b/src/main/java/appeng/container/implementations/ContainerPatternTermEx.java index e67269fce8d..8356e90b987 100644 --- a/src/main/java/appeng/container/implementations/ContainerPatternTermEx.java +++ b/src/main/java/appeng/container/implementations/ContainerPatternTermEx.java @@ -1,5 +1,8 @@ package appeng.container.implementations; +import static appeng.container.implementations.ContainerPatternTerm.canDoubleStacks; +import static appeng.container.implementations.ContainerPatternTerm.doubleStacksInternal; + import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; import appeng.api.storage.ITerminalHost; @@ -8,6 +11,8 @@ import appeng.helpers.IContainerCraftingPacket; import appeng.parts.reporting.PartPatternTerminalEx; import appeng.util.Platform; +import java.util.ArrayList; +import java.util.List; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ICrafting; @@ -18,125 +23,152 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import java.util.ArrayList; -import java.util.List; - -import static appeng.container.implementations.ContainerPatternTerm.canDoubleStacks; -import static appeng.container.implementations.ContainerPatternTerm.doubleStacksInternal; - -public class ContainerPatternTermEx extends ContainerMEMonitorable implements IOptionalSlotHost, IContainerCraftingPacket -{ +public class ContainerPatternTermEx extends ContainerMEMonitorable + implements IOptionalSlotHost, IContainerCraftingPacket { private static final int CRAFTING_GRID_PAGES = 2; private static final int CRAFTING_GRID_WIDTH = 4; private static final int CRAFTING_GRID_HEIGHT = 4; private static final int CRAFTING_GRID_SLOTS = CRAFTING_GRID_WIDTH * CRAFTING_GRID_HEIGHT; - private static class ProcessingSlotFake extends OptionalSlotFake - { + private static class ProcessingSlotFake extends OptionalSlotFake { private static final int POSITION_SHIFT = 9000; private boolean hidden = false; - public ProcessingSlotFake(IInventory inv, IOptionalSlotHost containerBus, int idx, int x, int y, int offX, int offY, int groupNum) - { + public ProcessingSlotFake( + IInventory inv, + IOptionalSlotHost containerBus, + int idx, + int x, + int y, + int offX, + int offY, + int groupNum) { super(inv, containerBus, idx, x, y, offX, offY, groupNum); this.setRenderDisabled(false); } - public void setHidden(boolean hide) - { + public void setHidden(boolean hide) { if (this.hidden != hide) { this.hidden = hide; - this.xDisplayPosition += (hide? -1: 1) * POSITION_SHIFT; + this.xDisplayPosition += (hide ? -1 : 1) * POSITION_SHIFT; } } - } - + private final PartPatternTerminalEx patternTerminal; - private final ProcessingSlotFake[] craftingSlots = new ProcessingSlotFake[CRAFTING_GRID_SLOTS * CRAFTING_GRID_PAGES]; + private final ProcessingSlotFake[] craftingSlots = + new ProcessingSlotFake[CRAFTING_GRID_SLOTS * CRAFTING_GRID_PAGES]; private final ProcessingSlotFake[] outputSlots = new ProcessingSlotFake[CRAFTING_GRID_SLOTS * CRAFTING_GRID_PAGES]; private final SlotRestrictedInput patternSlotIN; private final SlotRestrictedInput patternSlotOUT; - @GuiSync( 96 + (17-9) + 12 ) + @GuiSync(96 + (17 - 9) + 12) public boolean substitute = false; - @GuiSync( 96 + (17-9) + 16 ) + + @GuiSync(96 + (17 - 9) + 16) public boolean inverted; - @GuiSync( 96 + (17-9) + 17 ) + + @GuiSync(96 + (17 - 9) + 17) public int activePage = 0; - public ContainerPatternTermEx(final InventoryPlayer ip, final ITerminalHost monitorable ) - { - super( ip, monitorable, false ); + public ContainerPatternTermEx(final InventoryPlayer ip, final ITerminalHost monitorable) { + super(ip, monitorable, false); this.patternTerminal = (PartPatternTerminalEx) monitorable; inverted = patternTerminal.isInverted(); - final IInventory patternInv = this.getPatternTerminal().getInventoryByName( "pattern" ); - final IInventory output = this.getPatternTerminal().getInventoryByName( "output" ); + final IInventory patternInv = this.getPatternTerminal().getInventoryByName("pattern"); + final IInventory output = this.getPatternTerminal().getInventoryByName("output"); final IInventory crafting = this.getPatternTerminal().getInventoryByName("crafting"); for (int page = 0; page < CRAFTING_GRID_PAGES; page++) { for (int y = 0; y < CRAFTING_GRID_HEIGHT; y++) { for (int x = 0; x < CRAFTING_GRID_WIDTH; x++) { - this.addSlotToContainer(this.craftingSlots[x + y * CRAFTING_GRID_WIDTH + page * CRAFTING_GRID_SLOTS] = new ProcessingSlotFake(crafting, this, x + y * CRAFTING_GRID_WIDTH + page * CRAFTING_GRID_SLOTS, 15, -83, x, y, x + 4 )); + this.addSlotToContainer( + this.craftingSlots[x + y * CRAFTING_GRID_WIDTH + page * CRAFTING_GRID_SLOTS] = + new ProcessingSlotFake( + crafting, + this, + x + y * CRAFTING_GRID_WIDTH + page * CRAFTING_GRID_SLOTS, + 15, + -83, + x, + y, + x + 4)); } } for (int x = 0; x < CRAFTING_GRID_WIDTH; x++) { for (int y = 0; y < CRAFTING_GRID_HEIGHT; y++) { - this.addSlotToContainer( this.outputSlots[x * CRAFTING_GRID_HEIGHT + y + page * CRAFTING_GRID_SLOTS] = new ProcessingSlotFake( output, this, x * CRAFTING_GRID_HEIGHT + y + page * CRAFTING_GRID_SLOTS, 112, -83, -x, y, x ) ); + this.addSlotToContainer( + this.outputSlots[x * CRAFTING_GRID_HEIGHT + y + page * CRAFTING_GRID_SLOTS] = + new ProcessingSlotFake( + output, + this, + x * CRAFTING_GRID_HEIGHT + y + page * CRAFTING_GRID_SLOTS, + 112, + -83, + -x, + y, + x)); } } } - this.addSlotToContainer( this.patternSlotIN = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.BLANK_PATTERN, patternInv, 0, 147, -72 - 9, this.getInventoryPlayer() ) ); - this.addSlotToContainer( this.patternSlotOUT = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, patternInv, 1, 147, -72 + 34, this.getInventoryPlayer() ) ); - - this.patternSlotOUT.setStackLimit( 1 ); - - this.bindPlayerInventory( ip, 0, 0 ); + this.addSlotToContainer( + this.patternSlotIN = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.BLANK_PATTERN, + patternInv, + 0, + 147, + -72 - 9, + this.getInventoryPlayer())); + this.addSlotToContainer( + this.patternSlotOUT = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, + patternInv, + 1, + 147, + -72 + 34, + this.getInventoryPlayer())); + + this.patternSlotOUT.setStackLimit(1); + + this.bindPlayerInventory(ip, 0, 0); } - public void encodeAndMoveToInventory(boolean encodeWholeStack) - { + public void encodeAndMoveToInventory(boolean encodeWholeStack) { encode(); ItemStack output = this.patternSlotOUT.getStack(); - if ( output != null ) - { - if (encodeWholeStack) - { + if (output != null) { + if (encodeWholeStack) { ItemStack blanks = this.patternSlotIN.getStack(); this.patternSlotIN.putStack(null); - if (blanks != null) - output.stackSize += blanks.stackSize; + if (blanks != null) output.stackSize += blanks.stackSize; } - if (!getPlayerInv().addItemStackToInventory( output )) - { + if (!getPlayerInv().addItemStackToInventory(output)) { getPlayerInv().player.entityDropItem(output, 0); } - this.patternSlotOUT.putStack( null ); + this.patternSlotOUT.putStack(null); } } - public void encode() - { + public void encode() { ItemStack output = this.patternSlotOUT.getStack(); final ItemStack[] in = this.getInputs(); final ItemStack[] out = this.getOutputs(); // if there is no input, this would be silly. - if( in == null || out == null ) - { + if (in == null || out == null) { return; } // first check the output slots, should either be null, or a pattern if (output != null && this.isNotPattern(output)) { return; - }// if nothing is there we should snag a new pattern. + } // if nothing is there we should snag a new pattern. else if (output == null) { output = this.patternSlotIN.getStack(); if (this.isNotPattern(output)) { @@ -145,16 +177,19 @@ else if (output == null) { // remove one, and clear the input slot. output.stackSize--; - if( output.stackSize == 0 ) - { - this.patternSlotIN.putStack( null ); + if (output.stackSize == 0) { + this.patternSlotIN.putStack(null); } // add a new encoded pattern. - for( final ItemStack encodedPatternStack : AEApi.instance().definitions().items().encodedPattern().maybeStack( 1 ).asSet() ) - { + for (final ItemStack encodedPatternStack : AEApi.instance() + .definitions() + .items() + .encodedPattern() + .maybeStack(1) + .asSet()) { output = encodedPatternStack; - this.patternSlotOUT.putStack( output ); + this.patternSlotOUT.putStack(output); } } @@ -164,48 +199,41 @@ else if (output == null) { final NBTTagList tagIn = new NBTTagList(); final NBTTagList tagOut = new NBTTagList(); - for( final ItemStack i : in ) - { - tagIn.appendTag( this.createItemTag( i ) ); + for (final ItemStack i : in) { + tagIn.appendTag(this.createItemTag(i)); } - for( final ItemStack i : out ) - { - tagOut.appendTag( this.createItemTag( i ) ); + for (final ItemStack i : out) { + tagOut.appendTag(this.createItemTag(i)); } - encodedValue.setTag( "in", tagIn ); - encodedValue.setTag( "out", tagOut ); - encodedValue.setBoolean( "crafting", false ); - encodedValue.setBoolean( "substitute", this.isSubstitute() ); + encodedValue.setTag("in", tagIn); + encodedValue.setTag("out", tagOut); + encodedValue.setBoolean("crafting", false); + encodedValue.setBoolean("substitute", this.isSubstitute()); - output.setTagCompound( encodedValue ); + output.setTagCompound(encodedValue); } - private ItemStack[] getInputs() - { + private ItemStack[] getInputs() { final ItemStack[] input = new ItemStack[CRAFTING_GRID_SLOTS * CRAFTING_GRID_PAGES]; boolean hasValue = false; - for( int x = 0; x < this.craftingSlots.length; x++ ) - { + for (int x = 0; x < this.craftingSlots.length; x++) { input[x] = this.craftingSlots[x].getStack(); - if( input[x] != null ) - { + if (input[x] != null) { hasValue = true; } } - if( hasValue ) - { + if (hasValue) { return input; } return null; } - private ItemStack[] getOutputs() - { + private ItemStack[] getOutputs() { final List list = new ArrayList<>(CRAFTING_GRID_SLOTS * CRAFTING_GRID_PAGES); boolean hasValue = false; @@ -225,52 +253,43 @@ private ItemStack[] getOutputs() return null; } - private boolean isNotPattern(final ItemStack output ) - { - if( output == null ) - { + private boolean isNotPattern(final ItemStack output) { + if (output == null) { return true; } final IDefinitions definitions = AEApi.instance().definitions(); - boolean isPattern = definitions.items().encodedPattern().isSameAs( output ); - isPattern |= definitions.materials().blankPattern().isSameAs( output ); + boolean isPattern = definitions.items().encodedPattern().isSameAs(output); + isPattern |= definitions.materials().blankPattern().isSameAs(output); return !isPattern; } - private NBTBase createItemTag(final ItemStack i ) - { + private NBTBase createItemTag(final ItemStack i) { final NBTTagCompound c = new NBTTagCompound(); - if( i != null ) - { - i.writeToNBT( c ); - c.setInteger( "Count", i.stackSize ); + if (i != null) { + i.writeToNBT(c); + c.setInteger("Count", i.stackSize); } return c; } @Override - public boolean isSlotEnabled( final int idx ) - { + public boolean isSlotEnabled(final int idx) { if (idx < 4) // outputs { return inverted || idx == 0; - } - else - { + } else { return !inverted || idx == 4; } - } @Override - public void detectAndSendChanges() - { + public void detectAndSendChanges() { super.detectAndSendChanges(); if (Platform.isServer()) { @@ -281,127 +300,104 @@ public void detectAndSendChanges() activePage = patternTerminal.getActivePage(); offsetSlots(); } - } - } - private void offsetSlots() - { + private void offsetSlots() { for (int page = 0; page < CRAFTING_GRID_PAGES; page++) { for (int y = 0; y < CRAFTING_GRID_HEIGHT; y++) { for (int x = 0; x < CRAFTING_GRID_WIDTH; x++) { - this.craftingSlots[x + y * CRAFTING_GRID_WIDTH + page * CRAFTING_GRID_SLOTS].setHidden(page != activePage || x > 0 && inverted); - this.outputSlots[x * CRAFTING_GRID_HEIGHT + y + page * CRAFTING_GRID_SLOTS].setHidden(page != activePage || x > 0 && !inverted); + this.craftingSlots[x + y * CRAFTING_GRID_WIDTH + page * CRAFTING_GRID_SLOTS].setHidden( + page != activePage || x > 0 && inverted); + this.outputSlots[x * CRAFTING_GRID_HEIGHT + y + page * CRAFTING_GRID_SLOTS].setHidden( + page != activePage || x > 0 && !inverted); } } } - } @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - super.onUpdate( field, oldValue, newValue ); + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + super.onUpdate(field, oldValue, newValue); - if (field.equals( "inverted" ) || field.equals( "activePage" )) { + if (field.equals("inverted") || field.equals("activePage")) { offsetSlots(); } } @Override - public void onSlotChange( final Slot s ) - { - if( s == this.patternSlotOUT && Platform.isServer() ) - { + public void onSlotChange(final Slot s) { + if (s == this.patternSlotOUT && Platform.isServer()) { inverted = patternTerminal.isInverted(); - for( final Object crafter : this.crafters ) - { + for (final Object crafter : this.crafters) { final ICrafting icrafting = (ICrafting) crafter; - for( final Object g : this.inventorySlots ) - { - if( g instanceof OptionalSlotFake || g instanceof SlotFakeCraftingMatrix ) - { + for (final Object g : this.inventorySlots) { + if (g instanceof OptionalSlotFake || g instanceof SlotFakeCraftingMatrix) { final Slot sri = (Slot) g; - icrafting.sendSlotContents( this, sri.slotNumber, sri.getStack() ); + icrafting.sendSlotContents(this, sri.slotNumber, sri.getStack()); } } - ( (EntityPlayerMP) icrafting ).isChangingQuantityOnly = false; + ((EntityPlayerMP) icrafting).isChangingQuantityOnly = false; } this.detectAndSendChanges(); } } - public void clear() - { - for( final Slot s : this.craftingSlots ) - { - s.putStack( null ); + public void clear() { + for (final Slot s : this.craftingSlots) { + s.putStack(null); } - for( final Slot s : this.outputSlots ) - { - s.putStack( null ); + for (final Slot s : this.outputSlots) { + s.putStack(null); } this.detectAndSendChanges(); } @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "player" ) ) - { + public IInventory getInventoryByName(final String name) { + if (name.equals("player")) { return this.getInventoryPlayer(); } - return this.getPatternTerminal().getInventoryByName( name ); + return this.getPatternTerminal().getInventoryByName(name); } @Override - public boolean useRealItems() - { + public boolean useRealItems() { return false; } - public PartPatternTerminalEx getPatternTerminal() - { + public PartPatternTerminalEx getPatternTerminal() { return this.patternTerminal; } - private boolean isSubstitute() - { + private boolean isSubstitute() { return this.substitute; } - public void setSubstitute( final boolean substitute ) - { + public void setSubstitute(final boolean substitute) { this.substitute = substitute; } - public void setActivePage( final int activePage ) - { + public void setActivePage(final int activePage) { this.activePage = activePage; } - public int getActivePage() - { + public int getActivePage() { return this.activePage; } - public void doubleStacks(boolean isShift) - { - if (canDoubleStacks(craftingSlots) && canDoubleStacks(outputSlots)) - { + public void doubleStacks(boolean isShift) { + if (canDoubleStacks(craftingSlots) && canDoubleStacks(outputSlots)) { doubleStacksInternal(this.craftingSlots); doubleStacksInternal(this.outputSlots); - if (isShift) - { - while (canDoubleStacks(craftingSlots) && canDoubleStacks(outputSlots)) - { + if (isShift) { + while (canDoubleStacks(craftingSlots) && canDoubleStacks(outputSlots)) { doubleStacksInternal(this.craftingSlots); doubleStacksInternal(this.outputSlots); } @@ -409,5 +405,4 @@ public void doubleStacks(boolean isShift) this.detectAndSendChanges(); } } - } diff --git a/src/main/java/appeng/container/implementations/ContainerPatternValueAmount.java b/src/main/java/appeng/container/implementations/ContainerPatternValueAmount.java index d7b94cecff2..37740d8e7c2 100644 --- a/src/main/java/appeng/container/implementations/ContainerPatternValueAmount.java +++ b/src/main/java/appeng/container/implementations/ContainerPatternValueAmount.java @@ -13,54 +13,44 @@ import net.minecraft.inventory.Slot; import net.minecraft.world.World; -public class ContainerPatternValueAmount extends AEBaseContainer -{ +public class ContainerPatternValueAmount extends AEBaseContainer { private final Slot patternValue; private int valueIndex; - public ContainerPatternValueAmount( final InventoryPlayer ip, final ITerminalHost te ) - { - super( ip, te ); - this.patternValue = new SlotInaccessible( new AppEngInternalInventory( null, 1 ), 0, 34, 53 ); - this.addSlotToContainer( patternValue ); + public ContainerPatternValueAmount(final InventoryPlayer ip, final ITerminalHost te) { + super(ip, te); + this.patternValue = new SlotInaccessible(new AppEngInternalInventory(null, 1), 0, 34, 53); + this.addSlotToContainer(patternValue); } @Override - public void detectAndSendChanges() - { + public void detectAndSendChanges() { super.detectAndSendChanges(); - this.verifyPermissions( SecurityPermissions.CRAFT, false ); + this.verifyPermissions(SecurityPermissions.CRAFT, false); } - public IGrid getGrid() - { - final IActionHost h = ( (IActionHost) this.getTarget() ); + public IGrid getGrid() { + final IActionHost h = ((IActionHost) this.getTarget()); return h.getActionableNode().getGrid(); } - public World getWorld() - { + public World getWorld() { return this.getPlayerInv().player.worldObj; } - public BaseActionSource getActionSrc() - { - return new PlayerSource( this.getPlayerInv().player, (IActionHost) this.getTarget() ); + public BaseActionSource getActionSrc() { + return new PlayerSource(this.getPlayerInv().player, (IActionHost) this.getTarget()); } - public Slot getPatternValue() - { + public Slot getPatternValue() { return patternValue; } - public int getValueIndex() - { + public int getValueIndex() { return valueIndex; } - public void setValueIndex( int valueIndex ) - { + public void setValueIndex(int valueIndex) { this.valueIndex = valueIndex; } - } diff --git a/src/main/java/appeng/container/implementations/ContainerPriority.java b/src/main/java/appeng/container/implementations/ContainerPriority.java index 1247c221c8a..7e3d21efbdf 100644 --- a/src/main/java/appeng/container/implementations/ContainerPriority.java +++ b/src/main/java/appeng/container/implementations/ContainerPriority.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.SecurityPermissions; import appeng.api.parts.IPart; import appeng.container.AEBaseContainer; @@ -32,59 +31,50 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.tileentity.TileEntity; +public class ContainerPriority extends AEBaseContainer { -public class ContainerPriority extends AEBaseContainer -{ + private final IPriorityHost priHost; - private final IPriorityHost priHost; + @SideOnly(Side.CLIENT) + private GuiTextField textField; - @SideOnly( Side.CLIENT ) - private GuiTextField textField; - @GuiSync( 2 ) - public long PriorityValue = -1; + @GuiSync(2) + public long PriorityValue = -1; - public ContainerPriority( final InventoryPlayer ip, final IPriorityHost te ) - { - super( ip, (TileEntity) ( te instanceof TileEntity ? te : null ), (IPart) ( te instanceof IPart ? te : null ) ); - this.priHost = te; - } + public ContainerPriority(final InventoryPlayer ip, final IPriorityHost te) { + super(ip, (TileEntity) (te instanceof TileEntity ? te : null), (IPart) (te instanceof IPart ? te : null)); + this.priHost = te; + } - @SideOnly( Side.CLIENT ) - public void setTextField( final GuiTextField level ) - { - this.textField = level; - this.textField.setText( String.valueOf( this.PriorityValue ) ); - } + @SideOnly(Side.CLIENT) + public void setTextField(final GuiTextField level) { + this.textField = level; + this.textField.setText(String.valueOf(this.PriorityValue)); + } - public void setPriority( final int newValue, final EntityPlayer player ) - { - this.priHost.setPriority( newValue ); - this.PriorityValue = newValue; - } + public void setPriority(final int newValue, final EntityPlayer player) { + this.priHost.setPriority(newValue); + this.PriorityValue = newValue; + } - @Override - public void detectAndSendChanges() - { - super.detectAndSendChanges(); - this.verifyPermissions( SecurityPermissions.BUILD, false ); + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + this.verifyPermissions(SecurityPermissions.BUILD, false); - if( Platform.isServer() ) - { - this.PriorityValue = this.priHost.getPriority(); - } - } + if (Platform.isServer()) { + this.PriorityValue = this.priHost.getPriority(); + } + } - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - if( field.equals( "PriorityValue" ) ) - { - if( this.textField != null ) - { - this.textField.setText( String.valueOf( this.PriorityValue ) ); - } - } + @Override + public void onUpdate(final String field, final Object oldValue, final Object newValue) { + if (field.equals("PriorityValue")) { + if (this.textField != null) { + this.textField.setText(String.valueOf(this.PriorityValue)); + } + } - super.onUpdate( field, oldValue, newValue ); - } + super.onUpdate(field, oldValue, newValue); + } } diff --git a/src/main/java/appeng/container/implementations/ContainerQNB.java b/src/main/java/appeng/container/implementations/ContainerQNB.java index 3a9f0f3943a..c77343d1608 100644 --- a/src/main/java/appeng/container/implementations/ContainerQNB.java +++ b/src/main/java/appeng/container/implementations/ContainerQNB.java @@ -18,22 +18,25 @@ package appeng.container.implementations; - import appeng.container.AEBaseContainer; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.qnb.TileQuantumBridge; import net.minecraft.entity.player.InventoryPlayer; +public class ContainerQNB extends AEBaseContainer { -public class ContainerQNB extends AEBaseContainer -{ - - public ContainerQNB( final InventoryPlayer ip, final TileQuantumBridge quantumBridge ) - { - super( ip, quantumBridge, null ); + public ContainerQNB(final InventoryPlayer ip, final TileQuantumBridge quantumBridge) { + super(ip, quantumBridge, null); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.QE_SINGULARITY, quantumBridge, 0, 80, 37, this.getInventoryPlayer() ) ).setStackLimit( 1 ) ); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.QE_SINGULARITY, + quantumBridge, + 0, + 80, + 37, + this.getInventoryPlayer())) + .setStackLimit(1)); - this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 166 - /* height of player inventory */ 82); + } } diff --git a/src/main/java/appeng/container/implementations/ContainerQuartzKnife.java b/src/main/java/appeng/container/implementations/ContainerQuartzKnife.java index f4abe6749bf..1db456352f4 100644 --- a/src/main/java/appeng/container/implementations/ContainerQuartzKnife.java +++ b/src/main/java/appeng/container/implementations/ContainerQuartzKnife.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.AEApi; import appeng.container.AEBaseContainer; import appeng.container.slot.QuartzKnifeOutput; @@ -36,210 +35,173 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; - -public class ContainerQuartzKnife extends AEBaseContainer implements IAEAppEngInventory, IInventory -{ - - private final QuartzKnifeObj toolInv; - - private final AppEngInternalInventory inSlot = new AppEngInternalInventory( this, 1 ); - private final SlotRestrictedInput metals; - private final QuartzKnifeOutput output; - private String myName = ""; - - public ContainerQuartzKnife( final InventoryPlayer ip, final QuartzKnifeObj te ) - { - super( ip, null, null ); - this.toolInv = te; - - this.metals = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.METAL_INGOTS, this.inSlot, 0, 94, 44, ip ); - this.addSlotToContainer( this.metals ); - - this.output = new QuartzKnifeOutput( this, 0, 134, 44, -1 ); - this.addSlotToContainer( this.output ); - - this.lockPlayerInventorySlot( ip.currentItem ); - - this.bindPlayerInventory( ip, 0, 184 - /* height of player inventory */82 ); - } - - public void setName( final String value ) - { - this.myName = value; - } - - @Override - public void detectAndSendChanges() - { - final ItemStack currentItem = this.getPlayerInv().getCurrentItem(); - - if( currentItem != this.toolInv.getItemStack() ) - { - if( currentItem != null ) - { - if( Platform.isSameItem( this.toolInv.getItemStack(), currentItem ) ) - { - this.getPlayerInv().setInventorySlotContents( this.getPlayerInv().currentItem, this.toolInv.getItemStack() ); - } - else - { - this.setValidContainer( false ); - } - } - else - { - this.setValidContainer( false ); - } - } - - super.detectAndSendChanges(); - } - - @Override - public void onContainerClosed( final EntityPlayer par1EntityPlayer ) - { - if( this.inSlot.getStackInSlot( 0 ) != null ) - { - par1EntityPlayer.dropPlayerItemWithRandomChoice( this.inSlot.getStackInSlot( 0 ), false ); - } - } - - @Override - public void saveChanges() - { - - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - - } - - @Override - public int getSizeInventory() - { - return 1; - } - - @Override - public ItemStack getStackInSlot( final int var1 ) - { - final ItemStack input = this.inSlot.getStackInSlot( 0 ); - if( input == null ) - { - return null; - } - - if( SlotRestrictedInput.isMetalIngot( input ) ) - { - if( this.myName.length() > 0 ) - { - for( final ItemStack namePressStack : AEApi.instance().definitions().materials().namePress().maybeStack( 1 ).asSet() ) - { - final NBTTagCompound compound = Platform.openNbtData( namePressStack ); - compound.setString( "InscribeName", this.myName ); - - return namePressStack; - } - } - } - - return null; - } - - @Override - public ItemStack decrStackSize( final int var1, final int var2 ) - { - final ItemStack is = this.getStackInSlot( 0 ); - if( is != null ) - { - if( this.makePlate() ) - { - return is; - } - } - return null; - } - - private boolean makePlate() - { - if( this.inSlot.decrStackSize( 0, 1 ) != null ) - { - final ItemStack item = this.toolInv.getItemStack(); - item.damageItem( 1, this.getPlayerInv().player ); - - if( item.stackSize == 0 ) - { - this.getPlayerInv().mainInventory[this.getPlayerInv().currentItem] = null; - MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( this.getPlayerInv().player, item ) ); - } - - return true; - } - return false; - } - - @Override - public ItemStack getStackInSlotOnClosing( final int var1 ) - { - return null; - } - - @Override - public void setInventorySlotContents( final int var1, final ItemStack var2 ) - { - if( var2 == null && Platform.isServer() ) - { - this.makePlate(); - } - } - - @Override - public String getInventoryName() - { - return "Quartz Knife Output"; - } - - @Override - public boolean hasCustomInventoryName() - { - return false; - } - - @Override - public int getInventoryStackLimit() - { - return 1; - } - - @Override - public void markDirty() - { - - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer var1 ) - { - return false; - } - - @Override - public void openInventory() - { - - } - - @Override - public void closeInventory() - { - - } - - @Override - public boolean isItemValidForSlot( final int var1, final ItemStack var2 ) - { - return false; - } +public class ContainerQuartzKnife extends AEBaseContainer implements IAEAppEngInventory, IInventory { + + private final QuartzKnifeObj toolInv; + + private final AppEngInternalInventory inSlot = new AppEngInternalInventory(this, 1); + private final SlotRestrictedInput metals; + private final QuartzKnifeOutput output; + private String myName = ""; + + public ContainerQuartzKnife(final InventoryPlayer ip, final QuartzKnifeObj te) { + super(ip, null, null); + this.toolInv = te; + + this.metals = + new SlotRestrictedInput(SlotRestrictedInput.PlacableItemType.METAL_INGOTS, this.inSlot, 0, 94, 44, ip); + this.addSlotToContainer(this.metals); + + this.output = new QuartzKnifeOutput(this, 0, 134, 44, -1); + this.addSlotToContainer(this.output); + + this.lockPlayerInventorySlot(ip.currentItem); + + this.bindPlayerInventory(ip, 0, 184 - /* height of player inventory */ 82); + } + + public void setName(final String value) { + this.myName = value; + } + + @Override + public void detectAndSendChanges() { + final ItemStack currentItem = this.getPlayerInv().getCurrentItem(); + + if (currentItem != this.toolInv.getItemStack()) { + if (currentItem != null) { + if (Platform.isSameItem(this.toolInv.getItemStack(), currentItem)) { + this.getPlayerInv() + .setInventorySlotContents(this.getPlayerInv().currentItem, this.toolInv.getItemStack()); + } else { + this.setValidContainer(false); + } + } else { + this.setValidContainer(false); + } + } + + super.detectAndSendChanges(); + } + + @Override + public void onContainerClosed(final EntityPlayer par1EntityPlayer) { + if (this.inSlot.getStackInSlot(0) != null) { + par1EntityPlayer.dropPlayerItemWithRandomChoice(this.inSlot.getStackInSlot(0), false); + } + } + + @Override + public void saveChanges() {} + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) {} + + @Override + public int getSizeInventory() { + return 1; + } + + @Override + public ItemStack getStackInSlot(final int var1) { + final ItemStack input = this.inSlot.getStackInSlot(0); + if (input == null) { + return null; + } + + if (SlotRestrictedInput.isMetalIngot(input)) { + if (this.myName.length() > 0) { + for (final ItemStack namePressStack : AEApi.instance() + .definitions() + .materials() + .namePress() + .maybeStack(1) + .asSet()) { + final NBTTagCompound compound = Platform.openNbtData(namePressStack); + compound.setString("InscribeName", this.myName); + + return namePressStack; + } + } + } + + return null; + } + + @Override + public ItemStack decrStackSize(final int var1, final int var2) { + final ItemStack is = this.getStackInSlot(0); + if (is != null) { + if (this.makePlate()) { + return is; + } + } + return null; + } + + private boolean makePlate() { + if (this.inSlot.decrStackSize(0, 1) != null) { + final ItemStack item = this.toolInv.getItemStack(); + item.damageItem(1, this.getPlayerInv().player); + + if (item.stackSize == 0) { + this.getPlayerInv().mainInventory[this.getPlayerInv().currentItem] = null; + MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(this.getPlayerInv().player, item)); + } + + return true; + } + return false; + } + + @Override + public ItemStack getStackInSlotOnClosing(final int var1) { + return null; + } + + @Override + public void setInventorySlotContents(final int var1, final ItemStack var2) { + if (var2 == null && Platform.isServer()) { + this.makePlate(); + } + } + + @Override + public String getInventoryName() { + return "Quartz Knife Output"; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + @Override + public void markDirty() {} + + @Override + public boolean isUseableByPlayer(final EntityPlayer var1) { + return false; + } + + @Override + public void openInventory() {} + + @Override + public void closeInventory() {} + + @Override + public boolean isItemValidForSlot(final int var1, final ItemStack var2) { + return false; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerRenamer.java b/src/main/java/appeng/container/implementations/ContainerRenamer.java index 83de50b1fcb..d419c0fecc8 100644 --- a/src/main/java/appeng/container/implementations/ContainerRenamer.java +++ b/src/main/java/appeng/container/implementations/ContainerRenamer.java @@ -11,46 +11,37 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.tileentity.TileEntity; -public class ContainerRenamer extends AEBaseContainer -{ +public class ContainerRenamer extends AEBaseContainer { private final ICustomNameObject namedObject; - @SideOnly( Side.CLIENT ) + @SideOnly(Side.CLIENT) private MEGuiTextField textField; - public ContainerRenamer(InventoryPlayer ip, ICustomNameObject obj) - { - super(ip, obj instanceof TileEntity ? (TileEntity)obj : null, obj instanceof IPart ? (IPart)obj : null); + public ContainerRenamer(InventoryPlayer ip, ICustomNameObject obj) { + super(ip, obj instanceof TileEntity ? (TileEntity) obj : null, obj instanceof IPart ? (IPart) obj : null); namedObject = obj; } - @SideOnly( Side.CLIENT ) - public void setTextField( final MEGuiTextField name ) - { + @SideOnly(Side.CLIENT) + public void setTextField(final MEGuiTextField name) { this.textField = name; - if (getCustomName() != null) - textField.setText(getCustomName()); + if (getCustomName() != null) textField.setText(getCustomName()); } - public void setNewName(String newValue) - { - this.namedObject.setCustomName( newValue ); + public void setNewName(String newValue) { + this.namedObject.setCustomName(newValue); } @Override - public void setCustomName( final String customName ) - { + public void setCustomName(final String customName) { super.setCustomName(customName); - if (!Platform.isServer() && customName != null) - textField.setText(customName); + if (!Platform.isServer() && customName != null) textField.setText(customName); } @Override - public void detectAndSendChanges() - { - verifyPermissions( SecurityPermissions.BUILD, false ); + public void detectAndSendChanges() { + verifyPermissions(SecurityPermissions.BUILD, false); super.detectAndSendChanges(); - if (!Platform.isServer() && getCustomName() != null) - textField.setText(getCustomName()); + if (!Platform.isServer() && getCustomName() != null) textField.setText(getCustomName()); } } diff --git a/src/main/java/appeng/container/implementations/ContainerSecurity.java b/src/main/java/appeng/container/implementations/ContainerSecurity.java index 3c9aa485592..7ba54cac3ab 100644 --- a/src/main/java/appeng/container/implementations/ContainerSecurity.java +++ b/src/main/java/appeng/container/implementations/ContainerSecurity.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.AEApi; import appeng.api.config.SecurityPermissions; import appeng.api.features.INetworkEncodable; @@ -38,153 +37,142 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - -public class ContainerSecurity extends ContainerMEMonitorable implements IAEAppEngInventory -{ - - private final SlotRestrictedInput configSlot; - - private final AppEngInternalInventory wirelessEncoder = new AppEngInternalInventory( this, 2 ); - - private final SlotRestrictedInput wirelessIn; - private final SlotOutput wirelessOut; - - private final TileSecurity securityBox; - @GuiSync( 0 ) - public int permissionMode = 0; - - public ContainerSecurity( final InventoryPlayer ip, final ITerminalHost monitorable ) - { - super( ip, monitorable, false ); - - this.securityBox = (TileSecurity) monitorable; - - this.addSlotToContainer( this.configSlot = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.BIOMETRIC_CARD, this.securityBox.getConfigSlot(), 0, 37, -33, ip ) ); - - this.addSlotToContainer( this.wirelessIn = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODABLE_ITEM, this.wirelessEncoder, 0, 212, 10, ip ) ); - this.addSlotToContainer( this.wirelessOut = new SlotOutput( this.wirelessEncoder, 1, 212, 68, -1 ) ); - - this.bindPlayerInventory( ip, 0, 0 ); - } - - public void toggleSetting( final String value, final EntityPlayer player ) - { - try - { - final SecurityPermissions permission = SecurityPermissions.valueOf( value ); - - final ItemStack a = this.configSlot.getStack(); - if( a != null && a.getItem() instanceof IBiometricCard ) - { - final IBiometricCard bc = (IBiometricCard) a.getItem(); - if( bc.hasPermission( a, permission ) ) - { - bc.removePermission( a, permission ); - } - else - { - bc.addPermission( a, permission ); - } - } - } - catch( final EnumConstantNotPresentException ex ) - { - // :( - } - } - - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.SECURITY, false ); - - this.setPermissionMode( 0 ); - - final ItemStack a = this.configSlot.getStack(); - if( a != null && a.getItem() instanceof IBiometricCard ) - { - final IBiometricCard bc = (IBiometricCard) a.getItem(); - - for( final SecurityPermissions sp : bc.getPermissions( a ) ) - { - this.setPermissionMode( this.getPermissionMode() | ( 1 << sp.ordinal() ) ); - } - } - - this.updatePowerStatus(); - - super.detectAndSendChanges(); - } - - @Override - public void onContainerClosed( final EntityPlayer player ) - { - super.onContainerClosed( player ); - - if( this.wirelessIn.getHasStack() ) - { - player.dropPlayerItemWithRandomChoice( this.wirelessIn.getStack(), false ); - } - - if( this.wirelessOut.getHasStack() ) - { - player.dropPlayerItemWithRandomChoice( this.wirelessOut.getStack(), false ); - } - } - - @Override - public void saveChanges() - { - // :P - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - if( !this.wirelessOut.getHasStack() ) - { - if( this.wirelessIn.getHasStack() ) - { - final ItemStack term = this.wirelessIn.getStack().copy(); - INetworkEncodable networkEncodable = null; - - if( term.getItem() instanceof INetworkEncodable ) - { - networkEncodable = (INetworkEncodable) term.getItem(); - } - - final IWirelessTermHandler wTermHandler = AEApi.instance().registries().wireless().getWirelessTerminalHandler( term ); - if( wTermHandler != null ) - { - networkEncodable = wTermHandler; - } - - if( networkEncodable != null ) - { - networkEncodable.setEncryptionKey( term, String.valueOf( this.securityBox.getSecurityKey() ), "" ); - - this.wirelessIn.putStack( null ); - this.wirelessOut.putStack( term ); - - // update the two slots in question... - for( final Object crafter : this.crafters ) - { - final ICrafting icrafting = (ICrafting) crafter; - icrafting.sendSlotContents( this, this.wirelessIn.slotNumber, this.wirelessIn.getStack() ); - icrafting.sendSlotContents( this, this.wirelessOut.slotNumber, this.wirelessOut.getStack() ); - } - } - } - } - } - - public int getPermissionMode() - { - return this.permissionMode; - } - - private void setPermissionMode( final int permissionMode ) - { - this.permissionMode = permissionMode; - } +public class ContainerSecurity extends ContainerMEMonitorable implements IAEAppEngInventory { + + private final SlotRestrictedInput configSlot; + + private final AppEngInternalInventory wirelessEncoder = new AppEngInternalInventory(this, 2); + + private final SlotRestrictedInput wirelessIn; + private final SlotOutput wirelessOut; + + private final TileSecurity securityBox; + + @GuiSync(0) + public int permissionMode = 0; + + public ContainerSecurity(final InventoryPlayer ip, final ITerminalHost monitorable) { + super(ip, monitorable, false); + + this.securityBox = (TileSecurity) monitorable; + + this.addSlotToContainer( + this.configSlot = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.BIOMETRIC_CARD, + this.securityBox.getConfigSlot(), + 0, + 37, + -33, + ip)); + + this.addSlotToContainer( + this.wirelessIn = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.ENCODABLE_ITEM, this.wirelessEncoder, 0, 212, 10, ip)); + this.addSlotToContainer(this.wirelessOut = new SlotOutput(this.wirelessEncoder, 1, 212, 68, -1)); + + this.bindPlayerInventory(ip, 0, 0); + } + + public void toggleSetting(final String value, final EntityPlayer player) { + try { + final SecurityPermissions permission = SecurityPermissions.valueOf(value); + + final ItemStack a = this.configSlot.getStack(); + if (a != null && a.getItem() instanceof IBiometricCard) { + final IBiometricCard bc = (IBiometricCard) a.getItem(); + if (bc.hasPermission(a, permission)) { + bc.removePermission(a, permission); + } else { + bc.addPermission(a, permission); + } + } + } catch (final EnumConstantNotPresentException ex) { + // :( + } + } + + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.SECURITY, false); + + this.setPermissionMode(0); + + final ItemStack a = this.configSlot.getStack(); + if (a != null && a.getItem() instanceof IBiometricCard) { + final IBiometricCard bc = (IBiometricCard) a.getItem(); + + for (final SecurityPermissions sp : bc.getPermissions(a)) { + this.setPermissionMode(this.getPermissionMode() | (1 << sp.ordinal())); + } + } + + this.updatePowerStatus(); + + super.detectAndSendChanges(); + } + + @Override + public void onContainerClosed(final EntityPlayer player) { + super.onContainerClosed(player); + + if (this.wirelessIn.getHasStack()) { + player.dropPlayerItemWithRandomChoice(this.wirelessIn.getStack(), false); + } + + if (this.wirelessOut.getHasStack()) { + player.dropPlayerItemWithRandomChoice(this.wirelessOut.getStack(), false); + } + } + + @Override + public void saveChanges() { + // :P + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) { + if (!this.wirelessOut.getHasStack()) { + if (this.wirelessIn.getHasStack()) { + final ItemStack term = this.wirelessIn.getStack().copy(); + INetworkEncodable networkEncodable = null; + + if (term.getItem() instanceof INetworkEncodable) { + networkEncodable = (INetworkEncodable) term.getItem(); + } + + final IWirelessTermHandler wTermHandler = + AEApi.instance().registries().wireless().getWirelessTerminalHandler(term); + if (wTermHandler != null) { + networkEncodable = wTermHandler; + } + + if (networkEncodable != null) { + networkEncodable.setEncryptionKey(term, String.valueOf(this.securityBox.getSecurityKey()), ""); + + this.wirelessIn.putStack(null); + this.wirelessOut.putStack(term); + + // update the two slots in question... + for (final Object crafter : this.crafters) { + final ICrafting icrafting = (ICrafting) crafter; + icrafting.sendSlotContents(this, this.wirelessIn.slotNumber, this.wirelessIn.getStack()); + icrafting.sendSlotContents(this, this.wirelessOut.slotNumber, this.wirelessOut.getStack()); + } + } + } + } + } + + public int getPermissionMode() { + return this.permissionMode; + } + + private void setPermissionMode(final int permissionMode) { + this.permissionMode = permissionMode; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerSkyChest.java b/src/main/java/appeng/container/implementations/ContainerSkyChest.java index 6381b7c3b99..51d24be23c4 100644 --- a/src/main/java/appeng/container/implementations/ContainerSkyChest.java +++ b/src/main/java/appeng/container/implementations/ContainerSkyChest.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.container.AEBaseContainer; import appeng.container.slot.SlotNormal; import appeng.tile.storage.TileSkyChest; @@ -26,35 +25,29 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; - @ChestContainer -public class ContainerSkyChest extends AEBaseContainer -{ - - private final TileSkyChest chest; - - public ContainerSkyChest( final InventoryPlayer ip, final TileSkyChest chest ) - { - super( ip, chest, null ); - this.chest = chest; - - for( int y = 0; y < 4; y++ ) - { - for( int x = 0; x < 9; x++ ) - { - this.addSlotToContainer( new SlotNormal( this.chest, y * 9 + x, 8 + 18 * x, 24 + 18 * y ) ); - } - } - - this.chest.openInventory(); - - this.bindPlayerInventory( ip, 0, 195 - /* height of player inventory */82 ); - } - - @Override - public void onContainerClosed( final EntityPlayer par1EntityPlayer ) - { - super.onContainerClosed( par1EntityPlayer ); - this.chest.closeInventory(); - } +public class ContainerSkyChest extends AEBaseContainer { + + private final TileSkyChest chest; + + public ContainerSkyChest(final InventoryPlayer ip, final TileSkyChest chest) { + super(ip, chest, null); + this.chest = chest; + + for (int y = 0; y < 4; y++) { + for (int x = 0; x < 9; x++) { + this.addSlotToContainer(new SlotNormal(this.chest, y * 9 + x, 8 + 18 * x, 24 + 18 * y)); + } + } + + this.chest.openInventory(); + + this.bindPlayerInventory(ip, 0, 195 - /* height of player inventory */ 82); + } + + @Override + public void onContainerClosed(final EntityPlayer par1EntityPlayer) { + super.onContainerClosed(par1EntityPlayer); + this.chest.closeInventory(); + } } diff --git a/src/main/java/appeng/container/implementations/ContainerSpatialIOPort.java b/src/main/java/appeng/container/implementations/ContainerSpatialIOPort.java index 656b53f8ac1..8a0bb13802e 100644 --- a/src/main/java/appeng/container/implementations/ContainerSpatialIOPort.java +++ b/src/main/java/appeng/container/implementations/ContainerSpatialIOPort.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGrid; import appeng.api.networking.energy.IEnergyGrid; @@ -32,100 +31,95 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraftforge.common.util.ForgeDirection; - -public class ContainerSpatialIOPort extends AEBaseContainer -{ - - @GuiSync( 0 ) - public long currentPower; - @GuiSync( 1 ) - public long maxPower; - @GuiSync( 2 ) - public long reqPower; - @GuiSync( 3 ) - public long eff; - private IGrid network; - private int delay = 40; - - public ContainerSpatialIOPort( final InventoryPlayer ip, final TileSpatialIOPort spatialIOPort ) - { - super( ip, spatialIOPort, null ); - - if( Platform.isServer() ) - { - this.network = spatialIOPort.getGridNode( ForgeDirection.UNKNOWN ).getGrid(); - } - - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.SPATIAL_STORAGE_CELLS, spatialIOPort, 0, 52, 48, this.getInventoryPlayer() ) ); - this.addSlotToContainer( new SlotOutput( spatialIOPort, 1, 113, 48, SlotRestrictedInput.PlacableItemType.SPATIAL_STORAGE_CELLS.IIcon ) ); - - this.bindPlayerInventory( ip, 0, 197 - /* height of player inventory */82 ); - } - - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); - - if( Platform.isServer() ) - { - this.delay++; - if( this.delay > 15 && this.network != null ) - { - this.delay = 0; - - final IEnergyGrid eg = this.network.getCache( IEnergyGrid.class ); - final ISpatialCache sc = this.network.getCache( ISpatialCache.class ); - if( eg != null ) - { - this.setCurrentPower( (long) ( 100.0 * eg.getStoredPower() ) ); - this.setMaxPower( (long) ( 100.0 * eg.getMaxStoredPower() ) ); - this.setRequiredPower( (long) ( 100.0 * sc.requiredPower() ) ); - this.setEfficency( (long) ( 100.0f * sc.currentEfficiency() ) ); - } - } - } - - super.detectAndSendChanges(); - } - - public long getCurrentPower() - { - return this.currentPower; - } - - private void setCurrentPower( final long currentPower ) - { - this.currentPower = currentPower; - } - - public long getMaxPower() - { - return this.maxPower; - } - - private void setMaxPower( final long maxPower ) - { - this.maxPower = maxPower; - } - - public long getRequiredPower() - { - return this.reqPower; - } - - private void setRequiredPower( final long reqPower ) - { - this.reqPower = reqPower; - } - - public long getEfficency() - { - return this.eff; - } - - private void setEfficency( final long eff ) - { - this.eff = eff; - } +public class ContainerSpatialIOPort extends AEBaseContainer { + + @GuiSync(0) + public long currentPower; + + @GuiSync(1) + public long maxPower; + + @GuiSync(2) + public long reqPower; + + @GuiSync(3) + public long eff; + + private IGrid network; + private int delay = 40; + + public ContainerSpatialIOPort(final InventoryPlayer ip, final TileSpatialIOPort spatialIOPort) { + super(ip, spatialIOPort, null); + + if (Platform.isServer()) { + this.network = spatialIOPort.getGridNode(ForgeDirection.UNKNOWN).getGrid(); + } + + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.SPATIAL_STORAGE_CELLS, + spatialIOPort, + 0, + 52, + 48, + this.getInventoryPlayer())); + this.addSlotToContainer(new SlotOutput( + spatialIOPort, 1, 113, 48, SlotRestrictedInput.PlacableItemType.SPATIAL_STORAGE_CELLS.IIcon)); + + this.bindPlayerInventory(ip, 0, 197 - /* height of player inventory */ 82); + } + + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); + + if (Platform.isServer()) { + this.delay++; + if (this.delay > 15 && this.network != null) { + this.delay = 0; + + final IEnergyGrid eg = this.network.getCache(IEnergyGrid.class); + final ISpatialCache sc = this.network.getCache(ISpatialCache.class); + if (eg != null) { + this.setCurrentPower((long) (100.0 * eg.getStoredPower())); + this.setMaxPower((long) (100.0 * eg.getMaxStoredPower())); + this.setRequiredPower((long) (100.0 * sc.requiredPower())); + this.setEfficency((long) (100.0f * sc.currentEfficiency())); + } + } + } + + super.detectAndSendChanges(); + } + + public long getCurrentPower() { + return this.currentPower; + } + + private void setCurrentPower(final long currentPower) { + this.currentPower = currentPower; + } + + public long getMaxPower() { + return this.maxPower; + } + + private void setMaxPower(final long maxPower) { + this.maxPower = maxPower; + } + + public long getRequiredPower() { + return this.reqPower; + } + + private void setRequiredPower(final long reqPower) { + this.reqPower = reqPower; + } + + public long getEfficency() { + return this.eff; + } + + private void setEfficency(final long eff) { + this.eff = eff; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerStorageBus.java b/src/main/java/appeng/container/implementations/ContainerStorageBus.java index 395a23806ff..a3bc35d81ee 100644 --- a/src/main/java/appeng/container/implementations/ContainerStorageBus.java +++ b/src/main/java/appeng/container/implementations/ContainerStorageBus.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.AEApi; import appeng.api.config.*; import appeng.api.storage.IMEInventory; @@ -26,159 +25,166 @@ import appeng.api.storage.data.IItemList; import appeng.container.guisync.GuiSync; import appeng.container.slot.OptionalSlotFakeTypeOnly; -import appeng.container.slot.SlotFakeTypeOnly; import appeng.container.slot.SlotRestrictedInput; import appeng.parts.misc.PartStorageBus; import appeng.util.Platform; import appeng.util.iterators.NullIterator; +import java.util.Iterator; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.util.Iterator; - - -public class ContainerStorageBus extends ContainerUpgradeable -{ - - private final PartStorageBus storageBus; - - @GuiSync( 3 ) - public AccessRestriction rwMode = AccessRestriction.READ_WRITE; - - @GuiSync( 4 ) - public StorageFilter storageFilter = StorageFilter.EXTRACTABLE_ONLY; - - public ContainerStorageBus( final InventoryPlayer ip, final PartStorageBus te ) - { - super( ip, te ); - this.storageBus = te; - } - - @Override - protected int getHeight() - { - return 251; - } - - @Override - protected void setupConfig() - { - final int xo = 8; - final int yo = 23 + 6; - - final IInventory config = this.getUpgradeable().getInventoryByName( "config" ); - for( int y = 0; y < 7; y++ ) - { - for( int x = 0; x < 9; x++ ) - { - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( config, this, y * 9 + x, xo, yo, x, y, y ) ); - } - } - - final IInventory upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - - @Override - protected boolean supportCapacity() - { - return true; - } - - @Override - public int availableUpgrades() - { - return 5; - } - - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); - - if( Platform.isServer() ) - { - this.setFuzzyMode( (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting( Settings.FUZZY_MODE ) ); - this.setReadWriteMode( (AccessRestriction) this.getUpgradeable().getConfigManager().getSetting( Settings.ACCESS ) ); - this.setStorageFilter( (StorageFilter) this.getUpgradeable().getConfigManager().getSetting( Settings.STORAGE_FILTER ) ); - } - - this.standardDetectAndSendChanges(); - } - - @Override - public boolean isSlotEnabled( final int idx ) - { - if (this.getUpgradeable().getInstalledUpgrades(Upgrades.ORE_FILTER) > 0) - return false; - - final int upgrades = this.getUpgradeable().getInstalledUpgrades( Upgrades.CAPACITY ); - - return upgrades > (idx-2); - } - - public void clear() - { - final IInventory inv = this.getUpgradeable().getInventoryByName( "config" ); - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - inv.setInventorySlotContents( x, null ); - } - this.detectAndSendChanges(); - } - - public void partition() - { - final IInventory inv = this.getUpgradeable().getInventoryByName( "config" ); - - final IMEInventory cellInv = this.storageBus.getInternalHandler(); - - Iterator i = new NullIterator(); - if( cellInv != null ) - { - final IItemList list = cellInv.getAvailableItems( AEApi.instance().storage().createItemList() ); - i = list.iterator(); - } - - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - if( i.hasNext() && this.isSlotEnabled( ( x / 9 ) - 2 ) ) - { - final ItemStack g = i.next().getItemStack(); - g.stackSize = 1; - inv.setInventorySlotContents( x, g ); - } - else - { - inv.setInventorySlotContents( x, null ); - } - } - - this.detectAndSendChanges(); - } - - public AccessRestriction getReadWriteMode() - { - return this.rwMode; - } - - private void setReadWriteMode( final AccessRestriction rwMode ) - { - this.rwMode = rwMode; - } - - public StorageFilter getStorageFilter() - { - return this.storageFilter; - } - - private void setStorageFilter( final StorageFilter storageFilter ) - { - this.storageFilter = storageFilter; - } +public class ContainerStorageBus extends ContainerUpgradeable { + + private final PartStorageBus storageBus; + + @GuiSync(3) + public AccessRestriction rwMode = AccessRestriction.READ_WRITE; + + @GuiSync(4) + public StorageFilter storageFilter = StorageFilter.EXTRACTABLE_ONLY; + + public ContainerStorageBus(final InventoryPlayer ip, final PartStorageBus te) { + super(ip, te); + this.storageBus = te; + } + + @Override + protected int getHeight() { + return 251; + } + + @Override + protected void setupConfig() { + final int xo = 8; + final int yo = 23 + 6; + + final IInventory config = this.getUpgradeable().getInventoryByName("config"); + for (int y = 0; y < 7; y++) { + for (int x = 0; x < 9; x++) { + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(config, this, y * 9 + x, xo, yo, x, y, y)); + } + } + + final IInventory upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 1, + 187, + 8 + 18, + this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 2, + 187, + 8 + 18 * 2, + this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 3, + 187, + 8 + 18 * 3, + this.getInventoryPlayer())) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 4, + 187, + 8 + 18 * 4, + this.getInventoryPlayer())) + .setNotDraggable()); + } + + @Override + protected boolean supportCapacity() { + return true; + } + + @Override + public int availableUpgrades() { + return 5; + } + + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); + + if (Platform.isServer()) { + this.setFuzzyMode( + (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting(Settings.FUZZY_MODE)); + this.setReadWriteMode( + (AccessRestriction) this.getUpgradeable().getConfigManager().getSetting(Settings.ACCESS)); + this.setStorageFilter( + (StorageFilter) this.getUpgradeable().getConfigManager().getSetting(Settings.STORAGE_FILTER)); + } + + this.standardDetectAndSendChanges(); + } + + @Override + public boolean isSlotEnabled(final int idx) { + if (this.getUpgradeable().getInstalledUpgrades(Upgrades.ORE_FILTER) > 0) return false; + + final int upgrades = this.getUpgradeable().getInstalledUpgrades(Upgrades.CAPACITY); + + return upgrades > (idx - 2); + } + + public void clear() { + final IInventory inv = this.getUpgradeable().getInventoryByName("config"); + for (int x = 0; x < inv.getSizeInventory(); x++) { + inv.setInventorySlotContents(x, null); + } + this.detectAndSendChanges(); + } + + public void partition() { + final IInventory inv = this.getUpgradeable().getInventoryByName("config"); + + final IMEInventory cellInv = this.storageBus.getInternalHandler(); + + Iterator i = new NullIterator(); + if (cellInv != null) { + final IItemList list = + cellInv.getAvailableItems(AEApi.instance().storage().createItemList()); + i = list.iterator(); + } + + for (int x = 0; x < inv.getSizeInventory(); x++) { + if (i.hasNext() && this.isSlotEnabled((x / 9) - 2)) { + final ItemStack g = i.next().getItemStack(); + g.stackSize = 1; + inv.setInventorySlotContents(x, g); + } else { + inv.setInventorySlotContents(x, null); + } + } + + this.detectAndSendChanges(); + } + + public AccessRestriction getReadWriteMode() { + return this.rwMode; + } + + private void setReadWriteMode(final AccessRestriction rwMode) { + this.rwMode = rwMode; + } + + public StorageFilter getStorageFilter() { + return this.storageFilter; + } + + private void setStorageFilter(final StorageFilter storageFilter) { + this.storageFilter = storageFilter; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerUpgradeable.java b/src/main/java/appeng/container/implementations/ContainerUpgradeable.java index 70d7ef2df39..0cf1b43ae19 100644 --- a/src/main/java/appeng/container/implementations/ContainerUpgradeable.java +++ b/src/main/java/appeng/container/implementations/ContainerUpgradeable.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.*; import appeng.api.implementations.IUpgradeableHost; import appeng.api.implementations.guiobjects.IGuiItem; @@ -37,274 +36,263 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; - -public class ContainerUpgradeable extends AEBaseContainer implements IOptionalSlotHost -{ - - private final IUpgradeableHost upgradeable; - @GuiSync( 0 ) - public RedstoneMode rsMode = RedstoneMode.IGNORE; - @GuiSync( 1 ) - public FuzzyMode fzMode = FuzzyMode.IGNORE_ALL; - @GuiSync( 5 ) - public YesNo cMode = YesNo.NO; - @GuiSync( 6 ) - public SchedulingMode schedulingMode = SchedulingMode.DEFAULT; - private int tbSlot; - private NetworkToolViewer tbInventory; - - public ContainerUpgradeable( final InventoryPlayer ip, final IUpgradeableHost te ) - { - super( ip, (TileEntity) ( te instanceof TileEntity ? te : null ), (IPart) ( te instanceof IPart ? te : null ) ); - this.upgradeable = te; - - World w = null; - int xCoord = 0; - int yCoord = 0; - int zCoord = 0; - - if( te instanceof TileEntity ) - { - final TileEntity myTile = (TileEntity) te; - w = myTile.getWorldObj(); - xCoord = myTile.xCoord; - yCoord = myTile.yCoord; - zCoord = myTile.zCoord; - } - - if( te instanceof IPart ) - { - final TileEntity mk = te.getTile(); - w = mk.getWorldObj(); - xCoord = mk.xCoord; - yCoord = mk.yCoord; - zCoord = mk.zCoord; - } - - final IInventory pi = this.getPlayerInv(); - for( int x = 0; x < pi.getSizeInventory(); x++ ) - { - final ItemStack pii = pi.getStackInSlot( x ); - if( pii != null && pii.getItem() instanceof ToolNetworkTool ) - { - this.lockPlayerInventorySlot( x ); - this.tbSlot = x; - this.tbInventory = (NetworkToolViewer) ( (IGuiItem) pii.getItem() ).getGuiObject( pii, w, xCoord, yCoord, zCoord ); - break; - } - } - - if( this.hasToolbox() ) - { - for( int v = 0; v < 3; v++ ) - { - for( int u = 0; u < 3; u++ ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, this.tbInventory, u + v * 3, 186 + u * 18, this.getHeight() - 82 + v * 18, this.getInventoryPlayer() ) ).setPlayerSide() ); - } - } - } - - this.setupConfig(); - - this.bindPlayerInventory( ip, 0, this.getHeight() - /* height of player inventory */82 ); - } - - public boolean hasToolbox() - { - return this.tbInventory != null; - } - - protected int getHeight() - { - return 184; - } - - protected void setupConfig() - { - this.setupUpgrades(); - - final IInventory inv = this.getUpgradeable().getInventoryByName( "config" ); - final int y = 40; - final int x = 80; - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 0, x, y, 0, 0, 0 ) ); - if( this.supportCapacity() ) - { - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 1, x, y, -1, 0, 1 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 2, x, y, 1, 0, 1 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 3, x, y, 0, -1, 1 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 4, x, y, 0, 1, 1 ) ); - - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 5, x, y, -1, -1, 2 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 6, x, y, 1, -1, 2 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 7, x, y, -1, 1, 2 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 8, x, y, 1, 1, 2 ) ); - } - } - - protected void setupUpgrades() - { - final IInventory upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - if( this.availableUpgrades() > 0 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - if( this.availableUpgrades() > 1 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - if( this.availableUpgrades() > 2 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - if( this.availableUpgrades() > 3 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - } - - protected boolean supportCapacity() - { - return true; - } - - public int availableUpgrades() - { - return 4; - } - - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); - - if( Platform.isServer() ) - { - final IConfigManager cm = this.getUpgradeable().getConfigManager(); - this.loadSettingsFromHost( cm ); - } - - this.checkToolbox(); - - for( final Object o : this.inventorySlots ) - { - if( o instanceof OptionalSlotFake ) - { - final OptionalSlotFake fs = (OptionalSlotFake) o; - if( !fs.isEnabled() && fs.getDisplayStack() != null ) - { - fs.clearStack(); - } - } - } - - this.standardDetectAndSendChanges(); - } - - protected void loadSettingsFromHost( final IConfigManager cm ) - { - this.setFuzzyMode( (FuzzyMode) cm.getSetting( Settings.FUZZY_MODE ) ); - this.setRedStoneMode( (RedstoneMode) cm.getSetting( Settings.REDSTONE_CONTROLLED ) ); - if( this.getUpgradeable() instanceof PartExportBus ) - { - this.setCraftingMode( (YesNo) cm.getSetting( Settings.CRAFT_ONLY ) ); - this.setSchedulingMode( (SchedulingMode) cm.getSetting( Settings.SCHEDULING_MODE ) ); - } - } - - private void checkToolbox() - { - if( this.hasToolbox() ) - { - final ItemStack currentItem = this.getPlayerInv().getStackInSlot( this.tbSlot ); - - if( currentItem != this.tbInventory.getItemStack() ) - { - if( currentItem != null ) - { - if( Platform.isSameItem( this.tbInventory.getItemStack(), currentItem ) ) - { - this.getPlayerInv().setInventorySlotContents( this.tbSlot, this.tbInventory.getItemStack() ); - } - else - { - this.setValidContainer( false ); - } - } - else - { - this.setValidContainer( false ); - } - } - } - } - - protected void standardDetectAndSendChanges() - { - super.detectAndSendChanges(); - } - - @Override - public boolean isSlotEnabled( final int idx ) - { - if (this.getUpgradeable().getInstalledUpgrades( Upgrades.ORE_FILTER ) > 0) - return false; - - if (idx == 0) - return true; - - final int upgrades = this.getUpgradeable().getInstalledUpgrades( Upgrades.CAPACITY ); - - if( idx == 1 && upgrades > 0 ) - { - return true; - } - return idx == 2 && upgrades > 1; - - } - - public FuzzyMode getFuzzyMode() - { - return this.fzMode; - } - - void setFuzzyMode( final FuzzyMode fzMode ) - { - this.fzMode = fzMode; - } - - public YesNo getCraftingMode() - { - return this.cMode; - } - - public void setCraftingMode( final YesNo cMode ) - { - this.cMode = cMode; - } - - public RedstoneMode getRedStoneMode() - { - return this.rsMode; - } - - void setRedStoneMode( final RedstoneMode rsMode ) - { - this.rsMode = rsMode; - } - - public SchedulingMode getSchedulingMode() - { - return this.schedulingMode; - } - - private void setSchedulingMode( final SchedulingMode schedulingMode ) - { - this.schedulingMode = schedulingMode; - } - - IUpgradeableHost getUpgradeable() - { - return this.upgradeable; - } +public class ContainerUpgradeable extends AEBaseContainer implements IOptionalSlotHost { + + private final IUpgradeableHost upgradeable; + + @GuiSync(0) + public RedstoneMode rsMode = RedstoneMode.IGNORE; + + @GuiSync(1) + public FuzzyMode fzMode = FuzzyMode.IGNORE_ALL; + + @GuiSync(5) + public YesNo cMode = YesNo.NO; + + @GuiSync(6) + public SchedulingMode schedulingMode = SchedulingMode.DEFAULT; + + private int tbSlot; + private NetworkToolViewer tbInventory; + + public ContainerUpgradeable(final InventoryPlayer ip, final IUpgradeableHost te) { + super(ip, (TileEntity) (te instanceof TileEntity ? te : null), (IPart) (te instanceof IPart ? te : null)); + this.upgradeable = te; + + World w = null; + int xCoord = 0; + int yCoord = 0; + int zCoord = 0; + + if (te instanceof TileEntity) { + final TileEntity myTile = (TileEntity) te; + w = myTile.getWorldObj(); + xCoord = myTile.xCoord; + yCoord = myTile.yCoord; + zCoord = myTile.zCoord; + } + + if (te instanceof IPart) { + final TileEntity mk = te.getTile(); + w = mk.getWorldObj(); + xCoord = mk.xCoord; + yCoord = mk.yCoord; + zCoord = mk.zCoord; + } + + final IInventory pi = this.getPlayerInv(); + for (int x = 0; x < pi.getSizeInventory(); x++) { + final ItemStack pii = pi.getStackInSlot(x); + if (pii != null && pii.getItem() instanceof ToolNetworkTool) { + this.lockPlayerInventorySlot(x); + this.tbSlot = x; + this.tbInventory = + (NetworkToolViewer) ((IGuiItem) pii.getItem()).getGuiObject(pii, w, xCoord, yCoord, zCoord); + break; + } + } + + if (this.hasToolbox()) { + for (int v = 0; v < 3; v++) { + for (int u = 0; u < 3; u++) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + this.tbInventory, + u + v * 3, + 186 + u * 18, + this.getHeight() - 82 + v * 18, + this.getInventoryPlayer())) + .setPlayerSide()); + } + } + } + + this.setupConfig(); + + this.bindPlayerInventory(ip, 0, this.getHeight() - /* height of player inventory */ 82); + } + + public boolean hasToolbox() { + return this.tbInventory != null; + } + + protected int getHeight() { + return 184; + } + + protected void setupConfig() { + this.setupUpgrades(); + + final IInventory inv = this.getUpgradeable().getInventoryByName("config"); + final int y = 40; + final int x = 80; + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 0, x, y, 0, 0, 0)); + if (this.supportCapacity()) { + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 1, x, y, -1, 0, 1)); + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 2, x, y, 1, 0, 1)); + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 3, x, y, 0, -1, 1)); + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 4, x, y, 0, 1, 1)); + + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 5, x, y, -1, -1, 2)); + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 6, x, y, 1, -1, 2)); + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 7, x, y, -1, 1, 2)); + this.addSlotToContainer(new OptionalSlotFakeTypeOnly(inv, this, 8, x, y, 1, 1, 2)); + } + } + + protected void setupUpgrades() { + final IInventory upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + if (this.availableUpgrades() > 0) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 0, + 187, + 8, + this.getInventoryPlayer())) + .setNotDraggable()); + } + if (this.availableUpgrades() > 1) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 1, + 187, + 8 + 18, + this.getInventoryPlayer())) + .setNotDraggable()); + } + if (this.availableUpgrades() > 2) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 2, + 187, + 8 + 18 * 2, + this.getInventoryPlayer())) + .setNotDraggable()); + } + if (this.availableUpgrades() > 3) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 3, + 187, + 8 + 18 * 3, + this.getInventoryPlayer())) + .setNotDraggable()); + } + } + + protected boolean supportCapacity() { + return true; + } + + public int availableUpgrades() { + return 4; + } + + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); + + if (Platform.isServer()) { + final IConfigManager cm = this.getUpgradeable().getConfigManager(); + this.loadSettingsFromHost(cm); + } + + this.checkToolbox(); + + for (final Object o : this.inventorySlots) { + if (o instanceof OptionalSlotFake) { + final OptionalSlotFake fs = (OptionalSlotFake) o; + if (!fs.isEnabled() && fs.getDisplayStack() != null) { + fs.clearStack(); + } + } + } + + this.standardDetectAndSendChanges(); + } + + protected void loadSettingsFromHost(final IConfigManager cm) { + this.setFuzzyMode((FuzzyMode) cm.getSetting(Settings.FUZZY_MODE)); + this.setRedStoneMode((RedstoneMode) cm.getSetting(Settings.REDSTONE_CONTROLLED)); + if (this.getUpgradeable() instanceof PartExportBus) { + this.setCraftingMode((YesNo) cm.getSetting(Settings.CRAFT_ONLY)); + this.setSchedulingMode((SchedulingMode) cm.getSetting(Settings.SCHEDULING_MODE)); + } + } + + private void checkToolbox() { + if (this.hasToolbox()) { + final ItemStack currentItem = this.getPlayerInv().getStackInSlot(this.tbSlot); + + if (currentItem != this.tbInventory.getItemStack()) { + if (currentItem != null) { + if (Platform.isSameItem(this.tbInventory.getItemStack(), currentItem)) { + this.getPlayerInv().setInventorySlotContents(this.tbSlot, this.tbInventory.getItemStack()); + } else { + this.setValidContainer(false); + } + } else { + this.setValidContainer(false); + } + } + } + } + + protected void standardDetectAndSendChanges() { + super.detectAndSendChanges(); + } + + @Override + public boolean isSlotEnabled(final int idx) { + if (this.getUpgradeable().getInstalledUpgrades(Upgrades.ORE_FILTER) > 0) return false; + + if (idx == 0) return true; + + final int upgrades = this.getUpgradeable().getInstalledUpgrades(Upgrades.CAPACITY); + + if (idx == 1 && upgrades > 0) { + return true; + } + return idx == 2 && upgrades > 1; + } + + public FuzzyMode getFuzzyMode() { + return this.fzMode; + } + + void setFuzzyMode(final FuzzyMode fzMode) { + this.fzMode = fzMode; + } + + public YesNo getCraftingMode() { + return this.cMode; + } + + public void setCraftingMode(final YesNo cMode) { + this.cMode = cMode; + } + + public RedstoneMode getRedStoneMode() { + return this.rsMode; + } + + void setRedStoneMode(final RedstoneMode rsMode) { + this.rsMode = rsMode; + } + + public SchedulingMode getSchedulingMode() { + return this.schedulingMode; + } + + private void setSchedulingMode(final SchedulingMode schedulingMode) { + this.schedulingMode = schedulingMode; + } + + IUpgradeableHost getUpgradeable() { + return this.upgradeable; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java b/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java index f1cd5a14691..91354f5b6e1 100644 --- a/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java +++ b/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.container.AEBaseContainer; import appeng.container.guisync.GuiSync; import appeng.container.interfaces.IProgressProvider; @@ -27,54 +26,52 @@ import appeng.util.Platform; import net.minecraft.entity.player.InventoryPlayer; +public class ContainerVibrationChamber extends AEBaseContainer implements IProgressProvider { + + private static final int MAX_BURN_TIME = 200; + private final int aePerTick = 5; + private final TileVibrationChamber vibrationChamber; -public class ContainerVibrationChamber extends AEBaseContainer implements IProgressProvider -{ + @GuiSync(0) + public int burnProgress = 0; - private static final int MAX_BURN_TIME = 200; - private final int aePerTick = 5; - private final TileVibrationChamber vibrationChamber; - @GuiSync( 0 ) - public int burnProgress = 0; - @GuiSync( 1 ) - public int burnSpeed = 100; + @GuiSync(1) + public int burnSpeed = 100; - public ContainerVibrationChamber( final InventoryPlayer ip, final TileVibrationChamber vibrationChamber ) - { - super( ip, vibrationChamber, null ); - this.vibrationChamber = vibrationChamber; + public ContainerVibrationChamber(final InventoryPlayer ip, final TileVibrationChamber vibrationChamber) { + super(ip, vibrationChamber, null); + this.vibrationChamber = vibrationChamber; - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.FUEL, vibrationChamber, 0, 80, 37, this.getInventoryPlayer() ) ); + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.FUEL, vibrationChamber, 0, 80, 37, this.getInventoryPlayer())); - this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 166 - /* height of player inventory */ 82); + } - @Override - public void detectAndSendChanges() - { - if( Platform.isServer() ) - { - this.burnProgress = (int) ( this.vibrationChamber.getMaxBurnTime() <= 0 ? 0 : 12 * this.vibrationChamber.getBurnTime() / this.vibrationChamber.getMaxBurnTime() ); - this.burnSpeed = this.vibrationChamber.getBurnSpeed(); - } + @Override + public void detectAndSendChanges() { + if (Platform.isServer()) { + this.burnProgress = (int) + (this.vibrationChamber.getMaxBurnTime() <= 0 + ? 0 + : 12 * this.vibrationChamber.getBurnTime() / this.vibrationChamber.getMaxBurnTime()); + this.burnSpeed = this.vibrationChamber.getBurnSpeed(); + } - super.detectAndSendChanges(); - } + super.detectAndSendChanges(); + } - @Override - public int getCurrentProgress() - { - return this.burnProgress > 0 ? this.burnSpeed : 0; - } + @Override + public int getCurrentProgress() { + return this.burnProgress > 0 ? this.burnSpeed : 0; + } - @Override - public int getMaxProgress() - { - return MAX_BURN_TIME; - } + @Override + public int getMaxProgress() { + return MAX_BURN_TIME; + } - public int getAePerTick() - { - return this.aePerTick; - } + public int getAePerTick() { + return this.aePerTick; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerWireless.java b/src/main/java/appeng/container/implementations/ContainerWireless.java index 840f1ce1d03..8906732bae1 100644 --- a/src/main/java/appeng/container/implementations/ContainerWireless.java +++ b/src/main/java/appeng/container/implementations/ContainerWireless.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.container.AEBaseContainer; import appeng.container.guisync.GuiSync; import appeng.container.slot.SlotRestrictedInput; @@ -26,55 +25,56 @@ import appeng.tile.networking.TileWireless; import net.minecraft.entity.player.InventoryPlayer; +public class ContainerWireless extends AEBaseContainer { + + private final TileWireless wirelessTerminal; + private final SlotRestrictedInput boosterSlot; -public class ContainerWireless extends AEBaseContainer -{ + @GuiSync(1) + public long range = 0; - private final TileWireless wirelessTerminal; - private final SlotRestrictedInput boosterSlot; - @GuiSync( 1 ) - public long range = 0; - @GuiSync( 2 ) - public long drain = 0; + @GuiSync(2) + public long drain = 0; - public ContainerWireless( final InventoryPlayer ip, final TileWireless te ) - { - super( ip, te, null ); - this.wirelessTerminal = te; + public ContainerWireless(final InventoryPlayer ip, final TileWireless te) { + super(ip, te, null); + this.wirelessTerminal = te; - this.addSlotToContainer( this.boosterSlot = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.RANGE_BOOSTER, this.wirelessTerminal, 0, 80, 47, this.getInventoryPlayer() ) ); + this.addSlotToContainer( + this.boosterSlot = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.RANGE_BOOSTER, + this.wirelessTerminal, + 0, + 80, + 47, + this.getInventoryPlayer())); - this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); - } + this.bindPlayerInventory(ip, 0, 166 - /* height of player inventory */ 82); + } - @Override - public void detectAndSendChanges() - { - final int boosters = this.boosterSlot.getStack() == null ? 0 : this.boosterSlot.getStack().stackSize; + @Override + public void detectAndSendChanges() { + final int boosters = this.boosterSlot.getStack() == null ? 0 : this.boosterSlot.getStack().stackSize; - this.setRange( (long) ( 10 * AEConfig.instance.wireless_getMaxRange( boosters ) ) ); - this.setDrain( (long) ( 100 * AEConfig.instance.wireless_getPowerDrain( boosters ) ) ); + this.setRange((long) (10 * AEConfig.instance.wireless_getMaxRange(boosters))); + this.setDrain((long) (100 * AEConfig.instance.wireless_getPowerDrain(boosters))); - super.detectAndSendChanges(); - } + super.detectAndSendChanges(); + } - public long getRange() - { - return this.range; - } + public long getRange() { + return this.range; + } - private void setRange( final long range ) - { - this.range = range; - } + private void setRange(final long range) { + this.range = range; + } - public long getDrain() - { - return this.drain; - } + public long getDrain() { + return this.drain; + } - private void setDrain( final long drain ) - { - this.drain = drain; - } + private void setDrain(final long drain) { + this.drain = drain; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java b/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java index e545295cb94..cf3fe033931 100644 --- a/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java +++ b/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java @@ -18,42 +18,33 @@ package appeng.container.implementations; - import appeng.core.AEConfig; import appeng.core.localization.PlayerMessages; import appeng.helpers.WirelessTerminalGuiObject; import appeng.util.Platform; import net.minecraft.entity.player.InventoryPlayer; +public class ContainerWirelessTerm extends ContainerMEPortableCell { + + private final WirelessTerminalGuiObject wirelessTerminalGUIObject; + + public ContainerWirelessTerm(final InventoryPlayer ip, final WirelessTerminalGuiObject gui) { + super(ip, gui); + this.wirelessTerminalGUIObject = gui; + } + + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + + if (!this.wirelessTerminalGUIObject.rangeCheck()) { + if (Platform.isServer() && this.isValidContainer()) { + this.getPlayerInv().player.addChatMessage(PlayerMessages.OutOfRange.get()); + } -public class ContainerWirelessTerm extends ContainerMEPortableCell -{ - - private final WirelessTerminalGuiObject wirelessTerminalGUIObject; - - public ContainerWirelessTerm( final InventoryPlayer ip, final WirelessTerminalGuiObject gui ) - { - super( ip, gui ); - this.wirelessTerminalGUIObject = gui; - } - - @Override - public void detectAndSendChanges() - { - super.detectAndSendChanges(); - - if( !this.wirelessTerminalGUIObject.rangeCheck() ) - { - if( Platform.isServer() && this.isValidContainer() ) - { - this.getPlayerInv().player.addChatMessage( PlayerMessages.OutOfRange.get() ); - } - - this.setValidContainer( false ); - } - else - { - this.setPowerMultiplier( AEConfig.instance.wireless_getDrainRate( this.wirelessTerminalGUIObject.getRange() ) ); - } - } + this.setValidContainer(false); + } else { + this.setPowerMultiplier(AEConfig.instance.wireless_getDrainRate(this.wirelessTerminalGUIObject.getRange())); + } + } } diff --git a/src/main/java/appeng/container/implementations/CraftingCPURecord.java b/src/main/java/appeng/container/implementations/CraftingCPURecord.java index 2e284491e02..b968b3342da 100644 --- a/src/main/java/appeng/container/implementations/CraftingCPURecord.java +++ b/src/main/java/appeng/container/implementations/CraftingCPURecord.java @@ -18,57 +18,46 @@ package appeng.container.implementations; - import appeng.api.networking.crafting.ICraftingCPU; import appeng.util.ItemSorters; - import javax.annotation.Nonnull; - -public class CraftingCPURecord implements Comparable -{ - - private final String myName; - private final ICraftingCPU cpu; - private final long size; - private final int processors; - - public CraftingCPURecord( final long size, final int coProcessors, final ICraftingCPU server ) - { - this.size = size; - this.processors = coProcessors; - this.cpu = server; - this.myName = server.getName(); - } - - @Override - public int compareTo( @Nonnull final CraftingCPURecord o ) - { - final int a = ItemSorters.compareLong( o.getProcessors(), this.getProcessors() ); - if( a != 0 ) - { - return a; - } - return ItemSorters.compareLong( o.getSize(), this.getSize() ); - } - - ICraftingCPU getCpu() - { - return this.cpu; - } - - String getName() - { - return this.myName; - } - - int getProcessors() - { - return this.processors; - } - - long getSize() - { - return this.size; - } -} \ No newline at end of file +public class CraftingCPURecord implements Comparable { + + private final String myName; + private final ICraftingCPU cpu; + private final long size; + private final int processors; + + public CraftingCPURecord(final long size, final int coProcessors, final ICraftingCPU server) { + this.size = size; + this.processors = coProcessors; + this.cpu = server; + this.myName = server.getName(); + } + + @Override + public int compareTo(@Nonnull final CraftingCPURecord o) { + final int a = ItemSorters.compareLong(o.getProcessors(), this.getProcessors()); + if (a != 0) { + return a; + } + return ItemSorters.compareLong(o.getSize(), this.getSize()); + } + + ICraftingCPU getCpu() { + return this.cpu; + } + + String getName() { + return this.myName; + } + + int getProcessors() { + return this.processors; + } + + long getSize() { + return this.size; + } +} diff --git a/src/main/java/appeng/container/implementations/CraftingCPUStatus.java b/src/main/java/appeng/container/implementations/CraftingCPUStatus.java index 0121db472c4..729c4a65655 100644 --- a/src/main/java/appeng/container/implementations/CraftingCPUStatus.java +++ b/src/main/java/appeng/container/implementations/CraftingCPUStatus.java @@ -5,19 +5,18 @@ import appeng.util.ItemSorters; import appeng.util.item.AEItemStack; import io.netty.buffer.ByteBuf; +import java.io.*; +import javax.annotation.Nullable; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; -import javax.annotation.Nullable; -import java.io.*; - /** * Summary status for the crafting CPU selection widget */ -public class CraftingCPUStatus implements Comparable -{ +public class CraftingCPUStatus implements Comparable { @Nullable private final ICraftingCPU serverCluster; + private final String name; private final int serial; private final long storage; @@ -27,8 +26,7 @@ public class CraftingCPUStatus implements Comparable private final long remainingItems; private final IAEItemStack crafting; - public CraftingCPUStatus( ) - { + public CraftingCPUStatus() { this.serverCluster = null; this.name = "ERROR"; this.serial = 0; @@ -40,20 +38,16 @@ public CraftingCPUStatus( ) this.crafting = null; } - public CraftingCPUStatus( ICraftingCPU cluster, int serial ) - { + public CraftingCPUStatus(ICraftingCPU cluster, int serial) { this.serverCluster = cluster; this.name = cluster.getName(); this.serial = serial; this.isBusy = cluster.isBusy(); - if (isBusy) - { + if (isBusy) { crafting = cluster.getFinalOutput(); totalItems = cluster.getStartItemCount(); remainingItems = cluster.getRemainingItemCount(); - } - else - { + } else { crafting = null; totalItems = 0; remainingItems = 0; @@ -62,148 +56,120 @@ public CraftingCPUStatus( ICraftingCPU cluster, int serial ) this.coprocessors = cluster.getCoProcessors(); } - public CraftingCPUStatus( NBTTagCompound i ) - { + public CraftingCPUStatus(NBTTagCompound i) { this.serverCluster = null; - this.name = i.getString( "name" ); - this.serial = i.getInteger( "serial" ); + this.name = i.getString("name"); + this.serial = i.getInteger("serial"); this.storage = i.getLong("storage"); this.coprocessors = i.getLong("coprocessors"); this.isBusy = i.getBoolean("isBusy"); this.totalItems = i.getLong("totalItems"); this.remainingItems = i.getLong("remainingItems"); - this.crafting = i.hasKey( "crafting" ) ? AEItemStack.loadItemStackFromNBT( i.getCompoundTag( "crafting" ) ) : null; + this.crafting = i.hasKey("crafting") ? AEItemStack.loadItemStackFromNBT(i.getCompoundTag("crafting")) : null; } - public CraftingCPUStatus(ByteBuf packet) throws IOException - { - this(readNBTFromPacket( packet )); + public CraftingCPUStatus(ByteBuf packet) throws IOException { + this(readNBTFromPacket(packet)); } - private static NBTTagCompound readNBTFromPacket(ByteBuf packet) throws IOException - { + private static NBTTagCompound readNBTFromPacket(ByteBuf packet) throws IOException { final int size = packet.readInt(); final byte[] tagBytes = new byte[size]; - packet.readBytes( tagBytes ); - final ByteArrayInputStream di = new ByteArrayInputStream( tagBytes ); - return CompressedStreamTools.read( new DataInputStream( di )); + packet.readBytes(tagBytes); + final ByteArrayInputStream di = new ByteArrayInputStream(tagBytes); + return CompressedStreamTools.read(new DataInputStream(di)); } - public void writeToNBT( NBTTagCompound i ) - { - if (name != null && !name.isEmpty()) - { - i.setString( "name", name ); + public void writeToNBT(NBTTagCompound i) { + if (name != null && !name.isEmpty()) { + i.setString("name", name); } - i.setInteger( "serial", serial ); - i.setLong( "storage", storage ); - i.setLong( "coprocessors", coprocessors ); - i.setBoolean( "isBusy", isBusy ); - i.setLong( "totalItems", totalItems ); - i.setLong( "remainingItems", remainingItems ); - if (crafting != null) - { + i.setInteger("serial", serial); + i.setLong("storage", storage); + i.setLong("coprocessors", coprocessors); + i.setBoolean("isBusy", isBusy); + i.setLong("totalItems", totalItems); + i.setLong("remainingItems", remainingItems); + if (crafting != null) { NBTTagCompound stack = new NBTTagCompound(); - crafting.writeToNBT( stack ); - i.setTag( "crafting", stack ); + crafting.writeToNBT(stack); + i.setTag("crafting", stack); } } - public void writeToPacket( ByteBuf i ) throws IOException - { + public void writeToPacket(ByteBuf i) throws IOException { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - final DataOutputStream data = new DataOutputStream( bytes ); + final DataOutputStream data = new DataOutputStream(bytes); NBTTagCompound tag = new NBTTagCompound(); - this.writeToNBT( tag ); - CompressedStreamTools.write( tag, data ); + this.writeToNBT(tag); + CompressedStreamTools.write(tag, data); final byte[] tagBytes = bytes.toByteArray(); final int size = tagBytes.length; - i.writeInt( size ); - i.writeBytes( tagBytes ); + i.writeInt(size); + i.writeBytes(tagBytes); } @Nullable - public ICraftingCPU getServerCluster() - { + public ICraftingCPU getServerCluster() { return serverCluster; } - public String getName() - { + public String getName() { return name; } - public int getSerial() - { + public int getSerial() { return serial; } - public long getStorage() - { + public long getStorage() { return storage; } - public long getCoprocessors() - { + public long getCoprocessors() { return coprocessors; } - public long getTotalItems() - { + public long getTotalItems() { return totalItems; } - public long getRemainingItems() - { + public long getRemainingItems() { return remainingItems; } - public IAEItemStack getCrafting() - { + public IAEItemStack getCrafting() { return crafting; } - public boolean isBusy() - { + public boolean isBusy() { return isBusy; } @Override - public int compareTo( CraftingCPUStatus o ) - { - final int a = ItemSorters.compareLong( o.getCoprocessors(), this.getCoprocessors() ); - if( a != 0 ) - { + public int compareTo(CraftingCPUStatus o) { + final int a = ItemSorters.compareLong(o.getCoprocessors(), this.getCoprocessors()); + if (a != 0) { return a; } - return ItemSorters.compareLong( o.getStorage(), this.getStorage() ); + return ItemSorters.compareLong(o.getStorage(), this.getStorage()); } - public String formatStorage() - { + public String formatStorage() { long val = getStorage(); - if (val > 4_000_000_000_000L) - { + if (val > 4_000_000_000_000L) { return String.format("%dT", val / 1024 / 1024 / 1024 / 1024); - } - else if (val > 4_000_000_000L) - { + } else if (val > 4_000_000_000L) { return String.format("%dG", val / 1024 / 1024 / 1024); - } - else if (val > 4_000_000L) - { + } else if (val > 4_000_000L) { return String.format("%dM", val / 1024 / 1024); - } - else if (val > 4_000L) - { + } else if (val > 4_000L) { return String.format("%dk", val / 1024); - } - else - { - return Long.toString( val ); + } else { + return Long.toString(val); } } } diff --git a/src/main/java/appeng/container/interfaces/ICraftingCPUSelectorContainer.java b/src/main/java/appeng/container/interfaces/ICraftingCPUSelectorContainer.java index 95dd3f52c5d..f2cac85cd6d 100644 --- a/src/main/java/appeng/container/interfaces/ICraftingCPUSelectorContainer.java +++ b/src/main/java/appeng/container/interfaces/ICraftingCPUSelectorContainer.java @@ -1,6 +1,5 @@ package appeng.container.interfaces; -public interface ICraftingCPUSelectorContainer -{ +public interface ICraftingCPUSelectorContainer { void selectCPU(int cpu); } diff --git a/src/main/java/appeng/container/interfaces/IInventorySlotAware.java b/src/main/java/appeng/container/interfaces/IInventorySlotAware.java index 68b65b4acc4..be9f4bfbc91 100644 --- a/src/main/java/appeng/container/interfaces/IInventorySlotAware.java +++ b/src/main/java/appeng/container/interfaces/IInventorySlotAware.java @@ -1,36 +1,34 @@ -/* - * This file is part of Applied Energistics 2. - * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. - * - * Applied Energistics 2 is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Applied Energistics 2 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Applied Energistics 2. If not, see . - */ - -package appeng.container.interfaces; - - -/** - * Any item providing a GUI and depending on an exact inventory slot. - *

- * This interface is likely a volatile one until a general GUI refactoring occurred. - * Use it with care and expect changes. - */ -public interface IInventorySlotAware -{ - /** - * This is needed to select the correct slot index. - * - * @return the inventory index of this portable cell. - */ - int getInventorySlot(); -} +/* + * This file is part of Applied Energistics 2. + * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. + * + * Applied Energistics 2 is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Applied Energistics 2 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Applied Energistics 2. If not, see . + */ + +package appeng.container.interfaces; + +/** + * Any item providing a GUI and depending on an exact inventory slot. + *

+ * This interface is likely a volatile one until a general GUI refactoring occurred. + * Use it with care and expect changes. + */ +public interface IInventorySlotAware { + /** + * This is needed to select the correct slot index. + * + * @return the inventory index of this portable cell. + */ + int getInventorySlot(); +} diff --git a/src/main/java/appeng/container/interfaces/IProgressProvider.java b/src/main/java/appeng/container/interfaces/IProgressProvider.java index 90171c1b028..e00e486435e 100644 --- a/src/main/java/appeng/container/interfaces/IProgressProvider.java +++ b/src/main/java/appeng/container/interfaces/IProgressProvider.java @@ -1,50 +1,47 @@ -/* - * This file is part of Applied Energistics 2. - * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. - * - * Applied Energistics 2 is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Applied Energistics 2 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Applied Energistics 2. If not, see . - */ - -package appeng.container.interfaces; - - -import appeng.client.gui.widgets.GuiProgressBar; - - -/** - * This interface provides the data for anything simulating a progress. - *

- * Its main use is in combination with the {@link GuiProgressBar}, which ensures to scale it to a percentage of 0 to - * 100. - */ -public interface IProgressProvider -{ - - /** - * The current value of the progress. It should cover a range from 0 to the max progress - * - * @return An int representing the current progress - */ - int getCurrentProgress(); - - /** - * The max value the progress. - *

- * It is not limited to a value of 100 and can be scaled to fit the current needs. For example scaled down to - * decrease or scaled up to increase the precision. - * - * @return An int representing the max progress - */ - int getMaxProgress(); -} +/* + * This file is part of Applied Energistics 2. + * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. + * + * Applied Energistics 2 is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Applied Energistics 2 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Applied Energistics 2. If not, see . + */ + +package appeng.container.interfaces; + +import appeng.client.gui.widgets.GuiProgressBar; + +/** + * This interface provides the data for anything simulating a progress. + *

+ * Its main use is in combination with the {@link GuiProgressBar}, which ensures to scale it to a percentage of 0 to + * 100. + */ +public interface IProgressProvider { + + /** + * The current value of the progress. It should cover a range from 0 to the max progress + * + * @return An int representing the current progress + */ + int getCurrentProgress(); + + /** + * The max value the progress. + *

+ * It is not limited to a value of 100 and can be scaled to fit the current needs. For example scaled down to + * decrease or scaled up to increase the precision. + * + * @return An int representing the max progress + */ + int getMaxProgress(); +} diff --git a/src/main/java/appeng/container/slot/AppEngCraftingSlot.java b/src/main/java/appeng/container/slot/AppEngCraftingSlot.java index 527d0953afd..f5ceb3560f4 100644 --- a/src/main/java/appeng/container/slot/AppEngCraftingSlot.java +++ b/src/main/java/appeng/container/slot/AppEngCraftingSlot.java @@ -18,7 +18,6 @@ package appeng.container.slot; - import cpw.mods.fml.common.FMLCommonHandler; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; @@ -29,164 +28,147 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; - -public class AppEngCraftingSlot extends AppEngSlot -{ - - /** - * The craft matrix inventory linked to this result slot. - */ - private final IInventory craftMatrix; - - /** - * The player that is using the GUI where this slot resides. - */ - private final EntityPlayer thePlayer; - - /** - * The number of items that have been crafted so far. Gets passed to ItemStack.onCrafting before being reset. - */ - private int amountCrafted; - - public AppEngCraftingSlot( final EntityPlayer par1EntityPlayer, final IInventory par2IInventory, final IInventory par3IInventory, final int par4, final int par5, final int par6 ) - { - super( par3IInventory, par4, par5, par6 ); - this.thePlayer = par1EntityPlayer; - this.craftMatrix = par2IInventory; - } - - /** - * Check if the stack is a valid item for this slot. Always true beside for the armor slots. - */ - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } - - /** - * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. Typically increases an - * internal count then calls onCrafting(item). - */ - @Override - protected void onCrafting( final ItemStack par1ItemStack, final int par2 ) - { - this.amountCrafted += par2; - this.onCrafting( par1ItemStack ); - } - - /** - * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. - */ - @Override - protected void onCrafting( final ItemStack par1ItemStack ) - { - par1ItemStack.onCrafting( this.thePlayer.worldObj, this.thePlayer, this.amountCrafted ); - this.amountCrafted = 0; - - if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.crafting_table ) ) - { - this.thePlayer.addStat( AchievementList.buildWorkBench, 1 ); - } - - if( par1ItemStack.getItem() instanceof ItemPickaxe ) - { - this.thePlayer.addStat( AchievementList.buildPickaxe, 1 ); - } - - if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.furnace ) ) - { - this.thePlayer.addStat( AchievementList.buildFurnace, 1 ); - } - - if( par1ItemStack.getItem() instanceof ItemHoe ) - { - this.thePlayer.addStat( AchievementList.buildHoe, 1 ); - } - - if( par1ItemStack.getItem() == Items.bread ) - { - this.thePlayer.addStat( AchievementList.makeBread, 1 ); - } - - if( par1ItemStack.getItem() == Items.cake ) - { - this.thePlayer.addStat( AchievementList.bakeCake, 1 ); - } - - if( par1ItemStack.getItem() instanceof ItemPickaxe && ( (ItemTool) par1ItemStack.getItem() ).func_150913_i() != Item.ToolMaterial.WOOD ) - { - this.thePlayer.addStat( AchievementList.buildBetterPickaxe, 1 ); - } - - if( par1ItemStack.getItem() instanceof ItemSword ) - { - this.thePlayer.addStat( AchievementList.buildSword, 1 ); - } - - if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.enchanting_table ) ) - { - this.thePlayer.addStat( AchievementList.enchantments, 1 ); - } - - if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.bookshelf ) ) - { - this.thePlayer.addStat( AchievementList.bookcase, 1 ); - } - } - - @Override - public void onPickupFromSlot( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) - { - FMLCommonHandler.instance().firePlayerCraftingEvent( par1EntityPlayer, par2ItemStack, this.craftMatrix ); - this.onCrafting( par2ItemStack ); - - for( int i = 0; i < this.craftMatrix.getSizeInventory(); ++i ) - { - final ItemStack itemstack1 = this.craftMatrix.getStackInSlot( i ); - - if( itemstack1 != null ) - { - this.craftMatrix.decrStackSize( i, 1 ); - - if( itemstack1.getItem().hasContainerItem( itemstack1 ) ) - { - final ItemStack itemstack2 = itemstack1.getItem().getContainerItem( itemstack1 ); - - if( itemstack2 != null && itemstack2.isItemStackDamageable() && itemstack2.getItemDamage() > itemstack2.getMaxDamage() ) - { - MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( this.thePlayer, itemstack2 ) ); - continue; - } - - if( !itemstack1.getItem().doesContainerItemLeaveCraftingGrid( itemstack1 ) || !this.thePlayer.inventory.addItemStackToInventory( itemstack2 ) ) - { - if( this.craftMatrix.getStackInSlot( i ) == null ) - { - this.craftMatrix.setInventorySlotContents( i, itemstack2 ); - } - else - { - this.thePlayer.dropPlayerItemWithRandomChoice( itemstack2, false ); - } - } - } - } - } - } - - /** - * Decrease the size of the stack in slot (first int arg) by the amount of the second int arg. Returns the new - * stack. - */ - @Override - public ItemStack decrStackSize( final int par1 ) - { - if( this.getHasStack() ) - { - this.amountCrafted += Math.min( par1, this.getStack().stackSize ); - } - - return super.decrStackSize( par1 ); - } +public class AppEngCraftingSlot extends AppEngSlot { + + /** + * The craft matrix inventory linked to this result slot. + */ + private final IInventory craftMatrix; + + /** + * The player that is using the GUI where this slot resides. + */ + private final EntityPlayer thePlayer; + + /** + * The number of items that have been crafted so far. Gets passed to ItemStack.onCrafting before being reset. + */ + private int amountCrafted; + + public AppEngCraftingSlot( + final EntityPlayer par1EntityPlayer, + final IInventory par2IInventory, + final IInventory par3IInventory, + final int par4, + final int par5, + final int par6) { + super(par3IInventory, par4, par5, par6); + this.thePlayer = par1EntityPlayer; + this.craftMatrix = par2IInventory; + } + + /** + * Check if the stack is a valid item for this slot. Always true beside for the armor slots. + */ + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } + + /** + * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. Typically increases an + * internal count then calls onCrafting(item). + */ + @Override + protected void onCrafting(final ItemStack par1ItemStack, final int par2) { + this.amountCrafted += par2; + this.onCrafting(par1ItemStack); + } + + /** + * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. + */ + @Override + protected void onCrafting(final ItemStack par1ItemStack) { + par1ItemStack.onCrafting(this.thePlayer.worldObj, this.thePlayer, this.amountCrafted); + this.amountCrafted = 0; + + if (par1ItemStack.getItem() == Item.getItemFromBlock(Blocks.crafting_table)) { + this.thePlayer.addStat(AchievementList.buildWorkBench, 1); + } + + if (par1ItemStack.getItem() instanceof ItemPickaxe) { + this.thePlayer.addStat(AchievementList.buildPickaxe, 1); + } + + if (par1ItemStack.getItem() == Item.getItemFromBlock(Blocks.furnace)) { + this.thePlayer.addStat(AchievementList.buildFurnace, 1); + } + + if (par1ItemStack.getItem() instanceof ItemHoe) { + this.thePlayer.addStat(AchievementList.buildHoe, 1); + } + + if (par1ItemStack.getItem() == Items.bread) { + this.thePlayer.addStat(AchievementList.makeBread, 1); + } + + if (par1ItemStack.getItem() == Items.cake) { + this.thePlayer.addStat(AchievementList.bakeCake, 1); + } + + if (par1ItemStack.getItem() instanceof ItemPickaxe + && ((ItemTool) par1ItemStack.getItem()).func_150913_i() != Item.ToolMaterial.WOOD) { + this.thePlayer.addStat(AchievementList.buildBetterPickaxe, 1); + } + + if (par1ItemStack.getItem() instanceof ItemSword) { + this.thePlayer.addStat(AchievementList.buildSword, 1); + } + + if (par1ItemStack.getItem() == Item.getItemFromBlock(Blocks.enchanting_table)) { + this.thePlayer.addStat(AchievementList.enchantments, 1); + } + + if (par1ItemStack.getItem() == Item.getItemFromBlock(Blocks.bookshelf)) { + this.thePlayer.addStat(AchievementList.bookcase, 1); + } + } + + @Override + public void onPickupFromSlot(final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack) { + FMLCommonHandler.instance().firePlayerCraftingEvent(par1EntityPlayer, par2ItemStack, this.craftMatrix); + this.onCrafting(par2ItemStack); + + for (int i = 0; i < this.craftMatrix.getSizeInventory(); ++i) { + final ItemStack itemstack1 = this.craftMatrix.getStackInSlot(i); + + if (itemstack1 != null) { + this.craftMatrix.decrStackSize(i, 1); + + if (itemstack1.getItem().hasContainerItem(itemstack1)) { + final ItemStack itemstack2 = itemstack1.getItem().getContainerItem(itemstack1); + + if (itemstack2 != null + && itemstack2.isItemStackDamageable() + && itemstack2.getItemDamage() > itemstack2.getMaxDamage()) { + MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(this.thePlayer, itemstack2)); + continue; + } + + if (!itemstack1.getItem().doesContainerItemLeaveCraftingGrid(itemstack1) + || !this.thePlayer.inventory.addItemStackToInventory(itemstack2)) { + if (this.craftMatrix.getStackInSlot(i) == null) { + this.craftMatrix.setInventorySlotContents(i, itemstack2); + } else { + this.thePlayer.dropPlayerItemWithRandomChoice(itemstack2, false); + } + } + } + } + } + } + + /** + * Decrease the size of the stack in slot (first int arg) by the amount of the second int arg. Returns the new + * stack. + */ + @Override + public ItemStack decrStackSize(final int par1) { + if (this.getHasStack()) { + this.amountCrafted += Math.min(par1, this.getStack().stackSize); + } + + return super.decrStackSize(par1); + } } diff --git a/src/main/java/appeng/container/slot/AppEngSlot.java b/src/main/java/appeng/container/slot/AppEngSlot.java index 5b950108e1a..e2397076707 100644 --- a/src/main/java/appeng/container/slot/AppEngSlot.java +++ b/src/main/java/appeng/container/slot/AppEngSlot.java @@ -18,7 +18,6 @@ package appeng.container.slot; - import appeng.container.AEBaseContainer; import appeng.tile.inventory.AppEngInternalInventory; import net.minecraft.entity.player.EntityPlayer; @@ -26,227 +25,185 @@ import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; - -public class AppEngSlot extends Slot -{ - - private final int defX; - private final int defY; - private boolean isDraggable = true; - private boolean isPlayerSide = false; - private AEBaseContainer myContainer = null; - private int IIcon = -1; - private hasCalculatedValidness isValid; - private boolean isDisplay = false; - - public AppEngSlot( final IInventory inv, final int idx, final int x, final int y ) - { - super( inv, idx, x, y ); - this.defX = x; - this.defY = y; - this.setIsValid( hasCalculatedValidness.NotAvailable ); - } - - public Slot setNotDraggable() - { - this.setDraggable( false ); - return this; - } - - public Slot setPlayerSide() - { - this.isPlayerSide = true; - return this; - } - - public String getTooltip() - { - return null; - } - - public void clearStack() - { - super.putStack( null ); - } - - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - if( this.isEnabled() ) - { - return super.isItemValid( par1ItemStack ); - } - return false; - } - - @Override - public ItemStack getStack() - { - if( !this.isEnabled() ) - { - return null; - } - - if( this.inventory.getSizeInventory() <= this.getSlotIndex() ) - { - return null; - } - - if( this.isDisplay() ) - { - this.setDisplay( false ); - return this.getDisplayStack(); - } - return super.getStack(); - } - - @Override - public void putStack( final ItemStack par1ItemStack ) - { - if( this.isEnabled() ) - { - super.putStack( par1ItemStack ); - - if( this.getContainer() != null ) - { - this.getContainer().onSlotChange( this ); - } - } - } - - @Override - public void onSlotChanged() - { - if( this.inventory instanceof AppEngInternalInventory ) - { - ( (AppEngInternalInventory) this.inventory ).markDirty( this.getSlotIndex() ); - } - else - { - super.onSlotChanged(); - } - - this.setIsValid( hasCalculatedValidness.NotAvailable ); - } - - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - if( this.isEnabled() ) - { - return super.canTakeStack( par1EntityPlayer ); - } - return false; - } - - @Override - public boolean func_111238_b() - { - return this.isEnabled(); - } - - public ItemStack getDisplayStack() - { - return super.getStack(); - } - - public boolean isEnabled() - { - return true; - } - - public float getOpacityOfIcon() - { - return 0.4f; - } - - public boolean renderIconWithItem() - { - return false; - } - - public int getIcon() - { - return this.getIIcon(); - } - - public boolean isPlayerSide() - { - return this.isPlayerSide; - } - - public boolean shouldDisplay() - { - return this.isEnabled(); - } - - public int getX() - { - return this.defX; - } - - public int getY() - { - return this.defY; - } - - private int getIIcon() - { - return this.IIcon; - } - - public void setIIcon( final int iIcon ) - { - this.IIcon = iIcon; - } - - private boolean isDisplay() - { - return this.isDisplay; - } - - public void setDisplay( final boolean isDisplay ) - { - this.isDisplay = isDisplay; - } - - public boolean isDraggable() - { - return this.isDraggable; - } - - private void setDraggable( final boolean isDraggable ) - { - this.isDraggable = isDraggable; - } - - void setPlayerSide( final boolean isPlayerSide ) - { - this.isPlayerSide = isPlayerSide; - } - - public hasCalculatedValidness getIsValid() - { - return this.isValid; - } - - public void setIsValid( final hasCalculatedValidness isValid ) - { - this.isValid = isValid; - } - - AEBaseContainer getContainer() - { - return this.myContainer; - } - - public void setContainer( final AEBaseContainer myContainer ) - { - this.myContainer = myContainer; - } - - public enum hasCalculatedValidness - { - NotAvailable, Valid, Invalid - } +public class AppEngSlot extends Slot { + + private final int defX; + private final int defY; + private boolean isDraggable = true; + private boolean isPlayerSide = false; + private AEBaseContainer myContainer = null; + private int IIcon = -1; + private hasCalculatedValidness isValid; + private boolean isDisplay = false; + + public AppEngSlot(final IInventory inv, final int idx, final int x, final int y) { + super(inv, idx, x, y); + this.defX = x; + this.defY = y; + this.setIsValid(hasCalculatedValidness.NotAvailable); + } + + public Slot setNotDraggable() { + this.setDraggable(false); + return this; + } + + public Slot setPlayerSide() { + this.isPlayerSide = true; + return this; + } + + public String getTooltip() { + return null; + } + + public void clearStack() { + super.putStack(null); + } + + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + if (this.isEnabled()) { + return super.isItemValid(par1ItemStack); + } + return false; + } + + @Override + public ItemStack getStack() { + if (!this.isEnabled()) { + return null; + } + + if (this.inventory.getSizeInventory() <= this.getSlotIndex()) { + return null; + } + + if (this.isDisplay()) { + this.setDisplay(false); + return this.getDisplayStack(); + } + return super.getStack(); + } + + @Override + public void putStack(final ItemStack par1ItemStack) { + if (this.isEnabled()) { + super.putStack(par1ItemStack); + + if (this.getContainer() != null) { + this.getContainer().onSlotChange(this); + } + } + } + + @Override + public void onSlotChanged() { + if (this.inventory instanceof AppEngInternalInventory) { + ((AppEngInternalInventory) this.inventory).markDirty(this.getSlotIndex()); + } else { + super.onSlotChanged(); + } + + this.setIsValid(hasCalculatedValidness.NotAvailable); + } + + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + if (this.isEnabled()) { + return super.canTakeStack(par1EntityPlayer); + } + return false; + } + + @Override + public boolean func_111238_b() { + return this.isEnabled(); + } + + public ItemStack getDisplayStack() { + return super.getStack(); + } + + public boolean isEnabled() { + return true; + } + + public float getOpacityOfIcon() { + return 0.4f; + } + + public boolean renderIconWithItem() { + return false; + } + + public int getIcon() { + return this.getIIcon(); + } + + public boolean isPlayerSide() { + return this.isPlayerSide; + } + + public boolean shouldDisplay() { + return this.isEnabled(); + } + + public int getX() { + return this.defX; + } + + public int getY() { + return this.defY; + } + + private int getIIcon() { + return this.IIcon; + } + + public void setIIcon(final int iIcon) { + this.IIcon = iIcon; + } + + private boolean isDisplay() { + return this.isDisplay; + } + + public void setDisplay(final boolean isDisplay) { + this.isDisplay = isDisplay; + } + + public boolean isDraggable() { + return this.isDraggable; + } + + private void setDraggable(final boolean isDraggable) { + this.isDraggable = isDraggable; + } + + void setPlayerSide(final boolean isPlayerSide) { + this.isPlayerSide = isPlayerSide; + } + + public hasCalculatedValidness getIsValid() { + return this.isValid; + } + + public void setIsValid(final hasCalculatedValidness isValid) { + this.isValid = isValid; + } + + AEBaseContainer getContainer() { + return this.myContainer; + } + + public void setContainer(final AEBaseContainer myContainer) { + this.myContainer = myContainer; + } + + public enum hasCalculatedValidness { + NotAvailable, + Valid, + Invalid + } } diff --git a/src/main/java/appeng/container/slot/IOptionalSlotHost.java b/src/main/java/appeng/container/slot/IOptionalSlotHost.java index 995959ce039..72102091b33 100644 --- a/src/main/java/appeng/container/slot/IOptionalSlotHost.java +++ b/src/main/java/appeng/container/slot/IOptionalSlotHost.java @@ -18,9 +18,7 @@ package appeng.container.slot; +public interface IOptionalSlotHost { -public interface IOptionalSlotHost -{ - - boolean isSlotEnabled( int idx ); + boolean isSlotEnabled(int idx); } diff --git a/src/main/java/appeng/container/slot/NullSlot.java b/src/main/java/appeng/container/slot/NullSlot.java index c018203b908..ff0f827a0b2 100644 --- a/src/main/java/appeng/container/slot/NullSlot.java +++ b/src/main/java/appeng/container/slot/NullSlot.java @@ -18,84 +18,61 @@ package appeng.container.slot; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; +public class NullSlot extends Slot { -public class NullSlot extends Slot -{ - - public NullSlot() - { - super( null, 0, 0, 0 ); - } - - @Override - public void onSlotChange( final ItemStack par1ItemStack, final ItemStack par2ItemStack ) - { - - } - - @Override - public void onPickupFromSlot( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) - { - - } + public NullSlot() { + super(null, 0, 0, 0); + } - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } + @Override + public void onSlotChange(final ItemStack par1ItemStack, final ItemStack par2ItemStack) {} - @Override - public ItemStack getStack() - { - return null; - } + @Override + public void onPickupFromSlot(final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack) {} - @Override - public void putStack( final ItemStack par1ItemStack ) - { + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - } + @Override + public ItemStack getStack() { + return null; + } - @Override - public void onSlotChanged() - { + @Override + public void putStack(final ItemStack par1ItemStack) {} - } + @Override + public void onSlotChanged() {} - @Override - public int getSlotStackLimit() - { - return 0; - } + @Override + public int getSlotStackLimit() { + return 0; + } - @Override - public ItemStack decrStackSize( final int par1 ) - { - return null; - } + @Override + public ItemStack decrStackSize(final int par1) { + return null; + } - @Override - public boolean isSlotInInventory( final IInventory par1IInventory, final int par2 ) - { - return false; - } + @Override + public boolean isSlotInInventory(final IInventory par1IInventory, final int par2) { + return false; + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } - @Override - public int getSlotIndex() - { - return 0; - } + @Override + public int getSlotIndex() { + return 0; + } } diff --git a/src/main/java/appeng/container/slot/OptionalSlotFake.java b/src/main/java/appeng/container/slot/OptionalSlotFake.java index d2e5d3a639f..4a1e0f506f4 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotFake.java +++ b/src/main/java/appeng/container/slot/OptionalSlotFake.java @@ -18,76 +18,70 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - -public class OptionalSlotFake extends SlotFake -{ - - private final int srcX; - private final int srcY; - private final int groupNum; - private final IOptionalSlotHost host; - private boolean renderDisabled = true; - - public OptionalSlotFake( final IInventory inv, final IOptionalSlotHost containerBus, final int idx, final int x, final int y, final int offX, final int offY, final int groupNum ) - { - super( inv, idx, x + offX * 18, y + offY * 18 ); - this.srcX = x; - this.srcY = y; - this.groupNum = groupNum; - this.host = containerBus; - } - - @Override - public ItemStack getStack() - { - if( !this.isEnabled() ) - { - if( this.getDisplayStack() != null ) - { - this.clearStack(); - } - } - - return super.getStack(); - } - - @Override - public boolean isEnabled() - { - if( this.host == null ) - { - return false; - } - - return this.host.isSlotEnabled( this.groupNum ); - } - - public boolean renderDisabled() - { - return this.isRenderDisabled(); - } - - private boolean isRenderDisabled() - { - return this.renderDisabled; - } - - public void setRenderDisabled( final boolean renderDisabled ) - { - this.renderDisabled = renderDisabled; - } - - public int getSourceX() - { - return this.srcX; - } - - public int getSourceY() - { - return this.srcY; - } +public class OptionalSlotFake extends SlotFake { + + private final int srcX; + private final int srcY; + private final int groupNum; + private final IOptionalSlotHost host; + private boolean renderDisabled = true; + + public OptionalSlotFake( + final IInventory inv, + final IOptionalSlotHost containerBus, + final int idx, + final int x, + final int y, + final int offX, + final int offY, + final int groupNum) { + super(inv, idx, x + offX * 18, y + offY * 18); + this.srcX = x; + this.srcY = y; + this.groupNum = groupNum; + this.host = containerBus; + } + + @Override + public ItemStack getStack() { + if (!this.isEnabled()) { + if (this.getDisplayStack() != null) { + this.clearStack(); + } + } + + return super.getStack(); + } + + @Override + public boolean isEnabled() { + if (this.host == null) { + return false; + } + + return this.host.isSlotEnabled(this.groupNum); + } + + public boolean renderDisabled() { + return this.isRenderDisabled(); + } + + private boolean isRenderDisabled() { + return this.renderDisabled; + } + + public void setRenderDisabled(final boolean renderDisabled) { + this.renderDisabled = renderDisabled; + } + + public int getSourceX() { + return this.srcX; + } + + public int getSourceY() { + return this.srcY; + } } diff --git a/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java b/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java index 666d9b60478..6cd47705c5a 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java +++ b/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java @@ -18,35 +18,34 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - -public class OptionalSlotFakeTypeOnly extends OptionalSlotFake -{ - - public OptionalSlotFakeTypeOnly( final IInventory inv, final IOptionalSlotHost containerBus, final int idx, final int x, final int y, final int offX, final int offY, final int groupNum ) - { - super( inv, containerBus, idx, x, y, offX, offY, groupNum ); - } - - @Override - public void putStack( ItemStack is ) - { - if( is != null ) - { - is = is.copy(); - if( is.stackSize > 1 ) - { - is.stackSize = 1; - } - else if( is.stackSize < -1 ) - { - is.stackSize = -1; - } - } - - super.putStack( is ); - } +public class OptionalSlotFakeTypeOnly extends OptionalSlotFake { + + public OptionalSlotFakeTypeOnly( + final IInventory inv, + final IOptionalSlotHost containerBus, + final int idx, + final int x, + final int y, + final int offX, + final int offY, + final int groupNum) { + super(inv, containerBus, idx, x, y, offX, offY, groupNum); + } + + @Override + public void putStack(ItemStack is) { + if (is != null) { + is = is.copy(); + if (is.stackSize > 1) { + is.stackSize = 1; + } else if (is.stackSize < -1) { + is.stackSize = -1; + } + } + + super.putStack(is); + } } diff --git a/src/main/java/appeng/container/slot/OptionalSlotNormal.java b/src/main/java/appeng/container/slot/OptionalSlotNormal.java index 95247c9efbe..8bca16eea2a 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotNormal.java +++ b/src/main/java/appeng/container/slot/OptionalSlotNormal.java @@ -18,31 +18,31 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; - -public class OptionalSlotNormal extends AppEngSlot -{ - - private final int groupNum; - private final IOptionalSlotHost host; - - public OptionalSlotNormal( final IInventory inv, final IOptionalSlotHost containerBus, final int slot, final int xPos, final int yPos, final int groupNum ) - { - super( inv, slot, xPos, yPos ); - this.groupNum = groupNum; - this.host = containerBus; - } - - @Override - public boolean isEnabled() - { - if( this.host == null ) - { - return false; - } - - return this.host.isSlotEnabled( this.groupNum ); - } +public class OptionalSlotNormal extends AppEngSlot { + + private final int groupNum; + private final IOptionalSlotHost host; + + public OptionalSlotNormal( + final IInventory inv, + final IOptionalSlotHost containerBus, + final int slot, + final int xPos, + final int yPos, + final int groupNum) { + super(inv, slot, xPos, yPos); + this.groupNum = groupNum; + this.host = containerBus; + } + + @Override + public boolean isEnabled() { + if (this.host == null) { + return false; + } + + return this.host.isSlotEnabled(this.groupNum); + } } diff --git a/src/main/java/appeng/container/slot/OptionalSlotRestrictedInput.java b/src/main/java/appeng/container/slot/OptionalSlotRestrictedInput.java index a9c994af9ec..1e9b81304a6 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotRestrictedInput.java +++ b/src/main/java/appeng/container/slot/OptionalSlotRestrictedInput.java @@ -18,32 +18,34 @@ package appeng.container.slot; - import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; - -public class OptionalSlotRestrictedInput extends SlotRestrictedInput -{ - - private final int groupNum; - private final IOptionalSlotHost host; - - public OptionalSlotRestrictedInput( final PlacableItemType valid, final IInventory i, final IOptionalSlotHost host, final int slotIndex, final int x, final int y, final int grpNum, final InventoryPlayer invPlayer ) - { - super( valid, i, slotIndex, x, y, invPlayer ); - this.groupNum = grpNum; - this.host = host; - } - - @Override - public boolean isEnabled() - { - if( this.host == null ) - { - return false; - } - - return this.host.isSlotEnabled( this.groupNum ); - } +public class OptionalSlotRestrictedInput extends SlotRestrictedInput { + + private final int groupNum; + private final IOptionalSlotHost host; + + public OptionalSlotRestrictedInput( + final PlacableItemType valid, + final IInventory i, + final IOptionalSlotHost host, + final int slotIndex, + final int x, + final int y, + final int grpNum, + final InventoryPlayer invPlayer) { + super(valid, i, slotIndex, x, y, invPlayer); + this.groupNum = grpNum; + this.host = host; + } + + @Override + public boolean isEnabled() { + if (this.host == null) { + return false; + } + + return this.host.isSlotEnabled(this.groupNum); + } } diff --git a/src/main/java/appeng/container/slot/QuartzKnifeOutput.java b/src/main/java/appeng/container/slot/QuartzKnifeOutput.java index 319d479a43a..d17a140e486 100644 --- a/src/main/java/appeng/container/slot/QuartzKnifeOutput.java +++ b/src/main/java/appeng/container/slot/QuartzKnifeOutput.java @@ -18,15 +18,11 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; +public class QuartzKnifeOutput extends SlotOutput { -public class QuartzKnifeOutput extends SlotOutput -{ - - public QuartzKnifeOutput( final IInventory a, final int b, final int c, final int d, final int i ) - { - super( a, b, c, d, i ); - } + public QuartzKnifeOutput(final IInventory a, final int b, final int c, final int d, final int i) { + super(a, b, c, d, i); + } } diff --git a/src/main/java/appeng/container/slot/SlotCraftingMatrix.java b/src/main/java/appeng/container/slot/SlotCraftingMatrix.java index e87320a5207..28fe3dae9ab 100644 --- a/src/main/java/appeng/container/slot/SlotCraftingMatrix.java +++ b/src/main/java/appeng/container/slot/SlotCraftingMatrix.java @@ -18,48 +18,41 @@ package appeng.container.slot; - import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - -public class SlotCraftingMatrix extends AppEngSlot -{ - - private final Container c; - - public SlotCraftingMatrix( final Container c, final IInventory par1iInventory, final int par2, final int par3, final int par4 ) - { - super( par1iInventory, par2, par3, par4 ); - this.c = c; - } - - @Override - public void clearStack() - { - super.clearStack(); - this.c.onCraftMatrixChanged( this.inventory ); - } - - @Override - public void putStack( final ItemStack par1ItemStack ) - { - super.putStack( par1ItemStack ); - this.c.onCraftMatrixChanged( this.inventory ); - } - - @Override - public boolean isPlayerSide() - { - return true; - } - - @Override - public ItemStack decrStackSize( final int par1 ) - { - final ItemStack is = super.decrStackSize( par1 ); - this.c.onCraftMatrixChanged( this.inventory ); - return is; - } +public class SlotCraftingMatrix extends AppEngSlot { + + private final Container c; + + public SlotCraftingMatrix( + final Container c, final IInventory par1iInventory, final int par2, final int par3, final int par4) { + super(par1iInventory, par2, par3, par4); + this.c = c; + } + + @Override + public void clearStack() { + super.clearStack(); + this.c.onCraftMatrixChanged(this.inventory); + } + + @Override + public void putStack(final ItemStack par1ItemStack) { + super.putStack(par1ItemStack); + this.c.onCraftMatrixChanged(this.inventory); + } + + @Override + public boolean isPlayerSide() { + return true; + } + + @Override + public ItemStack decrStackSize(final int par1) { + final ItemStack is = super.decrStackSize(par1); + this.c.onCraftMatrixChanged(this.inventory); + return is; + } } diff --git a/src/main/java/appeng/container/slot/SlotCraftingTerm.java b/src/main/java/appeng/container/slot/SlotCraftingTerm.java index c287b9c5a64..f5a142122b6 100644 --- a/src/main/java/appeng/container/slot/SlotCraftingTerm.java +++ b/src/main/java/appeng/container/slot/SlotCraftingTerm.java @@ -18,7 +18,6 @@ package appeng.container.slot; - import appeng.api.config.Actionable; import appeng.api.networking.energy.IEnergySource; import appeng.api.networking.security.BaseActionSource; @@ -35,6 +34,8 @@ import appeng.util.inv.AdaptorPlayerHand; import appeng.util.item.AEItemStack; import appeng.util.prioitylist.IPartitionList; +import java.util.ArrayList; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; @@ -42,296 +43,284 @@ import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; -import java.util.ArrayList; -import java.util.List; - - -public class SlotCraftingTerm extends AppEngCraftingSlot -{ - - private final IInventory craftInv; - private final IInventory pattern; - - private final BaseActionSource mySrc; - private final IEnergySource energySrc; - private final IStorageMonitorable storage; - private final IContainerCraftingPacket container; - - public SlotCraftingTerm( final EntityPlayer player, final BaseActionSource mySrc, final IEnergySource energySrc, final IStorageMonitorable storage, final IInventory cMatrix, final IInventory secondMatrix, final IInventory output, final int x, final int y, final IContainerCraftingPacket ccp ) - { - super( player, cMatrix, output, 0, x, y ); - this.energySrc = energySrc; - this.storage = storage; - this.mySrc = mySrc; - this.pattern = cMatrix; - this.craftInv = secondMatrix; - this.container = ccp; - } - - public IInventory getCraftingMatrix() - { - return this.craftInv; - } - - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } - - @Override - public void onPickupFromSlot( final EntityPlayer p, final ItemStack is ) - { - } - - public void doClick( final InventoryAction action, final EntityPlayer who ) - { - if( this.getStack() == null ) - { - return; - } - if( Platform.isClient() ) - { - return; - } - - final IMEMonitor inv = this.storage.getItemInventory(); - final int howManyPerCraft = this.getStack().stackSize; - int maxTimesToCraft = 0; - - InventoryAdaptor ia = null; - if( action == InventoryAction.CRAFT_SHIFT ) // craft into player inventory... - { - ia = InventoryAdaptor.getAdaptor( who, null ); - maxTimesToCraft = (int) Math.floor( (double) this.getStack().getMaxStackSize() / (double) howManyPerCraft ); - } - else if( action == InventoryAction.CRAFT_STACK ) // craft into hand, full stack - { - ia = new AdaptorPlayerHand( who ); - maxTimesToCraft = (int) Math.floor( (double) this.getStack().getMaxStackSize() / (double) howManyPerCraft ); - } - else - // pick up what was crafted... - { - ia = new AdaptorPlayerHand( who ); - maxTimesToCraft = 1; - } - - maxTimesToCraft = this.capCraftingAttempts( maxTimesToCraft ); - - if( ia == null ) - return; - - final ItemStack rs = Platform.cloneItemStack( this.getStack() ); - if( rs == null ) - return; - rs.stackSize *= maxTimesToCraft; - if( ia.simulateAdd( rs ) != null ) - return; - final IItemList all = inv.getStorageList(); - do { - ItemStack res = this.craftItem(who, rs, inv, all); - if (res == null) - break; - rs.stackSize -= res.stackSize; - final ItemStack extra = ia.addItems(res); - if (extra != null) { - final List drops = new ArrayList(); - drops.add(extra); - Platform.spawnDrops(who.worldObj, (int) who.posX, (int) who.posY, (int) who.posZ, drops); - break; - } - } - while (rs.stackSize > 0); - } - - private int capCraftingAttempts( final int maxTimesToCraft ) - { - return maxTimesToCraft; - } - - private ItemStack craftItem( final EntityPlayer p, final ItemStack request, final IMEMonitor inv, final IItemList all ) - { - // update crafting matrix... - ItemStack is = this.getStack(); - - if( is != null && Platform.isSameItem( request, is ) ) - { - final ItemStack[] set = new ItemStack[this.getPattern().getSizeInventory()]; - int multiple = request.stackSize / is.stackSize; - - // add one of each item to the items on the board... - if( Platform.isServer() ) - { - final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); - for( int x = 0; x < 9; x++ ) - { - ic.setInventorySlotContents( x, this.getPattern().getStackInSlot( x ) ); - } - - final IRecipe r = Platform.findMatchingRecipe(ic, p.worldObj); - - if( r == null ) - { - if (request.stackSize > is.stackSize) // do not try to batch invalid recipes - return null; - final Item target = request.getItem(); - if( target.isDamageable() && target.isRepairable() ) - { - boolean isBad = false; - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - final ItemStack pis = ic.getStackInSlot( x ); - if( pis == null ) - { - continue; - } - if( pis.getItem() != target ) - { - isBad = true; - } - } - if( !isBad ) - { - super.onPickupFromSlot( p, is ); - // actually necessary to cleanup this case... - p.openContainer.onCraftMatrixChanged( this.craftInv ); - return request; - } - } - return null; - } - - is = r.getCraftingResult( ic ); - - if( inv != null ) - { - IPartitionList filter = ItemViewCell.createFilter( this.container.getViewCells() ); - if (!extractItems(p, inv, all, is, set, multiple, ic, r, filter)) - { - cleanup(p, inv, set); - multiple = 1; - extractItems(p, inv, all, is, set, 1, ic, r, filter); - } - } - } - - int crafted = 0; - if( this.preCraft( p, inv, set, is ) ) - { - for (int i = 0; i < multiple; ++i) - { - this.makeItem(p, is); - ++crafted; - // last craft may use up all the rest of the items in the system - // otherwise we need to leave the grid repopulated, to try another extraction & recipe match - if (!this.postCraft(p, inv, set, is) && i < (multiple-1)) - break; - } - } - is.stackSize *= crafted; - cleanup(p, inv, set); - - // shouldn't be necessary... - p.openContainer.onCraftMatrixChanged( this.craftInv ); - - return is; - } - - return null; - } - - private boolean extractItems(EntityPlayer p, IMEMonitor inv, IItemList all, ItemStack is, ItemStack[] set, int multiple, InventoryCrafting ic, IRecipe r, IPartitionList filter) { - for( int x = 0; x < this.getPattern().getSizeInventory(); x++ ) - { - if( this.getPattern().getStackInSlot( x ) != null ) - { - set[x] = Platform.extractItemsByRecipe( this.energySrc, this.mySrc, inv, p.worldObj, r, is, ic, this.getPattern().getStackInSlot( x ), x, all, Actionable.MODULATE, filter, multiple); - if (set[x] == null) { - if (multiple > 1) - return false; - set[x] = this.getPattern().getStackInSlot( x ).copy(); - set[x].stackSize = 0; - } - } - } - return true; - } - - private boolean preCraft( final EntityPlayer p, final IMEMonitor inv, final ItemStack[] set, final ItemStack result ) - { - return true; - } - - private void makeItem( final EntityPlayer p, final ItemStack is ) - { - super.onPickupFromSlot( p, is ); - } - - private boolean postCraft( final EntityPlayer p, final IMEMonitor inv, final ItemStack[] set, final ItemStack result ) - { - final List drops = new ArrayList(); - - boolean hadEmptyStacks = false; - // add one of each item to the items on the board... - if( Platform.isServer() ) - { - // set new items onto the crafting table... - for( int x = 0; x < this.craftInv.getSizeInventory(); x++ ) - { - if( this.craftInv.getStackInSlot( x ) == null ) - { - if (set[x] != null) { - if (set[x].stackSize > 0) { - ItemStack s = set[x].copy(); - s.stackSize = 1; - this.craftInv.setInventorySlotContents(x, s); - --set[x].stackSize; - } - hadEmptyStacks |= set[x].stackSize == 0; - } - } - else if( set[x] != null ) - { - if (!Platform.isSameItem(this.craftInv.getStackInSlot( x ), set[x])) { - // for the recipes that leave e.g. empty buckets in the grid, can't batch them - final IAEItemStack fail = inv.injectItems(AEItemStack.create(set[x]), Actionable.MODULATE, this.mySrc); - if (fail != null) { - drops.add(fail.getItemStack()); - } - set[x] = null; - hadEmptyStacks = true; - } - } - } - } - - if( drops.size() > 0 ) - { - Platform.spawnDrops( p.worldObj, (int) p.posX, (int) p.posY, (int) p.posZ, drops ); - } - return !hadEmptyStacks; - } - private void cleanup(final EntityPlayer p, final IMEMonitor inv, final ItemStack[] set) - { - if( Platform.isServer() ) { - final List drops = new ArrayList(); - for (int i = 0; i < set.length; ++i) { - if (set[i] != null && set[i].stackSize > 0) { - final IAEItemStack fail = inv.injectItems(AEItemStack.create(set[i]), Actionable.MODULATE, this.mySrc); - if (fail != null) { - drops.add(fail.getItemStack()); - } - } - } - if (drops.size() > 0) { - Platform.spawnDrops(p.worldObj, (int) p.posX, (int) p.posY, (int) p.posZ, drops); - } - } - } - - IInventory getPattern() - { - return this.pattern; - } +public class SlotCraftingTerm extends AppEngCraftingSlot { + + private final IInventory craftInv; + private final IInventory pattern; + + private final BaseActionSource mySrc; + private final IEnergySource energySrc; + private final IStorageMonitorable storage; + private final IContainerCraftingPacket container; + + public SlotCraftingTerm( + final EntityPlayer player, + final BaseActionSource mySrc, + final IEnergySource energySrc, + final IStorageMonitorable storage, + final IInventory cMatrix, + final IInventory secondMatrix, + final IInventory output, + final int x, + final int y, + final IContainerCraftingPacket ccp) { + super(player, cMatrix, output, 0, x, y); + this.energySrc = energySrc; + this.storage = storage; + this.mySrc = mySrc; + this.pattern = cMatrix; + this.craftInv = secondMatrix; + this.container = ccp; + } + + public IInventory getCraftingMatrix() { + return this.craftInv; + } + + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } + + @Override + public void onPickupFromSlot(final EntityPlayer p, final ItemStack is) {} + + public void doClick(final InventoryAction action, final EntityPlayer who) { + if (this.getStack() == null) { + return; + } + if (Platform.isClient()) { + return; + } + + final IMEMonitor inv = this.storage.getItemInventory(); + final int howManyPerCraft = this.getStack().stackSize; + int maxTimesToCraft = 0; + + InventoryAdaptor ia = null; + if (action == InventoryAction.CRAFT_SHIFT) // craft into player inventory... + { + ia = InventoryAdaptor.getAdaptor(who, null); + maxTimesToCraft = (int) Math.floor((double) this.getStack().getMaxStackSize() / (double) howManyPerCraft); + } else if (action == InventoryAction.CRAFT_STACK) // craft into hand, full stack + { + ia = new AdaptorPlayerHand(who); + maxTimesToCraft = (int) Math.floor((double) this.getStack().getMaxStackSize() / (double) howManyPerCraft); + } else + // pick up what was crafted... + { + ia = new AdaptorPlayerHand(who); + maxTimesToCraft = 1; + } + + maxTimesToCraft = this.capCraftingAttempts(maxTimesToCraft); + + if (ia == null) return; + + final ItemStack rs = Platform.cloneItemStack(this.getStack()); + if (rs == null) return; + rs.stackSize *= maxTimesToCraft; + if (ia.simulateAdd(rs) != null) return; + final IItemList all = inv.getStorageList(); + do { + ItemStack res = this.craftItem(who, rs, inv, all); + if (res == null) break; + rs.stackSize -= res.stackSize; + final ItemStack extra = ia.addItems(res); + if (extra != null) { + final List drops = new ArrayList(); + drops.add(extra); + Platform.spawnDrops(who.worldObj, (int) who.posX, (int) who.posY, (int) who.posZ, drops); + break; + } + } while (rs.stackSize > 0); + } + + private int capCraftingAttempts(final int maxTimesToCraft) { + return maxTimesToCraft; + } + + private ItemStack craftItem( + final EntityPlayer p, final ItemStack request, final IMEMonitor inv, final IItemList all) { + // update crafting matrix... + ItemStack is = this.getStack(); + + if (is != null && Platform.isSameItem(request, is)) { + final ItemStack[] set = new ItemStack[this.getPattern().getSizeInventory()]; + int multiple = request.stackSize / is.stackSize; + + // add one of each item to the items on the board... + if (Platform.isServer()) { + final InventoryCrafting ic = new InventoryCrafting(new ContainerNull(), 3, 3); + for (int x = 0; x < 9; x++) { + ic.setInventorySlotContents(x, this.getPattern().getStackInSlot(x)); + } + + final IRecipe r = Platform.findMatchingRecipe(ic, p.worldObj); + + if (r == null) { + if (request.stackSize > is.stackSize) // do not try to batch invalid recipes + return null; + final Item target = request.getItem(); + if (target.isDamageable() && target.isRepairable()) { + boolean isBad = false; + for (int x = 0; x < ic.getSizeInventory(); x++) { + final ItemStack pis = ic.getStackInSlot(x); + if (pis == null) { + continue; + } + if (pis.getItem() != target) { + isBad = true; + } + } + if (!isBad) { + super.onPickupFromSlot(p, is); + // actually necessary to cleanup this case... + p.openContainer.onCraftMatrixChanged(this.craftInv); + return request; + } + } + return null; + } + + is = r.getCraftingResult(ic); + + if (inv != null) { + IPartitionList filter = ItemViewCell.createFilter(this.container.getViewCells()); + if (!extractItems(p, inv, all, is, set, multiple, ic, r, filter)) { + cleanup(p, inv, set); + multiple = 1; + extractItems(p, inv, all, is, set, 1, ic, r, filter); + } + } + } + + int crafted = 0; + if (this.preCraft(p, inv, set, is)) { + for (int i = 0; i < multiple; ++i) { + this.makeItem(p, is); + ++crafted; + // last craft may use up all the rest of the items in the system + // otherwise we need to leave the grid repopulated, to try another extraction & recipe match + if (!this.postCraft(p, inv, set, is) && i < (multiple - 1)) break; + } + } + is.stackSize *= crafted; + cleanup(p, inv, set); + + // shouldn't be necessary... + p.openContainer.onCraftMatrixChanged(this.craftInv); + + return is; + } + + return null; + } + + private boolean extractItems( + EntityPlayer p, + IMEMonitor inv, + IItemList all, + ItemStack is, + ItemStack[] set, + int multiple, + InventoryCrafting ic, + IRecipe r, + IPartitionList filter) { + for (int x = 0; x < this.getPattern().getSizeInventory(); x++) { + if (this.getPattern().getStackInSlot(x) != null) { + set[x] = Platform.extractItemsByRecipe( + this.energySrc, + this.mySrc, + inv, + p.worldObj, + r, + is, + ic, + this.getPattern().getStackInSlot(x), + x, + all, + Actionable.MODULATE, + filter, + multiple); + if (set[x] == null) { + if (multiple > 1) return false; + set[x] = this.getPattern().getStackInSlot(x).copy(); + set[x].stackSize = 0; + } + } + } + return true; + } + + private boolean preCraft( + final EntityPlayer p, final IMEMonitor inv, final ItemStack[] set, final ItemStack result) { + return true; + } + + private void makeItem(final EntityPlayer p, final ItemStack is) { + super.onPickupFromSlot(p, is); + } + + private boolean postCraft( + final EntityPlayer p, final IMEMonitor inv, final ItemStack[] set, final ItemStack result) { + final List drops = new ArrayList(); + + boolean hadEmptyStacks = false; + // add one of each item to the items on the board... + if (Platform.isServer()) { + // set new items onto the crafting table... + for (int x = 0; x < this.craftInv.getSizeInventory(); x++) { + if (this.craftInv.getStackInSlot(x) == null) { + if (set[x] != null) { + if (set[x].stackSize > 0) { + ItemStack s = set[x].copy(); + s.stackSize = 1; + this.craftInv.setInventorySlotContents(x, s); + --set[x].stackSize; + } + hadEmptyStacks |= set[x].stackSize == 0; + } + } else if (set[x] != null) { + if (!Platform.isSameItem(this.craftInv.getStackInSlot(x), set[x])) { + // for the recipes that leave e.g. empty buckets in the grid, can't batch them + final IAEItemStack fail = + inv.injectItems(AEItemStack.create(set[x]), Actionable.MODULATE, this.mySrc); + if (fail != null) { + drops.add(fail.getItemStack()); + } + set[x] = null; + hadEmptyStacks = true; + } + } + } + } + + if (drops.size() > 0) { + Platform.spawnDrops(p.worldObj, (int) p.posX, (int) p.posY, (int) p.posZ, drops); + } + return !hadEmptyStacks; + } + + private void cleanup(final EntityPlayer p, final IMEMonitor inv, final ItemStack[] set) { + if (Platform.isServer()) { + final List drops = new ArrayList(); + for (int i = 0; i < set.length; ++i) { + if (set[i] != null && set[i].stackSize > 0) { + final IAEItemStack fail = + inv.injectItems(AEItemStack.create(set[i]), Actionable.MODULATE, this.mySrc); + if (fail != null) { + drops.add(fail.getItemStack()); + } + } + } + if (drops.size() > 0) { + Platform.spawnDrops(p.worldObj, (int) p.posX, (int) p.posY, (int) p.posZ, drops); + } + } + } + + IInventory getPattern() { + return this.pattern; + } } diff --git a/src/main/java/appeng/container/slot/SlotDisabled.java b/src/main/java/appeng/container/slot/SlotDisabled.java index f298e6e7b47..f038cbdb1f2 100644 --- a/src/main/java/appeng/container/slot/SlotDisabled.java +++ b/src/main/java/appeng/container/slot/SlotDisabled.java @@ -18,29 +18,23 @@ package appeng.container.slot; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public class SlotDisabled extends AppEngSlot { -public class SlotDisabled extends AppEngSlot -{ - - public SlotDisabled( final IInventory par1iInventory, final int slotIndex, final int x, final int y ) - { - super( par1iInventory, slotIndex, x, y ); - } + public SlotDisabled(final IInventory par1iInventory, final int slotIndex, final int x, final int y) { + super(par1iInventory, slotIndex, x, y); + } - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } } diff --git a/src/main/java/appeng/container/slot/SlotFake.java b/src/main/java/appeng/container/slot/SlotFake.java index 34b6b897488..a3898386004 100644 --- a/src/main/java/appeng/container/slot/SlotFake.java +++ b/src/main/java/appeng/container/slot/SlotFake.java @@ -18,61 +18,48 @@ package appeng.container.slot; - import appeng.api.storage.data.IAEItemStack; import appeng.util.item.AEItemStack; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - -public class SlotFake extends AppEngSlot -{ +public class SlotFake extends AppEngSlot { private IAEItemStack aeStack; - public SlotFake( final IInventory inv, final int idx, final int x, final int y ) - { - super( inv, idx, x, y ); - } + public SlotFake(final IInventory inv, final int idx, final int x, final int y) { + super(inv, idx, x, y); + } - @Override - public void onPickupFromSlot( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) - { - } + @Override + public void onPickupFromSlot(final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack) {} - @Override - public ItemStack decrStackSize( final int par1 ) - { - return null; - } + @Override + public ItemStack decrStackSize(final int par1) { + return null; + } - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - @Override - public void putStack( ItemStack is ) - { - if( is != null ) - { - is = is.copy(); - } - this.aeStack = AEItemStack.create( is ); - super.putStack( is ); - } + @Override + public void putStack(ItemStack is) { + if (is != null) { + is = is.copy(); + } + this.aeStack = AEItemStack.create(is); + super.putStack(is); + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } - public IAEItemStack getAEStack() - { + public IAEItemStack getAEStack() { return aeStack; } - } diff --git a/src/main/java/appeng/container/slot/SlotFakeBlacklist.java b/src/main/java/appeng/container/slot/SlotFakeBlacklist.java index b0d9ba51806..0e3e7b97ae1 100644 --- a/src/main/java/appeng/container/slot/SlotFakeBlacklist.java +++ b/src/main/java/appeng/container/slot/SlotFakeBlacklist.java @@ -18,37 +18,29 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; - -public class SlotFakeBlacklist extends SlotFakeTypeOnly -{ - - public SlotFakeBlacklist( final IInventory inv, final int idx, final int x, final int y ) - { - super( inv, idx, x, y ); - } - - @Override - public float getOpacityOfIcon() - { - return 0.8f; - } - - @Override - public boolean renderIconWithItem() - { - return true; - } - - @Override - public int getIcon() - { - if( this.getHasStack() ) - { - return this.getStack().stackSize > 0 ? 16 + 14 : 14; - } - return -1; - } +public class SlotFakeBlacklist extends SlotFakeTypeOnly { + + public SlotFakeBlacklist(final IInventory inv, final int idx, final int x, final int y) { + super(inv, idx, x, y); + } + + @Override + public float getOpacityOfIcon() { + return 0.8f; + } + + @Override + public boolean renderIconWithItem() { + return true; + } + + @Override + public int getIcon() { + if (this.getHasStack()) { + return this.getStack().stackSize > 0 ? 16 + 14 : 14; + } + return -1; + } } diff --git a/src/main/java/appeng/container/slot/SlotFakeCraftingMatrix.java b/src/main/java/appeng/container/slot/SlotFakeCraftingMatrix.java index e1bf15b222f..a9f058efb31 100644 --- a/src/main/java/appeng/container/slot/SlotFakeCraftingMatrix.java +++ b/src/main/java/appeng/container/slot/SlotFakeCraftingMatrix.java @@ -18,15 +18,11 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; +public class SlotFakeCraftingMatrix extends SlotFake { -public class SlotFakeCraftingMatrix extends SlotFake -{ - - public SlotFakeCraftingMatrix( final IInventory inv, final int idx, final int x, final int y ) - { - super( inv, idx, x, y ); - } + public SlotFakeCraftingMatrix(final IInventory inv, final int idx, final int x, final int y) { + super(inv, idx, x, y); + } } diff --git a/src/main/java/appeng/container/slot/SlotFakeTypeOnly.java b/src/main/java/appeng/container/slot/SlotFakeTypeOnly.java index 809da8ac0ee..afd01cdd4dd 100644 --- a/src/main/java/appeng/container/slot/SlotFakeTypeOnly.java +++ b/src/main/java/appeng/container/slot/SlotFakeTypeOnly.java @@ -18,35 +18,26 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - -public class SlotFakeTypeOnly extends SlotFake -{ - - public SlotFakeTypeOnly( final IInventory inv, final int idx, final int x, final int y ) - { - super( inv, idx, x, y ); - } - - @Override - public void putStack( ItemStack is ) - { - if( is != null ) - { - is = is.copy(); - if( is.stackSize > 1 ) - { - is.stackSize = 1; - } - else if( is.stackSize < -1 ) - { - is.stackSize = -1; - } - } - - super.putStack( is ); - } +public class SlotFakeTypeOnly extends SlotFake { + + public SlotFakeTypeOnly(final IInventory inv, final int idx, final int x, final int y) { + super(inv, idx, x, y); + } + + @Override + public void putStack(ItemStack is) { + if (is != null) { + is = is.copy(); + if (is.stackSize > 1) { + is.stackSize = 1; + } else if (is.stackSize < -1) { + is.stackSize = -1; + } + } + + super.putStack(is); + } } diff --git a/src/main/java/appeng/container/slot/SlotInaccessible.java b/src/main/java/appeng/container/slot/SlotInaccessible.java index b385a9c5b97..86511378547 100644 --- a/src/main/java/appeng/container/slot/SlotInaccessible.java +++ b/src/main/java/appeng/container/slot/SlotInaccessible.java @@ -18,52 +18,42 @@ package appeng.container.slot; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - -public class SlotInaccessible extends AppEngSlot -{ - - private ItemStack dspStack = null; - - public SlotInaccessible( final IInventory i, final int slotIdx, final int x, final int y ) - { - super( i, slotIdx, x, y ); - } - - @Override - public boolean isItemValid( final ItemStack i ) - { - return false; - } - - @Override - public void onSlotChanged() - { - super.onSlotChanged(); - this.dspStack = null; - } - - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } - - @Override - public ItemStack getDisplayStack() - { - if( this.dspStack == null ) - { - final ItemStack dsp = super.getDisplayStack(); - if( dsp != null ) - { - this.dspStack = dsp.copy(); - } - } - return this.dspStack; - } +public class SlotInaccessible extends AppEngSlot { + + private ItemStack dspStack = null; + + public SlotInaccessible(final IInventory i, final int slotIdx, final int x, final int y) { + super(i, slotIdx, x, y); + } + + @Override + public boolean isItemValid(final ItemStack i) { + return false; + } + + @Override + public void onSlotChanged() { + super.onSlotChanged(); + this.dspStack = null; + } + + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } + + @Override + public ItemStack getDisplayStack() { + if (this.dspStack == null) { + final ItemStack dsp = super.getDisplayStack(); + if (dsp != null) { + this.dspStack = dsp.copy(); + } + } + return this.dspStack; + } } diff --git a/src/main/java/appeng/container/slot/SlotInaccessibleHD.java b/src/main/java/appeng/container/slot/SlotInaccessibleHD.java index 10d675d48fa..1de9668a3ed 100644 --- a/src/main/java/appeng/container/slot/SlotInaccessibleHD.java +++ b/src/main/java/appeng/container/slot/SlotInaccessibleHD.java @@ -18,15 +18,11 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; +public class SlotInaccessibleHD extends SlotInaccessible { -public class SlotInaccessibleHD extends SlotInaccessible -{ - - public SlotInaccessibleHD( final IInventory i, final int slotIdx, final int x, final int y ) - { - super( i, slotIdx, x, y ); - } + public SlotInaccessibleHD(final IInventory i, final int slotIdx, final int x, final int y) { + super(i, slotIdx, x, y); + } } diff --git a/src/main/java/appeng/container/slot/SlotMACPattern.java b/src/main/java/appeng/container/slot/SlotMACPattern.java index 3b9d57762b2..0022fe91d23 100644 --- a/src/main/java/appeng/container/slot/SlotMACPattern.java +++ b/src/main/java/appeng/container/slot/SlotMACPattern.java @@ -18,26 +18,21 @@ package appeng.container.slot; - import appeng.container.implementations.ContainerMAC; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public class SlotMACPattern extends AppEngSlot { -public class SlotMACPattern extends AppEngSlot -{ - - private final ContainerMAC mac; + private final ContainerMAC mac; - public SlotMACPattern( final ContainerMAC mac, final IInventory i, final int slotIdx, final int x, final int y ) - { - super( i, slotIdx, x, y ); - this.mac = mac; - } + public SlotMACPattern(final ContainerMAC mac, final IInventory i, final int slotIdx, final int x, final int y) { + super(i, slotIdx, x, y); + this.mac = mac; + } - @Override - public boolean isItemValid( final ItemStack i ) - { - return this.mac.isValidItemForSlot( this.getSlotIndex(), i ); - } + @Override + public boolean isItemValid(final ItemStack i) { + return this.mac.isValidItemForSlot(this.getSlotIndex(), i); + } } diff --git a/src/main/java/appeng/container/slot/SlotNormal.java b/src/main/java/appeng/container/slot/SlotNormal.java index 96e705b28a3..413b31e928d 100644 --- a/src/main/java/appeng/container/slot/SlotNormal.java +++ b/src/main/java/appeng/container/slot/SlotNormal.java @@ -18,15 +18,11 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; +public class SlotNormal extends AppEngSlot { -public class SlotNormal extends AppEngSlot -{ - - public SlotNormal( final IInventory inv, final int slot, final int xPos, final int yPos ) - { - super( inv, slot, xPos, yPos ); - } + public SlotNormal(final IInventory inv, final int slot, final int xPos, final int yPos) { + super(inv, slot, xPos, yPos); + } } diff --git a/src/main/java/appeng/container/slot/SlotOutput.java b/src/main/java/appeng/container/slot/SlotOutput.java index 3c66243374c..fb785209d43 100644 --- a/src/main/java/appeng/container/slot/SlotOutput.java +++ b/src/main/java/appeng/container/slot/SlotOutput.java @@ -18,23 +18,18 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public class SlotOutput extends AppEngSlot { -public class SlotOutput extends AppEngSlot -{ - - public SlotOutput( final IInventory a, final int b, final int c, final int d, final int i ) - { - super( a, b, c, d ); - this.setIIcon( i ); - } + public SlotOutput(final IInventory a, final int b, final int c, final int d, final int i) { + super(a, b, c, d); + this.setIIcon(i); + } - @Override - public boolean isItemValid( final ItemStack i ) - { - return false; - } + @Override + public boolean isItemValid(final ItemStack i) { + return false; + } } diff --git a/src/main/java/appeng/container/slot/SlotPatternOutputs.java b/src/main/java/appeng/container/slot/SlotPatternOutputs.java index 49a85806baa..9aecce0c59e 100644 --- a/src/main/java/appeng/container/slot/SlotPatternOutputs.java +++ b/src/main/java/appeng/container/slot/SlotPatternOutputs.java @@ -18,27 +18,29 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; - -public class SlotPatternOutputs extends OptionalSlotFake -{ - - public SlotPatternOutputs( final IInventory inv, final IOptionalSlotHost containerBus, final int idx, final int x, final int y, final int offX, final int offY, final int groupNum ) - { - super( inv, containerBus, idx, x, y, offX, offY, groupNum ); - } - - @Override - public boolean isEnabled() - { - return true; - } - - @Override - public boolean shouldDisplay() - { - return super.isEnabled(); - } +public class SlotPatternOutputs extends OptionalSlotFake { + + public SlotPatternOutputs( + final IInventory inv, + final IOptionalSlotHost containerBus, + final int idx, + final int x, + final int y, + final int offX, + final int offY, + final int groupNum) { + super(inv, containerBus, idx, x, y, offX, offY, groupNum); + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public boolean shouldDisplay() { + return super.isEnabled(); + } } diff --git a/src/main/java/appeng/container/slot/SlotPatternTerm.java b/src/main/java/appeng/container/slot/SlotPatternTerm.java index aaf96d8208f..ddd584741c2 100644 --- a/src/main/java/appeng/container/slot/SlotPatternTerm.java +++ b/src/main/java/appeng/container/slot/SlotPatternTerm.java @@ -18,7 +18,6 @@ package appeng.container.slot; - import appeng.api.AEApi; import appeng.api.networking.energy.IEnergySource; import appeng.api.networking.security.BaseActionSource; @@ -26,54 +25,57 @@ import appeng.core.sync.AppEngPacket; import appeng.core.sync.packets.PacketPatternSlot; import appeng.helpers.IContainerCraftingPacket; +import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.io.IOException; - - -public class SlotPatternTerm extends SlotCraftingTerm -{ +public class SlotPatternTerm extends SlotCraftingTerm { - private final int groupNum; - private final IOptionalSlotHost host; + private final int groupNum; + private final IOptionalSlotHost host; - public SlotPatternTerm( final EntityPlayer player, final BaseActionSource mySrc, final IEnergySource energySrc, final IStorageMonitorable storage, final IInventory cMatrix, final IInventory secondMatrix, final IInventory output, final int x, final int y, final IOptionalSlotHost h, final int groupNumber, final IContainerCraftingPacket c ) - { - super( player, mySrc, energySrc, storage, cMatrix, secondMatrix, output, x, y, c ); + public SlotPatternTerm( + final EntityPlayer player, + final BaseActionSource mySrc, + final IEnergySource energySrc, + final IStorageMonitorable storage, + final IInventory cMatrix, + final IInventory secondMatrix, + final IInventory output, + final int x, + final int y, + final IOptionalSlotHost h, + final int groupNumber, + final IContainerCraftingPacket c) { + super(player, mySrc, energySrc, storage, cMatrix, secondMatrix, output, x, y, c); - this.host = h; - this.groupNum = groupNumber; - } + this.host = h; + this.groupNum = groupNumber; + } - public AppEngPacket getRequest( final boolean shift ) throws IOException - { - return new PacketPatternSlot( this.getPattern(), AEApi.instance().storage().createItemStack( this.getStack() ), shift ); - } + public AppEngPacket getRequest(final boolean shift) throws IOException { + return new PacketPatternSlot( + this.getPattern(), AEApi.instance().storage().createItemStack(this.getStack()), shift); + } - @Override - public ItemStack getStack() - { - if( !this.isEnabled() ) - { - if( this.getDisplayStack() != null ) - { - this.clearStack(); - } - } + @Override + public ItemStack getStack() { + if (!this.isEnabled()) { + if (this.getDisplayStack() != null) { + this.clearStack(); + } + } - return super.getStack(); - } + return super.getStack(); + } - @Override - public boolean isEnabled() - { - if( this.host == null ) - { - return false; - } + @Override + public boolean isEnabled() { + if (this.host == null) { + return false; + } - return this.host.isSlotEnabled( this.groupNum ); - } + return this.host.isSlotEnabled(this.groupNum); + } } diff --git a/src/main/java/appeng/container/slot/SlotPlayerHotBar.java b/src/main/java/appeng/container/slot/SlotPlayerHotBar.java index aba5e52cd8b..e8d89b5b670 100644 --- a/src/main/java/appeng/container/slot/SlotPlayerHotBar.java +++ b/src/main/java/appeng/container/slot/SlotPlayerHotBar.java @@ -18,16 +18,12 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; +public class SlotPlayerHotBar extends AppEngSlot { -public class SlotPlayerHotBar extends AppEngSlot -{ - - public SlotPlayerHotBar( final IInventory par1iInventory, final int par2, final int par3, final int par4 ) - { - super( par1iInventory, par2, par3, par4 ); - this.setPlayerSide( true ); - } + public SlotPlayerHotBar(final IInventory par1iInventory, final int par2, final int par3, final int par4) { + super(par1iInventory, par2, par3, par4); + this.setPlayerSide(true); + } } diff --git a/src/main/java/appeng/container/slot/SlotPlayerInv.java b/src/main/java/appeng/container/slot/SlotPlayerInv.java index a30f3766cfe..c832464ac1a 100644 --- a/src/main/java/appeng/container/slot/SlotPlayerInv.java +++ b/src/main/java/appeng/container/slot/SlotPlayerInv.java @@ -18,19 +18,15 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; // there is nothing special about this slot, its simply used to represent the players inventory, vs a container slot. +public class SlotPlayerInv extends AppEngSlot { -public class SlotPlayerInv extends AppEngSlot -{ - - public SlotPlayerInv( final IInventory par1iInventory, final int par2, final int par3, final int par4 ) - { - super( par1iInventory, par2, par3, par4 ); + public SlotPlayerInv(final IInventory par1iInventory, final int par2, final int par3, final int par4) { + super(par1iInventory, par2, par3, par4); - this.setPlayerSide( true ); - } + this.setPlayerSide(true); + } } diff --git a/src/main/java/appeng/container/slot/SlotRestrictedInput.java b/src/main/java/appeng/container/slot/SlotRestrictedInput.java index 45198e8bb0b..9a2ab97c3ed 100644 --- a/src/main/java/appeng/container/slot/SlotRestrictedInput.java +++ b/src/main/java/appeng/container/slot/SlotRestrictedInput.java @@ -18,7 +18,6 @@ package appeng.container.slot; - import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; import appeng.api.definitions.IItems; @@ -43,270 +42,260 @@ import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class SlotRestrictedInput extends AppEngSlot -{ - - private final PlacableItemType which; - private final InventoryPlayer p; - private boolean allowEdit = true; - private int stackLimit = -1; - - public SlotRestrictedInput( final PlacableItemType valid, final IInventory i, final int slotIndex, final int x, final int y, final InventoryPlayer p ) - { - super( i, slotIndex, x, y ); - this.which = valid; - this.setIIcon( valid.IIcon ); - this.p = p; - } - - @Override - public int getSlotStackLimit() - { - if( this.stackLimit != -1 ) - { - return this.stackLimit; - } - return super.getSlotStackLimit(); - } - - public boolean isValid( final ItemStack is, final World theWorld ) - { - if( this.which == PlacableItemType.VALID_ENCODED_PATTERN_W_OUTPUT ) - { - final ICraftingPatternDetails ap = is.getItem() instanceof ICraftingPatternItem ? ( (ICraftingPatternItem) is.getItem() ).getPatternForItem( is, theWorld ) : null; - return ap != null; - } - return true; - } - - public Slot setStackLimit( final int i ) - { - this.stackLimit = i; - return this; - } - - @Override - public boolean isItemValid( final ItemStack i ) - { - if (!isEnabled()) - return false; - if( !this.getContainer().isValidForSlot( this, i ) ) - { - return false; - } - - if( i == null ) - { - return false; - } - if( i.getItem() == null ) - { - return false; - } - - if( !this.inventory.isItemValidForSlot( this.getSlotIndex(), i ) ) - { - return false; - } - - if( !this.isAllowEdit() ) - { - return false; - } - - final IDefinitions definitions = AEApi.instance().definitions(); - final IMaterials materials = definitions.materials(); - final IItems items = definitions.items(); - - switch( this.which ) - { - case ENCODED_CRAFTING_PATTERN: - if( i.getItem() instanceof ICraftingPatternItem ) - { - final ICraftingPatternItem b = (ICraftingPatternItem) i.getItem(); - final ICraftingPatternDetails de = b.getPatternForItem( i, this.p.player.worldObj ); - if( de != null ) - { - return de.isCraftable(); - } - } - return false; - case VALID_ENCODED_PATTERN_W_OUTPUT: - case ENCODED_PATTERN_W_OUTPUT: - case ENCODED_PATTERN: - { - if( i.getItem() instanceof ICraftingPatternItem ) - { - return true; - } - // ICraftingPatternDetails pattern = i.getItem() instanceof ICraftingPatternItem ? - // ((ICraftingPatternItem) - // i.getItem()).getPatternForItem( i ) : null; - return false;// pattern != null; - } - case BLANK_PATTERN: - return materials.blankPattern().isSameAs( i ); - - case PATTERN: - - if( i.getItem() instanceof ICraftingPatternItem ) - { - return true; - } - - return materials.blankPattern().isSameAs( i ); - - case INSCRIBER_PLATE: - if( materials.namePress().isSameAs( i ) ) - { - return true; - } - - for( final ItemStack optional : AEApi.instance().registries().inscriber().getOptionals() ) - { - if( Platform.isSameItemPrecise( optional, i ) ) - { - return true; - } - } - - return false; - - case INSCRIBER_INPUT: - return true;/* - * for (ItemStack is : Inscribe.inputs) if ( Platform.isSameItemPrecise( is, i ) ) return - * true; - * return false; - */ - - case METAL_INGOTS: - - return isMetalIngot( i ); - - case VIEW_CELL: - return items.viewCell().isSameAs( i ); - case ORE: - return appeng.api.AEApi.instance().registries().grinder().getRecipeForInput( i ) != null; - case FUEL: - return TileEntityFurnace.getItemBurnTime( i ) > 0; - case POWERED_TOOL: - return Platform.isChargeable( i ); - case QE_SINGULARITY: - return materials.qESingularity().isSameAs( i ); - - case RANGE_BOOSTER: - return materials.wirelessBooster().isSameAs( i ); - - case SPATIAL_STORAGE_CELLS: - return i.getItem() instanceof ISpatialStorageCell && ( (ISpatialStorageCell) i.getItem() ).isSpatialStorage( i ); - case STORAGE_CELLS: - return AEApi.instance().registries().cell().isCellHandled( i ); - case WORKBENCH_CELL: - return i.getItem() instanceof ICellWorkbenchItem && ( (ICellWorkbenchItem) i.getItem() ).isEditable( i ); - case STORAGE_COMPONENT: - return i.getItem() instanceof IStorageComponent && ( (IStorageComponent) i.getItem() ).isStorageComponent( i ); - case TRASH: - if( AEApi.instance().registries().cell().isCellHandled( i ) ) - { - return false; - } - - return !( i.getItem() instanceof IStorageComponent && ( (IStorageComponent) i.getItem() ).isStorageComponent( i ) ); - case ENCODABLE_ITEM: - return i.getItem() instanceof INetworkEncodable || AEApi.instance().registries().wireless().isWirelessTerminal( i ); - case BIOMETRIC_CARD: - return i.getItem() instanceof IBiometricCard; - case UPGRADES: - return i.getItem() instanceof IUpgradeModule && ( (IUpgradeModule) i.getItem() ).getType( i ) != null; - default: - break; - } - - return false; - } - - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return this.isAllowEdit(); - } - - @Override - public ItemStack getDisplayStack() - { - if( Platform.isClient() && ( this.which == PlacableItemType.ENCODED_PATTERN ) ) - { - final ItemStack is = super.getStack(); - if( is != null && is.getItem() instanceof ItemEncodedPattern ) - { - final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); - final ItemStack out = iep.getOutput( is ); - if( out != null ) - { - return out; - } - } - } - return super.getStack(); - } - - public static boolean isMetalIngot( final ItemStack i ) - { - if( Platform.isSameItemPrecise( i, new ItemStack( Items.iron_ingot ) ) ) - { - return true; - } - - for( final String name : new String[] { "Copper", "Tin", "Obsidian", "Iron", "Lead", "Bronze", "Brass", "Nickel", "Aluminium" } ) - { - for( final ItemStack ingot : OreDictionary.getOres( "ingot" + name ) ) - { - if( Platform.isSameItemPrecise( i, ingot ) ) - { - return true; - } - } - } - - return false; - } - - private boolean isAllowEdit() - { - return this.allowEdit; - } - - public void setAllowEdit( final boolean allowEdit ) - { - this.allowEdit = allowEdit; - } - - public enum PlacableItemType - { - STORAGE_CELLS( 15 ), ORE( 16 + 15 ), STORAGE_COMPONENT( 3 * 16 + 15 ), - - ENCODABLE_ITEM( 4 * 16 + 15 ), TRASH( 5 * 16 + 15 ), VALID_ENCODED_PATTERN_W_OUTPUT( 7 * 16 + 15 ), ENCODED_PATTERN_W_OUTPUT( 7 * 16 + 15 ), - - ENCODED_CRAFTING_PATTERN( 7 * 16 + 15 ), ENCODED_PATTERN( 7 * 16 + 15 ), PATTERN( 8 * 16 + 15 ), BLANK_PATTERN( 8 * 16 + 15 ), POWERED_TOOL( 9 * 16 + 15 ), - - RANGE_BOOSTER( 6 * 16 + 15 ), QE_SINGULARITY( 10 * 16 + 15 ), SPATIAL_STORAGE_CELLS( 11 * 16 + 15 ), - - FUEL( 12 * 16 + 15 ), UPGRADES( 13 * 16 + 15 ), WORKBENCH_CELL( 15 ), BIOMETRIC_CARD( 14 * 16 + 15 ), VIEW_CELL( 4 * 16 + 14 ), - - INSCRIBER_PLATE( 2 * 16 + 14 ), INSCRIBER_INPUT( 3 * 16 + 14 ), METAL_INGOTS( 3 * 16 + 14 ); - - public final int IIcon; - - PlacableItemType( final int o ) - { - this.IIcon = o; - } - } +public class SlotRestrictedInput extends AppEngSlot { + + private final PlacableItemType which; + private final InventoryPlayer p; + private boolean allowEdit = true; + private int stackLimit = -1; + + public SlotRestrictedInput( + final PlacableItemType valid, + final IInventory i, + final int slotIndex, + final int x, + final int y, + final InventoryPlayer p) { + super(i, slotIndex, x, y); + this.which = valid; + this.setIIcon(valid.IIcon); + this.p = p; + } + + @Override + public int getSlotStackLimit() { + if (this.stackLimit != -1) { + return this.stackLimit; + } + return super.getSlotStackLimit(); + } + + public boolean isValid(final ItemStack is, final World theWorld) { + if (this.which == PlacableItemType.VALID_ENCODED_PATTERN_W_OUTPUT) { + final ICraftingPatternDetails ap = is.getItem() instanceof ICraftingPatternItem + ? ((ICraftingPatternItem) is.getItem()).getPatternForItem(is, theWorld) + : null; + return ap != null; + } + return true; + } + + public Slot setStackLimit(final int i) { + this.stackLimit = i; + return this; + } + + @Override + public boolean isItemValid(final ItemStack i) { + if (!isEnabled()) return false; + if (!this.getContainer().isValidForSlot(this, i)) { + return false; + } + + if (i == null) { + return false; + } + if (i.getItem() == null) { + return false; + } + + if (!this.inventory.isItemValidForSlot(this.getSlotIndex(), i)) { + return false; + } + + if (!this.isAllowEdit()) { + return false; + } + + final IDefinitions definitions = AEApi.instance().definitions(); + final IMaterials materials = definitions.materials(); + final IItems items = definitions.items(); + + switch (this.which) { + case ENCODED_CRAFTING_PATTERN: + if (i.getItem() instanceof ICraftingPatternItem) { + final ICraftingPatternItem b = (ICraftingPatternItem) i.getItem(); + final ICraftingPatternDetails de = b.getPatternForItem(i, this.p.player.worldObj); + if (de != null) { + return de.isCraftable(); + } + } + return false; + case VALID_ENCODED_PATTERN_W_OUTPUT: + case ENCODED_PATTERN_W_OUTPUT: + case ENCODED_PATTERN: { + if (i.getItem() instanceof ICraftingPatternItem) { + return true; + } + // ICraftingPatternDetails pattern = i.getItem() instanceof ICraftingPatternItem ? + // ((ICraftingPatternItem) + // i.getItem()).getPatternForItem( i ) : null; + return false; // pattern != null; + } + case BLANK_PATTERN: + return materials.blankPattern().isSameAs(i); + + case PATTERN: + if (i.getItem() instanceof ICraftingPatternItem) { + return true; + } + + return materials.blankPattern().isSameAs(i); + + case INSCRIBER_PLATE: + if (materials.namePress().isSameAs(i)) { + return true; + } + + for (final ItemStack optional : + AEApi.instance().registries().inscriber().getOptionals()) { + if (Platform.isSameItemPrecise(optional, i)) { + return true; + } + } + + return false; + + case INSCRIBER_INPUT: + return true; /* + * for (ItemStack is : Inscribe.inputs) if ( Platform.isSameItemPrecise( is, i ) ) return + * true; + * return false; + */ + + case METAL_INGOTS: + return isMetalIngot(i); + + case VIEW_CELL: + return items.viewCell().isSameAs(i); + case ORE: + return appeng.api.AEApi.instance().registries().grinder().getRecipeForInput(i) != null; + case FUEL: + return TileEntityFurnace.getItemBurnTime(i) > 0; + case POWERED_TOOL: + return Platform.isChargeable(i); + case QE_SINGULARITY: + return materials.qESingularity().isSameAs(i); + + case RANGE_BOOSTER: + return materials.wirelessBooster().isSameAs(i); + + case SPATIAL_STORAGE_CELLS: + return i.getItem() instanceof ISpatialStorageCell + && ((ISpatialStorageCell) i.getItem()).isSpatialStorage(i); + case STORAGE_CELLS: + return AEApi.instance().registries().cell().isCellHandled(i); + case WORKBENCH_CELL: + return i.getItem() instanceof ICellWorkbenchItem && ((ICellWorkbenchItem) i.getItem()).isEditable(i); + case STORAGE_COMPONENT: + return i.getItem() instanceof IStorageComponent + && ((IStorageComponent) i.getItem()).isStorageComponent(i); + case TRASH: + if (AEApi.instance().registries().cell().isCellHandled(i)) { + return false; + } + + return !(i.getItem() instanceof IStorageComponent + && ((IStorageComponent) i.getItem()).isStorageComponent(i)); + case ENCODABLE_ITEM: + return i.getItem() instanceof INetworkEncodable + || AEApi.instance().registries().wireless().isWirelessTerminal(i); + case BIOMETRIC_CARD: + return i.getItem() instanceof IBiometricCard; + case UPGRADES: + return i.getItem() instanceof IUpgradeModule && ((IUpgradeModule) i.getItem()).getType(i) != null; + default: + break; + } + + return false; + } + + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return this.isAllowEdit(); + } + + @Override + public ItemStack getDisplayStack() { + if (Platform.isClient() && (this.which == PlacableItemType.ENCODED_PATTERN)) { + final ItemStack is = super.getStack(); + if (is != null && is.getItem() instanceof ItemEncodedPattern) { + final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); + final ItemStack out = iep.getOutput(is); + if (out != null) { + return out; + } + } + } + return super.getStack(); + } + + public static boolean isMetalIngot(final ItemStack i) { + if (Platform.isSameItemPrecise(i, new ItemStack(Items.iron_ingot))) { + return true; + } + + for (final String name : + new String[] {"Copper", "Tin", "Obsidian", "Iron", "Lead", "Bronze", "Brass", "Nickel", "Aluminium"}) { + for (final ItemStack ingot : OreDictionary.getOres("ingot" + name)) { + if (Platform.isSameItemPrecise(i, ingot)) { + return true; + } + } + } + + return false; + } + + private boolean isAllowEdit() { + return this.allowEdit; + } + + public void setAllowEdit(final boolean allowEdit) { + this.allowEdit = allowEdit; + } + + public enum PlacableItemType { + STORAGE_CELLS(15), + ORE(16 + 15), + STORAGE_COMPONENT(3 * 16 + 15), + + ENCODABLE_ITEM(4 * 16 + 15), + TRASH(5 * 16 + 15), + VALID_ENCODED_PATTERN_W_OUTPUT(7 * 16 + 15), + ENCODED_PATTERN_W_OUTPUT(7 * 16 + 15), + + ENCODED_CRAFTING_PATTERN(7 * 16 + 15), + ENCODED_PATTERN(7 * 16 + 15), + PATTERN(8 * 16 + 15), + BLANK_PATTERN(8 * 16 + 15), + POWERED_TOOL(9 * 16 + 15), + + RANGE_BOOSTER(6 * 16 + 15), + QE_SINGULARITY(10 * 16 + 15), + SPATIAL_STORAGE_CELLS(11 * 16 + 15), + + FUEL(12 * 16 + 15), + UPGRADES(13 * 16 + 15), + WORKBENCH_CELL(15), + BIOMETRIC_CARD(14 * 16 + 15), + VIEW_CELL(4 * 16 + 14), + + INSCRIBER_PLATE(2 * 16 + 14), + INSCRIBER_INPUT(3 * 16 + 14), + METAL_INGOTS(3 * 16 + 14); + + public final int IIcon; + + PlacableItemType(final int o) { + this.IIcon = o; + } + } } diff --git a/src/main/java/appeng/core/AEConfig.java b/src/main/java/appeng/core/AEConfig.java index c12ed056656..e7792f59a94 100644 --- a/src/main/java/appeng/core/AEConfig.java +++ b/src/main/java/appeng/core/AEConfig.java @@ -18,7 +18,6 @@ package appeng.core; - import appeng.api.config.*; import appeng.api.util.IConfigManager; import appeng.api.util.IConfigurableObject; @@ -32,488 +31,516 @@ import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.ModContainer; import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.common.config.Property; - import java.io.File; import java.util.Arrays; import java.util.EnumSet; import java.util.List; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.common.config.Property; - -public final class AEConfig extends Configuration implements IConfigurableObject, IConfigManagerHost -{ - public static double TUNNEL_POWER_LOSS = 0.05; - public static final String VERSION = "GRADLETOKEN_VERSION"; - public static final String PACKET_CHANNEL = "AE"; - public static AEConfig instance; - public final IConfigManager settings = new ConfigManager( this ); - public final EnumSet featureFlags = EnumSet.noneOf( AEFeature.class ); - public final int[] craftByStacks = { 1, 10, 100, 1000 }; - public final int[] priorityByStacks = { 1, 10, 100, 1000 }; - public final int[] levelByStacks = { 1, 10, 100, 1000 }; - private final double WirelessHighWirelessCount = 64; - private final File configFile; - public int storageBiomeID = -1; - public int storageProviderID = -1; - public int formationPlaneEntityLimit = 128; - public float spawnChargedChance = 0.92f; - public int quartzOresPerCluster = 4; - public int quartzOresClusterAmount = 15; - public final int chargedChange = 4; - public int minMeteoriteDistance = 707; - public int minMeteoriteDistanceSq = this.minMeteoriteDistance * this.minMeteoriteDistance; - public double spatialPowerExponent = 1.35; - public double spatialPowerMultiplier = 1250.0; - public String[] grinderOres = { - // Vanilla Items - "Obsidian", "Ender", "EnderPearl", "Coal", "Iron", "Gold", "Charcoal", "NetherQuartz", - // Common Mod Ores - "Copper", "Tin", "Silver", "Lead", "Bronze", - // AE - "CertusQuartz", "Wheat", "Fluix", - // Other Mod Ores - "Brass", "Platinum", "Nickel", "Invar", "Aluminium", "Electrum", "Osmium", "Zinc" }; - public double oreDoublePercentage = 90.0; - public boolean enableEffects = true; - public boolean useLargeFonts = false; - public boolean useColoredCraftingStatus; - public boolean preserveSearchBar = true; - public boolean showOnlyInterfacesWithFreeSlotsInInterfaceTerminal = false; - public int MEMonitorableSmallSize = 6; - public int InterfaceTerminalSmallSize = 6; - - public boolean debugLogTiming = false; - public boolean debugPathFinding = false; - public boolean p2pBackboneTransfer = false; - public boolean quantumBridgeBackboneTransfer = false; - public int wirelessTerminalBattery = 1600000; - public int entropyManipulatorBattery = 200000; - public int matterCannonBattery = 200000; - public int portableCellBattery = 20000; - public int colorApplicatorBattery = 20000; - public int chargedStaffBattery = 8000; - public boolean disableColoredCableRecipesInNEI = true; - public boolean updatable = false; - public double meteoriteClusterChance = 0.1; - public double meteoriteSpawnChance = 0.3; - public int[] meteoriteDimensionWhitelist = { 0 }; - public int craftingCalculationTimePerTick = 5; - PowerUnits selectedPowerUnit = PowerUnits.AE; - private double WirelessBaseCost = 8; - private double WirelessCostMultiplier = 1; - private double WirelessTerminalDrainMultiplier = 1; - private double WirelessBaseRange = 16; - private double WirelessBoosterRangeMultiplier = 1; - private double WirelessBoosterExp = 1.5; - public int levelEmitterDelay = 40; - - public AEConfig( final File configFile ) - { - super( configFile ); - this.configFile = configFile; - - FMLCommonHandler.instance().bus().register( this ); - - final double DEFAULT_MEKANISM_EXCHANGE = 0.2; - PowerUnits.MK.conversionRatio = this.get( "PowerRatios", "Mekanism", DEFAULT_MEKANISM_EXCHANGE ).getDouble( DEFAULT_MEKANISM_EXCHANGE ); - final double DEFAULT_IC2_EXCHANGE = 2.0; - PowerUnits.EU.conversionRatio = this.get( "PowerRatios", "IC2", DEFAULT_IC2_EXCHANGE ).getDouble( DEFAULT_IC2_EXCHANGE ); - final double DEFAULT_RTC_EXCHANGE = 1.0 / 11256.0; - PowerUnits.WA.conversionRatio = this.get( "PowerRatios", "RotaryCraft", DEFAULT_RTC_EXCHANGE ).getDouble( DEFAULT_RTC_EXCHANGE ); - final double DEFAULT_RF_EXCHANGE = 0.5; - PowerUnits.RF.conversionRatio = this.get( "PowerRatios", "ThermalExpansion", DEFAULT_RF_EXCHANGE ).getDouble( DEFAULT_RF_EXCHANGE ); - final double DEFAULT_TUNNEL_POWER_LOSS = 0.05; - TUNNEL_POWER_LOSS = this.get("PowerRatios", "TunnelPowerLoss", DEFAULT_TUNNEL_POWER_LOSS).getDouble(DEFAULT_TUNNEL_POWER_LOSS); - if (TUNNEL_POWER_LOSS < 0 || TUNNEL_POWER_LOSS >= 1) - TUNNEL_POWER_LOSS = DEFAULT_TUNNEL_POWER_LOSS; - - final double usageEffective = this.get( "PowerRatios", "UsageMultiplier", 1.0 ).getDouble( 1.0 ); - PowerMultiplier.CONFIG.multiplier = Math.max( 0.01, usageEffective ); - - CondenserOutput.MATTER_BALLS.requiredPower = this.get( "Condenser", "MatterBalls", 256 ).getInt( 256 ); - CondenserOutput.SINGULARITY.requiredPower = this.get( "Condenser", "Singularity", 256000 ).getInt( 256000 ); - - this.grinderOres = this.get( "GrindStone", "grinderOres", this.grinderOres ).getStringList(); - this.oreDoublePercentage = this.get( "GrindStone", "oreDoublePercentage", this.oreDoublePercentage ).getDouble( this.oreDoublePercentage ); - - this.settings.registerSetting( Settings.SEARCH_TOOLTIPS, YesNo.YES ); - this.settings.registerSetting( Settings.TERMINAL_STYLE, TerminalStyle.TALL ); - this.settings.registerSetting( Settings.SEARCH_MODE, SearchBoxMode.AUTOSEARCH ); - this.settings.registerSetting( Settings.SAVE_SEARCH, YesNo.NO ); - this.settings.registerSetting( Settings.CRAFTING_STATUS, CraftingStatus.TILE); - - this.spawnChargedChance = (float) ( 1.0 - this.get( "worldGen", "spawnChargedChance", 1.0 - this.spawnChargedChance ).getDouble( 1.0 - this.spawnChargedChance ) ); - this.minMeteoriteDistance = this.get( "worldGen", "minMeteoriteDistance", this.minMeteoriteDistance ).getInt( this.minMeteoriteDistance ); - this.meteoriteClusterChance = this.get( "worldGen", "meteoriteClusterChance", this.meteoriteClusterChance ).getDouble( this.meteoriteClusterChance ); - this.meteoriteSpawnChance = this.get( "worldGen", "meteoriteSpawnChance", this.meteoriteSpawnChance ).getDouble( this.meteoriteSpawnChance ); - this.meteoriteDimensionWhitelist = this.get( "worldGen", "meteoriteDimensionWhitelist", this.meteoriteDimensionWhitelist ).getIntList(); - - this.quartzOresPerCluster = this.get( "worldGen", "quartzOresPerCluster", this.quartzOresPerCluster ).getInt( this.quartzOresPerCluster ); - this.quartzOresClusterAmount = this.get( "worldGen", "quartzOresClusterAmount", this.quartzOresClusterAmount ).getInt( this.quartzOresClusterAmount ); - - this.minMeteoriteDistanceSq = this.minMeteoriteDistance * this.minMeteoriteDistance; - - this.addCustomCategoryComment( "wireless", "Range= WirelessBaseRange + WirelessBoosterRangeMultiplier * Math.pow( boosters, WirelessBoosterExp )\nPowerDrain= WirelessBaseCost + WirelessCostMultiplier * Math.pow( boosters, 1 + boosters / WirelessHighWirelessCount )" ); - - this.WirelessBaseCost = this.get( "wireless", "WirelessBaseCost", this.WirelessBaseCost ).getDouble( this.WirelessBaseCost ); - this.WirelessCostMultiplier = this.get( "wireless", "WirelessCostMultiplier", this.WirelessCostMultiplier ).getDouble( this.WirelessCostMultiplier ); - this.WirelessBaseRange = this.get( "wireless", "WirelessBaseRange", this.WirelessBaseRange ).getDouble( this.WirelessBaseRange ); - this.WirelessBoosterRangeMultiplier = this.get( "wireless", "WirelessBoosterRangeMultiplier", this.WirelessBoosterRangeMultiplier ).getDouble( this.WirelessBoosterRangeMultiplier ); - this.WirelessBoosterExp = this.get( "wireless", "WirelessBoosterExp", this.WirelessBoosterExp ).getDouble( this.WirelessBoosterExp ); - this.WirelessTerminalDrainMultiplier = this.get( "wireless", "WirelessTerminalDrainMultiplier", this.WirelessTerminalDrainMultiplier ).getDouble( this.WirelessTerminalDrainMultiplier ); - - this.formationPlaneEntityLimit = this.get( "automation", "formationPlaneEntityLimit", this.formationPlaneEntityLimit ).getInt( this.formationPlaneEntityLimit ); - - this.wirelessTerminalBattery = this.get( "battery", "wirelessTerminal", this.wirelessTerminalBattery ).getInt( this.wirelessTerminalBattery ); - this.chargedStaffBattery = this.get( "battery", "chargedStaff", this.chargedStaffBattery ).getInt( this.chargedStaffBattery ); - this.entropyManipulatorBattery = this.get( "battery", "entropyManipulator", this.entropyManipulatorBattery ).getInt( this.entropyManipulatorBattery ); - this.portableCellBattery = this.get( "battery", "portableCell", this.portableCellBattery ).getInt( this.portableCellBattery ); - this.colorApplicatorBattery = this.get( "battery", "colorApplicator", this.colorApplicatorBattery ).getInt( this.colorApplicatorBattery ); - this.matterCannonBattery = this.get( "battery", "matterCannon", this.matterCannonBattery ).getInt( this.matterCannonBattery ); - - this.levelEmitterDelay = this.get( "tickrates", "LevelEmitterDelay", this.levelEmitterDelay ).getInt( this.levelEmitterDelay ); - this.debugLogTiming = this.get("debug", "LogTiming", this.debugLogTiming).getBoolean(this.debugLogTiming); - this.debugPathFinding = this.get("debug", "LogPathFinding", this.debugPathFinding).getBoolean(this.debugPathFinding); - this.p2pBackboneTransfer = this.get("debug", "EnableP2pBackboneTransfer", this.p2pBackboneTransfer).getBoolean(this.p2pBackboneTransfer); - this.quantumBridgeBackboneTransfer = this.get("debug", "EnableQuantumBridgeBackboneTransfer", this.quantumBridgeBackboneTransfer).getBoolean(this.quantumBridgeBackboneTransfer); - this.clientSync(); - - for( final AEFeature feature : AEFeature.values() ) - { - if( feature.isVisible() ) - { - if( this.get( "Features." + feature.category, feature.name(), feature.defaultValue ).getBoolean( feature.defaultValue ) ) - { - this.featureFlags.add( feature ); - } - } - else - { - this.featureFlags.add( feature ); - } - } - - final ModContainer imb = cpw.mods.fml.common.Loader.instance().getIndexedModList().get( "ImmibisCore" ); - if( imb != null ) - { - final List version = Arrays.asList( "59.0.0", "59.0.1", "59.0.2" ); - if( version.contains( imb.getVersion() ) ) - { - this.featureFlags.remove( AEFeature.AlphaPass ); - } - } - - try - { - this.selectedPowerUnit = PowerUnits.valueOf( this.get( "Client", "PowerUnit", this.selectedPowerUnit.name(), this.getListComment( this.selectedPowerUnit ) ).getString() ); - } - catch( final Throwable t ) - { - this.selectedPowerUnit = PowerUnits.AE; - } - - for( final TickRates tr : TickRates.values() ) - { - tr.Load( this ); - } - - if( this.isFeatureEnabled( AEFeature.SpatialIO ) ) - { - this.storageBiomeID = this.get( "spatialio", "storageBiomeID", this.storageBiomeID ).getInt( this.storageBiomeID ); - this.storageProviderID = this.get( "spatialio", "storageProviderID", this.storageProviderID ).getInt( this.storageProviderID ); - this.spatialPowerMultiplier = this.get( "spatialio", "spatialPowerMultiplier", this.spatialPowerMultiplier ).getDouble( this.spatialPowerMultiplier ); - this.spatialPowerExponent = this.get( "spatialio", "spatialPowerExponent", this.spatialPowerExponent ).getDouble( this.spatialPowerExponent ); - } - - if( this.isFeatureEnabled( AEFeature.CraftingCPU ) ) - { - this.craftingCalculationTimePerTick = this.get( "craftingCPU", "craftingCalculationTimePerTick", this.craftingCalculationTimePerTick ).getInt( this.craftingCalculationTimePerTick ); - } - - this.updatable = true; - } - - private void clientSync() - { - this.disableColoredCableRecipesInNEI = this.get( "Client", "disableColoredCableRecipesInNEI", true ).getBoolean( true ); - this.enableEffects = this.get( "Client", "enableEffects", true ).getBoolean( true ); - this.useLargeFonts = this.get( "Client", "useTerminalUseLargeFont", false ).getBoolean( false ); - this.useColoredCraftingStatus = this.get( "Client", "useColoredCraftingStatus", true ).getBoolean( true ); - this.preserveSearchBar = this.get( "Client", "preserveSearchBar", true ).getBoolean( true ); - this.showOnlyInterfacesWithFreeSlotsInInterfaceTerminal = this.get( "Client", "showOnlyInterfacesWithFreeSlotsInInterfaceTerminal", false ).getBoolean( false ); - this.MEMonitorableSmallSize = this.get( "Client", "MEMonitorableSmallSize", 6 ).getInt( 6 ); - this.InterfaceTerminalSmallSize = this.get( "Client", "InterfaceTerminalSmallSize", 6 ).getInt( 6 ); - // load buttons.. - for( int btnNum = 0; btnNum < 4; btnNum++ ) - { - final Property cmb = this.get( "Client", "craftAmtButton" + ( btnNum + 1 ), this.craftByStacks[btnNum] ); - final Property pmb = this.get( "Client", "priorityAmtButton" + ( btnNum + 1 ), this.priorityByStacks[btnNum] ); - final Property lmb = this.get( "Client", "levelAmtButton" + ( btnNum + 1 ), this.levelByStacks[btnNum] ); - - final int buttonCap = (int) ( Math.pow( 10, btnNum + 1 ) - 1 ); - - this.craftByStacks[btnNum] = Math.abs( cmb.getInt( this.craftByStacks[btnNum] ) ); - this.priorityByStacks[btnNum] = Math.abs( pmb.getInt( this.priorityByStacks[btnNum] ) ); - this.levelByStacks[btnNum] = Math.abs( pmb.getInt( this.levelByStacks[btnNum] ) ); - - cmb.comment = "Controls buttons on Crafting Screen : Capped at " + buttonCap; - pmb.comment = "Controls buttons on Priority Screen : Capped at " + buttonCap; - lmb.comment = "Controls buttons on Level Emitter Screen : Capped at " + buttonCap; - - this.craftByStacks[btnNum] = Math.min( this.craftByStacks[btnNum], buttonCap ); - this.priorityByStacks[btnNum] = Math.min( this.priorityByStacks[btnNum], buttonCap ); - this.levelByStacks[btnNum] = Math.min( this.levelByStacks[btnNum], buttonCap ); - } - - for( final Settings e : this.settings.getSettings() ) - { - final String Category = "Client"; // e.getClass().getSimpleName(); - Enum value = this.settings.getSetting( e ); - - final Property p = this.get( Category, e.name(), value.name(), this.getListComment( value ) ); - - try - { - value = Enum.valueOf( value.getClass(), p.getString() ); - } - catch( final IllegalArgumentException er ) - { - AELog.info( "Invalid value '" + p.getString() + "' for " + e.name() + " using '" + value.name() + "' instead" ); - } - - this.settings.putSetting( e, value ); - } - } - - private String getListComment( final Enum value ) - { - String comment = null; - - if( value != null ) - { - final EnumSet set = EnumSet.allOf( value.getClass() ); - - for( final Object Oeg : set ) - { - final Enum eg = (Enum) Oeg; - if( comment == null ) - { - comment = "Possible Values: " + eg.name(); - } - else - { - comment += ", " + eg.name(); - } - } - } - - return comment; - } - - public boolean isFeatureEnabled( final AEFeature f ) - { - return this.featureFlags.contains( f ); - } - - public double wireless_getDrainRate( final double range ) - { - return this.WirelessTerminalDrainMultiplier * range; - } - - public double wireless_getMaxRange( final int boosters ) - { - return this.WirelessBaseRange + this.WirelessBoosterRangeMultiplier * Math.pow( boosters, this.WirelessBoosterExp ); - } - - public double wireless_getPowerDrain( final int boosters ) - { - return this.WirelessBaseCost + this.WirelessCostMultiplier * Math.pow( boosters, 1 + boosters / this.WirelessHighWirelessCount ); - } - - @Override - public Property get( final String category, final String key, final String defaultValue, final String comment, final Property.Type type ) - { - final Property prop = super.get( category, key, defaultValue, comment, type ); - - if( prop != null ) - { - if( !category.equals( "Client" ) ) - { - prop.setRequiresMcRestart( true ); - } - } - - return prop; - } - - @Override - public void save() - { - if( this.isFeatureEnabled( AEFeature.SpatialIO ) ) - { - this.get( "spatialio", "storageBiomeID", this.storageBiomeID ).set( this.storageBiomeID ); - this.get( "spatialio", "storageProviderID", this.storageProviderID ).set( this.storageProviderID ); - } - - this.get( "Client", "PowerUnit", this.selectedPowerUnit.name(), this.getListComment( this.selectedPowerUnit ) ).set( this.selectedPowerUnit.name() ); - - if( this.hasChanged() ) - { - super.save(); - } - } - - @SubscribeEvent - public void onConfigChanged( final ConfigChangedEvent.OnConfigChangedEvent eventArgs ) - { - if( eventArgs.modID.equals( AppEng.MOD_ID ) ) - { - this.clientSync(); - } - } - - public boolean disableColoredCableRecipesInNEI() - { - return this.disableColoredCableRecipesInNEI; - } - - public String getFilePath() - { - return this.configFile.toString(); - } - - public boolean useAEVersion( final MaterialType mt ) - { - if( this.isFeatureEnabled( AEFeature.WebsiteRecipes ) ) - { - return true; - } - - this.setCategoryComment( "OreCamouflage", "AE2 Automatically uses alternative ores present in your instance of MC to blend better with its surroundings, if you prefer you can disable this selectively using these flags; Its important to note, that some if these items even if enabled may not be craftable in game because other items are overriding their recipes." ); - final Property p = this.get( "OreCamouflage", mt.name(), true ); - p.comment = "OreDictionary Names: " + mt.getOreName(); - - return !p.getBoolean( true ); - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum setting, final Enum newValue ) - { - for( final Settings e : this.settings.getSettings() ) - { - if( e == setting ) - { - final String Category = "Client"; - final Property p = this.get( Category, e.name(), this.settings.getSetting( e ).name(), this.getListComment( newValue ) ); - p.set( newValue.name() ); - } - } - - if( this.updatable ) - { - this.save(); - } - } - - public int getFreeMaterial( final int varID ) - { - return this.getFreeIDSLot( varID, "materials" ); - } - - public int getFreeIDSLot( final int varID, final String category ) - { - boolean alreadyUsed = false; - int min = 0; - - for( final Property p : this.getCategory( category ).getValues().values() ) - { - final int thisInt = p.getInt(); - - if( varID == thisInt ) - { - alreadyUsed = true; - } - - min = Math.max( min, thisInt + 1 ); - } - - if( alreadyUsed ) - { - if( min < 16383 ) - { - min = 16383; - } - - return min; - } - - return varID; - } - - public int getFreePart( final int varID ) - { - return this.getFreeIDSLot( varID, "parts" ); - } - - @Override - public IConfigManager getConfigManager() - { - return this.settings; - } - - public boolean useTerminalUseLargeFont() - { - return this.useLargeFonts; - } - - public int craftItemsByStackAmounts( final int i ) - { - return this.craftByStacks[i]; - } - - public int priorityByStacksAmounts( final int i ) - { - return this.priorityByStacks[i]; - } - - public int levelByStackAmounts( final int i ) - { - return this.levelByStacks[i]; - } - - public Enum getSetting( final String category, final Class class1, final Enum myDefault ) - { - final String name = class1.getSimpleName(); - final Property p = this.get( category, name, myDefault.name() ); - - try - { - return (Enum) class1.getField( p.toString() ).get( class1 ); - } - catch( final Throwable t ) - { - // :{ - } - - return myDefault; - } - - public void setSetting( final String category, final Enum s ) - { - final String name = s.getClass().getSimpleName(); - this.get( category, name, s.name() ).set( s.name() ); - this.save(); - } - - public PowerUnits selectedPowerUnit() - { - return this.selectedPowerUnit; - } - - public void nextPowerUnit( final boolean backwards ) - { - this.selectedPowerUnit = Platform.rotateEnum( this.selectedPowerUnit, backwards, Settings.POWER_UNITS.getPossibleValues() ); - this.save(); - } +public final class AEConfig extends Configuration implements IConfigurableObject, IConfigManagerHost { + public static double TUNNEL_POWER_LOSS = 0.05; + public static final String VERSION = "GRADLETOKEN_VERSION"; + public static final String PACKET_CHANNEL = "AE"; + public static AEConfig instance; + public final IConfigManager settings = new ConfigManager(this); + public final EnumSet featureFlags = EnumSet.noneOf(AEFeature.class); + public final int[] craftByStacks = {1, 10, 100, 1000}; + public final int[] priorityByStacks = {1, 10, 100, 1000}; + public final int[] levelByStacks = {1, 10, 100, 1000}; + private final double WirelessHighWirelessCount = 64; + private final File configFile; + public int storageBiomeID = -1; + public int storageProviderID = -1; + public int formationPlaneEntityLimit = 128; + public float spawnChargedChance = 0.92f; + public int quartzOresPerCluster = 4; + public int quartzOresClusterAmount = 15; + public final int chargedChange = 4; + public int minMeteoriteDistance = 707; + public int minMeteoriteDistanceSq = this.minMeteoriteDistance * this.minMeteoriteDistance; + public double spatialPowerExponent = 1.35; + public double spatialPowerMultiplier = 1250.0; + public String[] grinderOres = { + // Vanilla Items + "Obsidian", + "Ender", + "EnderPearl", + "Coal", + "Iron", + "Gold", + "Charcoal", + "NetherQuartz", + // Common Mod Ores + "Copper", + "Tin", + "Silver", + "Lead", + "Bronze", + // AE + "CertusQuartz", + "Wheat", + "Fluix", + // Other Mod Ores + "Brass", + "Platinum", + "Nickel", + "Invar", + "Aluminium", + "Electrum", + "Osmium", + "Zinc" + }; + public double oreDoublePercentage = 90.0; + public boolean enableEffects = true; + public boolean useLargeFonts = false; + public boolean useColoredCraftingStatus; + public boolean preserveSearchBar = true; + public boolean showOnlyInterfacesWithFreeSlotsInInterfaceTerminal = false; + public int MEMonitorableSmallSize = 6; + public int InterfaceTerminalSmallSize = 6; + + public boolean debugLogTiming = false; + public boolean debugPathFinding = false; + public boolean p2pBackboneTransfer = false; + public boolean quantumBridgeBackboneTransfer = false; + public int wirelessTerminalBattery = 1600000; + public int entropyManipulatorBattery = 200000; + public int matterCannonBattery = 200000; + public int portableCellBattery = 20000; + public int colorApplicatorBattery = 20000; + public int chargedStaffBattery = 8000; + public boolean disableColoredCableRecipesInNEI = true; + public boolean updatable = false; + public double meteoriteClusterChance = 0.1; + public double meteoriteSpawnChance = 0.3; + public int[] meteoriteDimensionWhitelist = {0}; + public int craftingCalculationTimePerTick = 5; + PowerUnits selectedPowerUnit = PowerUnits.AE; + private double WirelessBaseCost = 8; + private double WirelessCostMultiplier = 1; + private double WirelessTerminalDrainMultiplier = 1; + private double WirelessBaseRange = 16; + private double WirelessBoosterRangeMultiplier = 1; + private double WirelessBoosterExp = 1.5; + public int levelEmitterDelay = 40; + + public AEConfig(final File configFile) { + super(configFile); + this.configFile = configFile; + + FMLCommonHandler.instance().bus().register(this); + + final double DEFAULT_MEKANISM_EXCHANGE = 0.2; + PowerUnits.MK.conversionRatio = + this.get("PowerRatios", "Mekanism", DEFAULT_MEKANISM_EXCHANGE).getDouble(DEFAULT_MEKANISM_EXCHANGE); + final double DEFAULT_IC2_EXCHANGE = 2.0; + PowerUnits.EU.conversionRatio = + this.get("PowerRatios", "IC2", DEFAULT_IC2_EXCHANGE).getDouble(DEFAULT_IC2_EXCHANGE); + final double DEFAULT_RTC_EXCHANGE = 1.0 / 11256.0; + PowerUnits.WA.conversionRatio = + this.get("PowerRatios", "RotaryCraft", DEFAULT_RTC_EXCHANGE).getDouble(DEFAULT_RTC_EXCHANGE); + final double DEFAULT_RF_EXCHANGE = 0.5; + PowerUnits.RF.conversionRatio = + this.get("PowerRatios", "ThermalExpansion", DEFAULT_RF_EXCHANGE).getDouble(DEFAULT_RF_EXCHANGE); + final double DEFAULT_TUNNEL_POWER_LOSS = 0.05; + TUNNEL_POWER_LOSS = this.get("PowerRatios", "TunnelPowerLoss", DEFAULT_TUNNEL_POWER_LOSS) + .getDouble(DEFAULT_TUNNEL_POWER_LOSS); + if (TUNNEL_POWER_LOSS < 0 || TUNNEL_POWER_LOSS >= 1) TUNNEL_POWER_LOSS = DEFAULT_TUNNEL_POWER_LOSS; + + final double usageEffective = + this.get("PowerRatios", "UsageMultiplier", 1.0).getDouble(1.0); + PowerMultiplier.CONFIG.multiplier = Math.max(0.01, usageEffective); + + CondenserOutput.MATTER_BALLS.requiredPower = + this.get("Condenser", "MatterBalls", 256).getInt(256); + CondenserOutput.SINGULARITY.requiredPower = + this.get("Condenser", "Singularity", 256000).getInt(256000); + + this.grinderOres = + this.get("GrindStone", "grinderOres", this.grinderOres).getStringList(); + this.oreDoublePercentage = this.get("GrindStone", "oreDoublePercentage", this.oreDoublePercentage) + .getDouble(this.oreDoublePercentage); + + this.settings.registerSetting(Settings.SEARCH_TOOLTIPS, YesNo.YES); + this.settings.registerSetting(Settings.TERMINAL_STYLE, TerminalStyle.TALL); + this.settings.registerSetting(Settings.SEARCH_MODE, SearchBoxMode.AUTOSEARCH); + this.settings.registerSetting(Settings.SAVE_SEARCH, YesNo.NO); + this.settings.registerSetting(Settings.CRAFTING_STATUS, CraftingStatus.TILE); + + this.spawnChargedChance = (float) (1.0 + - this.get("worldGen", "spawnChargedChance", 1.0 - this.spawnChargedChance) + .getDouble(1.0 - this.spawnChargedChance)); + this.minMeteoriteDistance = this.get("worldGen", "minMeteoriteDistance", this.minMeteoriteDistance) + .getInt(this.minMeteoriteDistance); + this.meteoriteClusterChance = this.get("worldGen", "meteoriteClusterChance", this.meteoriteClusterChance) + .getDouble(this.meteoriteClusterChance); + this.meteoriteSpawnChance = this.get("worldGen", "meteoriteSpawnChance", this.meteoriteSpawnChance) + .getDouble(this.meteoriteSpawnChance); + this.meteoriteDimensionWhitelist = this.get( + "worldGen", "meteoriteDimensionWhitelist", this.meteoriteDimensionWhitelist) + .getIntList(); + + this.quartzOresPerCluster = this.get("worldGen", "quartzOresPerCluster", this.quartzOresPerCluster) + .getInt(this.quartzOresPerCluster); + this.quartzOresClusterAmount = this.get("worldGen", "quartzOresClusterAmount", this.quartzOresClusterAmount) + .getInt(this.quartzOresClusterAmount); + + this.minMeteoriteDistanceSq = this.minMeteoriteDistance * this.minMeteoriteDistance; + + this.addCustomCategoryComment( + "wireless", + "Range= WirelessBaseRange + WirelessBoosterRangeMultiplier * Math.pow( boosters, WirelessBoosterExp )\nPowerDrain= WirelessBaseCost + WirelessCostMultiplier * Math.pow( boosters, 1 + boosters / WirelessHighWirelessCount )"); + + this.WirelessBaseCost = + this.get("wireless", "WirelessBaseCost", this.WirelessBaseCost).getDouble(this.WirelessBaseCost); + this.WirelessCostMultiplier = this.get("wireless", "WirelessCostMultiplier", this.WirelessCostMultiplier) + .getDouble(this.WirelessCostMultiplier); + this.WirelessBaseRange = this.get("wireless", "WirelessBaseRange", this.WirelessBaseRange) + .getDouble(this.WirelessBaseRange); + this.WirelessBoosterRangeMultiplier = this.get( + "wireless", "WirelessBoosterRangeMultiplier", this.WirelessBoosterRangeMultiplier) + .getDouble(this.WirelessBoosterRangeMultiplier); + this.WirelessBoosterExp = this.get("wireless", "WirelessBoosterExp", this.WirelessBoosterExp) + .getDouble(this.WirelessBoosterExp); + this.WirelessTerminalDrainMultiplier = this.get( + "wireless", "WirelessTerminalDrainMultiplier", this.WirelessTerminalDrainMultiplier) + .getDouble(this.WirelessTerminalDrainMultiplier); + + this.formationPlaneEntityLimit = this.get( + "automation", "formationPlaneEntityLimit", this.formationPlaneEntityLimit) + .getInt(this.formationPlaneEntityLimit); + + this.wirelessTerminalBattery = this.get("battery", "wirelessTerminal", this.wirelessTerminalBattery) + .getInt(this.wirelessTerminalBattery); + this.chargedStaffBattery = + this.get("battery", "chargedStaff", this.chargedStaffBattery).getInt(this.chargedStaffBattery); + this.entropyManipulatorBattery = this.get("battery", "entropyManipulator", this.entropyManipulatorBattery) + .getInt(this.entropyManipulatorBattery); + this.portableCellBattery = + this.get("battery", "portableCell", this.portableCellBattery).getInt(this.portableCellBattery); + this.colorApplicatorBattery = this.get("battery", "colorApplicator", this.colorApplicatorBattery) + .getInt(this.colorApplicatorBattery); + this.matterCannonBattery = + this.get("battery", "matterCannon", this.matterCannonBattery).getInt(this.matterCannonBattery); + + this.levelEmitterDelay = this.get("tickrates", "LevelEmitterDelay", this.levelEmitterDelay) + .getInt(this.levelEmitterDelay); + this.debugLogTiming = + this.get("debug", "LogTiming", this.debugLogTiming).getBoolean(this.debugLogTiming); + this.debugPathFinding = + this.get("debug", "LogPathFinding", this.debugPathFinding).getBoolean(this.debugPathFinding); + this.p2pBackboneTransfer = this.get("debug", "EnableP2pBackboneTransfer", this.p2pBackboneTransfer) + .getBoolean(this.p2pBackboneTransfer); + this.quantumBridgeBackboneTransfer = this.get( + "debug", "EnableQuantumBridgeBackboneTransfer", this.quantumBridgeBackboneTransfer) + .getBoolean(this.quantumBridgeBackboneTransfer); + this.clientSync(); + + for (final AEFeature feature : AEFeature.values()) { + if (feature.isVisible()) { + if (this.get("Features." + feature.category, feature.name(), feature.defaultValue) + .getBoolean(feature.defaultValue)) { + this.featureFlags.add(feature); + } + } else { + this.featureFlags.add(feature); + } + } + + final ModContainer imb = + cpw.mods.fml.common.Loader.instance().getIndexedModList().get("ImmibisCore"); + if (imb != null) { + final List version = Arrays.asList("59.0.0", "59.0.1", "59.0.2"); + if (version.contains(imb.getVersion())) { + this.featureFlags.remove(AEFeature.AlphaPass); + } + } + + try { + this.selectedPowerUnit = PowerUnits.valueOf(this.get( + "Client", + "PowerUnit", + this.selectedPowerUnit.name(), + this.getListComment(this.selectedPowerUnit)) + .getString()); + } catch (final Throwable t) { + this.selectedPowerUnit = PowerUnits.AE; + } + + for (final TickRates tr : TickRates.values()) { + tr.Load(this); + } + + if (this.isFeatureEnabled(AEFeature.SpatialIO)) { + this.storageBiomeID = + this.get("spatialio", "storageBiomeID", this.storageBiomeID).getInt(this.storageBiomeID); + this.storageProviderID = this.get("spatialio", "storageProviderID", this.storageProviderID) + .getInt(this.storageProviderID); + this.spatialPowerMultiplier = this.get("spatialio", "spatialPowerMultiplier", this.spatialPowerMultiplier) + .getDouble(this.spatialPowerMultiplier); + this.spatialPowerExponent = this.get("spatialio", "spatialPowerExponent", this.spatialPowerExponent) + .getDouble(this.spatialPowerExponent); + } + + if (this.isFeatureEnabled(AEFeature.CraftingCPU)) { + this.craftingCalculationTimePerTick = this.get( + "craftingCPU", "craftingCalculationTimePerTick", this.craftingCalculationTimePerTick) + .getInt(this.craftingCalculationTimePerTick); + } + + this.updatable = true; + } + + private void clientSync() { + this.disableColoredCableRecipesInNEI = + this.get("Client", "disableColoredCableRecipesInNEI", true).getBoolean(true); + this.enableEffects = this.get("Client", "enableEffects", true).getBoolean(true); + this.useLargeFonts = + this.get("Client", "useTerminalUseLargeFont", false).getBoolean(false); + this.useColoredCraftingStatus = + this.get("Client", "useColoredCraftingStatus", true).getBoolean(true); + this.preserveSearchBar = this.get("Client", "preserveSearchBar", true).getBoolean(true); + this.showOnlyInterfacesWithFreeSlotsInInterfaceTerminal = this.get( + "Client", "showOnlyInterfacesWithFreeSlotsInInterfaceTerminal", false) + .getBoolean(false); + this.MEMonitorableSmallSize = + this.get("Client", "MEMonitorableSmallSize", 6).getInt(6); + this.InterfaceTerminalSmallSize = + this.get("Client", "InterfaceTerminalSmallSize", 6).getInt(6); + // load buttons.. + for (int btnNum = 0; btnNum < 4; btnNum++) { + final Property cmb = this.get("Client", "craftAmtButton" + (btnNum + 1), this.craftByStacks[btnNum]); + final Property pmb = this.get("Client", "priorityAmtButton" + (btnNum + 1), this.priorityByStacks[btnNum]); + final Property lmb = this.get("Client", "levelAmtButton" + (btnNum + 1), this.levelByStacks[btnNum]); + + final int buttonCap = (int) (Math.pow(10, btnNum + 1) - 1); + + this.craftByStacks[btnNum] = Math.abs(cmb.getInt(this.craftByStacks[btnNum])); + this.priorityByStacks[btnNum] = Math.abs(pmb.getInt(this.priorityByStacks[btnNum])); + this.levelByStacks[btnNum] = Math.abs(pmb.getInt(this.levelByStacks[btnNum])); + + cmb.comment = "Controls buttons on Crafting Screen : Capped at " + buttonCap; + pmb.comment = "Controls buttons on Priority Screen : Capped at " + buttonCap; + lmb.comment = "Controls buttons on Level Emitter Screen : Capped at " + buttonCap; + + this.craftByStacks[btnNum] = Math.min(this.craftByStacks[btnNum], buttonCap); + this.priorityByStacks[btnNum] = Math.min(this.priorityByStacks[btnNum], buttonCap); + this.levelByStacks[btnNum] = Math.min(this.levelByStacks[btnNum], buttonCap); + } + + for (final Settings e : this.settings.getSettings()) { + final String Category = "Client"; // e.getClass().getSimpleName(); + Enum value = this.settings.getSetting(e); + + final Property p = this.get(Category, e.name(), value.name(), this.getListComment(value)); + + try { + value = Enum.valueOf(value.getClass(), p.getString()); + } catch (final IllegalArgumentException er) { + AELog.info("Invalid value '" + p.getString() + "' for " + e.name() + " using '" + value.name() + + "' instead"); + } + + this.settings.putSetting(e, value); + } + } + + private String getListComment(final Enum value) { + String comment = null; + + if (value != null) { + final EnumSet set = EnumSet.allOf(value.getClass()); + + for (final Object Oeg : set) { + final Enum eg = (Enum) Oeg; + if (comment == null) { + comment = "Possible Values: " + eg.name(); + } else { + comment += ", " + eg.name(); + } + } + } + + return comment; + } + + public boolean isFeatureEnabled(final AEFeature f) { + return this.featureFlags.contains(f); + } + + public double wireless_getDrainRate(final double range) { + return this.WirelessTerminalDrainMultiplier * range; + } + + public double wireless_getMaxRange(final int boosters) { + return this.WirelessBaseRange + + this.WirelessBoosterRangeMultiplier * Math.pow(boosters, this.WirelessBoosterExp); + } + + public double wireless_getPowerDrain(final int boosters) { + return this.WirelessBaseCost + + this.WirelessCostMultiplier * Math.pow(boosters, 1 + boosters / this.WirelessHighWirelessCount); + } + + @Override + public Property get( + final String category, + final String key, + final String defaultValue, + final String comment, + final Property.Type type) { + final Property prop = super.get(category, key, defaultValue, comment, type); + + if (prop != null) { + if (!category.equals("Client")) { + prop.setRequiresMcRestart(true); + } + } + + return prop; + } + + @Override + public void save() { + if (this.isFeatureEnabled(AEFeature.SpatialIO)) { + this.get("spatialio", "storageBiomeID", this.storageBiomeID).set(this.storageBiomeID); + this.get("spatialio", "storageProviderID", this.storageProviderID).set(this.storageProviderID); + } + + this.get("Client", "PowerUnit", this.selectedPowerUnit.name(), this.getListComment(this.selectedPowerUnit)) + .set(this.selectedPowerUnit.name()); + + if (this.hasChanged()) { + super.save(); + } + } + + @SubscribeEvent + public void onConfigChanged(final ConfigChangedEvent.OnConfigChangedEvent eventArgs) { + if (eventArgs.modID.equals(AppEng.MOD_ID)) { + this.clientSync(); + } + } + + public boolean disableColoredCableRecipesInNEI() { + return this.disableColoredCableRecipesInNEI; + } + + public String getFilePath() { + return this.configFile.toString(); + } + + public boolean useAEVersion(final MaterialType mt) { + if (this.isFeatureEnabled(AEFeature.WebsiteRecipes)) { + return true; + } + + this.setCategoryComment( + "OreCamouflage", + "AE2 Automatically uses alternative ores present in your instance of MC to blend better with its surroundings, if you prefer you can disable this selectively using these flags; Its important to note, that some if these items even if enabled may not be craftable in game because other items are overriding their recipes."); + final Property p = this.get("OreCamouflage", mt.name(), true); + p.comment = "OreDictionary Names: " + mt.getOreName(); + + return !p.getBoolean(true); + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum setting, final Enum newValue) { + for (final Settings e : this.settings.getSettings()) { + if (e == setting) { + final String Category = "Client"; + final Property p = + this.get(Category, e.name(), this.settings.getSetting(e).name(), this.getListComment(newValue)); + p.set(newValue.name()); + } + } + + if (this.updatable) { + this.save(); + } + } + + public int getFreeMaterial(final int varID) { + return this.getFreeIDSLot(varID, "materials"); + } + + public int getFreeIDSLot(final int varID, final String category) { + boolean alreadyUsed = false; + int min = 0; + + for (final Property p : this.getCategory(category).getValues().values()) { + final int thisInt = p.getInt(); + + if (varID == thisInt) { + alreadyUsed = true; + } + + min = Math.max(min, thisInt + 1); + } + + if (alreadyUsed) { + if (min < 16383) { + min = 16383; + } + + return min; + } + + return varID; + } + + public int getFreePart(final int varID) { + return this.getFreeIDSLot(varID, "parts"); + } + + @Override + public IConfigManager getConfigManager() { + return this.settings; + } + + public boolean useTerminalUseLargeFont() { + return this.useLargeFonts; + } + + public int craftItemsByStackAmounts(final int i) { + return this.craftByStacks[i]; + } + + public int priorityByStacksAmounts(final int i) { + return this.priorityByStacks[i]; + } + + public int levelByStackAmounts(final int i) { + return this.levelByStacks[i]; + } + + public Enum getSetting(final String category, final Class class1, final Enum myDefault) { + final String name = class1.getSimpleName(); + final Property p = this.get(category, name, myDefault.name()); + + try { + return (Enum) class1.getField(p.toString()).get(class1); + } catch (final Throwable t) { + // :{ + } + + return myDefault; + } + + public void setSetting(final String category, final Enum s) { + final String name = s.getClass().getSimpleName(); + this.get(category, name, s.name()).set(s.name()); + this.save(); + } + + public PowerUnits selectedPowerUnit() { + return this.selectedPowerUnit; + } + + public void nextPowerUnit(final boolean backwards) { + this.selectedPowerUnit = + Platform.rotateEnum(this.selectedPowerUnit, backwards, Settings.POWER_UNITS.getPossibleValues()); + this.save(); + } } diff --git a/src/main/java/appeng/core/AELog.java b/src/main/java/appeng/core/AELog.java index 1eb89123cc1..986c59138f7 100644 --- a/src/main/java/appeng/core/AELog.java +++ b/src/main/java/appeng/core/AELog.java @@ -18,375 +18,340 @@ package appeng.core; - import appeng.core.features.AEFeature; import appeng.tile.AEBaseTile; import appeng.util.Platform; +import javax.annotation.Nonnull; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; -import javax.annotation.Nonnull; - - /** * Utility class for easier logging. */ -public final class AELog -{ - - private static final String LOGGER_PREFIX = "AE2:"; - private static final String SERVER_SUFFIX = "S"; - private static final String CLIENT_SUFFIX = "C"; - - private static final String BLOCK_UPDATE = "Block Update of %s @ ( %d, %d, %d )"; - - private static final String DEFAULT_EXCEPTION_MESSAGE = "Exception: "; - - private AELog() - { - } - - /** - * Returns a {@link Logger} logger suitable for the effective side (client/server). - * - * @return a suitable logger instance - */ - private static Logger getLogger() - { - final String loggerName = LOGGER_PREFIX + ( Platform.isServer() ? SERVER_SUFFIX : CLIENT_SUFFIX ); - final Logger logger = LogManager.getLogger( loggerName ); - - return logger; - } - - /** - * Indicates of the global log is enabled or disabled. - *

- * By default it is enabled. - * - * @return true when the log is enabled. - */ - public static boolean isLogEnabled() - { - return AEConfig.instance == null || AEConfig.instance.isFeatureEnabled( AEFeature.Logging ); - } - - /** - * Logs a formatted message with a specific log level. - *

- * This uses {@link String#format(String, Object...)} as opposed to the {@link ParameterizedMessage} to allow a more - * flexible formatting. - *

- * The output can be globally disabled via the configuration file. - * - * @param level the intended level. - * @param message the message to be formatted. - * @param params the parameters used for {@link String#format(String, Object...)}. - */ - public static void log( @Nonnull final Level level, @Nonnull final String message, final Object... params ) - { - if( AELog.isLogEnabled() ) - { - final String formattedMessage = String.format( message, params ); - final Logger logger = getLogger(); - - logger.log( level, formattedMessage ); - } - } - - /** - * Log an exception with a custom message formated via {@link String#format(String, Object...)} - *

- * Similar to {@link AELog#log(Level, String, Object...)}. - * - * @param level the intended level. - * @param exception - * @param message the message to be formatted. - * @param params the parameters used for {@link String#format(String, Object...)}. - * @see AELog#log(Level, String, Object...) - */ - public static void log( @Nonnull final Level level, @Nonnull final Throwable exception, @Nonnull String message, final Object... params ) - { - if( AELog.isLogEnabled() ) - { - final String formattedMessage = String.format( message, params ); - final Logger logger = getLogger(); - - logger.log( level, formattedMessage, exception ); - } - } - - /** - * @param format - * @param params - * @see AELog#log(Level, String, Object...) - */ - public static void info( @Nonnull final String format, final Object... params ) - { - log( Level.INFO, format, params ); - } - - /** - * Log exception as {@link Level#INFO} - * - * @param exception - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void info( @Nonnull final Throwable exception ) - { - log( Level.INFO, exception, DEFAULT_EXCEPTION_MESSAGE ); - } - - /** - * Log exception as {@link Level#INFO} - * - * @param exception - * @param message - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void info( @Nonnull final Throwable exception, @Nonnull final String message ) - { - log( Level.INFO, exception, message ); - } - - /** - * @param format - * @param params - * @see AELog#log(Level, String, Object...) - */ - public static void warn( @Nonnull final String format, final Object... params ) - { - log( Level.WARN, format, params ); - } - - /** - * Log exception as {@link Level#WARN} - * - * @param exception - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void warn( @Nonnull final Throwable exception ) - { - log( Level.WARN, exception, DEFAULT_EXCEPTION_MESSAGE ); - } - - /** - * Log exception as {@link Level#WARN} - * - * @param exception - * @param message - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void warn( @Nonnull final Throwable exception, @Nonnull final String message ) - { - log( Level.WARN, exception, message ); - } - - /** - * @param format - * @param params - * @see AELog#log(Level, String, Object...) - */ - public static void error( @Nonnull final String format, final Object... params ) - { - log( Level.ERROR, format, params ); - } - - /** - * Log exception as {@link Level#ERROR} - * - * @param exception - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void error( @Nonnull final Throwable exception ) - { - log( Level.ERROR, exception, DEFAULT_EXCEPTION_MESSAGE ); - } - - /** - * Log exception as {@link Level#ERROR} - * - * @param exception - * @param message - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void error( @Nonnull final Throwable exception, @Nonnull final String message ) - { - log( Level.ERROR, exception, message ); - } - - /** - * Log message as {@link Level#DEBUG} - * - * @param format - * @param data - * @see AELog#log(Level, String, Object...) - */ - public static void debug( @Nonnull final String format, final Object... data ) - { - if( AELog.isDebugLogEnabled() ) - { - log( Level.DEBUG, format, data ); - } - } - - /** - * Log exception as {@link Level#DEBUG} - * - * @param exception - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void debug( @Nonnull final Throwable exception ) - { - if( AELog.isDebugLogEnabled() ) - { - log( Level.DEBUG, exception, DEFAULT_EXCEPTION_MESSAGE ); - } - } - - /** - * Log exception as {@link Level#DEBUG} - * - * @param exception - * @param message - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void debug( @Nonnull final Throwable exception, @Nonnull final String message ) - { - if( AELog.isDebugLogEnabled() ) - { - log( Level.DEBUG, exception, message ); - } - } - - /** - * Use to check for an enabled debug log. - *

- * Can be used to prevent the execution of debug logic. - * - * @return true when the debug log is enabled. - */ - public static boolean isDebugLogEnabled() - { - return AEConfig.instance.isFeatureEnabled( AEFeature.DebugLogging ); - } - - // - // Specialized handlers - // - - /** - * A specialized logging for grinder recipes, can be disabled inside configuration file. - * - * @param message String to be logged - */ - public static void grinder( @Nonnull final String message ) - { - if( AEConfig.instance.isFeatureEnabled( AEFeature.GrinderLogging ) ) - { - log( Level.DEBUG, "grinder: " + message ); - } - } - - /** - * A specialized logging for mod integration errors, can be disabled inside configuration file. - * - * @param exception - */ - public static void integration( @Nonnull final Throwable exception ) - { - if( AEConfig.instance.isFeatureEnabled( AEFeature.IntegrationLogging ) ) - { - debug( exception ); - } - } - - /** - * Logging of block updates. - *

- * Off by default, can be enabled inside the configuration file. - * - * @param xCoord - * @param yCoord - * @param zCoord - * @param aeBaseTile - * @see AELog#log(Level, String, Object...) - */ - public static void blockUpdate( final int xCoord, final int yCoord, final int zCoord, @Nonnull final AEBaseTile aeBaseTile ) - { - if( AEConfig.instance.isFeatureEnabled( AEFeature.UpdateLogging ) ) - { - info( BLOCK_UPDATE, aeBaseTile.getClass().getName(), xCoord, +yCoord, +zCoord ); - } - } - - /** - * Use to check for an enabled crafting log. - *

- * Can be used to prevent the execution of unneeded logic. - * - * @return true when the crafting log is enabled. - */ - public static boolean isCraftingLogEnabled() - { - return AEConfig.instance.isFeatureEnabled( AEFeature.CraftingLog ); - } - - /** - * Logging for autocrafting. - *

- * Off by default, can be enabled inside the configuration file. - * - * @param message - * @param params - * @see AELog#log(Level, String, Object...) - */ - public static void crafting( @Nonnull final String message, final Object... params ) - { - if( AELog.isCraftingLogEnabled() ) - { - log( Level.INFO, message, params ); - } - } - - /** - * Use to check for an enabled crafting debug log. - *

- * Can be used to prevent the execution of unneeded logic. - * - * @return true when the crafting debug log is enabled. - */ - public static boolean isCraftingDebugLogEnabled() - { - return AEConfig.instance.isFeatureEnabled( AEFeature.CraftingLog ) && AEConfig.instance.isFeatureEnabled( AEFeature.DebugLogging ); - } - - /** - * Debug logging for autocrafting. - *

- * Off by default, can be enabled inside the configuration file. - * - * @param message - * @param params - * @see AELog#log(Level, String, Object...) - */ - public static void craftingDebug( @Nonnull final String message, final Object... params ) - { - if( AELog.isCraftingDebugLogEnabled() ) - { - log( Level.DEBUG, message, params ); - } - } +public final class AELog { + + private static final String LOGGER_PREFIX = "AE2:"; + private static final String SERVER_SUFFIX = "S"; + private static final String CLIENT_SUFFIX = "C"; + + private static final String BLOCK_UPDATE = "Block Update of %s @ ( %d, %d, %d )"; + + private static final String DEFAULT_EXCEPTION_MESSAGE = "Exception: "; + + private AELog() {} + + /** + * Returns a {@link Logger} logger suitable for the effective side (client/server). + * + * @return a suitable logger instance + */ + private static Logger getLogger() { + final String loggerName = LOGGER_PREFIX + (Platform.isServer() ? SERVER_SUFFIX : CLIENT_SUFFIX); + final Logger logger = LogManager.getLogger(loggerName); + + return logger; + } + + /** + * Indicates of the global log is enabled or disabled. + *

+ * By default it is enabled. + * + * @return true when the log is enabled. + */ + public static boolean isLogEnabled() { + return AEConfig.instance == null || AEConfig.instance.isFeatureEnabled(AEFeature.Logging); + } + + /** + * Logs a formatted message with a specific log level. + *

+ * This uses {@link String#format(String, Object...)} as opposed to the {@link ParameterizedMessage} to allow a more + * flexible formatting. + *

+ * The output can be globally disabled via the configuration file. + * + * @param level the intended level. + * @param message the message to be formatted. + * @param params the parameters used for {@link String#format(String, Object...)}. + */ + public static void log(@Nonnull final Level level, @Nonnull final String message, final Object... params) { + if (AELog.isLogEnabled()) { + final String formattedMessage = String.format(message, params); + final Logger logger = getLogger(); + + logger.log(level, formattedMessage); + } + } + + /** + * Log an exception with a custom message formated via {@link String#format(String, Object...)} + *

+ * Similar to {@link AELog#log(Level, String, Object...)}. + * + * @param level the intended level. + * @param exception + * @param message the message to be formatted. + * @param params the parameters used for {@link String#format(String, Object...)}. + * @see AELog#log(Level, String, Object...) + */ + public static void log( + @Nonnull final Level level, + @Nonnull final Throwable exception, + @Nonnull String message, + final Object... params) { + if (AELog.isLogEnabled()) { + final String formattedMessage = String.format(message, params); + final Logger logger = getLogger(); + + logger.log(level, formattedMessage, exception); + } + } + + /** + * @param format + * @param params + * @see AELog#log(Level, String, Object...) + */ + public static void info(@Nonnull final String format, final Object... params) { + log(Level.INFO, format, params); + } + + /** + * Log exception as {@link Level#INFO} + * + * @param exception + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void info(@Nonnull final Throwable exception) { + log(Level.INFO, exception, DEFAULT_EXCEPTION_MESSAGE); + } + + /** + * Log exception as {@link Level#INFO} + * + * @param exception + * @param message + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void info(@Nonnull final Throwable exception, @Nonnull final String message) { + log(Level.INFO, exception, message); + } + + /** + * @param format + * @param params + * @see AELog#log(Level, String, Object...) + */ + public static void warn(@Nonnull final String format, final Object... params) { + log(Level.WARN, format, params); + } + + /** + * Log exception as {@link Level#WARN} + * + * @param exception + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void warn(@Nonnull final Throwable exception) { + log(Level.WARN, exception, DEFAULT_EXCEPTION_MESSAGE); + } + + /** + * Log exception as {@link Level#WARN} + * + * @param exception + * @param message + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void warn(@Nonnull final Throwable exception, @Nonnull final String message) { + log(Level.WARN, exception, message); + } + + /** + * @param format + * @param params + * @see AELog#log(Level, String, Object...) + */ + public static void error(@Nonnull final String format, final Object... params) { + log(Level.ERROR, format, params); + } + + /** + * Log exception as {@link Level#ERROR} + * + * @param exception + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void error(@Nonnull final Throwable exception) { + log(Level.ERROR, exception, DEFAULT_EXCEPTION_MESSAGE); + } + + /** + * Log exception as {@link Level#ERROR} + * + * @param exception + * @param message + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void error(@Nonnull final Throwable exception, @Nonnull final String message) { + log(Level.ERROR, exception, message); + } + + /** + * Log message as {@link Level#DEBUG} + * + * @param format + * @param data + * @see AELog#log(Level, String, Object...) + */ + public static void debug(@Nonnull final String format, final Object... data) { + if (AELog.isDebugLogEnabled()) { + log(Level.DEBUG, format, data); + } + } + + /** + * Log exception as {@link Level#DEBUG} + * + * @param exception + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void debug(@Nonnull final Throwable exception) { + if (AELog.isDebugLogEnabled()) { + log(Level.DEBUG, exception, DEFAULT_EXCEPTION_MESSAGE); + } + } + + /** + * Log exception as {@link Level#DEBUG} + * + * @param exception + * @param message + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void debug(@Nonnull final Throwable exception, @Nonnull final String message) { + if (AELog.isDebugLogEnabled()) { + log(Level.DEBUG, exception, message); + } + } + + /** + * Use to check for an enabled debug log. + *

+ * Can be used to prevent the execution of debug logic. + * + * @return true when the debug log is enabled. + */ + public static boolean isDebugLogEnabled() { + return AEConfig.instance.isFeatureEnabled(AEFeature.DebugLogging); + } + + // + // Specialized handlers + // + + /** + * A specialized logging for grinder recipes, can be disabled inside configuration file. + * + * @param message String to be logged + */ + public static void grinder(@Nonnull final String message) { + if (AEConfig.instance.isFeatureEnabled(AEFeature.GrinderLogging)) { + log(Level.DEBUG, "grinder: " + message); + } + } + + /** + * A specialized logging for mod integration errors, can be disabled inside configuration file. + * + * @param exception + */ + public static void integration(@Nonnull final Throwable exception) { + if (AEConfig.instance.isFeatureEnabled(AEFeature.IntegrationLogging)) { + debug(exception); + } + } + + /** + * Logging of block updates. + *

+ * Off by default, can be enabled inside the configuration file. + * + * @param xCoord + * @param yCoord + * @param zCoord + * @param aeBaseTile + * @see AELog#log(Level, String, Object...) + */ + public static void blockUpdate( + final int xCoord, final int yCoord, final int zCoord, @Nonnull final AEBaseTile aeBaseTile) { + if (AEConfig.instance.isFeatureEnabled(AEFeature.UpdateLogging)) { + info(BLOCK_UPDATE, aeBaseTile.getClass().getName(), xCoord, +yCoord, +zCoord); + } + } + + /** + * Use to check for an enabled crafting log. + *

+ * Can be used to prevent the execution of unneeded logic. + * + * @return true when the crafting log is enabled. + */ + public static boolean isCraftingLogEnabled() { + return AEConfig.instance.isFeatureEnabled(AEFeature.CraftingLog); + } + + /** + * Logging for autocrafting. + *

+ * Off by default, can be enabled inside the configuration file. + * + * @param message + * @param params + * @see AELog#log(Level, String, Object...) + */ + public static void crafting(@Nonnull final String message, final Object... params) { + if (AELog.isCraftingLogEnabled()) { + log(Level.INFO, message, params); + } + } + + /** + * Use to check for an enabled crafting debug log. + *

+ * Can be used to prevent the execution of unneeded logic. + * + * @return true when the crafting debug log is enabled. + */ + public static boolean isCraftingDebugLogEnabled() { + return AEConfig.instance.isFeatureEnabled(AEFeature.CraftingLog) + && AEConfig.instance.isFeatureEnabled(AEFeature.DebugLogging); + } + + /** + * Debug logging for autocrafting. + *

+ * Off by default, can be enabled inside the configuration file. + * + * @param message + * @param params + * @see AELog#log(Level, String, Object...) + */ + public static void craftingDebug(@Nonnull final String message, final Object... params) { + if (AELog.isCraftingDebugLogEnabled()) { + log(Level.DEBUG, message, params); + } + } /** * Print current stack trace for debug purposes * * @param level Log level */ - public static void printStackTrace(Level level) - { + public static void printStackTrace(Level level) { log(level, "Stack trace:"); for (StackTraceElement traceElement : Thread.currentThread().getStackTrace()) log(level, "\t " + traceElement.toString()); diff --git a/src/main/java/appeng/core/Api.java b/src/main/java/appeng/core/Api.java index 3333cffbfe8..86607ebdfcb 100644 --- a/src/main/java/appeng/core/Api.java +++ b/src/main/java/appeng/core/Api.java @@ -18,7 +18,6 @@ package appeng.core; - import appeng.api.IAppEngApi; import appeng.api.definitions.Blocks; import appeng.api.definitions.Items; @@ -38,96 +37,82 @@ import appeng.util.Platform; import net.minecraftforge.common.util.ForgeDirection; - -public final class Api implements IAppEngApi -{ - public static final Api INSTANCE = new Api(); - - private final ApiPart partHelper; - - // private MovableTileRegistry MovableRegistry = new MovableTileRegistry(); - private final IRegistryContainer registryContainer; - private final IStorageHelper storageHelper; - private final Materials materials; - private final Items items; - private final Blocks blocks; - private final Parts parts; - private final ApiDefinitions definitions; - - private Api() - { - this.parts = new Parts(); - this.blocks = new Blocks(); - this.items = new Items(); - this.materials = new Materials(); - this.storageHelper = new ApiStorage(); - this.registryContainer = new RegistryContainer(); - this.partHelper = new ApiPart(); - this.definitions = new ApiDefinitions( this.partHelper ); - } - - @Override - public IRegistryContainer registries() - { - return this.registryContainer; - } - - @Override - public IStorageHelper storage() - { - return this.storageHelper; - } - - @Override - public ApiPart partHelper() - { - return this.partHelper; - } - - @Override - public Items items() - { - return this.items; - } - - @Override - public Materials materials() - { - return this.materials; - } - - @Override - public Blocks blocks() - { - return this.blocks; - } - - @Override - public Parts parts() - { - return this.parts; - } - - @Override - public ApiDefinitions definitions() - { - return this.definitions; - } - - @Override - public IGridNode createGridNode( final IGridBlock blk ) - { - if( Platform.isClient() ) - { - throw new IllegalStateException( "Grid features for " + blk + " are server side only." ); - } - - return new GridNode( blk ); - } - - @Override - public IGridConnection createGridConnection( final IGridNode a, final IGridNode b ) throws FailedConnection - { - return new GridConnection( a, b, ForgeDirection.UNKNOWN ); - } +public final class Api implements IAppEngApi { + public static final Api INSTANCE = new Api(); + + private final ApiPart partHelper; + + // private MovableTileRegistry MovableRegistry = new MovableTileRegistry(); + private final IRegistryContainer registryContainer; + private final IStorageHelper storageHelper; + private final Materials materials; + private final Items items; + private final Blocks blocks; + private final Parts parts; + private final ApiDefinitions definitions; + + private Api() { + this.parts = new Parts(); + this.blocks = new Blocks(); + this.items = new Items(); + this.materials = new Materials(); + this.storageHelper = new ApiStorage(); + this.registryContainer = new RegistryContainer(); + this.partHelper = new ApiPart(); + this.definitions = new ApiDefinitions(this.partHelper); + } + + @Override + public IRegistryContainer registries() { + return this.registryContainer; + } + + @Override + public IStorageHelper storage() { + return this.storageHelper; + } + + @Override + public ApiPart partHelper() { + return this.partHelper; + } + + @Override + public Items items() { + return this.items; + } + + @Override + public Materials materials() { + return this.materials; + } + + @Override + public Blocks blocks() { + return this.blocks; + } + + @Override + public Parts parts() { + return this.parts; + } + + @Override + public ApiDefinitions definitions() { + return this.definitions; + } + + @Override + public IGridNode createGridNode(final IGridBlock blk) { + if (Platform.isClient()) { + throw new IllegalStateException("Grid features for " + blk + " are server side only."); + } + + return new GridNode(blk); + } + + @Override + public IGridConnection createGridConnection(final IGridNode a, final IGridNode b) throws FailedConnection { + return new GridConnection(a, b, ForgeDirection.UNKNOWN); + } } diff --git a/src/main/java/appeng/core/ApiDefinitions.java b/src/main/java/appeng/core/ApiDefinitions.java index 5d1a44bf7ae..49d1c5ac37b 100644 --- a/src/main/java/appeng/core/ApiDefinitions.java +++ b/src/main/java/appeng/core/ApiDefinitions.java @@ -18,68 +18,58 @@ package appeng.core; - import appeng.api.definitions.IDefinitions; import appeng.api.parts.IPartHelper; import appeng.core.api.definitions.*; - /** * Internal implementation of the definitions for the API */ -public final class ApiDefinitions implements IDefinitions -{ - private final ApiBlocks blocks; - private final ApiItems items; - private final ApiMaterials materials; - private final ApiParts parts; - private final FeatureHandlerRegistry handlers; - private final FeatureRegistry features; +public final class ApiDefinitions implements IDefinitions { + private final ApiBlocks blocks; + private final ApiItems items; + private final ApiMaterials materials; + private final ApiParts parts; + private final FeatureHandlerRegistry handlers; + private final FeatureRegistry features; - public ApiDefinitions( final IPartHelper partHelper ) - { - this.features = new FeatureRegistry(); - this.handlers = new FeatureHandlerRegistry(); + public ApiDefinitions(final IPartHelper partHelper) { + this.features = new FeatureRegistry(); + this.handlers = new FeatureHandlerRegistry(); - final DefinitionConstructor constructor = new DefinitionConstructor( this.features, this.handlers ); + final DefinitionConstructor constructor = new DefinitionConstructor(this.features, this.handlers); - this.blocks = new ApiBlocks( constructor ); - this.items = new ApiItems( constructor ); - this.materials = new ApiMaterials( constructor ); - this.parts = new ApiParts( constructor, partHelper ); - } + this.blocks = new ApiBlocks(constructor); + this.items = new ApiItems(constructor); + this.materials = new ApiMaterials(constructor); + this.parts = new ApiParts(constructor, partHelper); + } - FeatureHandlerRegistry getFeatureHandlerRegistry() - { - return this.handlers; - } + FeatureHandlerRegistry getFeatureHandlerRegistry() { + return this.handlers; + } - FeatureRegistry getFeatureRegistry() - { - return this.features; - } + FeatureRegistry getFeatureRegistry() { + return this.features; + } - @Override - public ApiBlocks blocks() - { - return this.blocks; - } + @Override + public ApiBlocks blocks() { + return this.blocks; + } - @Override - public ApiItems items() - { - return this.items; - } + @Override + public ApiItems items() { + return this.items; + } - @Override - public ApiMaterials materials() - { - return this.materials; - } + @Override + public ApiMaterials materials() { + return this.materials; + } - @Override - public ApiParts parts() - { - return this.parts; - } + @Override + public ApiParts parts() { + return this.parts; + } } diff --git a/src/main/java/appeng/core/AppEng.java b/src/main/java/appeng/core/AppEng.java index 6d40d882ded..75813d2fcbd 100644 --- a/src/main/java/appeng/core/AppEng.java +++ b/src/main/java/appeng/core/AppEng.java @@ -18,7 +18,6 @@ package appeng.core; - import appeng.core.crash.CrashInfo; import appeng.core.crash.IntegrationCrashEnhancement; import appeng.core.crash.ModCrashEnhancement; @@ -44,199 +43,184 @@ import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.*; import cpw.mods.fml.common.network.NetworkRegistry; -import net.minecraftforge.common.config.Configuration; - -import javax.annotation.Nonnull; import java.io.File; import java.util.concurrent.TimeUnit; +import javax.annotation.Nonnull; +import net.minecraftforge.common.config.Configuration; + +@Mod( + modid = AppEng.MOD_ID, + acceptedMinecraftVersions = "[1.7.10]", + name = AppEng.MOD_NAME, + version = AEConfig.VERSION, + dependencies = AppEng.MOD_DEPENDENCIES, + guiFactory = "appeng.client.gui.config.AEConfigGuiFactory") +public final class AppEng { + public static final String MOD_ID = "appliedenergistics2"; + public static final String MOD_NAME = "Applied Energistics 2"; + public static final String MOD_DEPENDENCIES = + // a few mods, AE should load after, probably. + // required-after:AppliedEnergistics2API|all; + // "after:gregtech_addon;after:Mekanism;after:IC2;after:ThermalExpansion;after:BuildCraft|Core;" + + + // depend on version of forge used for build. + "after:appliedenergistics2-core;" + "required-after:Forge@[" // require forge. + + net.minecraftforge.common.ForgeVersion.majorVersion + '.' // majorVersion + + net.minecraftforge.common.ForgeVersion.minorVersion + '.' // minorVersion + + net.minecraftforge.common.ForgeVersion.revisionVersion + '.' // revisionVersion + + net.minecraftforge.common.ForgeVersion.buildVersion + ",)"; // buildVersion + + @Nonnull + private static final AppEng INSTANCE = new AppEng(); + + private final Registration registration; + + private File configDirectory; + private CustomRecipeConfig customRecipeConfig; + + /** + * Folder for recipes + *

+ * used for CSV item names and the recipes + */ + private File recipeDirectory; + + /** + * determined in pre-init but used in init + */ + private ExportConfig exportConfig; + + AppEng() { + FMLCommonHandler.instance().registerCrashCallable(new ModCrashEnhancement(CrashInfo.MOD_VERSION)); + + this.registration = new Registration(); + } + + @Nonnull + @Mod.InstanceFactory + public static AppEng instance() { + return INSTANCE; + } + + @Nonnull + public final Registration getRegistration() { + return this.registration; + } + + @EventHandler + private void preInit(final FMLPreInitializationEvent event) { + if (!Loader.isModLoaded("appliedenergistics2-core")) { + CommonHelper.proxy.missingCoreMod(); + } + + final Stopwatch watch = Stopwatch.createStarted(); + this.configDirectory = new File(event.getModConfigurationDirectory().getPath(), "AppliedEnergistics2"); + this.recipeDirectory = new File(this.configDirectory, "recipes"); + + final File configFile = new File(this.configDirectory, "AppliedEnergistics2.cfg"); + final File facadeFile = new File(this.configDirectory, "Facades.cfg"); + final File versionFile = new File(this.configDirectory, "VersionChecker.cfg"); + final File recipeFile = new File(this.configDirectory, "CustomRecipes.cfg"); + final Configuration recipeConfiguration = new Configuration(recipeFile); + + AEConfig.instance = new AEConfig(configFile); + FacadeConfig.instance = new FacadeConfig(facadeFile); + final VersionCheckerConfig versionCheckerConfig = new VersionCheckerConfig(versionFile); + this.customRecipeConfig = new CustomRecipeForgeConfiguration(recipeConfiguration); + this.exportConfig = new ForgeExportConfig(recipeConfiguration); + + AELog.info("Pre Initialization ( started )"); + + CreativeTab.init(); + if (AEConfig.instance.isFeatureEnabled(AEFeature.Facades)) { + CreativeTabFacade.init(); + } + + if (Platform.isClient()) { + CommonHelper.proxy.init(); + } + + this.registration.preInitialize(event); + + if (versionCheckerConfig.isVersionCheckingEnabled()) { + final VersionChecker versionChecker = new VersionChecker(versionCheckerConfig); + final Thread versionCheckerThread = new Thread(versionChecker); + + this.startService("AE2 VersionChecker", versionCheckerThread); + } + + AELog.info("Pre Initialization ( ended after " + watch.elapsed(TimeUnit.MILLISECONDS) + "ms )"); + } + + private void startService(final String serviceName, final Thread thread) { + thread.setName(serviceName); + thread.setPriority(Thread.MIN_PRIORITY); + + AELog.info("Starting " + serviceName); + thread.start(); + } + + @EventHandler + private void init(final FMLInitializationEvent event) { + final Stopwatch start = Stopwatch.createStarted(); + AELog.info("Initialization ( started )"); + + if (this.exportConfig.isExportingItemNamesEnabled()) { + final ExportProcess process = new ExportProcess(this.recipeDirectory, this.exportConfig); + final Thread exportProcessThread = new Thread(process); + + this.startService("AE2 CSV Export", exportProcessThread); + } + + this.registration.initialize(event, this.recipeDirectory, this.customRecipeConfig); + IntegrationRegistry.INSTANCE.init(); + + AELog.info("Initialization ( ended after " + start.elapsed(TimeUnit.MILLISECONDS) + "ms )"); + } + + @EventHandler + private void postInit(final FMLPostInitializationEvent event) { + final Stopwatch start = Stopwatch.createStarted(); + AELog.info("Post Initialization ( started )"); + + this.registration.postInit(event); + IntegrationRegistry.INSTANCE.postInit(); + FMLCommonHandler.instance().registerCrashCallable(new IntegrationCrashEnhancement()); + + CommonHelper.proxy.postInit(); + AEConfig.instance.save(); + + NetworkRegistry.INSTANCE.registerGuiHandler(this, GuiBridge.GUI_Handler); + NetworkHandler.instance = new NetworkHandler("AE2"); + + AELog.info("Post Initialization ( ended after " + start.elapsed(TimeUnit.MILLISECONDS) + "ms )"); + } + + @EventHandler + private void handleIMCEvent(final FMLInterModComms.IMCEvent event) { + final IMCHandler imcHandler = new IMCHandler(); + + imcHandler.handleIMCEvent(event); + } + + @EventHandler + private void serverAboutToStart(final FMLServerAboutToStartEvent evt) { + WorldData.onServerAboutToStart(); + } + + @EventHandler + private void serverStopping(final FMLServerStoppingEvent event) { + WorldData.instance().onServerStopping(); + } + @EventHandler + private void serverStopped(final FMLServerStoppedEvent event) { + if (WorldData.instance() != null) WorldData.instance().onServerStoppped(); + TickHandler.INSTANCE.shutdown(); + } -@Mod( modid = AppEng.MOD_ID, acceptedMinecraftVersions = "[1.7.10]", name = AppEng.MOD_NAME, version = AEConfig.VERSION, dependencies = AppEng.MOD_DEPENDENCIES, guiFactory = "appeng.client.gui.config.AEConfigGuiFactory" ) -public final class AppEng -{ - public static final String MOD_ID = "appliedenergistics2"; - public static final String MOD_NAME = "Applied Energistics 2"; - public static final String MOD_DEPENDENCIES = - // a few mods, AE should load after, probably. - // required-after:AppliedEnergistics2API|all; - // "after:gregtech_addon;after:Mekanism;after:IC2;after:ThermalExpansion;after:BuildCraft|Core;" + - - // depend on version of forge used for build. - "after:appliedenergistics2-core;" + "required-after:Forge@[" // require forge. - + net.minecraftforge.common.ForgeVersion.majorVersion + '.' // majorVersion - + net.minecraftforge.common.ForgeVersion.minorVersion + '.' // minorVersion - + net.minecraftforge.common.ForgeVersion.revisionVersion + '.' // revisionVersion - + net.minecraftforge.common.ForgeVersion.buildVersion + ",)"; // buildVersion - - @Nonnull - private static final AppEng INSTANCE = new AppEng(); - - private final Registration registration; - - private File configDirectory; - private CustomRecipeConfig customRecipeConfig; - - /** - * Folder for recipes - *

- * used for CSV item names and the recipes - */ - private File recipeDirectory; - - /** - * determined in pre-init but used in init - */ - private ExportConfig exportConfig; - - AppEng() - { - FMLCommonHandler.instance().registerCrashCallable( new ModCrashEnhancement( CrashInfo.MOD_VERSION ) ); - - this.registration = new Registration(); - } - - @Nonnull - @Mod.InstanceFactory - public static AppEng instance() - { - return INSTANCE; - } - - @Nonnull - public final Registration getRegistration() - { - return this.registration; - } - - @EventHandler - private void preInit( final FMLPreInitializationEvent event ) - { - if( !Loader.isModLoaded( "appliedenergistics2-core" ) ) - { - CommonHelper.proxy.missingCoreMod(); - } - - final Stopwatch watch = Stopwatch.createStarted(); - this.configDirectory = new File( event.getModConfigurationDirectory().getPath(), "AppliedEnergistics2" ); - this.recipeDirectory = new File( this.configDirectory, "recipes" ); - - final File configFile = new File( this.configDirectory, "AppliedEnergistics2.cfg" ); - final File facadeFile = new File( this.configDirectory, "Facades.cfg" ); - final File versionFile = new File( this.configDirectory, "VersionChecker.cfg" ); - final File recipeFile = new File( this.configDirectory, "CustomRecipes.cfg" ); - final Configuration recipeConfiguration = new Configuration( recipeFile ); - - AEConfig.instance = new AEConfig( configFile ); - FacadeConfig.instance = new FacadeConfig( facadeFile ); - final VersionCheckerConfig versionCheckerConfig = new VersionCheckerConfig( versionFile ); - this.customRecipeConfig = new CustomRecipeForgeConfiguration( recipeConfiguration ); - this.exportConfig = new ForgeExportConfig( recipeConfiguration ); - - AELog.info( "Pre Initialization ( started )" ); - - CreativeTab.init(); - if( AEConfig.instance.isFeatureEnabled( AEFeature.Facades ) ) - { - CreativeTabFacade.init(); - } - - if( Platform.isClient() ) - { - CommonHelper.proxy.init(); - } - - this.registration.preInitialize( event ); - - if( versionCheckerConfig.isVersionCheckingEnabled() ) - { - final VersionChecker versionChecker = new VersionChecker( versionCheckerConfig ); - final Thread versionCheckerThread = new Thread( versionChecker ); - - this.startService( "AE2 VersionChecker", versionCheckerThread ); - } - - AELog.info( "Pre Initialization ( ended after " + watch.elapsed( TimeUnit.MILLISECONDS ) + "ms )" ); - } - - private void startService( final String serviceName, final Thread thread ) - { - thread.setName( serviceName ); - thread.setPriority( Thread.MIN_PRIORITY ); - - AELog.info( "Starting " + serviceName ); - thread.start(); - } - - @EventHandler - private void init( final FMLInitializationEvent event ) - { - final Stopwatch start = Stopwatch.createStarted(); - AELog.info( "Initialization ( started )" ); - - if( this.exportConfig.isExportingItemNamesEnabled() ) - { - final ExportProcess process = new ExportProcess( this.recipeDirectory, this.exportConfig ); - final Thread exportProcessThread = new Thread( process ); - - this.startService( "AE2 CSV Export", exportProcessThread ); - } - - this.registration.initialize( event, this.recipeDirectory, this.customRecipeConfig ); - IntegrationRegistry.INSTANCE.init(); - - AELog.info( "Initialization ( ended after " + start.elapsed( TimeUnit.MILLISECONDS ) + "ms )" ); - } - - @EventHandler - private void postInit( final FMLPostInitializationEvent event ) - { - final Stopwatch start = Stopwatch.createStarted(); - AELog.info( "Post Initialization ( started )" ); - - this.registration.postInit( event ); - IntegrationRegistry.INSTANCE.postInit(); - FMLCommonHandler.instance().registerCrashCallable( new IntegrationCrashEnhancement() ); - - CommonHelper.proxy.postInit(); - AEConfig.instance.save(); - - NetworkRegistry.INSTANCE.registerGuiHandler( this, GuiBridge.GUI_Handler ); - NetworkHandler.instance = new NetworkHandler( "AE2" ); - - AELog.info( "Post Initialization ( ended after " + start.elapsed( TimeUnit.MILLISECONDS ) + "ms )" ); - } - - @EventHandler - private void handleIMCEvent( final FMLInterModComms.IMCEvent event ) - { - final IMCHandler imcHandler = new IMCHandler(); - - imcHandler.handleIMCEvent( event ); - } - - @EventHandler - private void serverAboutToStart( final FMLServerAboutToStartEvent evt ) - { - WorldData.onServerAboutToStart(); - } - - @EventHandler - private void serverStopping( final FMLServerStoppingEvent event ) - { - WorldData.instance().onServerStopping(); - } - - @EventHandler - private void serverStopped( final FMLServerStoppedEvent event ) - { - if (WorldData.instance() != null) - WorldData.instance().onServerStoppped(); - TickHandler.INSTANCE.shutdown(); - } - - @EventHandler - private void serverStarting( final FMLServerStartingEvent evt ) - { - evt.registerServerCommand( new AECommand( evt.getServer() ) ); - } + @EventHandler + private void serverStarting(final FMLServerStartingEvent evt) { + evt.registerServerCommand(new AECommand(evt.getServer())); + } } diff --git a/src/main/java/appeng/core/CommonHelper.java b/src/main/java/appeng/core/CommonHelper.java index c8684ec177f..97eb5122de1 100644 --- a/src/main/java/appeng/core/CommonHelper.java +++ b/src/main/java/appeng/core/CommonHelper.java @@ -18,64 +18,59 @@ package appeng.core; - import appeng.api.parts.CableRenderMode; import appeng.block.AEBaseBlock; import appeng.client.ActionKey; import appeng.client.EffectType; import appeng.core.sync.AppEngPacket; import cpw.mods.fml.common.SidedProxy; +import java.util.List; +import java.util.Random; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -import javax.annotation.Nonnull; -import java.util.List; -import java.util.Random; - - -public abstract class CommonHelper -{ +public abstract class CommonHelper { - @SidedProxy( clientSide = "appeng.client.ClientHelper", serverSide = "appeng.server.ServerHelper" ) - public static CommonHelper proxy; + @SidedProxy(clientSide = "appeng.client.ClientHelper", serverSide = "appeng.server.ServerHelper") + public static CommonHelper proxy; - public abstract void init(); + public abstract void init(); - public abstract World getWorld(); + public abstract World getWorld(); - public abstract void bindTileEntitySpecialRenderer( Class tile, AEBaseBlock blk ); + public abstract void bindTileEntitySpecialRenderer(Class tile, AEBaseBlock blk); - public abstract List getPlayers(); + public abstract List getPlayers(); - public abstract void sendToAllNearExcept( EntityPlayer p, double x, double y, double z, double dist, World w, AppEngPacket packet ); + public abstract void sendToAllNearExcept( + EntityPlayer p, double x, double y, double z, double dist, World w, AppEngPacket packet); - public abstract void spawnEffect( EffectType effect, World worldObj, double posX, double posY, double posZ, Object extra ); + public abstract void spawnEffect( + EffectType effect, World worldObj, double posX, double posY, double posZ, Object extra); - public abstract boolean shouldAddParticles( Random r ); + public abstract boolean shouldAddParticles(Random r); - public abstract MovingObjectPosition getMOP(); + public abstract MovingObjectPosition getMOP(); - public abstract void doRenderItem( ItemStack itemstack, World w ); + public abstract void doRenderItem(ItemStack itemstack, World w); - public abstract void postInit(); + public abstract void postInit(); - public abstract CableRenderMode getRenderMode(); + public abstract CableRenderMode getRenderMode(); - public abstract void triggerUpdates(); + public abstract void triggerUpdates(); - public abstract void updateRenderMode( EntityPlayer player ); + public abstract void updateRenderMode(EntityPlayer player); - public abstract void missingCoreMod(); + public abstract void missingCoreMod(); - public boolean isKeyPressed( ActionKey key ) - { - return false; - } + public boolean isKeyPressed(ActionKey key) { + return false; + } - public boolean isActionKey( ActionKey key, int pressedKeyCode ) - { - return false; - } + public boolean isActionKey(ActionKey key, int pressedKeyCode) { + return false; + } } diff --git a/src/main/java/appeng/core/CreativeTab.java b/src/main/java/appeng/core/CreativeTab.java index c61f884438d..a3d61fc7c5c 100644 --- a/src/main/java/appeng/core/CreativeTab.java +++ b/src/main/java/appeng/core/CreativeTab.java @@ -18,7 +18,6 @@ package appeng.core; - import appeng.api.AEApi; import appeng.api.definitions.*; import net.minecraft.creativetab.CreativeTabs; @@ -26,48 +25,47 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +public final class CreativeTab extends CreativeTabs { + public static CreativeTab instance = null; -public final class CreativeTab extends CreativeTabs -{ - public static CreativeTab instance = null; - - public CreativeTab() - { - super( "appliedenergistics2" ); - } + public CreativeTab() { + super("appliedenergistics2"); + } - static void init() - { - instance = new CreativeTab(); - } + static void init() { + instance = new CreativeTab(); + } - @Override - public Item getTabIconItem() - { - return this.getIconItemStack().getItem(); - } + @Override + public Item getTabIconItem() { + return this.getIconItemStack().getItem(); + } - @Override - public ItemStack getIconItemStack() - { - final IDefinitions definitions = AEApi.instance().definitions(); - final IBlocks blocks = definitions.blocks(); - final IItems items = definitions.items(); - final IMaterials materials = definitions.materials(); + @Override + public ItemStack getIconItemStack() { + final IDefinitions definitions = AEApi.instance().definitions(); + final IBlocks blocks = definitions.blocks(); + final IItems items = definitions.items(); + final IMaterials materials = definitions.materials(); - return this.findFirst( blocks.controller(), blocks.chest(), blocks.cellWorkbench(), blocks.fluix(), items.cell1k(), items.networkTool(), materials.fluixCrystal(), materials.certusQuartzCrystal() ); - } + return this.findFirst( + blocks.controller(), + blocks.chest(), + blocks.cellWorkbench(), + blocks.fluix(), + items.cell1k(), + items.networkTool(), + materials.fluixCrystal(), + materials.certusQuartzCrystal()); + } - private ItemStack findFirst( final IItemDefinition... choices ) - { - for( final IItemDefinition definition : choices ) - { - for( final ItemStack definitionStack : definition.maybeStack( 1 ).asSet() ) - { - return definitionStack; - } - } + private ItemStack findFirst(final IItemDefinition... choices) { + for (final IItemDefinition definition : choices) { + for (final ItemStack definitionStack : definition.maybeStack(1).asSet()) { + return definitionStack; + } + } - return new ItemStack( Blocks.chest ); - } -} \ No newline at end of file + return new ItemStack(Blocks.chest); + } +} diff --git a/src/main/java/appeng/core/CreativeTabFacade.java b/src/main/java/appeng/core/CreativeTabFacade.java index 3dc5d342c66..53c7d28759d 100644 --- a/src/main/java/appeng/core/CreativeTabFacade.java +++ b/src/main/java/appeng/core/CreativeTabFacade.java @@ -18,7 +18,6 @@ package appeng.core; - import appeng.api.AEApi; import appeng.items.parts.ItemFacade; import com.google.common.base.Optional; @@ -27,37 +26,31 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +public final class CreativeTabFacade extends CreativeTabs { -public final class CreativeTabFacade extends CreativeTabs -{ - - public static CreativeTabFacade instance = null; + public static CreativeTabFacade instance = null; - public CreativeTabFacade() - { - super( "appliedenergistics2.facades" ); - } + public CreativeTabFacade() { + super("appliedenergistics2.facades"); + } - static void init() - { - instance = new CreativeTabFacade(); - } + static void init() { + instance = new CreativeTabFacade(); + } - @Override - public Item getTabIconItem() - { - return this.getIconItemStack().getItem(); - } + @Override + public Item getTabIconItem() { + return this.getIconItemStack().getItem(); + } - @Override - public ItemStack getIconItemStack() - { - final Optional maybeFacade = AEApi.instance().definitions().items().facade().maybeItem(); - if( maybeFacade.isPresent() ) - { - return ( (ItemFacade) maybeFacade.get() ).getCreativeTabIcon(); - } + @Override + public ItemStack getIconItemStack() { + final Optional maybeFacade = + AEApi.instance().definitions().items().facade().maybeItem(); + if (maybeFacade.isPresent()) { + return ((ItemFacade) maybeFacade.get()).getCreativeTabIcon(); + } - return new ItemStack( Blocks.planks ); - } -} \ No newline at end of file + return new ItemStack(Blocks.planks); + } +} diff --git a/src/main/java/appeng/core/FacadeConfig.java b/src/main/java/appeng/core/FacadeConfig.java index a95613cd5ca..fd9de1f1aac 100644 --- a/src/main/java/appeng/core/FacadeConfig.java +++ b/src/main/java/appeng/core/FacadeConfig.java @@ -18,62 +18,49 @@ package appeng.core; - import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier; -import net.minecraft.block.Block; -import net.minecraftforge.common.config.Configuration; - import java.io.File; import java.lang.reflect.Field; import java.util.regex.Matcher; import java.util.regex.Pattern; +import net.minecraft.block.Block; +import net.minecraftforge.common.config.Configuration; +public class FacadeConfig extends Configuration { -public class FacadeConfig extends Configuration -{ - - public static FacadeConfig instance; - private final Pattern replacementPattern; + public static FacadeConfig instance; + private final Pattern replacementPattern; - public FacadeConfig( final File facadeFile ) - { - super( facadeFile ); - this.replacementPattern = Pattern.compile( "[^a-zA-Z0-9]" ); - } + public FacadeConfig(final File facadeFile) { + super(facadeFile); + this.replacementPattern = Pattern.compile("[^a-zA-Z0-9]"); + } - public boolean checkEnabled( final Block id, final int metadata, final boolean automatic ) - { - if( id == null ) - { - return false; - } + public boolean checkEnabled(final Block id, final int metadata, final boolean automatic) { + if (id == null) { + return false; + } - final UniqueIdentifier blk = GameRegistry.findUniqueIdentifierFor( id ); - if( blk == null ) - { - for( final Field f : Block.class.getFields() ) - { - try - { - if( f.get( Block.class ) == id ) - { - return this.get( "minecraft", f.getName() + ( metadata == 0 ? "" : "." + metadata ), automatic ).getBoolean( automatic ); - } - } - catch( final Throwable e ) - { - // :P - } - } - } - else - { - final Matcher mod = this.replacementPattern.matcher( blk.modId ); - final Matcher name = this.replacementPattern.matcher( blk.name ); - return this.get( mod.replaceAll( "" ), name.replaceAll( "" ) + ( metadata == 0 ? "" : "." + metadata ), automatic ).getBoolean( automatic ); - } + final UniqueIdentifier blk = GameRegistry.findUniqueIdentifierFor(id); + if (blk == null) { + for (final Field f : Block.class.getFields()) { + try { + if (f.get(Block.class) == id) { + return this.get("minecraft", f.getName() + (metadata == 0 ? "" : "." + metadata), automatic) + .getBoolean(automatic); + } + } catch (final Throwable e) { + // :P + } + } + } else { + final Matcher mod = this.replacementPattern.matcher(blk.modId); + final Matcher name = this.replacementPattern.matcher(blk.name); + return this.get(mod.replaceAll(""), name.replaceAll("") + (metadata == 0 ? "" : "." + metadata), automatic) + .getBoolean(automatic); + } - return false; - } + return false; + } } diff --git a/src/main/java/appeng/core/FeatureHandlerRegistry.java b/src/main/java/appeng/core/FeatureHandlerRegistry.java index 8494160dcaa..6328b82e663 100644 --- a/src/main/java/appeng/core/FeatureHandlerRegistry.java +++ b/src/main/java/appeng/core/FeatureHandlerRegistry.java @@ -18,24 +18,18 @@ package appeng.core; - import appeng.core.features.IFeatureHandler; - import java.util.LinkedHashSet; import java.util.Set; +public final class FeatureHandlerRegistry { + private final Set registry = new LinkedHashSet(); -public final class FeatureHandlerRegistry -{ - private final Set registry = new LinkedHashSet(); - - public void addFeatureHandler( final IFeatureHandler feature ) - { - this.registry.add( feature ); - } + public void addFeatureHandler(final IFeatureHandler feature) { + this.registry.add(feature); + } - Set getRegisteredFeatureHandlers() - { - return this.registry; - } + Set getRegisteredFeatureHandlers() { + return this.registry; + } } diff --git a/src/main/java/appeng/core/FeatureRegistry.java b/src/main/java/appeng/core/FeatureRegistry.java index aff90cebe60..8e5c8cff58d 100644 --- a/src/main/java/appeng/core/FeatureRegistry.java +++ b/src/main/java/appeng/core/FeatureRegistry.java @@ -18,24 +18,18 @@ package appeng.core; - import appeng.core.features.IAEFeature; - import java.util.LinkedHashSet; import java.util.Set; +public final class FeatureRegistry { + private final Set registry = new LinkedHashSet(); -public final class FeatureRegistry -{ - private final Set registry = new LinkedHashSet(); - - public void addFeature( final IAEFeature feature ) - { - this.registry.add( feature ); - } + public void addFeature(final IAEFeature feature) { + this.registry.add(feature); + } - Set getRegisteredFeatures() - { - return this.registry; - } + Set getRegisteredFeatures() { + return this.registry; + } } diff --git a/src/main/java/appeng/core/IMCHandler.java b/src/main/java/appeng/core/IMCHandler.java index d61ccc956ad..8ba8b4c9727 100644 --- a/src/main/java/appeng/core/IMCHandler.java +++ b/src/main/java/appeng/core/IMCHandler.java @@ -18,17 +18,14 @@ package appeng.core; - import appeng.api.config.TunnelType; import appeng.core.api.IIMCProcessor; import appeng.core.api.imc.*; import cpw.mods.fml.common.event.FMLInterModComms; - import java.util.HashMap; import java.util.Locale; import java.util.Map; - /** * Handles the delegation of the corresponding IMC messages to the suitable IMC processors * @@ -36,63 +33,54 @@ * @version rv3 - 10.08.2015 * @since rv1 */ -public class IMCHandler -{ - private static final int INITIAL_PROCESSORS_CAPACITY = 20; +public class IMCHandler { + private static final int INITIAL_PROCESSORS_CAPACITY = 20; - /** - * Contains the processors, - *

- * is mutable, but write access only by the constructor - */ - private final Map processors; + /** + * Contains the processors, + *

+ * is mutable, but write access only by the constructor + */ + private final Map processors; - /** - * Initializes the processors - */ - public IMCHandler() - { - this.processors = new HashMap( INITIAL_PROCESSORS_CAPACITY ); + /** + * Initializes the processors + */ + public IMCHandler() { + this.processors = new HashMap(INITIAL_PROCESSORS_CAPACITY); - this.processors.put( "blacklist-block-spatial", new IMCBlackListSpatial() ); - this.processors.put( "whitelist-spatial", new IMCSpatial() ); - this.processors.put( "add-grindable", new IMCGrinder() ); - this.processors.put( "add-mattercannon-ammo", new IMCMatterCannon() ); + this.processors.put("blacklist-block-spatial", new IMCBlackListSpatial()); + this.processors.put("whitelist-spatial", new IMCSpatial()); + this.processors.put("add-grindable", new IMCGrinder()); + this.processors.put("add-mattercannon-ammo", new IMCMatterCannon()); - for( final TunnelType type : TunnelType.values() ) - { - this.processors.put( "add-p2p-attunement-" + type.name().replace( '_', '-' ).toLowerCase( Locale.ENGLISH ), new IMCP2PAttunement() ); - } - } + for (final TunnelType type : TunnelType.values()) { + this.processors.put( + "add-p2p-attunement-" + type.name().replace('_', '-').toLowerCase(Locale.ENGLISH), + new IMCP2PAttunement()); + } + } - /** - * Tries to find every message matching the internal IMC keys. When found the corresponding handler will process the attached message. - * - * @param event Event carrying the identifier and message for the handlers - */ - void handleIMCEvent( final FMLInterModComms.IMCEvent event ) - { - for( final FMLInterModComms.IMCMessage message : event.getMessages() ) - { - final String key = message.key; + /** + * Tries to find every message matching the internal IMC keys. When found the corresponding handler will process the attached message. + * + * @param event Event carrying the identifier and message for the handlers + */ + void handleIMCEvent(final FMLInterModComms.IMCEvent event) { + for (final FMLInterModComms.IMCMessage message : event.getMessages()) { + final String key = message.key; - try - { - final IIMCProcessor handler = this.processors.get( key ); - if( handler != null ) - { - handler.process( message ); - } - else - { - throw new IllegalStateException( "Invalid IMC Called: " + key ); - } - } - catch( final Exception t ) - { - AELog.warn( "Problem detected when processing IMC " + key + " from " + message.getSender() ); - AELog.debug( t ); - } - } - } + try { + final IIMCProcessor handler = this.processors.get(key); + if (handler != null) { + handler.process(message); + } else { + throw new IllegalStateException("Invalid IMC Called: " + key); + } + } catch (final Exception t) { + AELog.warn("Problem detected when processing IMC " + key + " from " + message.getSender()); + AELog.debug(t); + } + } + } } diff --git a/src/main/java/appeng/core/RecipeLoader.java b/src/main/java/appeng/core/RecipeLoader.java index a5208f05f2a..0bff225adcd 100644 --- a/src/main/java/appeng/core/RecipeLoader.java +++ b/src/main/java/appeng/core/RecipeLoader.java @@ -18,20 +18,17 @@ package appeng.core; - import appeng.api.recipes.IRecipeHandler; import appeng.recipes.CustomRecipeConfig; import appeng.recipes.loader.ConfigLoader; import appeng.recipes.loader.JarLoader; import appeng.recipes.loader.RecipeResourceCopier; import com.google.common.base.Preconditions; -import org.apache.commons.io.FileUtils; - -import javax.annotation.Nonnull; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; - +import javax.annotation.Nonnull; +import org.apache.commons.io.FileUtils; /** * handles the decision if recipes should be loaded from jar, loaded from file system or force copied from jar @@ -40,75 +37,70 @@ * @version rv3 - 12.05.2015 * @since rv3 12.05.2015 */ -public class RecipeLoader implements Runnable -{ - /** - * recipe path in the jar - */ - private static final String ASSETS_RECIPE_PATH = "/assets/appliedenergistics2/recipes/"; +public class RecipeLoader implements Runnable { + /** + * recipe path in the jar + */ + private static final String ASSETS_RECIPE_PATH = "/assets/appliedenergistics2/recipes/"; + + @Nonnull + private final IRecipeHandler handler; + + @Nonnull + private final CustomRecipeConfig config; - @Nonnull - private final IRecipeHandler handler; - @Nonnull - private final CustomRecipeConfig config; - @Nonnull - private final File recipeDirectory; + @Nonnull + private final File recipeDirectory; - /** - * @param config configuration for the knowledge how to handle the loading process - * @param handler handler to load the recipes - * @throws NullPointerException if handler is null - */ - public RecipeLoader( @Nonnull final File recipeDirectory, @Nonnull final CustomRecipeConfig config, @Nonnull final IRecipeHandler handler ) - { - this.recipeDirectory = Preconditions.checkNotNull( recipeDirectory ); - Preconditions.checkArgument( !recipeDirectory.isFile() ); - this.config = Preconditions.checkNotNull( config ); - this.handler = Preconditions.checkNotNull( handler ); - } + /** + * @param config configuration for the knowledge how to handle the loading process + * @param handler handler to load the recipes + * @throws NullPointerException if handler is null + */ + public RecipeLoader( + @Nonnull final File recipeDirectory, + @Nonnull final CustomRecipeConfig config, + @Nonnull final IRecipeHandler handler) { + this.recipeDirectory = Preconditions.checkNotNull(recipeDirectory); + Preconditions.checkArgument(!recipeDirectory.isFile()); + this.config = Preconditions.checkNotNull(config); + this.handler = Preconditions.checkNotNull(handler); + } - @Override - public final void run() - { - if( this.config.isEnabled() ) - { - // setup copying - final RecipeResourceCopier copier = new RecipeResourceCopier( "assets/appliedenergistics2/recipes/" ); + @Override + public final void run() { + if (this.config.isEnabled()) { + // setup copying + final RecipeResourceCopier copier = new RecipeResourceCopier("assets/appliedenergistics2/recipes/"); - final File generatedRecipesDir = new File( this.recipeDirectory, "generated" ); - final File userRecipesDir = new File( this.recipeDirectory, "user" ); + final File generatedRecipesDir = new File(this.recipeDirectory, "generated"); + final File userRecipesDir = new File(this.recipeDirectory, "user"); - // generates generated and user recipes dir - // will clean the generated every time to keep it up to date - // copies over the recipes in the jar over to the generated folder - // copies over the readmes - try - { - FileUtils.forceMkdir( generatedRecipesDir ); - FileUtils.forceMkdir( userRecipesDir ); - FileUtils.cleanDirectory( generatedRecipesDir ); + // generates generated and user recipes dir + // will clean the generated every time to keep it up to date + // copies over the recipes in the jar over to the generated folder + // copies over the readmes + try { + FileUtils.forceMkdir(generatedRecipesDir); + FileUtils.forceMkdir(userRecipesDir); + FileUtils.cleanDirectory(generatedRecipesDir); - copier.copyTo( ".recipe", generatedRecipesDir ); - copier.copyTo( ".html", this.recipeDirectory ); + copier.copyTo(".recipe", generatedRecipesDir); + copier.copyTo(".html", this.recipeDirectory); - // parse recipes prioritising the user scripts by using the generated as template - this.handler.parseRecipes( new ConfigLoader( generatedRecipesDir, userRecipesDir ), "index.recipe" ); - } - // on failure use jar parsing - catch( final IOException e ) - { - AELog.debug( e ); - this.handler.parseRecipes( new JarLoader( ASSETS_RECIPE_PATH ), "index.recipe" ); - } - catch( final URISyntaxException e ) - { - AELog.debug( e ); - this.handler.parseRecipes( new JarLoader( ASSETS_RECIPE_PATH ), "index.recipe" ); - } - } - else - { - this.handler.parseRecipes( new JarLoader( ASSETS_RECIPE_PATH ), "index.recipe" ); - } - } + // parse recipes prioritising the user scripts by using the generated as template + this.handler.parseRecipes(new ConfigLoader(generatedRecipesDir, userRecipesDir), "index.recipe"); + } + // on failure use jar parsing + catch (final IOException e) { + AELog.debug(e); + this.handler.parseRecipes(new JarLoader(ASSETS_RECIPE_PATH), "index.recipe"); + } catch (final URISyntaxException e) { + AELog.debug(e); + this.handler.parseRecipes(new JarLoader(ASSETS_RECIPE_PATH), "index.recipe"); + } + } else { + this.handler.parseRecipes(new JarLoader(ASSETS_RECIPE_PATH), "index.recipe"); + } + } } diff --git a/src/main/java/appeng/core/Registration.java b/src/main/java/appeng/core/Registration.java index aeb4a610d1f..b1606fda895 100644 --- a/src/main/java/appeng/core/Registration.java +++ b/src/main/java/appeng/core/Registration.java @@ -18,7 +18,6 @@ package appeng.core; - import appeng.api.AEApi; import appeng.api.IAppEngApi; import appeng.api.config.Upgrades; @@ -76,6 +75,8 @@ import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.VillagerRegistry; +import java.io.File; +import javax.annotation.Nonnull; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -87,667 +88,648 @@ import net.minecraftforge.oredict.RecipeSorter; import net.minecraftforge.oredict.RecipeSorter.Category; -import javax.annotation.Nonnull; -import java.io.File; - - -public final class Registration -{ - private final RecipeHandler recipeHandler; - private final DefinitionConverter converter; - private BiomeGenBase storageBiome; - - Registration() - { - this.converter = new DefinitionConverter(); - this.recipeHandler = new RecipeHandler(); - } - - public BiomeGenBase getStorageBiome() - { - return this.storageBiome; - } - - void preInitialize( final FMLPreInitializationEvent event ) - { - this.registerSpatial( false ); - - final Api api = Api.INSTANCE; - final IRecipeHandlerRegistry recipeRegistry = api.registries().recipes(); - this.registerCraftHandlers( recipeRegistry ); - - RecipeSorter.register( "AE2-Facade", FacadeRecipe.class, Category.SHAPED, "" ); - RecipeSorter.register( "AE2-Shaped", ShapedRecipe.class, Category.SHAPED, "" ); - RecipeSorter.register( "AE2-Shapeless", ShapelessRecipe.class, Category.SHAPELESS, "" ); - - MinecraftForge.EVENT_BUS.register( OreDictionaryHandler.INSTANCE ); - - final ApiDefinitions definitions = api.definitions(); - - final IBlocks apiBlocks = definitions.blocks(); - final IItems apiItems = definitions.items(); - final IMaterials apiMaterials = definitions.materials(); - final IParts apiParts = definitions.parts(); - - final Items items = api.items(); - final Materials materials = api.materials(); - final Parts parts = api.parts(); - final Blocks blocks = api.blocks(); - - this.assignMaterials( materials, apiMaterials ); - this.assignParts( parts, apiParts ); - this.assignBlocks( blocks, apiBlocks ); - this.assignItems( items, apiItems ); - - // Register all detected handlers and features (items, blocks) in pre-init - for( final IFeatureHandler handler : definitions.getFeatureHandlerRegistry().getRegisteredFeatureHandlers() ) - { - handler.register(); - } - - for( final IAEFeature feature : definitions.getFeatureRegistry().getRegisteredFeatures() ) - { - feature.postInit(); - } - } - - private void registerSpatial( final boolean force ) - { - if( !AEConfig.instance.isFeatureEnabled( AEFeature.SpatialIO ) ) - { - return; - } - - final AEConfig config = AEConfig.instance; - - if( this.storageBiome == null ) - { - if( force && config.storageBiomeID == -1 ) - { - config.storageBiomeID = Platform.findEmpty( BiomeGenBase.getBiomeGenArray() ); - if( config.storageBiomeID == -1 ) - { - throw new IllegalStateException( "Biome Array is full, please free up some Biome ID's or disable spatial." ); - } - - this.storageBiome = new BiomeGenStorage( config.storageBiomeID ); - config.save(); - } - - if( !force && config.storageBiomeID != -1 ) - { - this.storageBiome = new BiomeGenStorage( config.storageBiomeID ); - } - } - - if( config.storageProviderID != -1 ) - { - DimensionManager.registerProviderType( config.storageProviderID, StorageWorldProvider.class, false ); - } - - if( config.storageProviderID == -1 && force ) - { - config.storageProviderID = -11; - - while( !DimensionManager.registerProviderType( config.storageProviderID, StorageWorldProvider.class, false ) ) - { - config.storageProviderID--; - } - - config.save(); - } - } - - private void registerCraftHandlers( final IRecipeHandlerRegistry registry ) - { - registry.addNewSubItemResolver( new AEItemResolver() ); - - registry.addNewCraftHandler( "hccrusher", HCCrusher.class ); - registry.addNewCraftHandler( "mekcrusher", MekCrusher.class ); - registry.addNewCraftHandler( "mekechamber", MekEnrichment.class ); - registry.addNewCraftHandler( "grind", Grind.class ); - registry.addNewCraftHandler( "crusher", Crusher.class ); - registry.addNewCraftHandler( "grindfz", GrindFZ.class ); - registry.addNewCraftHandler( "pulverizer", Pulverizer.class ); - registry.addNewCraftHandler( "macerator", Macerator.class ); - - registry.addNewCraftHandler( "smelt", Smelt.class ); - registry.addNewCraftHandler( "inscribe", Inscribe.class ); - registry.addNewCraftHandler( "press", Press.class ); - - registry.addNewCraftHandler( "shaped", Shaped.class ); - registry.addNewCraftHandler( "shapeless", Shapeless.class ); - } - - /** - * Assigns materials from the new API to the old API - *

- * Uses direct cast, since its only a temporary solution anyways - * - * @param target old API - * @param source new API - * @deprecated to be removed when the public definition API is removed - */ - @Deprecated - private void assignMaterials( final Materials target, final IMaterials source ) - { - target.materialCell2SpatialPart = this.converter.of( source.cell2SpatialPart() ); - target.materialCell16SpatialPart = this.converter.of( source.cell16SpatialPart() ); - target.materialCell128SpatialPart = this.converter.of( source.cell128SpatialPart() ); - - target.materialSilicon = this.converter.of( source.silicon() ); - target.materialSkyDust = this.converter.of( source.skyDust() ); - - target.materialCalcProcessorPress = this.converter.of( source.calcProcessorPress() ); - target.materialEngProcessorPress = this.converter.of( source.engProcessorPress() ); - target.materialLogicProcessorPress = this.converter.of( source.logicProcessorPress() ); - - target.materialCalcProcessorPrint = this.converter.of( source.calcProcessorPrint() ); - target.materialEngProcessorPrint = this.converter.of( source.engProcessorPrint() ); - target.materialLogicProcessorPrint = this.converter.of( source.logicProcessorPrint() ); - - target.materialSiliconPress = this.converter.of( source.siliconPress() ); - target.materialSiliconPrint = this.converter.of( source.siliconPrint() ); - - target.materialNamePress = this.converter.of( source.namePress() ); - - target.materialLogicProcessor = this.converter.of( source.logicProcessor() ); - target.materialCalcProcessor = this.converter.of( source.calcProcessor() ); - target.materialEngProcessor = this.converter.of( source.engProcessor() ); - - target.materialBasicCard = this.converter.of( source.basicCard() ); - target.materialAdvCard = this.converter.of( source.advCard() ); - - target.materialPurifiedCertusQuartzCrystal = this.converter.of( source.purifiedCertusQuartzCrystal() ); - target.materialPurifiedNetherQuartzCrystal = this.converter.of( source.purifiedNetherQuartzCrystal() ); - target.materialPurifiedFluixCrystal = this.converter.of( source.purifiedFluixCrystal() ); - - target.materialCell1kPart = this.converter.of( source.cell1kPart() ); - target.materialCell4kPart = this.converter.of( source.cell4kPart() ); - target.materialCell16kPart = this.converter.of( source.cell16kPart() ); - target.materialCell64kPart = this.converter.of( source.cell64kPart() ); - target.materialEmptyStorageCell = this.converter.of( source.emptyStorageCell() ); - - target.materialCardRedstone = this.converter.of( source.cardRedstone() ); - target.materialCardSpeed = this.converter.of( source.cardSpeed() ); - target.materialCardCapacity = this.converter.of( source.cardCapacity() ); - target.materialCardFuzzy = this.converter.of( source.cardFuzzy() ); - target.materialCardInverter = this.converter.of( source.cardInverter() ); - target.materialCardCrafting = this.converter.of( source.cardCrafting() ); - - target.materialEnderDust = this.converter.of( source.enderDust() ); - target.materialFlour = this.converter.of( source.flour() ); - target.materialGoldDust = this.converter.of( source.goldDust() ); - target.materialIronDust = this.converter.of( source.ironDust() ); - target.materialFluixDust = this.converter.of( source.fluixDust() ); - target.materialCertusQuartzDust = this.converter.of( source.certusQuartzDust() ); - target.materialNetherQuartzDust = this.converter.of( source.netherQuartzDust() ); - - target.materialMatterBall = this.converter.of( source.matterBall() ); - target.materialIronNugget = this.converter.of( source.ironNugget() ); - - target.materialCertusQuartzCrystal = this.converter.of( source.certusQuartzCrystal() ); - target.materialCertusQuartzCrystalCharged = this.converter.of( source.certusQuartzCrystalCharged() ); - target.materialFluixCrystal = this.converter.of( source.fluixCrystal() ); - target.materialFluixPearl = this.converter.of( source.fluixPearl() ); - - target.materialWoodenGear = this.converter.of( source.woodenGear() ); - - target.materialWireless = this.converter.of( source.wireless() ); - target.materialWirelessBooster = this.converter.of( source.wirelessBooster() ); - - target.materialAnnihilationCore = this.converter.of( source.annihilationCore() ); - target.materialFormationCore = this.converter.of( source.formationCore() ); - - target.materialSingularity = this.converter.of( source.singularity() ); - target.materialQESingularity = this.converter.of( source.qESingularity() ); - target.materialBlankPattern = this.converter.of( source.blankPattern() ); - } - - /** - * Assigns parts from the new API to the old API - * - * @param target old API - * @param source new API - * @deprecated to be removed when the public definition API is removed - */ - @Deprecated - private void assignParts( final Parts target, final IParts source ) - { - target.partCableSmart = source.cableSmart(); - target.partCableCovered = source.cableCovered(); - target.partCableGlass = source.cableGlass(); - target.partCableDense = source.cableDense(); - target.partCableDenseCovered = source.cableDenseCovered(); - target.partCableUltraDenseSmart = source.cableUltraDenseSmart(); - target.partCableUltraDenseCovered = source.cableUltraDenseCovered(); - // target.partLumenCableSmart = source.lumenCableSmart(); - // target.partLumenCableCovered = source.lumenCableCovered(); - // target.partLumenCableGlass = source.lumenCableGlass(); - // target.partLumenCableDense = source.lumenCableDense(); - target.partQuartzFiber = this.converter.of( source.quartzFiber() ); - target.partToggleBus = this.converter.of( source.toggleBus() ); - target.partInvertedToggleBus = this.converter.of( source.invertedToggleBus() ); - target.partStorageBus = this.converter.of( source.storageBus() ); - target.partImportBus = this.converter.of( source.importBus() ); - target.partExportBus = this.converter.of( source.exportBus() ); - target.partInterface = this.converter.of( source.iface() ); - target.partLevelEmitter = this.converter.of( source.levelEmitter() ); - target.partAnnihilationPlane = this.converter.of( source.annihilationPlane() ); - target.partFormationPlane = this.converter.of( source.formationPlane() ); - - target.partCableAnchor = this.converter.of( source.cableAnchor() ); - target.partP2PTunnelLight = target.partCableAnchor; - target.partP2PTunnelRF = target.partP2PTunnelLight; - target.partP2PTunnelEU = target.partP2PTunnelRF; - target.partP2PTunnelLiquids = target.partP2PTunnelEU; - target.partP2PTunnelItems = target.partP2PTunnelLiquids; - target.partP2PTunnelRedstone = target.partP2PTunnelItems; - target.partP2PTunnelME = target.partP2PTunnelRedstone; - target.partMonitor = this.converter.of( source.monitor() ); - target.partSemiDarkMonitor = this.converter.of( source.semiDarkMonitor() ); - target.partDarkMonitor = this.converter.of( source.darkMonitor() ); - target.partInterfaceTerminal = this.converter.of( source.interfaceTerminal() ); - target.partPatternTerminal = this.converter.of( source.patternTerminal() ); - target.partCraftingTerminal = this.converter.of( source.craftingTerminal() ); - target.partTerminal = this.converter.of( source.terminal() ); - target.partStorageMonitor = this.converter.of( source.storageMonitor() ); - target.partConversionMonitor = this.converter.of( source.conversionMonitor() ); - } - - /** - * Assigns blocks from the new API to the old API - * - * @param target old API - * @param source new API - * @deprecated to be removed when the public definition API is removed - */ - @Deprecated - private void assignBlocks( final Blocks target, final IBlocks source ) - { - target.blockMultiPart = this.converter.of( source.multiPart() ); - - target.blockCraftingUnit = this.converter.of( source.craftingUnit() ); - target.blockCraftingAccelerator = this.converter.of( source.craftingAccelerator() ); - target.blockCraftingAccelerator4x = this.converter.of( source.craftingAccelerator4x() ); - target.blockCraftingAccelerator16x = this.converter.of( source.craftingAccelerator16x() ); - target.blockCraftingMonitor = this.converter.of( source.craftingMonitor() ); - target.blockCraftingStorage1k = this.converter.of( source.craftingStorage1k() ); - target.blockCraftingStorage4k = this.converter.of( source.craftingStorage4k() ); - target.blockCraftingStorage16k = this.converter.of( source.craftingStorage16k() ); - target.blockCraftingStorage64k = this.converter.of( source.craftingStorage64k() ); - target.blockMolecularAssembler = this.converter.of( source.molecularAssembler() ); - - target.blockQuartzOre = this.converter.of( source.quartzOre() ); - target.blockQuartzOreCharged = this.converter.of( source.quartzOreCharged() ); - target.blockMatrixFrame = this.converter.of( source.matrixFrame() ); - target.blockQuartz = this.converter.of( source.quartz() ); - target.blockFluix = this.converter.of( source.fluix() ); - target.blockSkyStone = this.converter.of( source.skyStone() ); - target.blockSkyChest = this.converter.of( source.skyChest() ); - target.blockSkyCompass = this.converter.of( source.skyCompass() ); - - target.blockQuartzGlass = this.converter.of( source.quartzGlass() ); - target.blockQuartzVibrantGlass = this.converter.of( source.quartzVibrantGlass() ); - target.blockQuartzPillar = this.converter.of( source.quartzPillar() ); - target.blockQuartzChiseled = this.converter.of( source.quartzChiseled() ); - target.blockQuartzTorch = this.converter.of( source.quartzTorch() ); - target.blockLightDetector = this.converter.of( source.lightDetector() ); - target.blockCharger = this.converter.of( source.charger() ); - target.blockQuartzGrowthAccelerator = this.converter.of( source.quartzGrowthAccelerator() ); - - target.blockGrindStone = this.converter.of( source.grindStone() ); - target.blockCrankHandle = this.converter.of( source.crankHandle() ); - target.blockInscriber = this.converter.of( source.inscriber() ); - target.blockWireless = this.converter.of( source.wireless() ); - target.blockTinyTNT = this.converter.of( source.tinyTNT() ); - - target.blockQuantumRing = this.converter.of( source.quantumRing() ); - target.blockQuantumLink = this.converter.of( source.quantumLink() ); - - target.blockSpatialPylon = this.converter.of( source.spatialPylon() ); - target.blockSpatialIOPort = this.converter.of( source.spatialIOPort() ); - - target.blockController = this.converter.of( source.controller() ); - target.blockDrive = this.converter.of( source.drive() ); - target.blockChest = this.converter.of( source.chest() ); - target.blockInterface = this.converter.of( source.iface() ); - target.blockCellWorkbench = this.converter.of( source.cellWorkbench() ); - target.blockIOPort = this.converter.of( source.iOPort() ); - target.blockCondenser = this.converter.of( source.condenser() ); - target.blockEnergyAcceptor = this.converter.of( source.energyAcceptor() ); - target.blockVibrationChamber = this.converter.of( source.vibrationChamber() ); - - target.blockEnergyCell = this.converter.of( source.energyCell() ); - target.blockEnergyCellDense = this.converter.of( source.energyCellDense() ); - target.blockEnergyCellCreative = this.converter.of( source.energyCellCreative() ); - - target.blockSecurity = this.converter.of( source.security() ); - target.blockPaint = this.converter.of( source.paint() ); - } - - /** - * Assigns materials from the new API to the old API - * - * @param target old API - * @param source new API - * @deprecated to be removed when the public definition API is removed - */ - @Deprecated - private void assignItems( final Items target, final IItems source ) - { - target.itemCellCreative = this.converter.of( source.cellCreative() ); - target.itemViewCell = this.converter.of( source.viewCell() ); - target.itemEncodedPattern = this.converter.of( source.encodedPattern() ); - - target.itemCell1k = this.converter.of( source.cell1k() ); - target.itemCell4k = this.converter.of( source.cell4k() ); - target.itemCell16k = this.converter.of( source.cell16k() ); - target.itemCell64k = this.converter.of( source.cell64k() ); - - target.itemSpatialCell2 = this.converter.of( source.spatialCell2() ); - target.itemSpatialCell16 = this.converter.of( source.spatialCell16() ); - target.itemSpatialCell128 = this.converter.of( source.spatialCell128() ); - - target.itemCertusQuartzKnife = this.converter.of( source.certusQuartzKnife() ); - target.itemCertusQuartzWrench = this.converter.of( source.certusQuartzWrench() ); - target.itemCertusQuartzAxe = this.converter.of( source.certusQuartzAxe() ); - target.itemCertusQuartzHoe = this.converter.of( source.certusQuartzHoe() ); - target.itemCertusQuartzPick = this.converter.of( source.certusQuartzPick() ); - target.itemCertusQuartzShovel = this.converter.of( source.certusQuartzShovel() ); - target.itemCertusQuartzSword = this.converter.of( source.certusQuartzSword() ); - - target.itemNetherQuartzKnife = this.converter.of( source.netherQuartzKnife() ); - target.itemNetherQuartzWrench = this.converter.of( source.netherQuartzWrench() ); - target.itemNetherQuartzAxe = this.converter.of( source.netherQuartzAxe() ); - target.itemNetherQuartzHoe = this.converter.of( source.netherQuartzHoe() ); - target.itemNetherQuartzPick = this.converter.of( source.netherQuartzPick() ); - target.itemNetherQuartzShovel = this.converter.of( source.netherQuartzShovel() ); - target.itemNetherQuartzSword = this.converter.of( source.netherQuartzSword() ); - - target.itemMassCannon = this.converter.of( source.massCannon() ); - target.itemMemoryCard = this.converter.of( source.memoryCard() ); - target.itemChargedStaff = this.converter.of( source.chargedStaff() ); - target.itemEntropyManipulator = this.converter.of( source.entropyManipulator() ); - target.itemColorApplicator = this.converter.of( source.colorApplicator() ); - - target.itemWirelessTerminal = this.converter.of( source.wirelessTerminal() ); - target.itemNetworkTool = this.converter.of( source.networkTool() ); - target.itemPortableCell = this.converter.of( source.portableCell() ); - target.itemBiometricCard = this.converter.of( source.biometricCard() ); - - target.itemFacade = this.converter.of( source.facade() ); - target.itemCrystalSeed = this.converter.of( source.crystalSeed() ); - - target.itemPaintBall = source.coloredPaintBall(); - target.itemLumenPaintBall = source.coloredLumenPaintBall(); - } - - void initialize( @Nonnull final FMLInitializationEvent event, @Nonnull final File recipeDirectory, @Nonnull final CustomRecipeConfig customRecipeConfig ) - { - Preconditions.checkNotNull( event ); - Preconditions.checkNotNull( recipeDirectory ); - Preconditions.checkArgument( !recipeDirectory.isFile() ); - Preconditions.checkNotNull( customRecipeConfig ); - - final IAppEngApi api = AEApi.instance(); - final IPartHelper partHelper = api.partHelper(); - final IRegistryContainer registries = api.registries(); - - // Perform ore camouflage! - ItemMultiMaterial.instance.makeUnique(); - - final Runnable recipeLoader = new RecipeLoader( recipeDirectory, customRecipeConfig, this.recipeHandler ); - recipeLoader.run(); - - partHelper.registerNewLayer( "appeng.parts.layers.LayerISidedInventory", "net.minecraft.inventory.ISidedInventory" ); - partHelper.registerNewLayer( "appeng.parts.layers.LayerIFluidHandler", "net.minecraftforge.fluids.IFluidHandler" ); - partHelper.registerNewLayer( "appeng.parts.layers.LayerITileStorageMonitorable", "appeng.api.implementations.tiles.ITileStorageMonitorable" ); - - FMLCommonHandler.instance().bus().register( TickHandler.INSTANCE ); - MinecraftForge.EVENT_BUS.register( TickHandler.INSTANCE ); - - final PartPlacement pp = new PartPlacement(); - MinecraftForge.EVENT_BUS.register( pp ); - FMLCommonHandler.instance().bus().register( pp ); - - final IGridCacheRegistry gcr = registries.gridCache(); - gcr.registerGridCache( ITickManager.class, TickManagerCache.class ); - gcr.registerGridCache( IEnergyGrid.class, EnergyGridCache.class ); - gcr.registerGridCache( IPathingGrid.class, PathGridCache.class ); - gcr.registerGridCache( IStorageGrid.class, GridStorageCache.class ); - gcr.registerGridCache( P2PCache.class, P2PCache.class ); - gcr.registerGridCache( ISpatialCache.class, SpatialPylonCache.class ); - gcr.registerGridCache( ISecurityGrid.class, SecurityCache.class ); - gcr.registerGridCache( ICraftingGrid.class, CraftingGridCache.class ); - - registries.externalStorage().addExternalStorageInterface( new AEExternalHandler() ); - - registries.cell().addCellHandler( new BasicCellHandler() ); - registries.cell().addCellHandler( new CreativeCellHandler() ); - - for( final ItemStack ammoStack : api.definitions().materials().matterBall().maybeStack( 1 ).asSet() ) - { - final double weight = 32; - - registries.matterCannon().registerAmmo( ammoStack, weight ); - } - - this.recipeHandler.injectRecipes(); - - final PlayerStatsRegistration registration = new PlayerStatsRegistration( FMLCommonHandler.instance().bus(), AEConfig.instance ); - registration.registerAchievementHandlers(); - registration.registerAchievements(); - - if( AEConfig.instance.isFeatureEnabled( AEFeature.EnableDisassemblyCrafting ) ) - { - GameRegistry.addRecipe( new DisassembleRecipe() ); - RecipeSorter.register( "appliedenergistics2:disassemble", DisassembleRecipe.class, Category.SHAPELESS, "after:minecraft:shapeless" ); - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.EnableFacadeCrafting ) ) - { - GameRegistry.addRecipe( new FacadeRecipe() ); - RecipeSorter.register( "appliedenergistics2:facade", FacadeRecipe.class, Category.SHAPED, "after:minecraft:shaped" ); - } - } - - void postInit( final FMLPostInitializationEvent event ) - { - this.registerSpatial( true ); - - final IAppEngApi api = AEApi.instance(); - final IRegistryContainer registries = api.registries(); - final IDefinitions definitions = api.definitions(); - final IParts parts = definitions.parts(); - final IBlocks blocks = definitions.blocks(); - final IItems items = definitions.items(); - - // default settings.. - ( (P2PTunnelRegistry) registries.p2pTunnel() ).configure(); - - // add to localization.. - PlayerMessages.values(); - GuiText.values(); - - Api.INSTANCE.partHelper().initFMPSupport(); - for( final Block block : blocks.multiPart().maybeBlock().asSet() ) - { - ( (BlockCableBus) block ).setupTile(); - } - - // Interface - Upgrades.CRAFTING.registerItem( parts.iface(), 1 ); - Upgrades.CRAFTING.registerItem( blocks.iface(), 1 ); - Upgrades.PATTERN_CAPACITY.registerItem( parts.iface(), 3 ); - Upgrades.PATTERN_CAPACITY.registerItem( blocks.iface(), 3 ); - - // IO Port! - Upgrades.SPEED.registerItem( blocks.iOPort(), 3 ); - Upgrades.REDSTONE.registerItem( blocks.iOPort(), 1 ); - - // Level Emitter! - Upgrades.FUZZY.registerItem( parts.levelEmitter(), 1 ); - Upgrades.CRAFTING.registerItem( parts.levelEmitter(), 1 ); - - // Import Bus - Upgrades.FUZZY.registerItem( parts.importBus(), 1 ); - Upgrades.REDSTONE.registerItem( parts.importBus(), 1 ); - Upgrades.CAPACITY.registerItem( parts.importBus(), 2 ); - Upgrades.SPEED.registerItem( parts.importBus(), 4 ); - Upgrades.ORE_FILTER.registerItem( parts.importBus(), 1 ); - - // Export Bus - Upgrades.FUZZY.registerItem( parts.exportBus(), 1 ); - Upgrades.REDSTONE.registerItem( parts.exportBus(), 1 ); - Upgrades.CAPACITY.registerItem( parts.exportBus(), 2 ); - Upgrades.SPEED.registerItem( parts.exportBus(), 4 ); - Upgrades.CRAFTING.registerItem( parts.exportBus(), 1 ); - Upgrades.ORE_FILTER.registerItem( parts.exportBus(), 1 ); - - // Storage Cells - Upgrades.FUZZY.registerItem( items.cell1k(), 1 ); - Upgrades.INVERTER.registerItem( items.cell1k(), 1 ); - Upgrades.ORE_FILTER.registerItem( items.cell1k(), 1 ); - - Upgrades.FUZZY.registerItem( items.cell4k(), 1 ); - Upgrades.INVERTER.registerItem( items.cell4k(), 1 ); - Upgrades.ORE_FILTER.registerItem( items.cell4k(), 1 ); - - Upgrades.FUZZY.registerItem( items.cell16k(), 1 ); - Upgrades.INVERTER.registerItem( items.cell16k(), 1 ); - Upgrades.ORE_FILTER.registerItem( items.cell16k(), 1 ); - - Upgrades.FUZZY.registerItem( items.cell64k(), 1 ); - Upgrades.INVERTER.registerItem( items.cell64k(), 1 ); - Upgrades.ORE_FILTER.registerItem( items.cell64k(), 1 ); - - Upgrades.FUZZY.registerItem( items.portableCell(), 1 ); - Upgrades.INVERTER.registerItem( items.portableCell(), 1 ); - Upgrades.ORE_FILTER.registerItem( items.portableCell(), 1 ); - - Upgrades.FUZZY.registerItem( items.viewCell(), 1 ); - Upgrades.INVERTER.registerItem( items.viewCell(), 1 ); - Upgrades.ORE_FILTER.registerItem( items.viewCell(), 1 ); - - // Storage Bus - Upgrades.FUZZY.registerItem( parts.storageBus(), 1 ); - Upgrades.INVERTER.registerItem( parts.storageBus(), 1 ); - Upgrades.CAPACITY.registerItem( parts.storageBus(), 5 ); - Upgrades.ORE_FILTER.registerItem( parts.storageBus(), 1 ); - - // Formation Plane - Upgrades.FUZZY.registerItem( parts.formationPlane(), 1 ); - Upgrades.INVERTER.registerItem( parts.formationPlane(), 1 ); - Upgrades.CAPACITY.registerItem( parts.formationPlane(), 5 ); - //Upgrades.ORE_FILTER.registerItem( parts.formationPlane(), 1 ); - - // Matter Cannon - Upgrades.FUZZY.registerItem( items.massCannon(), 1 ); - Upgrades.INVERTER.registerItem( items.massCannon(), 1 ); - Upgrades.SPEED.registerItem( items.massCannon(), 4 ); - - // Molecular Assembler - Upgrades.SPEED.registerItem( blocks.molecularAssembler(), 5 ); - - // Inscriber - Upgrades.SPEED.registerItem( blocks.inscriber(), 3 ); - - for( final Item wirelessTerminalItem : items.wirelessTerminal().maybeItem().asSet() ) - { - registries.wireless().registerWirelessHandler( (IWirelessTermHandler) wirelessTerminalItem ); - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.ChestLoot ) ) - { - final ChestGenHooks d = ChestGenHooks.getInfo( ChestGenHooks.MINESHAFT_CORRIDOR ); - - final IMaterials materials = definitions.materials(); - - for( final ItemStack crystal : materials.certusQuartzCrystal().maybeStack( 1 ).asSet() ) - { - d.addItem( new WeightedRandomChestContent( crystal, 1, 4, 2 ) ); - } - for( final ItemStack dust : materials.certusQuartzDust().maybeStack( 1 ).asSet() ) - { - d.addItem( new WeightedRandomChestContent( dust, 1, 4, 2 ) ); - } - } - - // add villager trading to black smiths for a few basic materials - if( AEConfig.instance.isFeatureEnabled( AEFeature.VillagerTrading ) ) - { - VillagerRegistry.instance().registerVillageTradeHandler( 3, new AETrading() ); - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.CertusQuartzWorldGen ) ) - { - GameRegistry.registerWorldGenerator( new QuartzWorldGen(), 0 ); - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.MeteoriteWorldGen ) ) - { - GameRegistry.registerWorldGenerator( new MeteoriteWorldGen(), 0 ); - } - - final IMovableRegistry mr = registries.movable(); - - /** - * You can't move bed rock. - */ - mr.blacklistBlock( net.minecraft.init.Blocks.bedrock ); - - /* - * White List Vanilla... - */ - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityBeacon.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityBrewingStand.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityChest.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityCommandBlock.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityComparator.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityDaylightDetector.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityDispenser.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityDropper.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityEnchantmentTable.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityEnderChest.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityEndPortal.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntitySkull.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityFurnace.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityMobSpawner.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntitySign.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityPiston.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityFlowerPot.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityNote.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityHopper.class ); - - /** - * Whitelist AE2 - */ - mr.whiteListTileEntity( AEBaseTile.class ); - - /** - * world gen - */ - for( final WorldGenType type : WorldGenType.values() ) - { - registries.worldgen().disableWorldGenForProviderID( type, StorageWorldProvider.class ); - - // nether - registries.worldgen().disableWorldGenForDimension( type, -1 ); - - // end - registries.worldgen().disableWorldGenForDimension( type, 1 ); - } - - // whitelist from config - for( final int dimension : AEConfig.instance.meteoriteDimensionWhitelist ) - { - registries.worldgen().enableWorldGenForDimension( WorldGenType.Meteorites, dimension ); - } - - /** - * initial recipe bake, if ore dictionary changes after this it re-bakes. - */ - OreDictionaryHandler.INSTANCE.bakeRecipes(); - } +public final class Registration { + private final RecipeHandler recipeHandler; + private final DefinitionConverter converter; + private BiomeGenBase storageBiome; + + Registration() { + this.converter = new DefinitionConverter(); + this.recipeHandler = new RecipeHandler(); + } + + public BiomeGenBase getStorageBiome() { + return this.storageBiome; + } + + void preInitialize(final FMLPreInitializationEvent event) { + this.registerSpatial(false); + + final Api api = Api.INSTANCE; + final IRecipeHandlerRegistry recipeRegistry = api.registries().recipes(); + this.registerCraftHandlers(recipeRegistry); + + RecipeSorter.register("AE2-Facade", FacadeRecipe.class, Category.SHAPED, ""); + RecipeSorter.register("AE2-Shaped", ShapedRecipe.class, Category.SHAPED, ""); + RecipeSorter.register("AE2-Shapeless", ShapelessRecipe.class, Category.SHAPELESS, ""); + + MinecraftForge.EVENT_BUS.register(OreDictionaryHandler.INSTANCE); + + final ApiDefinitions definitions = api.definitions(); + + final IBlocks apiBlocks = definitions.blocks(); + final IItems apiItems = definitions.items(); + final IMaterials apiMaterials = definitions.materials(); + final IParts apiParts = definitions.parts(); + + final Items items = api.items(); + final Materials materials = api.materials(); + final Parts parts = api.parts(); + final Blocks blocks = api.blocks(); + + this.assignMaterials(materials, apiMaterials); + this.assignParts(parts, apiParts); + this.assignBlocks(blocks, apiBlocks); + this.assignItems(items, apiItems); + + // Register all detected handlers and features (items, blocks) in pre-init + for (final IFeatureHandler handler : + definitions.getFeatureHandlerRegistry().getRegisteredFeatureHandlers()) { + handler.register(); + } + + for (final IAEFeature feature : definitions.getFeatureRegistry().getRegisteredFeatures()) { + feature.postInit(); + } + } + + private void registerSpatial(final boolean force) { + if (!AEConfig.instance.isFeatureEnabled(AEFeature.SpatialIO)) { + return; + } + + final AEConfig config = AEConfig.instance; + + if (this.storageBiome == null) { + if (force && config.storageBiomeID == -1) { + config.storageBiomeID = Platform.findEmpty(BiomeGenBase.getBiomeGenArray()); + if (config.storageBiomeID == -1) { + throw new IllegalStateException( + "Biome Array is full, please free up some Biome ID's or disable spatial."); + } + + this.storageBiome = new BiomeGenStorage(config.storageBiomeID); + config.save(); + } + + if (!force && config.storageBiomeID != -1) { + this.storageBiome = new BiomeGenStorage(config.storageBiomeID); + } + } + + if (config.storageProviderID != -1) { + DimensionManager.registerProviderType(config.storageProviderID, StorageWorldProvider.class, false); + } + + if (config.storageProviderID == -1 && force) { + config.storageProviderID = -11; + + while (!DimensionManager.registerProviderType( + config.storageProviderID, StorageWorldProvider.class, false)) { + config.storageProviderID--; + } + + config.save(); + } + } + + private void registerCraftHandlers(final IRecipeHandlerRegistry registry) { + registry.addNewSubItemResolver(new AEItemResolver()); + + registry.addNewCraftHandler("hccrusher", HCCrusher.class); + registry.addNewCraftHandler("mekcrusher", MekCrusher.class); + registry.addNewCraftHandler("mekechamber", MekEnrichment.class); + registry.addNewCraftHandler("grind", Grind.class); + registry.addNewCraftHandler("crusher", Crusher.class); + registry.addNewCraftHandler("grindfz", GrindFZ.class); + registry.addNewCraftHandler("pulverizer", Pulverizer.class); + registry.addNewCraftHandler("macerator", Macerator.class); + + registry.addNewCraftHandler("smelt", Smelt.class); + registry.addNewCraftHandler("inscribe", Inscribe.class); + registry.addNewCraftHandler("press", Press.class); + + registry.addNewCraftHandler("shaped", Shaped.class); + registry.addNewCraftHandler("shapeless", Shapeless.class); + } + + /** + * Assigns materials from the new API to the old API + *

+ * Uses direct cast, since its only a temporary solution anyways + * + * @param target old API + * @param source new API + * @deprecated to be removed when the public definition API is removed + */ + @Deprecated + private void assignMaterials(final Materials target, final IMaterials source) { + target.materialCell2SpatialPart = this.converter.of(source.cell2SpatialPart()); + target.materialCell16SpatialPart = this.converter.of(source.cell16SpatialPart()); + target.materialCell128SpatialPart = this.converter.of(source.cell128SpatialPart()); + + target.materialSilicon = this.converter.of(source.silicon()); + target.materialSkyDust = this.converter.of(source.skyDust()); + + target.materialCalcProcessorPress = this.converter.of(source.calcProcessorPress()); + target.materialEngProcessorPress = this.converter.of(source.engProcessorPress()); + target.materialLogicProcessorPress = this.converter.of(source.logicProcessorPress()); + + target.materialCalcProcessorPrint = this.converter.of(source.calcProcessorPrint()); + target.materialEngProcessorPrint = this.converter.of(source.engProcessorPrint()); + target.materialLogicProcessorPrint = this.converter.of(source.logicProcessorPrint()); + + target.materialSiliconPress = this.converter.of(source.siliconPress()); + target.materialSiliconPrint = this.converter.of(source.siliconPrint()); + + target.materialNamePress = this.converter.of(source.namePress()); + + target.materialLogicProcessor = this.converter.of(source.logicProcessor()); + target.materialCalcProcessor = this.converter.of(source.calcProcessor()); + target.materialEngProcessor = this.converter.of(source.engProcessor()); + + target.materialBasicCard = this.converter.of(source.basicCard()); + target.materialAdvCard = this.converter.of(source.advCard()); + + target.materialPurifiedCertusQuartzCrystal = this.converter.of(source.purifiedCertusQuartzCrystal()); + target.materialPurifiedNetherQuartzCrystal = this.converter.of(source.purifiedNetherQuartzCrystal()); + target.materialPurifiedFluixCrystal = this.converter.of(source.purifiedFluixCrystal()); + + target.materialCell1kPart = this.converter.of(source.cell1kPart()); + target.materialCell4kPart = this.converter.of(source.cell4kPart()); + target.materialCell16kPart = this.converter.of(source.cell16kPart()); + target.materialCell64kPart = this.converter.of(source.cell64kPart()); + target.materialEmptyStorageCell = this.converter.of(source.emptyStorageCell()); + + target.materialCardRedstone = this.converter.of(source.cardRedstone()); + target.materialCardSpeed = this.converter.of(source.cardSpeed()); + target.materialCardCapacity = this.converter.of(source.cardCapacity()); + target.materialCardFuzzy = this.converter.of(source.cardFuzzy()); + target.materialCardInverter = this.converter.of(source.cardInverter()); + target.materialCardCrafting = this.converter.of(source.cardCrafting()); + + target.materialEnderDust = this.converter.of(source.enderDust()); + target.materialFlour = this.converter.of(source.flour()); + target.materialGoldDust = this.converter.of(source.goldDust()); + target.materialIronDust = this.converter.of(source.ironDust()); + target.materialFluixDust = this.converter.of(source.fluixDust()); + target.materialCertusQuartzDust = this.converter.of(source.certusQuartzDust()); + target.materialNetherQuartzDust = this.converter.of(source.netherQuartzDust()); + + target.materialMatterBall = this.converter.of(source.matterBall()); + target.materialIronNugget = this.converter.of(source.ironNugget()); + + target.materialCertusQuartzCrystal = this.converter.of(source.certusQuartzCrystal()); + target.materialCertusQuartzCrystalCharged = this.converter.of(source.certusQuartzCrystalCharged()); + target.materialFluixCrystal = this.converter.of(source.fluixCrystal()); + target.materialFluixPearl = this.converter.of(source.fluixPearl()); + + target.materialWoodenGear = this.converter.of(source.woodenGear()); + + target.materialWireless = this.converter.of(source.wireless()); + target.materialWirelessBooster = this.converter.of(source.wirelessBooster()); + + target.materialAnnihilationCore = this.converter.of(source.annihilationCore()); + target.materialFormationCore = this.converter.of(source.formationCore()); + + target.materialSingularity = this.converter.of(source.singularity()); + target.materialQESingularity = this.converter.of(source.qESingularity()); + target.materialBlankPattern = this.converter.of(source.blankPattern()); + } + + /** + * Assigns parts from the new API to the old API + * + * @param target old API + * @param source new API + * @deprecated to be removed when the public definition API is removed + */ + @Deprecated + private void assignParts(final Parts target, final IParts source) { + target.partCableSmart = source.cableSmart(); + target.partCableCovered = source.cableCovered(); + target.partCableGlass = source.cableGlass(); + target.partCableDense = source.cableDense(); + target.partCableDenseCovered = source.cableDenseCovered(); + target.partCableUltraDenseSmart = source.cableUltraDenseSmart(); + target.partCableUltraDenseCovered = source.cableUltraDenseCovered(); + // target.partLumenCableSmart = source.lumenCableSmart(); + // target.partLumenCableCovered = source.lumenCableCovered(); + // target.partLumenCableGlass = source.lumenCableGlass(); + // target.partLumenCableDense = source.lumenCableDense(); + target.partQuartzFiber = this.converter.of(source.quartzFiber()); + target.partToggleBus = this.converter.of(source.toggleBus()); + target.partInvertedToggleBus = this.converter.of(source.invertedToggleBus()); + target.partStorageBus = this.converter.of(source.storageBus()); + target.partImportBus = this.converter.of(source.importBus()); + target.partExportBus = this.converter.of(source.exportBus()); + target.partInterface = this.converter.of(source.iface()); + target.partLevelEmitter = this.converter.of(source.levelEmitter()); + target.partAnnihilationPlane = this.converter.of(source.annihilationPlane()); + target.partFormationPlane = this.converter.of(source.formationPlane()); + + target.partCableAnchor = this.converter.of(source.cableAnchor()); + target.partP2PTunnelLight = target.partCableAnchor; + target.partP2PTunnelRF = target.partP2PTunnelLight; + target.partP2PTunnelEU = target.partP2PTunnelRF; + target.partP2PTunnelLiquids = target.partP2PTunnelEU; + target.partP2PTunnelItems = target.partP2PTunnelLiquids; + target.partP2PTunnelRedstone = target.partP2PTunnelItems; + target.partP2PTunnelME = target.partP2PTunnelRedstone; + target.partMonitor = this.converter.of(source.monitor()); + target.partSemiDarkMonitor = this.converter.of(source.semiDarkMonitor()); + target.partDarkMonitor = this.converter.of(source.darkMonitor()); + target.partInterfaceTerminal = this.converter.of(source.interfaceTerminal()); + target.partPatternTerminal = this.converter.of(source.patternTerminal()); + target.partCraftingTerminal = this.converter.of(source.craftingTerminal()); + target.partTerminal = this.converter.of(source.terminal()); + target.partStorageMonitor = this.converter.of(source.storageMonitor()); + target.partConversionMonitor = this.converter.of(source.conversionMonitor()); + } + + /** + * Assigns blocks from the new API to the old API + * + * @param target old API + * @param source new API + * @deprecated to be removed when the public definition API is removed + */ + @Deprecated + private void assignBlocks(final Blocks target, final IBlocks source) { + target.blockMultiPart = this.converter.of(source.multiPart()); + + target.blockCraftingUnit = this.converter.of(source.craftingUnit()); + target.blockCraftingAccelerator = this.converter.of(source.craftingAccelerator()); + target.blockCraftingAccelerator4x = this.converter.of(source.craftingAccelerator4x()); + target.blockCraftingAccelerator16x = this.converter.of(source.craftingAccelerator16x()); + target.blockCraftingMonitor = this.converter.of(source.craftingMonitor()); + target.blockCraftingStorage1k = this.converter.of(source.craftingStorage1k()); + target.blockCraftingStorage4k = this.converter.of(source.craftingStorage4k()); + target.blockCraftingStorage16k = this.converter.of(source.craftingStorage16k()); + target.blockCraftingStorage64k = this.converter.of(source.craftingStorage64k()); + target.blockMolecularAssembler = this.converter.of(source.molecularAssembler()); + + target.blockQuartzOre = this.converter.of(source.quartzOre()); + target.blockQuartzOreCharged = this.converter.of(source.quartzOreCharged()); + target.blockMatrixFrame = this.converter.of(source.matrixFrame()); + target.blockQuartz = this.converter.of(source.quartz()); + target.blockFluix = this.converter.of(source.fluix()); + target.blockSkyStone = this.converter.of(source.skyStone()); + target.blockSkyChest = this.converter.of(source.skyChest()); + target.blockSkyCompass = this.converter.of(source.skyCompass()); + + target.blockQuartzGlass = this.converter.of(source.quartzGlass()); + target.blockQuartzVibrantGlass = this.converter.of(source.quartzVibrantGlass()); + target.blockQuartzPillar = this.converter.of(source.quartzPillar()); + target.blockQuartzChiseled = this.converter.of(source.quartzChiseled()); + target.blockQuartzTorch = this.converter.of(source.quartzTorch()); + target.blockLightDetector = this.converter.of(source.lightDetector()); + target.blockCharger = this.converter.of(source.charger()); + target.blockQuartzGrowthAccelerator = this.converter.of(source.quartzGrowthAccelerator()); + + target.blockGrindStone = this.converter.of(source.grindStone()); + target.blockCrankHandle = this.converter.of(source.crankHandle()); + target.blockInscriber = this.converter.of(source.inscriber()); + target.blockWireless = this.converter.of(source.wireless()); + target.blockTinyTNT = this.converter.of(source.tinyTNT()); + + target.blockQuantumRing = this.converter.of(source.quantumRing()); + target.blockQuantumLink = this.converter.of(source.quantumLink()); + + target.blockSpatialPylon = this.converter.of(source.spatialPylon()); + target.blockSpatialIOPort = this.converter.of(source.spatialIOPort()); + + target.blockController = this.converter.of(source.controller()); + target.blockDrive = this.converter.of(source.drive()); + target.blockChest = this.converter.of(source.chest()); + target.blockInterface = this.converter.of(source.iface()); + target.blockCellWorkbench = this.converter.of(source.cellWorkbench()); + target.blockIOPort = this.converter.of(source.iOPort()); + target.blockCondenser = this.converter.of(source.condenser()); + target.blockEnergyAcceptor = this.converter.of(source.energyAcceptor()); + target.blockVibrationChamber = this.converter.of(source.vibrationChamber()); + + target.blockEnergyCell = this.converter.of(source.energyCell()); + target.blockEnergyCellDense = this.converter.of(source.energyCellDense()); + target.blockEnergyCellCreative = this.converter.of(source.energyCellCreative()); + + target.blockSecurity = this.converter.of(source.security()); + target.blockPaint = this.converter.of(source.paint()); + } + + /** + * Assigns materials from the new API to the old API + * + * @param target old API + * @param source new API + * @deprecated to be removed when the public definition API is removed + */ + @Deprecated + private void assignItems(final Items target, final IItems source) { + target.itemCellCreative = this.converter.of(source.cellCreative()); + target.itemViewCell = this.converter.of(source.viewCell()); + target.itemEncodedPattern = this.converter.of(source.encodedPattern()); + + target.itemCell1k = this.converter.of(source.cell1k()); + target.itemCell4k = this.converter.of(source.cell4k()); + target.itemCell16k = this.converter.of(source.cell16k()); + target.itemCell64k = this.converter.of(source.cell64k()); + + target.itemSpatialCell2 = this.converter.of(source.spatialCell2()); + target.itemSpatialCell16 = this.converter.of(source.spatialCell16()); + target.itemSpatialCell128 = this.converter.of(source.spatialCell128()); + + target.itemCertusQuartzKnife = this.converter.of(source.certusQuartzKnife()); + target.itemCertusQuartzWrench = this.converter.of(source.certusQuartzWrench()); + target.itemCertusQuartzAxe = this.converter.of(source.certusQuartzAxe()); + target.itemCertusQuartzHoe = this.converter.of(source.certusQuartzHoe()); + target.itemCertusQuartzPick = this.converter.of(source.certusQuartzPick()); + target.itemCertusQuartzShovel = this.converter.of(source.certusQuartzShovel()); + target.itemCertusQuartzSword = this.converter.of(source.certusQuartzSword()); + + target.itemNetherQuartzKnife = this.converter.of(source.netherQuartzKnife()); + target.itemNetherQuartzWrench = this.converter.of(source.netherQuartzWrench()); + target.itemNetherQuartzAxe = this.converter.of(source.netherQuartzAxe()); + target.itemNetherQuartzHoe = this.converter.of(source.netherQuartzHoe()); + target.itemNetherQuartzPick = this.converter.of(source.netherQuartzPick()); + target.itemNetherQuartzShovel = this.converter.of(source.netherQuartzShovel()); + target.itemNetherQuartzSword = this.converter.of(source.netherQuartzSword()); + + target.itemMassCannon = this.converter.of(source.massCannon()); + target.itemMemoryCard = this.converter.of(source.memoryCard()); + target.itemChargedStaff = this.converter.of(source.chargedStaff()); + target.itemEntropyManipulator = this.converter.of(source.entropyManipulator()); + target.itemColorApplicator = this.converter.of(source.colorApplicator()); + + target.itemWirelessTerminal = this.converter.of(source.wirelessTerminal()); + target.itemNetworkTool = this.converter.of(source.networkTool()); + target.itemPortableCell = this.converter.of(source.portableCell()); + target.itemBiometricCard = this.converter.of(source.biometricCard()); + + target.itemFacade = this.converter.of(source.facade()); + target.itemCrystalSeed = this.converter.of(source.crystalSeed()); + + target.itemPaintBall = source.coloredPaintBall(); + target.itemLumenPaintBall = source.coloredLumenPaintBall(); + } + + void initialize( + @Nonnull final FMLInitializationEvent event, + @Nonnull final File recipeDirectory, + @Nonnull final CustomRecipeConfig customRecipeConfig) { + Preconditions.checkNotNull(event); + Preconditions.checkNotNull(recipeDirectory); + Preconditions.checkArgument(!recipeDirectory.isFile()); + Preconditions.checkNotNull(customRecipeConfig); + + final IAppEngApi api = AEApi.instance(); + final IPartHelper partHelper = api.partHelper(); + final IRegistryContainer registries = api.registries(); + + // Perform ore camouflage! + ItemMultiMaterial.instance.makeUnique(); + + final Runnable recipeLoader = new RecipeLoader(recipeDirectory, customRecipeConfig, this.recipeHandler); + recipeLoader.run(); + + partHelper.registerNewLayer( + "appeng.parts.layers.LayerISidedInventory", "net.minecraft.inventory.ISidedInventory"); + partHelper.registerNewLayer( + "appeng.parts.layers.LayerIFluidHandler", "net.minecraftforge.fluids.IFluidHandler"); + partHelper.registerNewLayer( + "appeng.parts.layers.LayerITileStorageMonitorable", + "appeng.api.implementations.tiles.ITileStorageMonitorable"); + + FMLCommonHandler.instance().bus().register(TickHandler.INSTANCE); + MinecraftForge.EVENT_BUS.register(TickHandler.INSTANCE); + + final PartPlacement pp = new PartPlacement(); + MinecraftForge.EVENT_BUS.register(pp); + FMLCommonHandler.instance().bus().register(pp); + + final IGridCacheRegistry gcr = registries.gridCache(); + gcr.registerGridCache(ITickManager.class, TickManagerCache.class); + gcr.registerGridCache(IEnergyGrid.class, EnergyGridCache.class); + gcr.registerGridCache(IPathingGrid.class, PathGridCache.class); + gcr.registerGridCache(IStorageGrid.class, GridStorageCache.class); + gcr.registerGridCache(P2PCache.class, P2PCache.class); + gcr.registerGridCache(ISpatialCache.class, SpatialPylonCache.class); + gcr.registerGridCache(ISecurityGrid.class, SecurityCache.class); + gcr.registerGridCache(ICraftingGrid.class, CraftingGridCache.class); + + registries.externalStorage().addExternalStorageInterface(new AEExternalHandler()); + + registries.cell().addCellHandler(new BasicCellHandler()); + registries.cell().addCellHandler(new CreativeCellHandler()); + + for (final ItemStack ammoStack : + api.definitions().materials().matterBall().maybeStack(1).asSet()) { + final double weight = 32; + + registries.matterCannon().registerAmmo(ammoStack, weight); + } + + this.recipeHandler.injectRecipes(); + + final PlayerStatsRegistration registration = + new PlayerStatsRegistration(FMLCommonHandler.instance().bus(), AEConfig.instance); + registration.registerAchievementHandlers(); + registration.registerAchievements(); + + if (AEConfig.instance.isFeatureEnabled(AEFeature.EnableDisassemblyCrafting)) { + GameRegistry.addRecipe(new DisassembleRecipe()); + RecipeSorter.register( + "appliedenergistics2:disassemble", + DisassembleRecipe.class, + Category.SHAPELESS, + "after:minecraft:shapeless"); + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.EnableFacadeCrafting)) { + GameRegistry.addRecipe(new FacadeRecipe()); + RecipeSorter.register( + "appliedenergistics2:facade", FacadeRecipe.class, Category.SHAPED, "after:minecraft:shaped"); + } + } + + void postInit(final FMLPostInitializationEvent event) { + this.registerSpatial(true); + + final IAppEngApi api = AEApi.instance(); + final IRegistryContainer registries = api.registries(); + final IDefinitions definitions = api.definitions(); + final IParts parts = definitions.parts(); + final IBlocks blocks = definitions.blocks(); + final IItems items = definitions.items(); + + // default settings.. + ((P2PTunnelRegistry) registries.p2pTunnel()).configure(); + + // add to localization.. + PlayerMessages.values(); + GuiText.values(); + + Api.INSTANCE.partHelper().initFMPSupport(); + for (final Block block : blocks.multiPart().maybeBlock().asSet()) { + ((BlockCableBus) block).setupTile(); + } + + // Interface + Upgrades.CRAFTING.registerItem(parts.iface(), 1); + Upgrades.CRAFTING.registerItem(blocks.iface(), 1); + Upgrades.PATTERN_CAPACITY.registerItem(parts.iface(), 3); + Upgrades.PATTERN_CAPACITY.registerItem(blocks.iface(), 3); + + // IO Port! + Upgrades.SPEED.registerItem(blocks.iOPort(), 3); + Upgrades.REDSTONE.registerItem(blocks.iOPort(), 1); + + // Level Emitter! + Upgrades.FUZZY.registerItem(parts.levelEmitter(), 1); + Upgrades.CRAFTING.registerItem(parts.levelEmitter(), 1); + + // Import Bus + Upgrades.FUZZY.registerItem(parts.importBus(), 1); + Upgrades.REDSTONE.registerItem(parts.importBus(), 1); + Upgrades.CAPACITY.registerItem(parts.importBus(), 2); + Upgrades.SPEED.registerItem(parts.importBus(), 4); + Upgrades.ORE_FILTER.registerItem(parts.importBus(), 1); + + // Export Bus + Upgrades.FUZZY.registerItem(parts.exportBus(), 1); + Upgrades.REDSTONE.registerItem(parts.exportBus(), 1); + Upgrades.CAPACITY.registerItem(parts.exportBus(), 2); + Upgrades.SPEED.registerItem(parts.exportBus(), 4); + Upgrades.CRAFTING.registerItem(parts.exportBus(), 1); + Upgrades.ORE_FILTER.registerItem(parts.exportBus(), 1); + + // Storage Cells + Upgrades.FUZZY.registerItem(items.cell1k(), 1); + Upgrades.INVERTER.registerItem(items.cell1k(), 1); + Upgrades.ORE_FILTER.registerItem(items.cell1k(), 1); + + Upgrades.FUZZY.registerItem(items.cell4k(), 1); + Upgrades.INVERTER.registerItem(items.cell4k(), 1); + Upgrades.ORE_FILTER.registerItem(items.cell4k(), 1); + + Upgrades.FUZZY.registerItem(items.cell16k(), 1); + Upgrades.INVERTER.registerItem(items.cell16k(), 1); + Upgrades.ORE_FILTER.registerItem(items.cell16k(), 1); + + Upgrades.FUZZY.registerItem(items.cell64k(), 1); + Upgrades.INVERTER.registerItem(items.cell64k(), 1); + Upgrades.ORE_FILTER.registerItem(items.cell64k(), 1); + + Upgrades.FUZZY.registerItem(items.portableCell(), 1); + Upgrades.INVERTER.registerItem(items.portableCell(), 1); + Upgrades.ORE_FILTER.registerItem(items.portableCell(), 1); + + Upgrades.FUZZY.registerItem(items.viewCell(), 1); + Upgrades.INVERTER.registerItem(items.viewCell(), 1); + Upgrades.ORE_FILTER.registerItem(items.viewCell(), 1); + + // Storage Bus + Upgrades.FUZZY.registerItem(parts.storageBus(), 1); + Upgrades.INVERTER.registerItem(parts.storageBus(), 1); + Upgrades.CAPACITY.registerItem(parts.storageBus(), 5); + Upgrades.ORE_FILTER.registerItem(parts.storageBus(), 1); + + // Formation Plane + Upgrades.FUZZY.registerItem(parts.formationPlane(), 1); + Upgrades.INVERTER.registerItem(parts.formationPlane(), 1); + Upgrades.CAPACITY.registerItem(parts.formationPlane(), 5); + // Upgrades.ORE_FILTER.registerItem( parts.formationPlane(), 1 ); + + // Matter Cannon + Upgrades.FUZZY.registerItem(items.massCannon(), 1); + Upgrades.INVERTER.registerItem(items.massCannon(), 1); + Upgrades.SPEED.registerItem(items.massCannon(), 4); + + // Molecular Assembler + Upgrades.SPEED.registerItem(blocks.molecularAssembler(), 5); + + // Inscriber + Upgrades.SPEED.registerItem(blocks.inscriber(), 3); + + for (final Item wirelessTerminalItem : + items.wirelessTerminal().maybeItem().asSet()) { + registries.wireless().registerWirelessHandler((IWirelessTermHandler) wirelessTerminalItem); + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.ChestLoot)) { + final ChestGenHooks d = ChestGenHooks.getInfo(ChestGenHooks.MINESHAFT_CORRIDOR); + + final IMaterials materials = definitions.materials(); + + for (final ItemStack crystal : + materials.certusQuartzCrystal().maybeStack(1).asSet()) { + d.addItem(new WeightedRandomChestContent(crystal, 1, 4, 2)); + } + for (final ItemStack dust : + materials.certusQuartzDust().maybeStack(1).asSet()) { + d.addItem(new WeightedRandomChestContent(dust, 1, 4, 2)); + } + } + + // add villager trading to black smiths for a few basic materials + if (AEConfig.instance.isFeatureEnabled(AEFeature.VillagerTrading)) { + VillagerRegistry.instance().registerVillageTradeHandler(3, new AETrading()); + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.CertusQuartzWorldGen)) { + GameRegistry.registerWorldGenerator(new QuartzWorldGen(), 0); + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.MeteoriteWorldGen)) { + GameRegistry.registerWorldGenerator(new MeteoriteWorldGen(), 0); + } + + final IMovableRegistry mr = registries.movable(); + + /** + * You can't move bed rock. + */ + mr.blacklistBlock(net.minecraft.init.Blocks.bedrock); + + /* + * White List Vanilla... + */ + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityBeacon.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityBrewingStand.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityChest.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityCommandBlock.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityComparator.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityDaylightDetector.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityDispenser.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityDropper.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityEnchantmentTable.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityEnderChest.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityEndPortal.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntitySkull.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityFurnace.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityMobSpawner.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntitySign.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityPiston.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityFlowerPot.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityNote.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityHopper.class); + + /** + * Whitelist AE2 + */ + mr.whiteListTileEntity(AEBaseTile.class); + + /** + * world gen + */ + for (final WorldGenType type : WorldGenType.values()) { + registries.worldgen().disableWorldGenForProviderID(type, StorageWorldProvider.class); + + // nether + registries.worldgen().disableWorldGenForDimension(type, -1); + + // end + registries.worldgen().disableWorldGenForDimension(type, 1); + } + + // whitelist from config + for (final int dimension : AEConfig.instance.meteoriteDimensionWhitelist) { + registries.worldgen().enableWorldGenForDimension(WorldGenType.Meteorites, dimension); + } + + /** + * initial recipe bake, if ore dictionary changes after this it re-bakes. + */ + OreDictionaryHandler.INSTANCE.bakeRecipes(); + } } diff --git a/src/main/java/appeng/core/api/ApiPart.java b/src/main/java/appeng/core/api/ApiPart.java index 2ebcadb23de..406d55f6a94 100644 --- a/src/main/java/appeng/core/api/ApiPart.java +++ b/src/main/java/appeng/core/api/ApiPart.java @@ -18,7 +18,6 @@ package appeng.core.api; - import appeng.api.parts.CableRenderMode; import appeng.api.parts.IPartHelper; import appeng.api.parts.IPartItem; @@ -33,6 +32,10 @@ import appeng.tile.networking.TileCableBus; import appeng.util.Platform; import com.google.common.base.Joiner; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.util.*; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -48,313 +51,253 @@ import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Method; -import java.util.*; - - -public class ApiPart implements IPartHelper -{ - - private final Map tileImplementations = new HashMap(); - private final Map, String> interfaces2Layer = new HashMap, String>(); - private final Map roots = new HashMap(); - private final List desc = new LinkedList(); - - public void initFMPSupport() - { - for( final Class layerInterface : this.interfaces2Layer.keySet() ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.FMP ) ) - { - ( (IFMP) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.FMP ) ).registerPassThrough( layerInterface ); - } - } - } - - public Class getCombinedInstance( final String base ) - { - if( this.desc.isEmpty() ) - { - try - { - return Class.forName( base ); - } - catch( final ClassNotFoundException e ) - { - throw new IllegalStateException( e ); - } - } - - final String description = base + ':' + Joiner.on( ";" ).skipNulls().join( this.desc.iterator() ); - - if( this.tileImplementations.get( description ) != null ) - { - return this.tileImplementations.get( description ); - } - - String f = base;// TileCableBus.class.getName(); - String Addendum = ""; - try - { - Addendum = Class.forName( base ).getSimpleName(); - } - catch( final ClassNotFoundException e ) - { - AELog.debug( e ); - } - Class myCLass; - - try - { - myCLass = Class.forName( f ); - } - catch( final ClassNotFoundException e ) - { - throw new IllegalStateException( e ); - } - - String path = f; - - for( final String name : this.desc ) - { - try - { - final String newPath = path + ';' + name; - myCLass = this.getClassByDesc( Addendum, newPath, f, this.interfaces2Layer.get( Class.forName( name ) ) ); - path = newPath; - } - catch( final Throwable t ) - { - AELog.warn( "Error loading " + name ); - AELog.debug( t ); - // throw new RuntimeException( t ); - } - f = myCLass.getName(); - } - - this.tileImplementations.put( description, myCLass ); - - return myCLass; - } - - private Class getClassByDesc( final String addendum, final String fullPath, final String root, final String next ) - { - if( this.roots.get( fullPath ) != null ) - { - return this.roots.get( fullPath ); - } - - final ClassWriter cw = new ClassWriter( ClassWriter.COMPUTE_MAXS ); - final ClassNode n = this.getReader( next ); - final String originalName = n.name; - - try - { - n.name = n.name + '_' + addendum; - n.superName = Class.forName( root ).getName().replace( ".", "/" ); - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - - for( final MethodNode mn : n.methods ) - { - final Iterator i = mn.instructions.iterator(); - while( i.hasNext() ) - { - this.processNode( i.next(), n.superName ); - } - } - - final DefaultPackageClassNameRemapper remapper = new DefaultPackageClassNameRemapper(); - remapper.inputOutput.put( "appeng/api/parts/LayerBase", n.superName ); - remapper.inputOutput.put( originalName, n.name ); - n.accept( new RemappingClassAdapter( cw, remapper ) ); - // n.accept( cw ); - - // n.accept( new TraceClassVisitor( new PrintWriter( System.out ) ) ); - final byte[] byteArray = cw.toByteArray(); - final int size = byteArray.length; - final Class clazz = this.loadClass( n.name.replace( "/", "." ), byteArray ); - - try - { - final Object fish = clazz.newInstance(); - final Class rootC = Class.forName( root ); - - boolean hasError = false; - - if( !rootC.isInstance( fish ) ) - { - hasError = true; - AELog.error( "Error, Expected layer to implement " + root + " did not." ); - } - - if( fish instanceof LayerBase ) - { - hasError = true; - AELog.error( "Error, Expected layer to NOT implement LayerBase but it DID." ); - } - - if( !fullPath.contains( ".fmp." ) ) - { - if( !( fish instanceof TileCableBus ) ) - { - hasError = true; - AELog.error( "Error, Expected layer to implement TileCableBus did not." ); - } - - if( !( fish instanceof TileEntity ) ) - { - hasError = true; - AELog.error( "Error, Expected layer to implement TileEntity did not." ); - } - } - - if( !hasError ) - { - AELog.info( "Layer: " + n.name + " loaded successfully - " + size + " bytes" ); - } - } - catch( final Throwable t ) - { - AELog.error( "Layer: " + n.name + " Failed." ); - AELog.debug( t ); - } - - this.roots.put( fullPath, clazz ); - return clazz; - } - - private ClassNode getReader( final String name ) - { - final String path = '/' + name.replace( ".", "/" ) + ".class"; - final InputStream is = this.getClass().getResourceAsStream( path ); - try - { - final ClassReader cr = new ClassReader( is ); - - final ClassNode cn = new ClassNode(); - cr.accept( cn, ClassReader.EXPAND_FRAMES ); - - return cn; - } - catch( final IOException e ) - { - throw new IllegalStateException( "Error loading " + name, e ); - } - } - - private void processNode( final AbstractInsnNode next, final String nePar ) - { - if( next instanceof MethodInsnNode ) - { - final MethodInsnNode min = (MethodInsnNode) next; - if( min.owner.equals( "appeng/api/parts/LayerBase" ) ) - { - min.owner = nePar; - } - } - } - - private Class loadClass( final String name, byte[] b ) - { - // override classDefine (as it is protected) and define the class. - Class clazz = null; - try - { - final ClassLoader loader = this.getClass().getClassLoader();// ClassLoader.getSystemClassLoader(); - final Class root = ClassLoader.class; - final Class cls = loader.getClass(); - final Method defineClassMethod = root.getDeclaredMethod( "defineClass", String.class, byte[].class, int.class, int.class ); - final Method runTransformersMethod = cls.getDeclaredMethod( "runTransformers", String.class, String.class, byte[].class ); - - runTransformersMethod.setAccessible( true ); - defineClassMethod.setAccessible( true ); - try - { - final Object[] argsA = { name, name, b }; - b = (byte[]) runTransformersMethod.invoke( loader, argsA ); - - final Object[] args = { name, b, 0, b.length }; - clazz = (Class) defineClassMethod.invoke( loader, args ); - } - finally - { - runTransformersMethod.setAccessible( false ); - defineClassMethod.setAccessible( false ); - } - } - catch( final Exception e ) - { - AELog.debug( e ); - throw new IllegalStateException( "Unable to manage part API.", e ); - } - return clazz; - } - - @Override - public boolean registerNewLayer( final String layer, final String layerInterface ) - { - try - { - final Class layerInterfaceClass = Class.forName( layerInterface ); - if( this.interfaces2Layer.get( layerInterfaceClass ) == null ) - { - this.interfaces2Layer.put( layerInterfaceClass, layer ); - this.desc.add( layerInterface ); - return true; - } - else - { - AELog.info( "Layer " + layer + " not registered, " + layerInterface + " already has a layer." ); - } - } - catch( final Throwable ignored ) - { - } - - return false; - } - - @Override - public void setItemBusRenderer( final IPartItem i ) - { - if( Platform.isClient() && i instanceof Item ) - { - MinecraftForgeClient.registerItemRenderer( (Item) i, BusRenderer.INSTANCE ); - } - } - - @Override - public boolean placeBus( final ItemStack is, final int x, final int y, final int z, final int side, final EntityPlayer player, final World w ) - { - return PartPlacement.place( is, x, y, z, side, player, w, PartPlacement.PlaceType.PLACE_ITEM, 0 ); - } - - @Override - public CableRenderMode getCableRenderMode() - { - return CommonHelper.proxy.getRenderMode(); - } - - private static class DefaultPackageClassNameRemapper extends Remapper - { - - private final HashMap inputOutput = new HashMap(); - - @Override - public String map( final String typeName ) - { - final String o = this.inputOutput.get( typeName ); - if( o == null ) - { - return typeName; - } - return o; - } - } +public class ApiPart implements IPartHelper { + + private final Map tileImplementations = new HashMap(); + private final Map, String> interfaces2Layer = new HashMap, String>(); + private final Map roots = new HashMap(); + private final List desc = new LinkedList(); + + public void initFMPSupport() { + for (final Class layerInterface : this.interfaces2Layer.keySet()) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.FMP)) { + ((IFMP) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.FMP)) + .registerPassThrough(layerInterface); + } + } + } + + public Class getCombinedInstance(final String base) { + if (this.desc.isEmpty()) { + try { + return Class.forName(base); + } catch (final ClassNotFoundException e) { + throw new IllegalStateException(e); + } + } + + final String description = base + ':' + Joiner.on(";").skipNulls().join(this.desc.iterator()); + + if (this.tileImplementations.get(description) != null) { + return this.tileImplementations.get(description); + } + + String f = base; // TileCableBus.class.getName(); + String Addendum = ""; + try { + Addendum = Class.forName(base).getSimpleName(); + } catch (final ClassNotFoundException e) { + AELog.debug(e); + } + Class myCLass; + + try { + myCLass = Class.forName(f); + } catch (final ClassNotFoundException e) { + throw new IllegalStateException(e); + } + + String path = f; + + for (final String name : this.desc) { + try { + final String newPath = path + ';' + name; + myCLass = this.getClassByDesc(Addendum, newPath, f, this.interfaces2Layer.get(Class.forName(name))); + path = newPath; + } catch (final Throwable t) { + AELog.warn("Error loading " + name); + AELog.debug(t); + // throw new RuntimeException( t ); + } + f = myCLass.getName(); + } + + this.tileImplementations.put(description, myCLass); + + return myCLass; + } + + private Class getClassByDesc(final String addendum, final String fullPath, final String root, final String next) { + if (this.roots.get(fullPath) != null) { + return this.roots.get(fullPath); + } + + final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + final ClassNode n = this.getReader(next); + final String originalName = n.name; + + try { + n.name = n.name + '_' + addendum; + n.superName = Class.forName(root).getName().replace(".", "/"); + } catch (final Throwable t) { + AELog.debug(t); + } + + for (final MethodNode mn : n.methods) { + final Iterator i = mn.instructions.iterator(); + while (i.hasNext()) { + this.processNode(i.next(), n.superName); + } + } + + final DefaultPackageClassNameRemapper remapper = new DefaultPackageClassNameRemapper(); + remapper.inputOutput.put("appeng/api/parts/LayerBase", n.superName); + remapper.inputOutput.put(originalName, n.name); + n.accept(new RemappingClassAdapter(cw, remapper)); + // n.accept( cw ); + + // n.accept( new TraceClassVisitor( new PrintWriter( System.out ) ) ); + final byte[] byteArray = cw.toByteArray(); + final int size = byteArray.length; + final Class clazz = this.loadClass(n.name.replace("/", "."), byteArray); + + try { + final Object fish = clazz.newInstance(); + final Class rootC = Class.forName(root); + + boolean hasError = false; + + if (!rootC.isInstance(fish)) { + hasError = true; + AELog.error("Error, Expected layer to implement " + root + " did not."); + } + + if (fish instanceof LayerBase) { + hasError = true; + AELog.error("Error, Expected layer to NOT implement LayerBase but it DID."); + } + + if (!fullPath.contains(".fmp.")) { + if (!(fish instanceof TileCableBus)) { + hasError = true; + AELog.error("Error, Expected layer to implement TileCableBus did not."); + } + + if (!(fish instanceof TileEntity)) { + hasError = true; + AELog.error("Error, Expected layer to implement TileEntity did not."); + } + } + + if (!hasError) { + AELog.info("Layer: " + n.name + " loaded successfully - " + size + " bytes"); + } + } catch (final Throwable t) { + AELog.error("Layer: " + n.name + " Failed."); + AELog.debug(t); + } + + this.roots.put(fullPath, clazz); + return clazz; + } + + private ClassNode getReader(final String name) { + final String path = '/' + name.replace(".", "/") + ".class"; + final InputStream is = this.getClass().getResourceAsStream(path); + try { + final ClassReader cr = new ClassReader(is); + + final ClassNode cn = new ClassNode(); + cr.accept(cn, ClassReader.EXPAND_FRAMES); + + return cn; + } catch (final IOException e) { + throw new IllegalStateException("Error loading " + name, e); + } + } + + private void processNode(final AbstractInsnNode next, final String nePar) { + if (next instanceof MethodInsnNode) { + final MethodInsnNode min = (MethodInsnNode) next; + if (min.owner.equals("appeng/api/parts/LayerBase")) { + min.owner = nePar; + } + } + } + + private Class loadClass(final String name, byte[] b) { + // override classDefine (as it is protected) and define the class. + Class clazz = null; + try { + final ClassLoader loader = this.getClass().getClassLoader(); // ClassLoader.getSystemClassLoader(); + final Class root = ClassLoader.class; + final Class cls = loader.getClass(); + final Method defineClassMethod = + root.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class); + final Method runTransformersMethod = + cls.getDeclaredMethod("runTransformers", String.class, String.class, byte[].class); + + runTransformersMethod.setAccessible(true); + defineClassMethod.setAccessible(true); + try { + final Object[] argsA = {name, name, b}; + b = (byte[]) runTransformersMethod.invoke(loader, argsA); + + final Object[] args = {name, b, 0, b.length}; + clazz = (Class) defineClassMethod.invoke(loader, args); + } finally { + runTransformersMethod.setAccessible(false); + defineClassMethod.setAccessible(false); + } + } catch (final Exception e) { + AELog.debug(e); + throw new IllegalStateException("Unable to manage part API.", e); + } + return clazz; + } + + @Override + public boolean registerNewLayer(final String layer, final String layerInterface) { + try { + final Class layerInterfaceClass = Class.forName(layerInterface); + if (this.interfaces2Layer.get(layerInterfaceClass) == null) { + this.interfaces2Layer.put(layerInterfaceClass, layer); + this.desc.add(layerInterface); + return true; + } else { + AELog.info("Layer " + layer + " not registered, " + layerInterface + " already has a layer."); + } + } catch (final Throwable ignored) { + } + + return false; + } + + @Override + public void setItemBusRenderer(final IPartItem i) { + if (Platform.isClient() && i instanceof Item) { + MinecraftForgeClient.registerItemRenderer((Item) i, BusRenderer.INSTANCE); + } + } + + @Override + public boolean placeBus( + final ItemStack is, + final int x, + final int y, + final int z, + final int side, + final EntityPlayer player, + final World w) { + return PartPlacement.place(is, x, y, z, side, player, w, PartPlacement.PlaceType.PLACE_ITEM, 0); + } + + @Override + public CableRenderMode getCableRenderMode() { + return CommonHelper.proxy.getRenderMode(); + } + + private static class DefaultPackageClassNameRemapper extends Remapper { + + private final HashMap inputOutput = new HashMap(); + + @Override + public String map(final String typeName) { + final String o = this.inputOutput.get(typeName); + if (o == null) { + return typeName; + } + return o; + } + } } diff --git a/src/main/java/appeng/core/api/ApiStorage.java b/src/main/java/appeng/core/api/ApiStorage.java index 86a559fca9f..f5146d6c317 100644 --- a/src/main/java/appeng/core/api/ApiStorage.java +++ b/src/main/java/appeng/core/api/ApiStorage.java @@ -18,7 +18,6 @@ package appeng.core.api; - import appeng.api.networking.crafting.ICraftingLink; import appeng.api.networking.crafting.ICraftingRequester; import appeng.api.networking.energy.IEnergySource; @@ -32,73 +31,68 @@ import appeng.util.Platform; import appeng.util.item.*; import io.netty.buffer.ByteBuf; +import java.io.IOException; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidStack; -import java.io.IOException; - - -public class ApiStorage implements IStorageHelper -{ - - @Override - public ICraftingLink loadCraftingLink( final NBTTagCompound data, final ICraftingRequester req ) - { - return new CraftingLink( data, req ); - } - - @Override - public IAEItemStack createItemStack( final ItemStack is ) - { - return AEItemStack.create( is ); - } - - @Override - public IAEFluidStack createFluidStack( final FluidStack is ) - { - return AEFluidStack.create( is ); - } - - @Override - public IItemList createItemList() - { - return new ItemList(); - } - - @Override - public IItemList createPrimitiveItemList() - { - return new HashBasedItemList(); - } - - @Override - public IItemList createFluidList() - { - return new FluidList(); - } - - @Override - public IAEItemStack readItemFromPacket( final ByteBuf input ) throws IOException - { - return AEItemStack.loadItemStackFromPacket( input ); - } - - @Override - public IAEFluidStack readFluidFromPacket( final ByteBuf input ) throws IOException - { - return AEFluidStack.loadFluidStackFromPacket( input ); - } - - @Override - public IAEItemStack poweredExtraction( final IEnergySource energy, final IMEInventory cell, final IAEItemStack request, final BaseActionSource src ) - { - return Platform.poweredExtraction( energy, cell, request, src ); - } - - @Override - public IAEItemStack poweredInsert( final IEnergySource energy, final IMEInventory cell, final IAEItemStack input, final BaseActionSource src ) - { - return Platform.poweredInsert( energy, cell, input, src ); - } +public class ApiStorage implements IStorageHelper { + + @Override + public ICraftingLink loadCraftingLink(final NBTTagCompound data, final ICraftingRequester req) { + return new CraftingLink(data, req); + } + + @Override + public IAEItemStack createItemStack(final ItemStack is) { + return AEItemStack.create(is); + } + + @Override + public IAEFluidStack createFluidStack(final FluidStack is) { + return AEFluidStack.create(is); + } + + @Override + public IItemList createItemList() { + return new ItemList(); + } + + @Override + public IItemList createPrimitiveItemList() { + return new HashBasedItemList(); + } + + @Override + public IItemList createFluidList() { + return new FluidList(); + } + + @Override + public IAEItemStack readItemFromPacket(final ByteBuf input) throws IOException { + return AEItemStack.loadItemStackFromPacket(input); + } + + @Override + public IAEFluidStack readFluidFromPacket(final ByteBuf input) throws IOException { + return AEFluidStack.loadFluidStackFromPacket(input); + } + + @Override + public IAEItemStack poweredExtraction( + final IEnergySource energy, + final IMEInventory cell, + final IAEItemStack request, + final BaseActionSource src) { + return Platform.poweredExtraction(energy, cell, request, src); + } + + @Override + public IAEItemStack poweredInsert( + final IEnergySource energy, + final IMEInventory cell, + final IAEItemStack input, + final BaseActionSource src) { + return Platform.poweredInsert(energy, cell, input, src); + } } diff --git a/src/main/java/appeng/core/api/IIMCProcessor.java b/src/main/java/appeng/core/api/IIMCProcessor.java index 47e0b55b00f..e449d07f54b 100644 --- a/src/main/java/appeng/core/api/IIMCProcessor.java +++ b/src/main/java/appeng/core/api/IIMCProcessor.java @@ -18,11 +18,8 @@ package appeng.core.api; - import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; - -public interface IIMCProcessor -{ - void process( IMCMessage m ); +public interface IIMCProcessor { + void process(IMCMessage m); } diff --git a/src/main/java/appeng/core/api/definitions/ApiBlocks.java b/src/main/java/appeng/core/api/definitions/ApiBlocks.java index 6351a65a76a..c48dd8efc1c 100644 --- a/src/main/java/appeng/core/api/definitions/ApiBlocks.java +++ b/src/main/java/appeng/core/api/definitions/ApiBlocks.java @@ -18,7 +18,6 @@ package appeng.core.api.definitions; - import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IBlocks; import appeng.api.definitions.ITileDefinition; @@ -50,600 +49,534 @@ import appeng.debug.BlockItemGen; import appeng.debug.BlockPhantomNode; import com.google.common.collect.ImmutableSet; - import java.util.EnumSet; import java.util.Set; - /** * Internal implementation for the API blocks */ -public final class ApiBlocks implements IBlocks -{ - private final IBlockDefinition quartzOre; - private final IBlockDefinition quartzOreCharged; - private final IBlockDefinition matrixFrame; - private final IBlockDefinition quartz; - private final IBlockDefinition quartzPillar; - private final IBlockDefinition quartzChiseled; - private final IBlockDefinition quartzGlass; - private final IBlockDefinition quartzVibrantGlass; - private final IBlockDefinition quartzTorch; - private final IBlockDefinition fluix; - private final IBlockDefinition skyStone; - private final IBlockDefinition skyChest; - private final IBlockDefinition skyCompass; - private final ITileDefinition grindStone; - private final ITileDefinition crankHandle; - private final ITileDefinition inscriber; - private final ITileDefinition wireless; - private final ITileDefinition charger; - private final IBlockDefinition tinyTNT; - private final ITileDefinition security; - private final ITileDefinition quantumRing; - private final ITileDefinition quantumLink; - private final ITileDefinition spatialPylon; - private final ITileDefinition spatialIOPort; - private final ITileDefinition multiPart; - private final ITileDefinition controller; - private final ITileDefinition drive; - private final ITileDefinition chest; - private final ITileDefinition iface; - private final ITileDefinition cellWorkbench; - private final ITileDefinition iOPort; - private final ITileDefinition condenser; - private final ITileDefinition energyAcceptor; - private final ITileDefinition vibrationChamber; - private final ITileDefinition quartzGrowthAccelerator; - private final ITileDefinition energyCell; - private final ITileDefinition energyCellDense; - private final ITileDefinition energyCellCreative; - private final ITileDefinition craftingUnit; - private final ITileDefinition craftingAccelerator; +public final class ApiBlocks implements IBlocks { + private final IBlockDefinition quartzOre; + private final IBlockDefinition quartzOreCharged; + private final IBlockDefinition matrixFrame; + private final IBlockDefinition quartz; + private final IBlockDefinition quartzPillar; + private final IBlockDefinition quartzChiseled; + private final IBlockDefinition quartzGlass; + private final IBlockDefinition quartzVibrantGlass; + private final IBlockDefinition quartzTorch; + private final IBlockDefinition fluix; + private final IBlockDefinition skyStone; + private final IBlockDefinition skyChest; + private final IBlockDefinition skyCompass; + private final ITileDefinition grindStone; + private final ITileDefinition crankHandle; + private final ITileDefinition inscriber; + private final ITileDefinition wireless; + private final ITileDefinition charger; + private final IBlockDefinition tinyTNT; + private final ITileDefinition security; + private final ITileDefinition quantumRing; + private final ITileDefinition quantumLink; + private final ITileDefinition spatialPylon; + private final ITileDefinition spatialIOPort; + private final ITileDefinition multiPart; + private final ITileDefinition controller; + private final ITileDefinition drive; + private final ITileDefinition chest; + private final ITileDefinition iface; + private final ITileDefinition cellWorkbench; + private final ITileDefinition iOPort; + private final ITileDefinition condenser; + private final ITileDefinition energyAcceptor; + private final ITileDefinition vibrationChamber; + private final ITileDefinition quartzGrowthAccelerator; + private final ITileDefinition energyCell; + private final ITileDefinition energyCellDense; + private final ITileDefinition energyCellCreative; + private final ITileDefinition craftingUnit; + private final ITileDefinition craftingAccelerator; private final ITileDefinition craftingAccelerator4x; private final ITileDefinition craftingAccelerator16x; - private final ITileDefinition craftingStorage1k; - private final ITileDefinition craftingStorage4k; - private final ITileDefinition craftingStorage16k; - private final ITileDefinition craftingStorage64k; - private final ITileDefinition craftingMonitor; - private final ITileDefinition molecularAssembler; - private final ITileDefinition lightDetector; - private final ITileDefinition paint; - private final IBlockDefinition skyStoneStair; - private final IBlockDefinition skyStoneBlockStair; - private final IBlockDefinition skyStoneBrickStair; - private final IBlockDefinition skyStoneSmallBrickStair; - private final IBlockDefinition fluixStair; - private final IBlockDefinition quartzStair; - private final IBlockDefinition chiseledQuartzStair; - private final IBlockDefinition quartzPillarStair; - private final IBlockDefinition skyStoneSlab; - private final IBlockDefinition skyStoneBlockSlab; - private final IBlockDefinition skyStoneBrickSlab; - private final IBlockDefinition skyStoneSmallBrickSlab; - private final IBlockDefinition fluixSlab; - private final IBlockDefinition quartzSlab; - private final IBlockDefinition chiseledQuartzSlab; - private final IBlockDefinition quartzPillarSlab; - - private final IBlockDefinition itemGen; - private final IBlockDefinition chunkLoader; - private final IBlockDefinition phantomNode; - private final IBlockDefinition cubeGenerator; - - private final Set orientables; - - public ApiBlocks( final DefinitionConstructor constructor ) - { - final BlockLightDetector lightDetector = new BlockLightDetector(); - final BlockQuartzPillar quartzPillar = new BlockQuartzPillar(); - final BlockSkyStone skyStone = new BlockSkyStone(); - final BlockFluix fluixBlock = new BlockFluix(); - final BlockQuartzGrowthAccelerator cga = new BlockQuartzGrowthAccelerator(); - final BlockQuartzTorch quartzTorch = new BlockQuartzTorch(); - final BlockQuartz quartzBlock = new BlockQuartz(); - final BlockQuartzChiseled chiseledQuartz = new BlockQuartzChiseled(); - - this.orientables = ImmutableSet.of( lightDetector, quartzPillar, skyStone, cga, quartzTorch ); - - this.quartzOre = constructor.registerBlockDefinition( new OreQuartz() ); - this.quartzOreCharged = constructor.registerBlockDefinition( new OreQuartzCharged() ); - this.matrixFrame = constructor.registerBlockDefinition( new BlockMatrixFrame() ); - this.quartz = constructor.registerBlockDefinition( quartzBlock ); - this.quartzPillar = constructor.registerBlockDefinition( quartzPillar ); - this.quartzChiseled = constructor.registerBlockDefinition( chiseledQuartz ); - this.quartzGlass = constructor.registerBlockDefinition( new BlockQuartzGlass() ); - this.quartzVibrantGlass = constructor.registerBlockDefinition( new BlockQuartzLamp() ); - this.quartzTorch = constructor.registerBlockDefinition( quartzTorch ); - this.fluix = constructor.registerBlockDefinition( fluixBlock ); - this.skyStone = constructor.registerBlockDefinition( skyStone ); - this.skyChest = constructor.registerBlockDefinition( new BlockSkyChest() ); - this.skyCompass = constructor.registerBlockDefinition( new BlockSkyCompass() ); - this.grindStone = constructor.registerTileDefinition( new BlockGrinder() ); - this.crankHandle = constructor.registerTileDefinition( new BlockCrank() ); - this.inscriber = constructor.registerTileDefinition( new BlockInscriber() ); - this.wireless = constructor.registerTileDefinition( new BlockWireless() ); - this.charger = constructor.registerTileDefinition( new BlockCharger() ); - this.tinyTNT = constructor.registerBlockDefinition( new BlockTinyTNT() ); - this.security = constructor.registerTileDefinition( new BlockSecurity() ); - this.quantumRing = constructor.registerTileDefinition( new BlockQuantumRing() ); - this.quantumLink = constructor.registerTileDefinition( new BlockQuantumLinkChamber() ); - this.spatialPylon = constructor.registerTileDefinition( new BlockSpatialPylon() ); - this.spatialIOPort = constructor.registerTileDefinition( new BlockSpatialIOPort() ); - this.multiPart = constructor.registerTileDefinition( new BlockCableBus() ); - this.controller = constructor.registerTileDefinition( new BlockController() ); - this.drive = constructor.registerTileDefinition( new BlockDrive() ); - this.chest = constructor.registerTileDefinition( new BlockChest() ); - this.iface = constructor.registerTileDefinition( new BlockInterface() ); - this.cellWorkbench = constructor.registerTileDefinition( new BlockCellWorkbench() ); - this.iOPort = constructor.registerTileDefinition( new BlockIOPort() ); - this.condenser = constructor.registerTileDefinition( new BlockCondenser() ); - this.energyAcceptor = constructor.registerTileDefinition( new BlockEnergyAcceptor() ); - this.vibrationChamber = constructor.registerTileDefinition( new BlockVibrationChamber() ); - this.quartzGrowthAccelerator = constructor.registerTileDefinition( cga ); - this.energyCell = constructor.registerTileDefinition( new BlockEnergyCell() ); - this.energyCellDense = constructor.registerTileDefinition( new BlockDenseEnergyCell() ); - this.energyCellCreative = constructor.registerTileDefinition( new BlockCreativeEnergyCell() ); - this.craftingUnit = constructor.registerTileDefinition( new BlockCraftingUnit() ); - this.craftingAccelerator = new WrappedDamageItemDefinition( this.craftingUnit, 1 ); - this.craftingAccelerator4x = new WrappedDamageItemDefinition( this.craftingUnit, 2 ); - this.craftingAccelerator16x = new WrappedDamageItemDefinition( this.craftingUnit, 3 ); - this.craftingStorage1k = constructor.registerTileDefinition( new BlockCraftingStorage() ); - this.craftingStorage4k = new WrappedDamageItemDefinition( this.craftingStorage1k, 1 ); - this.craftingStorage16k = new WrappedDamageItemDefinition( this.craftingStorage1k, 2 ); - this.craftingStorage64k = new WrappedDamageItemDefinition( this.craftingStorage1k, 3 ); - this.craftingMonitor = constructor.registerTileDefinition( new BlockCraftingMonitor() ); - this.molecularAssembler = constructor.registerTileDefinition( new BlockMolecularAssembler() ); - this.lightDetector = constructor.registerTileDefinition( lightDetector ); - this.paint = constructor.registerTileDefinition( new BlockPaint() ); - - this.skyStoneStair = constructor.registerBlockDefinition( new SkyStoneStairBlock( skyStone, 0 ) ); - this.skyStoneBlockStair = constructor.registerBlockDefinition( new SkyStoneBlockStairBlock( skyStone, 1 ) ); - this.skyStoneBrickStair = constructor.registerBlockDefinition( new SkyStoneBrickStairBlock( skyStone, 2 ) ); - this.skyStoneSmallBrickStair = constructor.registerBlockDefinition( new SkyStoneSmallBrickStairBlock( skyStone, 3 ) ); - - this.fluixStair = constructor.registerBlockDefinition( new FluixStairBlock( fluixBlock ) ); - - this.quartzStair = constructor.registerBlockDefinition( new QuartzStairBlock( quartzBlock ) ); - - this.chiseledQuartzStair = constructor.registerBlockDefinition( new ChiseledQuartzStairBlock( chiseledQuartz ) ); - - this.quartzPillarStair = constructor.registerBlockDefinition( new QuartzPillarStairBlock( quartzPillar ) ); - - this.skyStoneSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( skyStone, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "SkyStoneSlabBlock" ) ); - this.skyStoneBlockSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( skyStone, 1, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "SkyStoneBlockSlabBlock" ) ); - this.skyStoneBrickSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( skyStone, 2, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "SkyStoneBrickSlabBlock" ) ); - this.skyStoneSmallBrickSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( skyStone, 3, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "SkyStoneSmallBrickSlabBlock" ) ); - this.fluixSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( fluixBlock, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "FluixSlabBlock" ) ); - this.quartzSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( quartzBlock, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "QuartzSlabBlock" ) ); - this.chiseledQuartzSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( chiseledQuartz, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "ChiseledQuartzSlabBlock" ) ); - this.quartzPillarSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( quartzPillar, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "QuartzPillarSlabBlock" ) ); - - this.itemGen = constructor.registerBlockDefinition( new BlockItemGen() ); - this.chunkLoader = constructor.registerBlockDefinition( new BlockChunkloader() ); - this.phantomNode = constructor.registerBlockDefinition( new BlockPhantomNode() ); - this.cubeGenerator = constructor.registerBlockDefinition( new BlockCubeGenerator() ); - } - - @Override - public IBlockDefinition quartzOre() - { - return this.quartzOre; - } - - @Override - public IBlockDefinition quartzOreCharged() - { - return this.quartzOreCharged; - } - - @Override - public IBlockDefinition matrixFrame() - { - return this.matrixFrame; - } - - @Override - public IBlockDefinition quartz() - { - return this.quartz; - } - - @Override - public IBlockDefinition quartzPillar() - { - return this.quartzPillar; - } - - @Override - public IBlockDefinition quartzChiseled() - { - return this.quartzChiseled; - } - - @Override - public IBlockDefinition quartzGlass() - { - return this.quartzGlass; - } - - @Override - public IBlockDefinition quartzVibrantGlass() - { - return this.quartzVibrantGlass; - } - - @Override - public IBlockDefinition quartzTorch() - { - return this.quartzTorch; - } - - @Override - public IBlockDefinition fluix() - { - return this.fluix; - } - - @Override - public IBlockDefinition skyStone() - { - return this.skyStone; - } - - @Override - public IBlockDefinition skyChest() - { - return this.skyChest; - } - - @Override - public IBlockDefinition skyCompass() - { - return this.skyCompass; - } - - @Override - public IBlockDefinition skyStoneStair() - { - return this.skyStoneStair; - } - - @Override - public IBlockDefinition skyStoneBlockStair() - { - return this.skyStoneBlockStair; - } - - @Override - public IBlockDefinition skyStoneBrickStair() - { - return this.skyStoneBrickStair; - } - - @Override - public IBlockDefinition skyStoneSmallBrickStair() - { - return this.skyStoneSmallBrickStair; - } - - @Override - public IBlockDefinition fluixStair() - { - return this.fluixStair; - } - - @Override - public IBlockDefinition quartzStair() - { - return this.quartzStair; - } - - @Override - public IBlockDefinition chiseledQuartzStair() - { - return this.chiseledQuartzStair; - } - - @Override - public IBlockDefinition quartzPillarStair() - { - return this.quartzPillarStair; - } - - @Override - public IBlockDefinition skyStoneSlab() - { - return this.skyStoneSlab; - } - - @Override - public IBlockDefinition skyStoneBlockSlab() - { - return this.skyStoneBlockSlab; - } - - @Override - public IBlockDefinition skyStoneBrickSlab() - { - return this.skyStoneBrickSlab; - } - - @Override - public IBlockDefinition skyStoneSmallBrickSlab() - { - return this.skyStoneSmallBrickSlab; - } - - @Override - public IBlockDefinition fluixSlab() - { - return this.fluixSlab; - } - - @Override - public IBlockDefinition quartzSlab() - { - return this.quartzSlab; - } - - @Override - public IBlockDefinition chiseledQuartzSlab() - { - return this.chiseledQuartzSlab; - } - - @Override - public IBlockDefinition quartzPillarSlab() - { - return this.quartzPillarSlab; - } - - @Override - public ITileDefinition grindStone() - { - return this.grindStone; - } - - @Override - public ITileDefinition crankHandle() - { - return this.crankHandle; - } - - @Override - public ITileDefinition inscriber() - { - return this.inscriber; - } - - @Override - public ITileDefinition wireless() - { - return this.wireless; - } - - @Override - public ITileDefinition charger() - { - return this.charger; - } - - @Override - public IBlockDefinition tinyTNT() - { - return this.tinyTNT; - } - - @Override - public ITileDefinition security() - { - return this.security; - } - - @Override - public ITileDefinition quantumRing() - { - return this.quantumRing; - } - - @Override - public ITileDefinition quantumLink() - { - return this.quantumLink; - } - - @Override - public ITileDefinition spatialPylon() - { - return this.spatialPylon; - } - - @Override - public ITileDefinition spatialIOPort() - { - return this.spatialIOPort; - } - - @Override - public ITileDefinition multiPart() - { - return this.multiPart; - } - - @Override - public ITileDefinition controller() - { - return this.controller; - } - - @Override - public ITileDefinition drive() - { - return this.drive; - } - - @Override - public ITileDefinition chest() - { - return this.chest; - } - - @Override - public ITileDefinition iface() - { - return this.iface; - } - - @Override - public ITileDefinition cellWorkbench() - { - return this.cellWorkbench; - } - - @Override - public ITileDefinition iOPort() - { - return this.iOPort; - } - - @Override - public ITileDefinition condenser() - { - return this.condenser; - } - - @Override - public ITileDefinition energyAcceptor() - { - return this.energyAcceptor; - } - - @Override - public ITileDefinition vibrationChamber() - { - return this.vibrationChamber; - } - - @Override - public ITileDefinition quartzGrowthAccelerator() - { - return this.quartzGrowthAccelerator; - } - - @Override - public ITileDefinition energyCell() - { - return this.energyCell; - } - - @Override - public ITileDefinition energyCellDense() - { - return this.energyCellDense; - } - - @Override - public ITileDefinition energyCellCreative() - { - return this.energyCellCreative; - } - - @Override - public ITileDefinition craftingUnit() - { - return this.craftingUnit; - } - - @Override - public ITileDefinition craftingAccelerator() - { - return this.craftingAccelerator; - } - - @Override - public ITileDefinition craftingAccelerator4x() - { + private final ITileDefinition craftingStorage1k; + private final ITileDefinition craftingStorage4k; + private final ITileDefinition craftingStorage16k; + private final ITileDefinition craftingStorage64k; + private final ITileDefinition craftingMonitor; + private final ITileDefinition molecularAssembler; + private final ITileDefinition lightDetector; + private final ITileDefinition paint; + private final IBlockDefinition skyStoneStair; + private final IBlockDefinition skyStoneBlockStair; + private final IBlockDefinition skyStoneBrickStair; + private final IBlockDefinition skyStoneSmallBrickStair; + private final IBlockDefinition fluixStair; + private final IBlockDefinition quartzStair; + private final IBlockDefinition chiseledQuartzStair; + private final IBlockDefinition quartzPillarStair; + private final IBlockDefinition skyStoneSlab; + private final IBlockDefinition skyStoneBlockSlab; + private final IBlockDefinition skyStoneBrickSlab; + private final IBlockDefinition skyStoneSmallBrickSlab; + private final IBlockDefinition fluixSlab; + private final IBlockDefinition quartzSlab; + private final IBlockDefinition chiseledQuartzSlab; + private final IBlockDefinition quartzPillarSlab; + + private final IBlockDefinition itemGen; + private final IBlockDefinition chunkLoader; + private final IBlockDefinition phantomNode; + private final IBlockDefinition cubeGenerator; + + private final Set orientables; + + public ApiBlocks(final DefinitionConstructor constructor) { + final BlockLightDetector lightDetector = new BlockLightDetector(); + final BlockQuartzPillar quartzPillar = new BlockQuartzPillar(); + final BlockSkyStone skyStone = new BlockSkyStone(); + final BlockFluix fluixBlock = new BlockFluix(); + final BlockQuartzGrowthAccelerator cga = new BlockQuartzGrowthAccelerator(); + final BlockQuartzTorch quartzTorch = new BlockQuartzTorch(); + final BlockQuartz quartzBlock = new BlockQuartz(); + final BlockQuartzChiseled chiseledQuartz = new BlockQuartzChiseled(); + + this.orientables = ImmutableSet.of(lightDetector, quartzPillar, skyStone, cga, quartzTorch); + + this.quartzOre = constructor.registerBlockDefinition(new OreQuartz()); + this.quartzOreCharged = constructor.registerBlockDefinition(new OreQuartzCharged()); + this.matrixFrame = constructor.registerBlockDefinition(new BlockMatrixFrame()); + this.quartz = constructor.registerBlockDefinition(quartzBlock); + this.quartzPillar = constructor.registerBlockDefinition(quartzPillar); + this.quartzChiseled = constructor.registerBlockDefinition(chiseledQuartz); + this.quartzGlass = constructor.registerBlockDefinition(new BlockQuartzGlass()); + this.quartzVibrantGlass = constructor.registerBlockDefinition(new BlockQuartzLamp()); + this.quartzTorch = constructor.registerBlockDefinition(quartzTorch); + this.fluix = constructor.registerBlockDefinition(fluixBlock); + this.skyStone = constructor.registerBlockDefinition(skyStone); + this.skyChest = constructor.registerBlockDefinition(new BlockSkyChest()); + this.skyCompass = constructor.registerBlockDefinition(new BlockSkyCompass()); + this.grindStone = constructor.registerTileDefinition(new BlockGrinder()); + this.crankHandle = constructor.registerTileDefinition(new BlockCrank()); + this.inscriber = constructor.registerTileDefinition(new BlockInscriber()); + this.wireless = constructor.registerTileDefinition(new BlockWireless()); + this.charger = constructor.registerTileDefinition(new BlockCharger()); + this.tinyTNT = constructor.registerBlockDefinition(new BlockTinyTNT()); + this.security = constructor.registerTileDefinition(new BlockSecurity()); + this.quantumRing = constructor.registerTileDefinition(new BlockQuantumRing()); + this.quantumLink = constructor.registerTileDefinition(new BlockQuantumLinkChamber()); + this.spatialPylon = constructor.registerTileDefinition(new BlockSpatialPylon()); + this.spatialIOPort = constructor.registerTileDefinition(new BlockSpatialIOPort()); + this.multiPart = constructor.registerTileDefinition(new BlockCableBus()); + this.controller = constructor.registerTileDefinition(new BlockController()); + this.drive = constructor.registerTileDefinition(new BlockDrive()); + this.chest = constructor.registerTileDefinition(new BlockChest()); + this.iface = constructor.registerTileDefinition(new BlockInterface()); + this.cellWorkbench = constructor.registerTileDefinition(new BlockCellWorkbench()); + this.iOPort = constructor.registerTileDefinition(new BlockIOPort()); + this.condenser = constructor.registerTileDefinition(new BlockCondenser()); + this.energyAcceptor = constructor.registerTileDefinition(new BlockEnergyAcceptor()); + this.vibrationChamber = constructor.registerTileDefinition(new BlockVibrationChamber()); + this.quartzGrowthAccelerator = constructor.registerTileDefinition(cga); + this.energyCell = constructor.registerTileDefinition(new BlockEnergyCell()); + this.energyCellDense = constructor.registerTileDefinition(new BlockDenseEnergyCell()); + this.energyCellCreative = constructor.registerTileDefinition(new BlockCreativeEnergyCell()); + this.craftingUnit = constructor.registerTileDefinition(new BlockCraftingUnit()); + this.craftingAccelerator = new WrappedDamageItemDefinition(this.craftingUnit, 1); + this.craftingAccelerator4x = new WrappedDamageItemDefinition(this.craftingUnit, 2); + this.craftingAccelerator16x = new WrappedDamageItemDefinition(this.craftingUnit, 3); + this.craftingStorage1k = constructor.registerTileDefinition(new BlockCraftingStorage()); + this.craftingStorage4k = new WrappedDamageItemDefinition(this.craftingStorage1k, 1); + this.craftingStorage16k = new WrappedDamageItemDefinition(this.craftingStorage1k, 2); + this.craftingStorage64k = new WrappedDamageItemDefinition(this.craftingStorage1k, 3); + this.craftingMonitor = constructor.registerTileDefinition(new BlockCraftingMonitor()); + this.molecularAssembler = constructor.registerTileDefinition(new BlockMolecularAssembler()); + this.lightDetector = constructor.registerTileDefinition(lightDetector); + this.paint = constructor.registerTileDefinition(new BlockPaint()); + + this.skyStoneStair = constructor.registerBlockDefinition(new SkyStoneStairBlock(skyStone, 0)); + this.skyStoneBlockStair = constructor.registerBlockDefinition(new SkyStoneBlockStairBlock(skyStone, 1)); + this.skyStoneBrickStair = constructor.registerBlockDefinition(new SkyStoneBrickStairBlock(skyStone, 2)); + this.skyStoneSmallBrickStair = + constructor.registerBlockDefinition(new SkyStoneSmallBrickStairBlock(skyStone, 3)); + + this.fluixStair = constructor.registerBlockDefinition(new FluixStairBlock(fluixBlock)); + + this.quartzStair = constructor.registerBlockDefinition(new QuartzStairBlock(quartzBlock)); + + this.chiseledQuartzStair = constructor.registerBlockDefinition(new ChiseledQuartzStairBlock(chiseledQuartz)); + + this.quartzPillarStair = constructor.registerBlockDefinition(new QuartzPillarStairBlock(quartzPillar)); + + this.skyStoneSlab = constructor.registerBlockDefinition(new AEBaseSlabBlock( + skyStone, 0, EnumSet.of(AEFeature.DecorativeQuartzBlocks), false, "SkyStoneSlabBlock")); + this.skyStoneBlockSlab = constructor.registerBlockDefinition(new AEBaseSlabBlock( + skyStone, 1, EnumSet.of(AEFeature.DecorativeQuartzBlocks), false, "SkyStoneBlockSlabBlock")); + this.skyStoneBrickSlab = constructor.registerBlockDefinition(new AEBaseSlabBlock( + skyStone, 2, EnumSet.of(AEFeature.DecorativeQuartzBlocks), false, "SkyStoneBrickSlabBlock")); + this.skyStoneSmallBrickSlab = constructor.registerBlockDefinition(new AEBaseSlabBlock( + skyStone, 3, EnumSet.of(AEFeature.DecorativeQuartzBlocks), false, "SkyStoneSmallBrickSlabBlock")); + this.fluixSlab = constructor.registerBlockDefinition(new AEBaseSlabBlock( + fluixBlock, 0, EnumSet.of(AEFeature.DecorativeQuartzBlocks), false, "FluixSlabBlock")); + this.quartzSlab = constructor.registerBlockDefinition(new AEBaseSlabBlock( + quartzBlock, 0, EnumSet.of(AEFeature.DecorativeQuartzBlocks), false, "QuartzSlabBlock")); + this.chiseledQuartzSlab = constructor.registerBlockDefinition(new AEBaseSlabBlock( + chiseledQuartz, 0, EnumSet.of(AEFeature.DecorativeQuartzBlocks), false, "ChiseledQuartzSlabBlock")); + this.quartzPillarSlab = constructor.registerBlockDefinition(new AEBaseSlabBlock( + quartzPillar, 0, EnumSet.of(AEFeature.DecorativeQuartzBlocks), false, "QuartzPillarSlabBlock")); + + this.itemGen = constructor.registerBlockDefinition(new BlockItemGen()); + this.chunkLoader = constructor.registerBlockDefinition(new BlockChunkloader()); + this.phantomNode = constructor.registerBlockDefinition(new BlockPhantomNode()); + this.cubeGenerator = constructor.registerBlockDefinition(new BlockCubeGenerator()); + } + + @Override + public IBlockDefinition quartzOre() { + return this.quartzOre; + } + + @Override + public IBlockDefinition quartzOreCharged() { + return this.quartzOreCharged; + } + + @Override + public IBlockDefinition matrixFrame() { + return this.matrixFrame; + } + + @Override + public IBlockDefinition quartz() { + return this.quartz; + } + + @Override + public IBlockDefinition quartzPillar() { + return this.quartzPillar; + } + + @Override + public IBlockDefinition quartzChiseled() { + return this.quartzChiseled; + } + + @Override + public IBlockDefinition quartzGlass() { + return this.quartzGlass; + } + + @Override + public IBlockDefinition quartzVibrantGlass() { + return this.quartzVibrantGlass; + } + + @Override + public IBlockDefinition quartzTorch() { + return this.quartzTorch; + } + + @Override + public IBlockDefinition fluix() { + return this.fluix; + } + + @Override + public IBlockDefinition skyStone() { + return this.skyStone; + } + + @Override + public IBlockDefinition skyChest() { + return this.skyChest; + } + + @Override + public IBlockDefinition skyCompass() { + return this.skyCompass; + } + + @Override + public IBlockDefinition skyStoneStair() { + return this.skyStoneStair; + } + + @Override + public IBlockDefinition skyStoneBlockStair() { + return this.skyStoneBlockStair; + } + + @Override + public IBlockDefinition skyStoneBrickStair() { + return this.skyStoneBrickStair; + } + + @Override + public IBlockDefinition skyStoneSmallBrickStair() { + return this.skyStoneSmallBrickStair; + } + + @Override + public IBlockDefinition fluixStair() { + return this.fluixStair; + } + + @Override + public IBlockDefinition quartzStair() { + return this.quartzStair; + } + + @Override + public IBlockDefinition chiseledQuartzStair() { + return this.chiseledQuartzStair; + } + + @Override + public IBlockDefinition quartzPillarStair() { + return this.quartzPillarStair; + } + + @Override + public IBlockDefinition skyStoneSlab() { + return this.skyStoneSlab; + } + + @Override + public IBlockDefinition skyStoneBlockSlab() { + return this.skyStoneBlockSlab; + } + + @Override + public IBlockDefinition skyStoneBrickSlab() { + return this.skyStoneBrickSlab; + } + + @Override + public IBlockDefinition skyStoneSmallBrickSlab() { + return this.skyStoneSmallBrickSlab; + } + + @Override + public IBlockDefinition fluixSlab() { + return this.fluixSlab; + } + + @Override + public IBlockDefinition quartzSlab() { + return this.quartzSlab; + } + + @Override + public IBlockDefinition chiseledQuartzSlab() { + return this.chiseledQuartzSlab; + } + + @Override + public IBlockDefinition quartzPillarSlab() { + return this.quartzPillarSlab; + } + + @Override + public ITileDefinition grindStone() { + return this.grindStone; + } + + @Override + public ITileDefinition crankHandle() { + return this.crankHandle; + } + + @Override + public ITileDefinition inscriber() { + return this.inscriber; + } + + @Override + public ITileDefinition wireless() { + return this.wireless; + } + + @Override + public ITileDefinition charger() { + return this.charger; + } + + @Override + public IBlockDefinition tinyTNT() { + return this.tinyTNT; + } + + @Override + public ITileDefinition security() { + return this.security; + } + + @Override + public ITileDefinition quantumRing() { + return this.quantumRing; + } + + @Override + public ITileDefinition quantumLink() { + return this.quantumLink; + } + + @Override + public ITileDefinition spatialPylon() { + return this.spatialPylon; + } + + @Override + public ITileDefinition spatialIOPort() { + return this.spatialIOPort; + } + + @Override + public ITileDefinition multiPart() { + return this.multiPart; + } + + @Override + public ITileDefinition controller() { + return this.controller; + } + + @Override + public ITileDefinition drive() { + return this.drive; + } + + @Override + public ITileDefinition chest() { + return this.chest; + } + + @Override + public ITileDefinition iface() { + return this.iface; + } + + @Override + public ITileDefinition cellWorkbench() { + return this.cellWorkbench; + } + + @Override + public ITileDefinition iOPort() { + return this.iOPort; + } + + @Override + public ITileDefinition condenser() { + return this.condenser; + } + + @Override + public ITileDefinition energyAcceptor() { + return this.energyAcceptor; + } + + @Override + public ITileDefinition vibrationChamber() { + return this.vibrationChamber; + } + + @Override + public ITileDefinition quartzGrowthAccelerator() { + return this.quartzGrowthAccelerator; + } + + @Override + public ITileDefinition energyCell() { + return this.energyCell; + } + + @Override + public ITileDefinition energyCellDense() { + return this.energyCellDense; + } + + @Override + public ITileDefinition energyCellCreative() { + return this.energyCellCreative; + } + + @Override + public ITileDefinition craftingUnit() { + return this.craftingUnit; + } + + @Override + public ITileDefinition craftingAccelerator() { + return this.craftingAccelerator; + } + + @Override + public ITileDefinition craftingAccelerator4x() { return this.craftingAccelerator4x; } @Override - public ITileDefinition craftingAccelerator16x() - { + public ITileDefinition craftingAccelerator16x() { return this.craftingAccelerator16x; } - @Override - public ITileDefinition craftingStorage1k() - { - return this.craftingStorage1k; - } - - @Override - public ITileDefinition craftingStorage4k() - { - return this.craftingStorage4k; - } - - @Override - public ITileDefinition craftingStorage16k() - { - return this.craftingStorage16k; - } - - @Override - public ITileDefinition craftingStorage64k() - { - return this.craftingStorage64k; - } - - @Override - public ITileDefinition craftingMonitor() - { - return this.craftingMonitor; - } - - @Override - public ITileDefinition molecularAssembler() - { - return this.molecularAssembler; - } - - @Override - public ITileDefinition lightDetector() - { - return this.lightDetector; - } - - @Override - public ITileDefinition paint() - { - return this.paint; - } - - public IBlockDefinition chunkLoader() - { - return this.chunkLoader; - } - - public IBlockDefinition itemGen() - { - return this.itemGen; - } - - public IBlockDefinition phantomNode() - { - return this.phantomNode; - } - - public IBlockDefinition cubeGenerator() - { - return this.cubeGenerator; - } - - public Set orientables() - { - return this.orientables; - } + @Override + public ITileDefinition craftingStorage1k() { + return this.craftingStorage1k; + } + + @Override + public ITileDefinition craftingStorage4k() { + return this.craftingStorage4k; + } + + @Override + public ITileDefinition craftingStorage16k() { + return this.craftingStorage16k; + } + + @Override + public ITileDefinition craftingStorage64k() { + return this.craftingStorage64k; + } + + @Override + public ITileDefinition craftingMonitor() { + return this.craftingMonitor; + } + + @Override + public ITileDefinition molecularAssembler() { + return this.molecularAssembler; + } + + @Override + public ITileDefinition lightDetector() { + return this.lightDetector; + } + + @Override + public ITileDefinition paint() { + return this.paint; + } + + public IBlockDefinition chunkLoader() { + return this.chunkLoader; + } + + public IBlockDefinition itemGen() { + return this.itemGen; + } + + public IBlockDefinition phantomNode() { + return this.phantomNode; + } + + public IBlockDefinition cubeGenerator() { + return this.cubeGenerator; + } + + public Set orientables() { + return this.orientables; + } } diff --git a/src/main/java/appeng/core/api/definitions/ApiItems.java b/src/main/java/appeng/core/api/definitions/ApiItems.java index c86dd7cd9f7..74f5ec1f51f 100644 --- a/src/main/java/appeng/core/api/definitions/ApiItems.java +++ b/src/main/java/appeng/core/api/definitions/ApiItems.java @@ -18,7 +18,6 @@ package appeng.core.api.definitions; - import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.IItems; import appeng.api.util.AEColoredItemDefinition; @@ -42,366 +41,323 @@ import appeng.items.tools.powered.*; import appeng.items.tools.quartz.*; - /** * Internal implementation for the API items */ -public final class ApiItems implements IItems -{ - private final IItemDefinition certusQuartzAxe; - private final IItemDefinition certusQuartzHoe; - private final IItemDefinition certusQuartzShovel; - private final IItemDefinition certusQuartzPick; - private final IItemDefinition certusQuartzSword; - private final IItemDefinition certusQuartzWrench; - private final IItemDefinition certusQuartzKnife; - - private final IItemDefinition netherQuartzAxe; - private final IItemDefinition netherQuartzHoe; - private final IItemDefinition netherQuartzShovel; - private final IItemDefinition netherQuartzPick; - private final IItemDefinition netherQuartzSword; - private final IItemDefinition netherQuartzWrench; - private final IItemDefinition netherQuartzKnife; - - private final IItemDefinition entropyManipulator; - private final IItemDefinition wirelessTerminal; - private final IItemDefinition biometricCard; - private final IItemDefinition chargedStaff; - private final IItemDefinition massCannon; - private final IItemDefinition memoryCard; - private final IItemDefinition networkTool; - private final IItemDefinition portableCell; - - private final IItemDefinition cellCreative; - private final IItemDefinition viewCell; - - private final IItemDefinition cell1k; - private final IItemDefinition cell4k; - private final IItemDefinition cell16k; - private final IItemDefinition cell64k; - - private final IItemDefinition spatialCell2; - private final IItemDefinition spatialCell16; - private final IItemDefinition spatialCell128; - - private final IItemDefinition facade; - private final IItemDefinition crystalSeed; - - // rv1 - private final IItemDefinition encodedPattern; - private final IItemDefinition colorApplicator; - - private final IItemDefinition paintBall; - private final AEColoredItemDefinition coloredPaintBall; - private final AEColoredItemDefinition coloredLumenPaintBall; - - // unsupported dev tools - private final IItemDefinition toolEraser; - private final IItemDefinition toolMeteoritePlacer; - private final IItemDefinition toolDebugCard; - private final IItemDefinition toolReplicatorCard; - - public ApiItems( final DefinitionConstructor constructor ) - { - this.certusQuartzAxe = constructor.registerItemDefinition( new ToolQuartzAxe( AEFeature.CertusQuartzTools ) ); - this.certusQuartzHoe = constructor.registerItemDefinition( new ToolQuartzHoe( AEFeature.CertusQuartzTools ) ); - this.certusQuartzShovel = constructor.registerItemDefinition( new ToolQuartzSpade( AEFeature.CertusQuartzTools ) ); - this.certusQuartzPick = constructor.registerItemDefinition( new ToolQuartzPickaxe( AEFeature.CertusQuartzTools ) ); - this.certusQuartzSword = constructor.registerItemDefinition( new ToolQuartzSword( AEFeature.CertusQuartzTools ) ); - this.certusQuartzWrench = constructor.registerItemDefinition( new ToolQuartzWrench( AEFeature.CertusQuartzTools ) ); - this.certusQuartzKnife = constructor.registerItemDefinition( new ToolQuartzCuttingKnife( AEFeature.CertusQuartzTools ) ); - - this.netherQuartzAxe = constructor.registerItemDefinition( new ToolQuartzAxe( AEFeature.NetherQuartzTools ) ); - this.netherQuartzHoe = constructor.registerItemDefinition( new ToolQuartzHoe( AEFeature.NetherQuartzTools ) ); - this.netherQuartzShovel = constructor.registerItemDefinition( new ToolQuartzSpade( AEFeature.NetherQuartzTools ) ); - this.netherQuartzPick = constructor.registerItemDefinition( new ToolQuartzPickaxe( AEFeature.NetherQuartzTools ) ); - this.netherQuartzSword = constructor.registerItemDefinition( new ToolQuartzSword( AEFeature.NetherQuartzTools ) ); - this.netherQuartzWrench = constructor.registerItemDefinition( new ToolQuartzWrench( AEFeature.NetherQuartzTools ) ); - this.netherQuartzKnife = constructor.registerItemDefinition( new ToolQuartzCuttingKnife( AEFeature.NetherQuartzTools ) ); - - this.entropyManipulator = constructor.registerItemDefinition( new ToolEntropyManipulator() ); - this.wirelessTerminal = constructor.registerItemDefinition( new ToolWirelessTerminal() ); - this.biometricCard = constructor.registerItemDefinition( new ToolBiometricCard() ); - this.chargedStaff = constructor.registerItemDefinition( new ToolChargedStaff() ); - this.massCannon = constructor.registerItemDefinition( new ToolMassCannon() ); - this.memoryCard = constructor.registerItemDefinition( new ToolMemoryCard() ); - this.networkTool = constructor.registerItemDefinition( new ToolNetworkTool() ); - this.portableCell = constructor.registerItemDefinition( new ToolPortableCell() ); - - this.cellCreative = constructor.registerItemDefinition( new ItemCreativeStorageCell() ); - this.viewCell = constructor.registerItemDefinition( new ItemViewCell() ); - - this.cell1k = constructor.registerItemDefinition( new ItemBasicStorageCell( MaterialType.Cell1kPart, 1 ) ); - this.cell4k = constructor.registerItemDefinition( new ItemBasicStorageCell( MaterialType.Cell4kPart, 4 ) ); - this.cell16k = constructor.registerItemDefinition( new ItemBasicStorageCell( MaterialType.Cell16kPart, 16 ) ); - this.cell64k = constructor.registerItemDefinition( new ItemBasicStorageCell( MaterialType.Cell64kPart, 64 ) ); - - this.spatialCell2 = constructor.registerItemDefinition( new ItemSpatialStorageCell( 2 ) ); - this.spatialCell16 = constructor.registerItemDefinition( new ItemSpatialStorageCell( 16 ) ); - this.spatialCell128 = constructor.registerItemDefinition( new ItemSpatialStorageCell( 128 ) ); - - this.facade = constructor.registerItemDefinition( new ItemFacade() ); - this.crystalSeed = constructor.registerItemDefinition( new ItemCrystalSeed() ); - - // rv1 - this.encodedPattern = constructor.registerItemDefinition( new ItemEncodedPattern() ); - this.colorApplicator = constructor.registerItemDefinition( new ToolColorApplicator() ); - - this.paintBall = constructor.registerItemDefinition( new ItemPaintBall() ); - this.coloredPaintBall = constructor.constructColoredDefinition( this.paintBall, 0 ); - this.coloredLumenPaintBall = constructor.constructColoredDefinition( this.paintBall, 20 ); - - this.toolEraser = constructor.registerItemDefinition( new ToolEraser() ); - this.toolMeteoritePlacer = constructor.registerItemDefinition( new ToolMeteoritePlacer() ); - this.toolDebugCard = constructor.registerItemDefinition( new ToolDebugCard() ); - this.toolReplicatorCard = constructor.registerItemDefinition( new ToolReplicatorCard() ); - } - - @Override - public IItemDefinition certusQuartzAxe() - { - return this.certusQuartzAxe; - } - - @Override - public IItemDefinition certusQuartzHoe() - { - return this.certusQuartzHoe; - } - - @Override - public IItemDefinition certusQuartzShovel() - { - return this.certusQuartzShovel; - } - - @Override - public IItemDefinition certusQuartzPick() - { - return this.certusQuartzPick; - } - - @Override - public IItemDefinition certusQuartzSword() - { - return this.certusQuartzSword; - } - - @Override - public IItemDefinition certusQuartzWrench() - { - return this.certusQuartzWrench; - } - - @Override - public IItemDefinition certusQuartzKnife() - { - return this.certusQuartzKnife; - } - - @Override - public IItemDefinition netherQuartzAxe() - { - return this.netherQuartzAxe; - } - - @Override - public IItemDefinition netherQuartzHoe() - { - return this.netherQuartzHoe; - } - - @Override - public IItemDefinition netherQuartzShovel() - { - return this.netherQuartzShovel; - } - - @Override - public IItemDefinition netherQuartzPick() - { - return this.netherQuartzPick; - } - - @Override - public IItemDefinition netherQuartzSword() - { - return this.netherQuartzSword; - } - - @Override - public IItemDefinition netherQuartzWrench() - { - return this.netherQuartzWrench; - } - - @Override - public IItemDefinition netherQuartzKnife() - { - return this.netherQuartzKnife; - } - - @Override - public IItemDefinition entropyManipulator() - { - return this.entropyManipulator; - } - - @Override - public IItemDefinition wirelessTerminal() - { - return this.wirelessTerminal; - } - - @Override - public IItemDefinition biometricCard() - { - return this.biometricCard; - } - - @Override - public IItemDefinition chargedStaff() - { - return this.memoryCard; - } - - @Override - public IItemDefinition massCannon() - { - return this.massCannon; - } - - @Override - public IItemDefinition memoryCard() - { - return this.memoryCard; - } - - @Override - public IItemDefinition networkTool() - { - return this.networkTool; - } - - @Override - public IItemDefinition portableCell() - { - return this.portableCell; - } - - @Override - public IItemDefinition cellCreative() - { - return this.cellCreative; - } - - @Override - public IItemDefinition viewCell() - { - return this.viewCell; - } - - @Override - public IItemDefinition cell1k() - { - return this.cell1k; - } - - @Override - public IItemDefinition cell4k() - { - return this.cell4k; - } - - @Override - public IItemDefinition cell16k() - { - return this.cell16k; - } - - @Override - public IItemDefinition cell64k() - { - return this.cell64k; - } - - @Override - public IItemDefinition spatialCell2() - { - return this.spatialCell2; - } - - @Override - public IItemDefinition spatialCell16() - { - return this.spatialCell16; - } - - @Override - public IItemDefinition spatialCell128() - { - return this.spatialCell128; - } - - @Override - public IItemDefinition facade() - { - return this.facade; - } - - @Override - public IItemDefinition crystalSeed() - { - return this.crystalSeed; - } - - @Override - public IItemDefinition encodedPattern() - { - return this.encodedPattern; - } - - @Override - public IItemDefinition colorApplicator() - { - return this.colorApplicator; - } - - @Override - public AEColoredItemDefinition coloredPaintBall() - { - return this.coloredPaintBall; - } - - @Override - public AEColoredItemDefinition coloredLumenPaintBall() - { - return this.coloredLumenPaintBall; - } - - public IItemDefinition paintBall() - { - return this.paintBall; - } - - public IItemDefinition toolEraser() - { - return this.toolEraser; - } - - public IItemDefinition toolMeteoritePlacer() - { - return this.toolMeteoritePlacer; - } - - public IItemDefinition toolDebugCard() - { - return this.toolDebugCard; - } - - public IItemDefinition toolReplicatorCard() - { - return this.toolReplicatorCard; - } +public final class ApiItems implements IItems { + private final IItemDefinition certusQuartzAxe; + private final IItemDefinition certusQuartzHoe; + private final IItemDefinition certusQuartzShovel; + private final IItemDefinition certusQuartzPick; + private final IItemDefinition certusQuartzSword; + private final IItemDefinition certusQuartzWrench; + private final IItemDefinition certusQuartzKnife; + + private final IItemDefinition netherQuartzAxe; + private final IItemDefinition netherQuartzHoe; + private final IItemDefinition netherQuartzShovel; + private final IItemDefinition netherQuartzPick; + private final IItemDefinition netherQuartzSword; + private final IItemDefinition netherQuartzWrench; + private final IItemDefinition netherQuartzKnife; + + private final IItemDefinition entropyManipulator; + private final IItemDefinition wirelessTerminal; + private final IItemDefinition biometricCard; + private final IItemDefinition chargedStaff; + private final IItemDefinition massCannon; + private final IItemDefinition memoryCard; + private final IItemDefinition networkTool; + private final IItemDefinition portableCell; + + private final IItemDefinition cellCreative; + private final IItemDefinition viewCell; + + private final IItemDefinition cell1k; + private final IItemDefinition cell4k; + private final IItemDefinition cell16k; + private final IItemDefinition cell64k; + + private final IItemDefinition spatialCell2; + private final IItemDefinition spatialCell16; + private final IItemDefinition spatialCell128; + + private final IItemDefinition facade; + private final IItemDefinition crystalSeed; + + // rv1 + private final IItemDefinition encodedPattern; + private final IItemDefinition colorApplicator; + + private final IItemDefinition paintBall; + private final AEColoredItemDefinition coloredPaintBall; + private final AEColoredItemDefinition coloredLumenPaintBall; + + // unsupported dev tools + private final IItemDefinition toolEraser; + private final IItemDefinition toolMeteoritePlacer; + private final IItemDefinition toolDebugCard; + private final IItemDefinition toolReplicatorCard; + + public ApiItems(final DefinitionConstructor constructor) { + this.certusQuartzAxe = constructor.registerItemDefinition(new ToolQuartzAxe(AEFeature.CertusQuartzTools)); + this.certusQuartzHoe = constructor.registerItemDefinition(new ToolQuartzHoe(AEFeature.CertusQuartzTools)); + this.certusQuartzShovel = constructor.registerItemDefinition(new ToolQuartzSpade(AEFeature.CertusQuartzTools)); + this.certusQuartzPick = constructor.registerItemDefinition(new ToolQuartzPickaxe(AEFeature.CertusQuartzTools)); + this.certusQuartzSword = constructor.registerItemDefinition(new ToolQuartzSword(AEFeature.CertusQuartzTools)); + this.certusQuartzWrench = constructor.registerItemDefinition(new ToolQuartzWrench(AEFeature.CertusQuartzTools)); + this.certusQuartzKnife = + constructor.registerItemDefinition(new ToolQuartzCuttingKnife(AEFeature.CertusQuartzTools)); + + this.netherQuartzAxe = constructor.registerItemDefinition(new ToolQuartzAxe(AEFeature.NetherQuartzTools)); + this.netherQuartzHoe = constructor.registerItemDefinition(new ToolQuartzHoe(AEFeature.NetherQuartzTools)); + this.netherQuartzShovel = constructor.registerItemDefinition(new ToolQuartzSpade(AEFeature.NetherQuartzTools)); + this.netherQuartzPick = constructor.registerItemDefinition(new ToolQuartzPickaxe(AEFeature.NetherQuartzTools)); + this.netherQuartzSword = constructor.registerItemDefinition(new ToolQuartzSword(AEFeature.NetherQuartzTools)); + this.netherQuartzWrench = constructor.registerItemDefinition(new ToolQuartzWrench(AEFeature.NetherQuartzTools)); + this.netherQuartzKnife = + constructor.registerItemDefinition(new ToolQuartzCuttingKnife(AEFeature.NetherQuartzTools)); + + this.entropyManipulator = constructor.registerItemDefinition(new ToolEntropyManipulator()); + this.wirelessTerminal = constructor.registerItemDefinition(new ToolWirelessTerminal()); + this.biometricCard = constructor.registerItemDefinition(new ToolBiometricCard()); + this.chargedStaff = constructor.registerItemDefinition(new ToolChargedStaff()); + this.massCannon = constructor.registerItemDefinition(new ToolMassCannon()); + this.memoryCard = constructor.registerItemDefinition(new ToolMemoryCard()); + this.networkTool = constructor.registerItemDefinition(new ToolNetworkTool()); + this.portableCell = constructor.registerItemDefinition(new ToolPortableCell()); + + this.cellCreative = constructor.registerItemDefinition(new ItemCreativeStorageCell()); + this.viewCell = constructor.registerItemDefinition(new ItemViewCell()); + + this.cell1k = constructor.registerItemDefinition(new ItemBasicStorageCell(MaterialType.Cell1kPart, 1)); + this.cell4k = constructor.registerItemDefinition(new ItemBasicStorageCell(MaterialType.Cell4kPart, 4)); + this.cell16k = constructor.registerItemDefinition(new ItemBasicStorageCell(MaterialType.Cell16kPart, 16)); + this.cell64k = constructor.registerItemDefinition(new ItemBasicStorageCell(MaterialType.Cell64kPart, 64)); + + this.spatialCell2 = constructor.registerItemDefinition(new ItemSpatialStorageCell(2)); + this.spatialCell16 = constructor.registerItemDefinition(new ItemSpatialStorageCell(16)); + this.spatialCell128 = constructor.registerItemDefinition(new ItemSpatialStorageCell(128)); + + this.facade = constructor.registerItemDefinition(new ItemFacade()); + this.crystalSeed = constructor.registerItemDefinition(new ItemCrystalSeed()); + + // rv1 + this.encodedPattern = constructor.registerItemDefinition(new ItemEncodedPattern()); + this.colorApplicator = constructor.registerItemDefinition(new ToolColorApplicator()); + + this.paintBall = constructor.registerItemDefinition(new ItemPaintBall()); + this.coloredPaintBall = constructor.constructColoredDefinition(this.paintBall, 0); + this.coloredLumenPaintBall = constructor.constructColoredDefinition(this.paintBall, 20); + + this.toolEraser = constructor.registerItemDefinition(new ToolEraser()); + this.toolMeteoritePlacer = constructor.registerItemDefinition(new ToolMeteoritePlacer()); + this.toolDebugCard = constructor.registerItemDefinition(new ToolDebugCard()); + this.toolReplicatorCard = constructor.registerItemDefinition(new ToolReplicatorCard()); + } + + @Override + public IItemDefinition certusQuartzAxe() { + return this.certusQuartzAxe; + } + + @Override + public IItemDefinition certusQuartzHoe() { + return this.certusQuartzHoe; + } + + @Override + public IItemDefinition certusQuartzShovel() { + return this.certusQuartzShovel; + } + + @Override + public IItemDefinition certusQuartzPick() { + return this.certusQuartzPick; + } + + @Override + public IItemDefinition certusQuartzSword() { + return this.certusQuartzSword; + } + + @Override + public IItemDefinition certusQuartzWrench() { + return this.certusQuartzWrench; + } + + @Override + public IItemDefinition certusQuartzKnife() { + return this.certusQuartzKnife; + } + + @Override + public IItemDefinition netherQuartzAxe() { + return this.netherQuartzAxe; + } + + @Override + public IItemDefinition netherQuartzHoe() { + return this.netherQuartzHoe; + } + + @Override + public IItemDefinition netherQuartzShovel() { + return this.netherQuartzShovel; + } + + @Override + public IItemDefinition netherQuartzPick() { + return this.netherQuartzPick; + } + + @Override + public IItemDefinition netherQuartzSword() { + return this.netherQuartzSword; + } + + @Override + public IItemDefinition netherQuartzWrench() { + return this.netherQuartzWrench; + } + + @Override + public IItemDefinition netherQuartzKnife() { + return this.netherQuartzKnife; + } + + @Override + public IItemDefinition entropyManipulator() { + return this.entropyManipulator; + } + + @Override + public IItemDefinition wirelessTerminal() { + return this.wirelessTerminal; + } + + @Override + public IItemDefinition biometricCard() { + return this.biometricCard; + } + + @Override + public IItemDefinition chargedStaff() { + return this.memoryCard; + } + + @Override + public IItemDefinition massCannon() { + return this.massCannon; + } + + @Override + public IItemDefinition memoryCard() { + return this.memoryCard; + } + + @Override + public IItemDefinition networkTool() { + return this.networkTool; + } + + @Override + public IItemDefinition portableCell() { + return this.portableCell; + } + + @Override + public IItemDefinition cellCreative() { + return this.cellCreative; + } + + @Override + public IItemDefinition viewCell() { + return this.viewCell; + } + + @Override + public IItemDefinition cell1k() { + return this.cell1k; + } + + @Override + public IItemDefinition cell4k() { + return this.cell4k; + } + + @Override + public IItemDefinition cell16k() { + return this.cell16k; + } + + @Override + public IItemDefinition cell64k() { + return this.cell64k; + } + + @Override + public IItemDefinition spatialCell2() { + return this.spatialCell2; + } + + @Override + public IItemDefinition spatialCell16() { + return this.spatialCell16; + } + + @Override + public IItemDefinition spatialCell128() { + return this.spatialCell128; + } + + @Override + public IItemDefinition facade() { + return this.facade; + } + + @Override + public IItemDefinition crystalSeed() { + return this.crystalSeed; + } + + @Override + public IItemDefinition encodedPattern() { + return this.encodedPattern; + } + + @Override + public IItemDefinition colorApplicator() { + return this.colorApplicator; + } + + @Override + public AEColoredItemDefinition coloredPaintBall() { + return this.coloredPaintBall; + } + + @Override + public AEColoredItemDefinition coloredLumenPaintBall() { + return this.coloredLumenPaintBall; + } + + public IItemDefinition paintBall() { + return this.paintBall; + } + + public IItemDefinition toolEraser() { + return this.toolEraser; + } + + public IItemDefinition toolMeteoritePlacer() { + return this.toolMeteoritePlacer; + } + + public IItemDefinition toolDebugCard() { + return this.toolDebugCard; + } + + public IItemDefinition toolReplicatorCard() { + return this.toolReplicatorCard; + } } diff --git a/src/main/java/appeng/core/api/definitions/ApiMaterials.java b/src/main/java/appeng/core/api/definitions/ApiMaterials.java index ea24ac8542c..f98e9a6eac8 100644 --- a/src/main/java/appeng/core/api/definitions/ApiMaterials.java +++ b/src/main/java/appeng/core/api/definitions/ApiMaterials.java @@ -18,499 +18,465 @@ package appeng.core.api.definitions; - import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.IMaterials; import appeng.core.features.DamagedItemDefinition; import appeng.items.materials.ItemMultiMaterial; import appeng.items.materials.MaterialType; - /** * Internal implementation for the API materials */ -public final class ApiMaterials implements IMaterials -{ - private final IItemDefinition cell2SpatialPart; - private final IItemDefinition cell16SpatialPart; - private final IItemDefinition cell128SpatialPart; - - private final IItemDefinition silicon; - private final IItemDefinition skyDust; - - private final IItemDefinition calcProcessorPress; - private final IItemDefinition engProcessorPress; - private final IItemDefinition logicProcessorPress; - - private final IItemDefinition calcProcessorPrint; - private final IItemDefinition engProcessorPrint; - private final IItemDefinition logicProcessorPrint; - - private final IItemDefinition siliconPress; - private final IItemDefinition siliconPrint; - - private final IItemDefinition namePress; - - private final IItemDefinition logicProcessor; - private final IItemDefinition calcProcessor; - private final IItemDefinition engProcessor; - - private final IItemDefinition basicCard; - private final IItemDefinition advCard; - - private final IItemDefinition purifiedCertusQuartzCrystal; - private final IItemDefinition purifiedNetherQuartzCrystal; - private final IItemDefinition purifiedFluixCrystal; - - private final IItemDefinition cell1kPart; - private final IItemDefinition cell4kPart; - private final IItemDefinition cell16kPart; - private final IItemDefinition cell64kPart; - private final IItemDefinition emptyStorageCell; - - private final IItemDefinition cardRedstone; - private final IItemDefinition cardSpeed; - private final IItemDefinition cardCapacity; - private final IItemDefinition cardPatternCapacity; - private final IItemDefinition cardFuzzy; - private final IItemDefinition cardInverter; - private final IItemDefinition cardCrafting; - private final IItemDefinition cardOreFilter; - private final IItemDefinition enderDust; - private final IItemDefinition flour; - private final IItemDefinition goldDust; - private final IItemDefinition ironDust; - private final IItemDefinition fluixDust; - private final IItemDefinition certusQuartzDust; - private final IItemDefinition netherQuartzDust; - - private final IItemDefinition matterBall; - private final IItemDefinition ironNugget; - - private final IItemDefinition certusQuartzCrystal; - private final IItemDefinition certusQuartzCrystalCharged; - private final IItemDefinition fluixCrystal; - private final IItemDefinition fluixPearl; - - private final IItemDefinition woodenGear; - - private final IItemDefinition wireless; - private final IItemDefinition wirelessBooster; - - private final IItemDefinition annihilationCore; - private final IItemDefinition formationCore; - - private final IItemDefinition singularity; - private final IItemDefinition qESingularity; - private final IItemDefinition blankPattern; - - public ApiMaterials( final DefinitionConstructor constructor ) - { - final ItemMultiMaterial itemMultiMaterial = new ItemMultiMaterial(); - constructor.registerItemDefinition( itemMultiMaterial ); - - this.cell2SpatialPart = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Cell2SpatialPart ) ); - this.cell16SpatialPart = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Cell16SpatialPart ) ); - this.cell128SpatialPart = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Cell128SpatialPart ) ); - - this.silicon = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Silicon ) ); - this.skyDust = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.SkyDust ) ); - - this.calcProcessorPress = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CalcProcessorPress ) ); - this.engProcessorPress = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.EngProcessorPress ) ); - this.logicProcessorPress = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.LogicProcessorPress ) ); - - this.calcProcessorPrint = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CalcProcessorPrint ) ); - this.engProcessorPrint = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.EngProcessorPrint ) ); - this.logicProcessorPrint = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.LogicProcessorPrint ) ); - - this.siliconPress = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.SiliconPress ) ); - this.siliconPrint = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.SiliconPrint ) ); - - this.namePress = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.NamePress ) ); - - this.logicProcessor = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.LogicProcessor ) ); - this.calcProcessor = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CalcProcessor ) ); - this.engProcessor = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.EngProcessor ) ); - - this.basicCard = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.BasicCard ) ); - this.advCard = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.AdvCard ) ); - - this.purifiedCertusQuartzCrystal = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.PurifiedCertusQuartzCrystal ) ); - this.purifiedNetherQuartzCrystal = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.PurifiedNetherQuartzCrystal ) ); - this.purifiedFluixCrystal = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.PurifiedFluixCrystal ) ); - - this.cell1kPart = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Cell1kPart ) ); - this.cell4kPart = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Cell4kPart ) ); - this.cell16kPart = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Cell16kPart ) ); - this.cell64kPart = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Cell64kPart ) ); - this.emptyStorageCell = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.EmptyStorageCell ) ); - - this.cardRedstone = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CardRedstone ) ); - this.cardSpeed = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CardSpeed ) ); - this.cardCapacity = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CardCapacity ) ); - this.cardPatternCapacity = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CardPatternCapacity ) ); - this.cardFuzzy = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CardFuzzy ) ); - this.cardInverter = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CardInverter ) ); - this.cardCrafting = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CardCrafting ) ); - this.cardOreFilter = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CardOreFilter ) ); - - this.enderDust = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.EnderDust ) ); - this.flour = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Flour ) ); - this.goldDust = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.GoldDust ) ); - this.ironDust = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.IronDust ) ); - this.fluixDust = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.FluixDust ) ); - this.certusQuartzDust = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CertusQuartzDust ) ); - this.netherQuartzDust = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.NetherQuartzDust ) ); - - this.matterBall = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.MatterBall ) ); - this.ironNugget = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.IronNugget ) ); - - this.certusQuartzCrystal = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CertusQuartzCrystal ) ); - this.certusQuartzCrystalCharged = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CertusQuartzCrystalCharged ) ); - this.fluixCrystal = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.FluixCrystal ) ); - this.fluixPearl = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.FluixPearl ) ); - - this.woodenGear = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.WoodenGear ) ); - - this.wireless = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Wireless ) ); - this.wirelessBooster = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.WirelessBooster ) ); - - this.annihilationCore = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.AnnihilationCore ) ); - this.formationCore = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.FormationCore ) ); - - this.singularity = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Singularity ) ); - this.qESingularity = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.QESingularity ) ); - this.blankPattern = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.BlankPattern ) ); - } - - @Override - public IItemDefinition cell2SpatialPart() - { - return this.cell2SpatialPart; - } - - @Override - public IItemDefinition cell16SpatialPart() - { - return this.cell16SpatialPart; - } - - @Override - public IItemDefinition cell128SpatialPart() - { - return this.cell128SpatialPart; - } - - @Override - public IItemDefinition silicon() - { - return this.silicon; - } - - @Override - public IItemDefinition skyDust() - { - return this.skyDust; - } - - @Override - public IItemDefinition calcProcessorPress() - { - return this.calcProcessorPress; - } - - @Override - public IItemDefinition engProcessorPress() - { - return this.engProcessorPress; - } - - @Override - public IItemDefinition logicProcessorPress() - { - return this.logicProcessorPress; - } - - @Override - public IItemDefinition calcProcessorPrint() - { - return this.calcProcessorPrint; - } - - @Override - public IItemDefinition engProcessorPrint() - { - return this.engProcessorPrint; - } - - @Override - public IItemDefinition logicProcessorPrint() - { - return this.logicProcessorPrint; - } - - @Override - public IItemDefinition siliconPress() - { - return this.siliconPress; - } - - @Override - public IItemDefinition siliconPrint() - { - return this.siliconPrint; - } - - @Override - public IItemDefinition namePress() - { - return this.namePress; - } - - @Override - public IItemDefinition logicProcessor() - { - return this.logicProcessor; - } - - @Override - public IItemDefinition calcProcessor() - { - return this.calcProcessor; - } - - @Override - public IItemDefinition engProcessor() - { - return this.engProcessor; - } - - @Override - public IItemDefinition basicCard() - { - return this.basicCard; - } - - @Override - public IItemDefinition advCard() - { - return this.advCard; - } - - @Override - public IItemDefinition purifiedCertusQuartzCrystal() - { - return this.purifiedCertusQuartzCrystal; - } - - @Override - public IItemDefinition purifiedNetherQuartzCrystal() - { - return this.purifiedNetherQuartzCrystal; - } - - @Override - public IItemDefinition purifiedFluixCrystal() - { - return this.purifiedFluixCrystal; - } - - @Override - public IItemDefinition cell1kPart() - { - return this.cell1kPart; - } - - @Override - public IItemDefinition cell4kPart() - { - return this.cell4kPart; - } - - @Override - public IItemDefinition cell16kPart() - { - return this.cell16kPart; - } - - @Override - public IItemDefinition cell64kPart() - { - return this.cell64kPart; - } - - @Override - public IItemDefinition emptyStorageCell() - { - return this.emptyStorageCell; - } - - @Override - public IItemDefinition cardRedstone() - { - return this.cardRedstone; - } - - @Override - public IItemDefinition cardSpeed() - { - return this.cardSpeed; - } - - @Override - public IItemDefinition cardCapacity() - { - return this.cardCapacity; - } - - @Override - public IItemDefinition cardPatternCapacity() { return this.cardPatternCapacity; } - - @Override - public IItemDefinition cardOreFilter() { return this.cardOreFilter; } - - @Override - public IItemDefinition cardFuzzy() - { - return this.cardFuzzy; - } - - @Override - public IItemDefinition cardInverter() - { - return this.cardInverter; - } - - @Override - public IItemDefinition cardCrafting() - { - return this.cardCrafting; - } - - @Override - public IItemDefinition enderDust() - { - return this.enderDust; - } - - @Override - public IItemDefinition flour() - { - return this.flour; - } - - @Override - public IItemDefinition goldDust() - { - return this.goldDust; - } - - @Override - public IItemDefinition ironDust() - { - return this.ironDust; - } - - @Override - public IItemDefinition fluixDust() - { - return this.fluixDust; - } - - @Override - public IItemDefinition certusQuartzDust() - { - return this.certusQuartzDust; - } - - @Override - public IItemDefinition netherQuartzDust() - { - return this.netherQuartzDust; - } - - @Override - public IItemDefinition matterBall() - { - return this.matterBall; - } - - @Override - public IItemDefinition ironNugget() - { - return this.ironNugget; - } - - @Override - public IItemDefinition certusQuartzCrystal() - { - return this.certusQuartzCrystal; - } - - @Override - public IItemDefinition certusQuartzCrystalCharged() - { - return this.certusQuartzCrystalCharged; - } - - @Override - public IItemDefinition fluixCrystal() - { - return this.fluixCrystal; - } - - @Override - public IItemDefinition fluixPearl() - { - return this.fluixPearl; - } - - @Override - public IItemDefinition woodenGear() - { - return this.woodenGear; - } - - @Override - public IItemDefinition wireless() - { - return this.wireless; - } - - @Override - public IItemDefinition wirelessBooster() - { - return this.wirelessBooster; - } - - @Override - public IItemDefinition annihilationCore() - { - return this.annihilationCore; - } - - @Override - public IItemDefinition formationCore() - { - return this.formationCore; - } - - @Override - public IItemDefinition singularity() - { - return this.singularity; - } - - @Override - public IItemDefinition qESingularity() - { - return this.qESingularity; - } - - @Override - public IItemDefinition blankPattern() - { - return this.blankPattern; - } +public final class ApiMaterials implements IMaterials { + private final IItemDefinition cell2SpatialPart; + private final IItemDefinition cell16SpatialPart; + private final IItemDefinition cell128SpatialPart; + + private final IItemDefinition silicon; + private final IItemDefinition skyDust; + + private final IItemDefinition calcProcessorPress; + private final IItemDefinition engProcessorPress; + private final IItemDefinition logicProcessorPress; + + private final IItemDefinition calcProcessorPrint; + private final IItemDefinition engProcessorPrint; + private final IItemDefinition logicProcessorPrint; + + private final IItemDefinition siliconPress; + private final IItemDefinition siliconPrint; + + private final IItemDefinition namePress; + + private final IItemDefinition logicProcessor; + private final IItemDefinition calcProcessor; + private final IItemDefinition engProcessor; + + private final IItemDefinition basicCard; + private final IItemDefinition advCard; + + private final IItemDefinition purifiedCertusQuartzCrystal; + private final IItemDefinition purifiedNetherQuartzCrystal; + private final IItemDefinition purifiedFluixCrystal; + + private final IItemDefinition cell1kPart; + private final IItemDefinition cell4kPart; + private final IItemDefinition cell16kPart; + private final IItemDefinition cell64kPart; + private final IItemDefinition emptyStorageCell; + + private final IItemDefinition cardRedstone; + private final IItemDefinition cardSpeed; + private final IItemDefinition cardCapacity; + private final IItemDefinition cardPatternCapacity; + private final IItemDefinition cardFuzzy; + private final IItemDefinition cardInverter; + private final IItemDefinition cardCrafting; + private final IItemDefinition cardOreFilter; + private final IItemDefinition enderDust; + private final IItemDefinition flour; + private final IItemDefinition goldDust; + private final IItemDefinition ironDust; + private final IItemDefinition fluixDust; + private final IItemDefinition certusQuartzDust; + private final IItemDefinition netherQuartzDust; + + private final IItemDefinition matterBall; + private final IItemDefinition ironNugget; + + private final IItemDefinition certusQuartzCrystal; + private final IItemDefinition certusQuartzCrystalCharged; + private final IItemDefinition fluixCrystal; + private final IItemDefinition fluixPearl; + + private final IItemDefinition woodenGear; + + private final IItemDefinition wireless; + private final IItemDefinition wirelessBooster; + + private final IItemDefinition annihilationCore; + private final IItemDefinition formationCore; + + private final IItemDefinition singularity; + private final IItemDefinition qESingularity; + private final IItemDefinition blankPattern; + + public ApiMaterials(final DefinitionConstructor constructor) { + final ItemMultiMaterial itemMultiMaterial = new ItemMultiMaterial(); + constructor.registerItemDefinition(itemMultiMaterial); + + this.cell2SpatialPart = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.Cell2SpatialPart)); + this.cell16SpatialPart = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.Cell16SpatialPart)); + this.cell128SpatialPart = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.Cell128SpatialPart)); + + this.silicon = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.Silicon)); + this.skyDust = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.SkyDust)); + + this.calcProcessorPress = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.CalcProcessorPress)); + this.engProcessorPress = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.EngProcessorPress)); + this.logicProcessorPress = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.LogicProcessorPress)); + + this.calcProcessorPrint = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.CalcProcessorPrint)); + this.engProcessorPrint = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.EngProcessorPrint)); + this.logicProcessorPrint = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.LogicProcessorPrint)); + + this.siliconPress = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.SiliconPress)); + this.siliconPrint = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.SiliconPrint)); + + this.namePress = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.NamePress)); + + this.logicProcessor = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.LogicProcessor)); + this.calcProcessor = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.CalcProcessor)); + this.engProcessor = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.EngProcessor)); + + this.basicCard = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.BasicCard)); + this.advCard = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.AdvCard)); + + this.purifiedCertusQuartzCrystal = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.PurifiedCertusQuartzCrystal)); + this.purifiedNetherQuartzCrystal = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.PurifiedNetherQuartzCrystal)); + this.purifiedFluixCrystal = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.PurifiedFluixCrystal)); + + this.cell1kPart = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.Cell1kPart)); + this.cell4kPart = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.Cell4kPart)); + this.cell16kPart = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.Cell16kPart)); + this.cell64kPart = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.Cell64kPart)); + this.emptyStorageCell = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.EmptyStorageCell)); + + this.cardRedstone = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.CardRedstone)); + this.cardSpeed = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.CardSpeed)); + this.cardCapacity = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.CardCapacity)); + this.cardPatternCapacity = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.CardPatternCapacity)); + this.cardFuzzy = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.CardFuzzy)); + this.cardInverter = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.CardInverter)); + this.cardCrafting = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.CardCrafting)); + this.cardOreFilter = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.CardOreFilter)); + + this.enderDust = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.EnderDust)); + this.flour = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.Flour)); + this.goldDust = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.GoldDust)); + this.ironDust = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.IronDust)); + this.fluixDust = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.FluixDust)); + this.certusQuartzDust = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.CertusQuartzDust)); + this.netherQuartzDust = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.NetherQuartzDust)); + + this.matterBall = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.MatterBall)); + this.ironNugget = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.IronNugget)); + + this.certusQuartzCrystal = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.CertusQuartzCrystal)); + this.certusQuartzCrystalCharged = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.CertusQuartzCrystalCharged)); + this.fluixCrystal = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.FluixCrystal)); + this.fluixPearl = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.FluixPearl)); + + this.woodenGear = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.WoodenGear)); + + this.wireless = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.Wireless)); + this.wirelessBooster = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.WirelessBooster)); + + this.annihilationCore = + new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.AnnihilationCore)); + this.formationCore = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.FormationCore)); + + this.singularity = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.Singularity)); + this.qESingularity = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.QESingularity)); + this.blankPattern = new DamagedItemDefinition(itemMultiMaterial.createMaterial(MaterialType.BlankPattern)); + } + + @Override + public IItemDefinition cell2SpatialPart() { + return this.cell2SpatialPart; + } + + @Override + public IItemDefinition cell16SpatialPart() { + return this.cell16SpatialPart; + } + + @Override + public IItemDefinition cell128SpatialPart() { + return this.cell128SpatialPart; + } + + @Override + public IItemDefinition silicon() { + return this.silicon; + } + + @Override + public IItemDefinition skyDust() { + return this.skyDust; + } + + @Override + public IItemDefinition calcProcessorPress() { + return this.calcProcessorPress; + } + + @Override + public IItemDefinition engProcessorPress() { + return this.engProcessorPress; + } + + @Override + public IItemDefinition logicProcessorPress() { + return this.logicProcessorPress; + } + + @Override + public IItemDefinition calcProcessorPrint() { + return this.calcProcessorPrint; + } + + @Override + public IItemDefinition engProcessorPrint() { + return this.engProcessorPrint; + } + + @Override + public IItemDefinition logicProcessorPrint() { + return this.logicProcessorPrint; + } + + @Override + public IItemDefinition siliconPress() { + return this.siliconPress; + } + + @Override + public IItemDefinition siliconPrint() { + return this.siliconPrint; + } + + @Override + public IItemDefinition namePress() { + return this.namePress; + } + + @Override + public IItemDefinition logicProcessor() { + return this.logicProcessor; + } + + @Override + public IItemDefinition calcProcessor() { + return this.calcProcessor; + } + + @Override + public IItemDefinition engProcessor() { + return this.engProcessor; + } + + @Override + public IItemDefinition basicCard() { + return this.basicCard; + } + + @Override + public IItemDefinition advCard() { + return this.advCard; + } + + @Override + public IItemDefinition purifiedCertusQuartzCrystal() { + return this.purifiedCertusQuartzCrystal; + } + + @Override + public IItemDefinition purifiedNetherQuartzCrystal() { + return this.purifiedNetherQuartzCrystal; + } + + @Override + public IItemDefinition purifiedFluixCrystal() { + return this.purifiedFluixCrystal; + } + + @Override + public IItemDefinition cell1kPart() { + return this.cell1kPart; + } + + @Override + public IItemDefinition cell4kPart() { + return this.cell4kPart; + } + + @Override + public IItemDefinition cell16kPart() { + return this.cell16kPart; + } + + @Override + public IItemDefinition cell64kPart() { + return this.cell64kPart; + } + + @Override + public IItemDefinition emptyStorageCell() { + return this.emptyStorageCell; + } + + @Override + public IItemDefinition cardRedstone() { + return this.cardRedstone; + } + + @Override + public IItemDefinition cardSpeed() { + return this.cardSpeed; + } + + @Override + public IItemDefinition cardCapacity() { + return this.cardCapacity; + } + + @Override + public IItemDefinition cardPatternCapacity() { + return this.cardPatternCapacity; + } + + @Override + public IItemDefinition cardOreFilter() { + return this.cardOreFilter; + } + + @Override + public IItemDefinition cardFuzzy() { + return this.cardFuzzy; + } + + @Override + public IItemDefinition cardInverter() { + return this.cardInverter; + } + + @Override + public IItemDefinition cardCrafting() { + return this.cardCrafting; + } + + @Override + public IItemDefinition enderDust() { + return this.enderDust; + } + + @Override + public IItemDefinition flour() { + return this.flour; + } + + @Override + public IItemDefinition goldDust() { + return this.goldDust; + } + + @Override + public IItemDefinition ironDust() { + return this.ironDust; + } + + @Override + public IItemDefinition fluixDust() { + return this.fluixDust; + } + + @Override + public IItemDefinition certusQuartzDust() { + return this.certusQuartzDust; + } + + @Override + public IItemDefinition netherQuartzDust() { + return this.netherQuartzDust; + } + + @Override + public IItemDefinition matterBall() { + return this.matterBall; + } + + @Override + public IItemDefinition ironNugget() { + return this.ironNugget; + } + + @Override + public IItemDefinition certusQuartzCrystal() { + return this.certusQuartzCrystal; + } + + @Override + public IItemDefinition certusQuartzCrystalCharged() { + return this.certusQuartzCrystalCharged; + } + + @Override + public IItemDefinition fluixCrystal() { + return this.fluixCrystal; + } + + @Override + public IItemDefinition fluixPearl() { + return this.fluixPearl; + } + + @Override + public IItemDefinition woodenGear() { + return this.woodenGear; + } + + @Override + public IItemDefinition wireless() { + return this.wireless; + } + + @Override + public IItemDefinition wirelessBooster() { + return this.wirelessBooster; + } + + @Override + public IItemDefinition annihilationCore() { + return this.annihilationCore; + } + + @Override + public IItemDefinition formationCore() { + return this.formationCore; + } + + @Override + public IItemDefinition singularity() { + return this.singularity; + } + + @Override + public IItemDefinition qESingularity() { + return this.qESingularity; + } + + @Override + public IItemDefinition blankPattern() { + return this.blankPattern; + } } diff --git a/src/main/java/appeng/core/api/definitions/ApiParts.java b/src/main/java/appeng/core/api/definitions/ApiParts.java index 5f2a6fd325c..d356bafb53e 100644 --- a/src/main/java/appeng/core/api/definitions/ApiParts.java +++ b/src/main/java/appeng/core/api/definitions/ApiParts.java @@ -18,7 +18,6 @@ package appeng.core.api.definitions; - import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.IParts; import appeng.api.exceptions.MissingDefinition; @@ -28,365 +27,323 @@ import appeng.items.parts.ItemMultiPart; import appeng.items.parts.PartType; - /** * Internal implementation for the API parts */ -public final class ApiParts implements IParts -{ - private final AEColoredItemDefinition cableSmart; - private final AEColoredItemDefinition cableCovered; - private final AEColoredItemDefinition cableGlass; - private final AEColoredItemDefinition cableDense; - private final AEColoredItemDefinition cableDenseCovered; - private final AEColoredItemDefinition cableUltraDenseSmart; - private final AEColoredItemDefinition cableUltraDenseCovered; - // private final AEColoredItemDefinition lumenCableSmart; - // private final AEColoredItemDefinition lumenCableCovered; - // private final AEColoredItemDefinition lumenCableGlass; - // private final AEColoredItemDefinition lumenCableDense; - private final IItemDefinition quartzFiber; - private final IItemDefinition toggleBus; - private final IItemDefinition invertedToggleBus; - private final IItemDefinition storageBus; - private final IItemDefinition importBus; - private final IItemDefinition exportBus; - private final IItemDefinition iface; - private final IItemDefinition levelEmitter; - private final IItemDefinition annihilationPlane; - private final IItemDefinition identityAnnihilationPlane; - private final IItemDefinition formationPlane; - private final IItemDefinition p2PTunnelME; - private final IItemDefinition p2PTunnelRedstone; - private final IItemDefinition p2PTunnelItems; - private final IItemDefinition p2PTunnelLiquids; - private final IItemDefinition p2PTunnelEU; - private final IItemDefinition p2PTunnelRF; - private final IItemDefinition p2PTunnelLight; - private final IItemDefinition p2PTunnelOpenComputers; - private final IItemDefinition p2PTunnelPneumaticCraft; - private final IItemDefinition p2PTunnelGregtech; - private final IItemDefinition cableAnchor; - private final IItemDefinition monitor; - private final IItemDefinition semiDarkMonitor; - private final IItemDefinition darkMonitor; - private final IItemDefinition interfaceTerminal; - private final IItemDefinition patternTerminal; - private final IItemDefinition patternTerminalEx; - private final IItemDefinition craftingTerminal; - private final IItemDefinition terminal; - private final IItemDefinition storageMonitor; - private final IItemDefinition conversionMonitor; - - public ApiParts( final DefinitionConstructor constructor, final IPartHelper partHelper ) - { - final ItemMultiPart itemMultiPart = new ItemMultiPart( partHelper ); - constructor.registerItemDefinition( itemMultiPart ); - - this.cableSmart = constructor.constructColoredDefinition( itemMultiPart, PartType.CableSmart ); - this.cableCovered = constructor.constructColoredDefinition( itemMultiPart, PartType.CableCovered ); - this.cableGlass = constructor.constructColoredDefinition( itemMultiPart, PartType.CableGlass ); - this.cableDense = constructor.constructColoredDefinition( itemMultiPart, PartType.CableDense ); - this.cableDenseCovered = constructor.constructColoredDefinition( itemMultiPart, PartType.CableDenseCovered ); - this.cableUltraDenseSmart = constructor.constructColoredDefinition( itemMultiPart, PartType.CableUltraDenseSmart ); - this.cableUltraDenseCovered = constructor.constructColoredDefinition( itemMultiPart, PartType.CableUltraDenseCovered ); - // this.lumenCableSmart = Optional.absent(); // has yet to be implemented, no PartType defined for it yet - // this.lumenCableCovered = Optional.absent(); // has yet to be implemented, no PartType defined for it yet - // this.lumenCableGlass = Optional.absent(); // has yet to be implemented, no PartType defined for it yet - // this.lumenCableDense = Optional.absent(); // has yet to be implemented, no PartType defined for it yet - this.quartzFiber = new DamagedItemDefinition( itemMultiPart.createPart( PartType.QuartzFiber ) ); - this.toggleBus = new DamagedItemDefinition( itemMultiPart.createPart( PartType.ToggleBus ) ); - this.invertedToggleBus = new DamagedItemDefinition( itemMultiPart.createPart( PartType.InvertedToggleBus ) ); - this.storageBus = new DamagedItemDefinition( itemMultiPart.createPart( PartType.StorageBus ) ); - this.importBus = new DamagedItemDefinition( itemMultiPart.createPart( PartType.ImportBus ) ); - this.exportBus = new DamagedItemDefinition( itemMultiPart.createPart( PartType.ExportBus ) ); - this.iface = new DamagedItemDefinition( itemMultiPart.createPart( PartType.Interface ) ); - this.levelEmitter = new DamagedItemDefinition( itemMultiPart.createPart( PartType.LevelEmitter ) ); - this.annihilationPlane = new DamagedItemDefinition( itemMultiPart.createPart( PartType.AnnihilationPlane ) ); - this.identityAnnihilationPlane = new DamagedItemDefinition( itemMultiPart.createPart( PartType.IdentityAnnihilationPlane ) ); - this.formationPlane = new DamagedItemDefinition( itemMultiPart.createPart( PartType.FormationPlane ) ); - this.p2PTunnelME = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelME ) ); - this.p2PTunnelRedstone = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelRedstone ) ); - this.p2PTunnelItems = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelItems ) ); - this.p2PTunnelLiquids = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelLiquids ) ); - this.p2PTunnelEU = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelEU ) ); - this.p2PTunnelRF = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelRF ) ); - this.p2PTunnelLight = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelLight ) ); - this.p2PTunnelOpenComputers = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelOpenComputers ) ); - this.p2PTunnelPneumaticCraft = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelPressure ) ); - this.p2PTunnelGregtech = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelGT ) ); - this.cableAnchor = new DamagedItemDefinition( itemMultiPart.createPart( PartType.CableAnchor ) ); - this.monitor = new DamagedItemDefinition( itemMultiPart.createPart( PartType.Monitor ) ); - this.semiDarkMonitor = new DamagedItemDefinition( itemMultiPart.createPart( PartType.SemiDarkMonitor ) ); - this.darkMonitor = new DamagedItemDefinition( itemMultiPart.createPart( PartType.DarkMonitor ) ); - this.interfaceTerminal = new DamagedItemDefinition( itemMultiPart.createPart( PartType.InterfaceTerminal ) ); - this.patternTerminal = new DamagedItemDefinition( itemMultiPart.createPart( PartType.PatternTerminal ) ); - this.patternTerminalEx = new DamagedItemDefinition( itemMultiPart.createPart( PartType.PatternTerminalEx ) ); - this.craftingTerminal = new DamagedItemDefinition( itemMultiPart.createPart( PartType.CraftingTerminal ) ); - this.terminal = new DamagedItemDefinition( itemMultiPart.createPart( PartType.Terminal ) ); - this.storageMonitor = new DamagedItemDefinition( itemMultiPart.createPart( PartType.StorageMonitor ) ); - this.conversionMonitor = new DamagedItemDefinition( itemMultiPart.createPart( PartType.ConversionMonitor ) ); - } - - @Override - public AEColoredItemDefinition cableSmart() - { - return this.cableSmart; - } - - @Override - public AEColoredItemDefinition cableCovered() - { - return this.cableCovered; - } - - @Override - public AEColoredItemDefinition cableGlass() - { - return this.cableGlass; - } - - @Override - public AEColoredItemDefinition cableDense() - { - return this.cableDense; - } - - @Override - public AEColoredItemDefinition cableDenseCovered() - { - return this.cableDenseCovered; - } - - @Override - public AEColoredItemDefinition cableUltraDenseSmart() - { - return this.cableUltraDenseSmart; - } - - @Override - public AEColoredItemDefinition cableUltraDenseCovered() - { - return this.cableUltraDenseCovered; - } - - @Override - public AEColoredItemDefinition lumenCableSmart() - { - throw new MissingDefinition( "Lumen Smart Cable has yet to be implemented." ); - // return this.lumenCableSmart; - } - - @Override - public AEColoredItemDefinition lumenCableCovered() - { - throw new MissingDefinition( "Lumen Covered Cable has yet to be implemented." ); - // return this.lumenCableCovered; - } - - @Override - public AEColoredItemDefinition lumenCableGlass() - { - throw new MissingDefinition( "Lumen Glass Cable has yet to be implemented." ); - // return this.lumenCableGlass; - } - - @Override - public AEColoredItemDefinition lumenCableDense() - { - throw new MissingDefinition( "Lumen Dense Cable has yet to be implemented." ); - // return this.lumenCableDense; - } - - @Override - public IItemDefinition quartzFiber() - { - return this.quartzFiber; - } - - @Override - public IItemDefinition toggleBus() - { - return this.toggleBus; - } - - @Override - public IItemDefinition invertedToggleBus() - { - return this.invertedToggleBus; - } - - @Override - public IItemDefinition storageBus() - { - return this.storageBus; - } - - @Override - public IItemDefinition importBus() - { - return this.importBus; - } - - @Override - public IItemDefinition exportBus() - { - return this.exportBus; - } - - @Override - public IItemDefinition iface() - { - return this.iface; - } - - @Override - public IItemDefinition levelEmitter() - { - return this.levelEmitter; - } - - @Override - public IItemDefinition annihilationPlane() - { - return this.annihilationPlane; - } - - @Override - public IItemDefinition identityAnnihilationPlane() - { - return this.identityAnnihilationPlane; - } - - @Override - public IItemDefinition formationPlane() - { - return this.formationPlane; - } - - @Override - public IItemDefinition p2PTunnelME() - { - return this.p2PTunnelME; - } - - @Override - public IItemDefinition p2PTunnelRedstone() - { - return this.p2PTunnelRedstone; - } - - @Override - public IItemDefinition p2PTunnelItems() - { - return this.p2PTunnelItems; - } - - @Override - public IItemDefinition p2PTunnelLiquids() - { - return this.p2PTunnelLiquids; - } - - @Override - public IItemDefinition p2PTunnelEU() - { - return this.p2PTunnelEU; - } - - @Override - public IItemDefinition p2PTunnelRF() - { - return this.p2PTunnelRF; - } - - @Override - public IItemDefinition p2PTunnelLight() - { - return this.p2PTunnelLight; - } - - @Override - public IItemDefinition p2PTunnelOpenComputers() - { - return this.p2PTunnelOpenComputers; - } - - @Override - public IItemDefinition p2PTunnelPneumaticCraft() - { - return this.p2PTunnelPneumaticCraft; - } - - @Override - public IItemDefinition p2PTunnelGregtech() - { - return this.p2PTunnelGregtech; - } - - @Override - public IItemDefinition cableAnchor() - { - return this.cableAnchor; - } - - @Override - public IItemDefinition monitor() - { - return this.monitor; - } - - @Override - public IItemDefinition semiDarkMonitor() - { - return this.semiDarkMonitor; - } - - @Override - public IItemDefinition darkMonitor() - { - return this.darkMonitor; - } - - @Override - public IItemDefinition interfaceTerminal() - { - return this.interfaceTerminal; - } - - @Override - public IItemDefinition patternTerminal() - { - return this.patternTerminal; - } - - @Override - public IItemDefinition patternTerminalEx() - { - return this.patternTerminalEx; - } - - @Override - public IItemDefinition craftingTerminal() - { - return this.craftingTerminal; - } - - @Override - public IItemDefinition terminal() - { - return this.terminal; - } - - @Override - public IItemDefinition storageMonitor() - { - return this.storageMonitor; - } - - @Override - public IItemDefinition conversionMonitor() - { - return this.conversionMonitor; - } +public final class ApiParts implements IParts { + private final AEColoredItemDefinition cableSmart; + private final AEColoredItemDefinition cableCovered; + private final AEColoredItemDefinition cableGlass; + private final AEColoredItemDefinition cableDense; + private final AEColoredItemDefinition cableDenseCovered; + private final AEColoredItemDefinition cableUltraDenseSmart; + private final AEColoredItemDefinition cableUltraDenseCovered; + // private final AEColoredItemDefinition lumenCableSmart; + // private final AEColoredItemDefinition lumenCableCovered; + // private final AEColoredItemDefinition lumenCableGlass; + // private final AEColoredItemDefinition lumenCableDense; + private final IItemDefinition quartzFiber; + private final IItemDefinition toggleBus; + private final IItemDefinition invertedToggleBus; + private final IItemDefinition storageBus; + private final IItemDefinition importBus; + private final IItemDefinition exportBus; + private final IItemDefinition iface; + private final IItemDefinition levelEmitter; + private final IItemDefinition annihilationPlane; + private final IItemDefinition identityAnnihilationPlane; + private final IItemDefinition formationPlane; + private final IItemDefinition p2PTunnelME; + private final IItemDefinition p2PTunnelRedstone; + private final IItemDefinition p2PTunnelItems; + private final IItemDefinition p2PTunnelLiquids; + private final IItemDefinition p2PTunnelEU; + private final IItemDefinition p2PTunnelRF; + private final IItemDefinition p2PTunnelLight; + private final IItemDefinition p2PTunnelOpenComputers; + private final IItemDefinition p2PTunnelPneumaticCraft; + private final IItemDefinition p2PTunnelGregtech; + private final IItemDefinition cableAnchor; + private final IItemDefinition monitor; + private final IItemDefinition semiDarkMonitor; + private final IItemDefinition darkMonitor; + private final IItemDefinition interfaceTerminal; + private final IItemDefinition patternTerminal; + private final IItemDefinition patternTerminalEx; + private final IItemDefinition craftingTerminal; + private final IItemDefinition terminal; + private final IItemDefinition storageMonitor; + private final IItemDefinition conversionMonitor; + + public ApiParts(final DefinitionConstructor constructor, final IPartHelper partHelper) { + final ItemMultiPart itemMultiPart = new ItemMultiPart(partHelper); + constructor.registerItemDefinition(itemMultiPart); + + this.cableSmart = constructor.constructColoredDefinition(itemMultiPart, PartType.CableSmart); + this.cableCovered = constructor.constructColoredDefinition(itemMultiPart, PartType.CableCovered); + this.cableGlass = constructor.constructColoredDefinition(itemMultiPart, PartType.CableGlass); + this.cableDense = constructor.constructColoredDefinition(itemMultiPart, PartType.CableDense); + this.cableDenseCovered = constructor.constructColoredDefinition(itemMultiPart, PartType.CableDenseCovered); + this.cableUltraDenseSmart = + constructor.constructColoredDefinition(itemMultiPart, PartType.CableUltraDenseSmart); + this.cableUltraDenseCovered = + constructor.constructColoredDefinition(itemMultiPart, PartType.CableUltraDenseCovered); + // this.lumenCableSmart = Optional.absent(); // has yet to be implemented, no PartType defined for it yet + // this.lumenCableCovered = Optional.absent(); // has yet to be implemented, no PartType defined for it yet + // this.lumenCableGlass = Optional.absent(); // has yet to be implemented, no PartType defined for it yet + // this.lumenCableDense = Optional.absent(); // has yet to be implemented, no PartType defined for it yet + this.quartzFiber = new DamagedItemDefinition(itemMultiPart.createPart(PartType.QuartzFiber)); + this.toggleBus = new DamagedItemDefinition(itemMultiPart.createPart(PartType.ToggleBus)); + this.invertedToggleBus = new DamagedItemDefinition(itemMultiPart.createPart(PartType.InvertedToggleBus)); + this.storageBus = new DamagedItemDefinition(itemMultiPart.createPart(PartType.StorageBus)); + this.importBus = new DamagedItemDefinition(itemMultiPart.createPart(PartType.ImportBus)); + this.exportBus = new DamagedItemDefinition(itemMultiPart.createPart(PartType.ExportBus)); + this.iface = new DamagedItemDefinition(itemMultiPart.createPart(PartType.Interface)); + this.levelEmitter = new DamagedItemDefinition(itemMultiPart.createPart(PartType.LevelEmitter)); + this.annihilationPlane = new DamagedItemDefinition(itemMultiPart.createPart(PartType.AnnihilationPlane)); + this.identityAnnihilationPlane = + new DamagedItemDefinition(itemMultiPart.createPart(PartType.IdentityAnnihilationPlane)); + this.formationPlane = new DamagedItemDefinition(itemMultiPart.createPart(PartType.FormationPlane)); + this.p2PTunnelME = new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelME)); + this.p2PTunnelRedstone = new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelRedstone)); + this.p2PTunnelItems = new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelItems)); + this.p2PTunnelLiquids = new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelLiquids)); + this.p2PTunnelEU = new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelEU)); + this.p2PTunnelRF = new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelRF)); + this.p2PTunnelLight = new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelLight)); + this.p2PTunnelOpenComputers = + new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelOpenComputers)); + this.p2PTunnelPneumaticCraft = new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelPressure)); + this.p2PTunnelGregtech = new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelGT)); + this.cableAnchor = new DamagedItemDefinition(itemMultiPart.createPart(PartType.CableAnchor)); + this.monitor = new DamagedItemDefinition(itemMultiPart.createPart(PartType.Monitor)); + this.semiDarkMonitor = new DamagedItemDefinition(itemMultiPart.createPart(PartType.SemiDarkMonitor)); + this.darkMonitor = new DamagedItemDefinition(itemMultiPart.createPart(PartType.DarkMonitor)); + this.interfaceTerminal = new DamagedItemDefinition(itemMultiPart.createPart(PartType.InterfaceTerminal)); + this.patternTerminal = new DamagedItemDefinition(itemMultiPart.createPart(PartType.PatternTerminal)); + this.patternTerminalEx = new DamagedItemDefinition(itemMultiPart.createPart(PartType.PatternTerminalEx)); + this.craftingTerminal = new DamagedItemDefinition(itemMultiPart.createPart(PartType.CraftingTerminal)); + this.terminal = new DamagedItemDefinition(itemMultiPart.createPart(PartType.Terminal)); + this.storageMonitor = new DamagedItemDefinition(itemMultiPart.createPart(PartType.StorageMonitor)); + this.conversionMonitor = new DamagedItemDefinition(itemMultiPart.createPart(PartType.ConversionMonitor)); + } + + @Override + public AEColoredItemDefinition cableSmart() { + return this.cableSmart; + } + + @Override + public AEColoredItemDefinition cableCovered() { + return this.cableCovered; + } + + @Override + public AEColoredItemDefinition cableGlass() { + return this.cableGlass; + } + + @Override + public AEColoredItemDefinition cableDense() { + return this.cableDense; + } + + @Override + public AEColoredItemDefinition cableDenseCovered() { + return this.cableDenseCovered; + } + + @Override + public AEColoredItemDefinition cableUltraDenseSmart() { + return this.cableUltraDenseSmart; + } + + @Override + public AEColoredItemDefinition cableUltraDenseCovered() { + return this.cableUltraDenseCovered; + } + + @Override + public AEColoredItemDefinition lumenCableSmart() { + throw new MissingDefinition("Lumen Smart Cable has yet to be implemented."); + // return this.lumenCableSmart; + } + + @Override + public AEColoredItemDefinition lumenCableCovered() { + throw new MissingDefinition("Lumen Covered Cable has yet to be implemented."); + // return this.lumenCableCovered; + } + + @Override + public AEColoredItemDefinition lumenCableGlass() { + throw new MissingDefinition("Lumen Glass Cable has yet to be implemented."); + // return this.lumenCableGlass; + } + + @Override + public AEColoredItemDefinition lumenCableDense() { + throw new MissingDefinition("Lumen Dense Cable has yet to be implemented."); + // return this.lumenCableDense; + } + + @Override + public IItemDefinition quartzFiber() { + return this.quartzFiber; + } + + @Override + public IItemDefinition toggleBus() { + return this.toggleBus; + } + + @Override + public IItemDefinition invertedToggleBus() { + return this.invertedToggleBus; + } + + @Override + public IItemDefinition storageBus() { + return this.storageBus; + } + + @Override + public IItemDefinition importBus() { + return this.importBus; + } + + @Override + public IItemDefinition exportBus() { + return this.exportBus; + } + + @Override + public IItemDefinition iface() { + return this.iface; + } + + @Override + public IItemDefinition levelEmitter() { + return this.levelEmitter; + } + + @Override + public IItemDefinition annihilationPlane() { + return this.annihilationPlane; + } + + @Override + public IItemDefinition identityAnnihilationPlane() { + return this.identityAnnihilationPlane; + } + + @Override + public IItemDefinition formationPlane() { + return this.formationPlane; + } + + @Override + public IItemDefinition p2PTunnelME() { + return this.p2PTunnelME; + } + + @Override + public IItemDefinition p2PTunnelRedstone() { + return this.p2PTunnelRedstone; + } + + @Override + public IItemDefinition p2PTunnelItems() { + return this.p2PTunnelItems; + } + + @Override + public IItemDefinition p2PTunnelLiquids() { + return this.p2PTunnelLiquids; + } + + @Override + public IItemDefinition p2PTunnelEU() { + return this.p2PTunnelEU; + } + + @Override + public IItemDefinition p2PTunnelRF() { + return this.p2PTunnelRF; + } + + @Override + public IItemDefinition p2PTunnelLight() { + return this.p2PTunnelLight; + } + + @Override + public IItemDefinition p2PTunnelOpenComputers() { + return this.p2PTunnelOpenComputers; + } + + @Override + public IItemDefinition p2PTunnelPneumaticCraft() { + return this.p2PTunnelPneumaticCraft; + } + + @Override + public IItemDefinition p2PTunnelGregtech() { + return this.p2PTunnelGregtech; + } + + @Override + public IItemDefinition cableAnchor() { + return this.cableAnchor; + } + + @Override + public IItemDefinition monitor() { + return this.monitor; + } + + @Override + public IItemDefinition semiDarkMonitor() { + return this.semiDarkMonitor; + } + + @Override + public IItemDefinition darkMonitor() { + return this.darkMonitor; + } + + @Override + public IItemDefinition interfaceTerminal() { + return this.interfaceTerminal; + } + + @Override + public IItemDefinition patternTerminal() { + return this.patternTerminal; + } + + @Override + public IItemDefinition patternTerminalEx() { + return this.patternTerminalEx; + } + + @Override + public IItemDefinition craftingTerminal() { + return this.craftingTerminal; + } + + @Override + public IItemDefinition terminal() { + return this.terminal; + } + + @Override + public IItemDefinition storageMonitor() { + return this.storageMonitor; + } + + @Override + public IItemDefinition conversionMonitor() { + return this.conversionMonitor; + } } diff --git a/src/main/java/appeng/core/api/definitions/DefinitionConstructor.java b/src/main/java/appeng/core/api/definitions/DefinitionConstructor.java index c81805c9a28..740d15fba6c 100644 --- a/src/main/java/appeng/core/api/definitions/DefinitionConstructor.java +++ b/src/main/java/appeng/core/api/definitions/DefinitionConstructor.java @@ -18,7 +18,6 @@ package appeng.core.api.definitions; - import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.ITileDefinition; @@ -31,85 +30,71 @@ import appeng.items.parts.PartType; import net.minecraft.item.Item; +public class DefinitionConstructor { + private final FeatureRegistry features; + private final FeatureHandlerRegistry handlers; -public class DefinitionConstructor -{ - private final FeatureRegistry features; - private final FeatureHandlerRegistry handlers; - - public DefinitionConstructor( final FeatureRegistry features, final FeatureHandlerRegistry handlers ) - { - this.features = features; - this.handlers = handlers; - } + public DefinitionConstructor(final FeatureRegistry features, final FeatureHandlerRegistry handlers) { + this.features = features; + this.handlers = handlers; + } - final ITileDefinition registerTileDefinition( final IAEFeature feature ) - { - final IBlockDefinition definition = this.registerBlockDefinition( feature ); + final ITileDefinition registerTileDefinition(final IAEFeature feature) { + final IBlockDefinition definition = this.registerBlockDefinition(feature); - if( definition instanceof ITileDefinition ) - { - return ( (ITileDefinition) definition ); - } + if (definition instanceof ITileDefinition) { + return ((ITileDefinition) definition); + } - throw new IllegalStateException( "No tile definition for " + feature ); - } + throw new IllegalStateException("No tile definition for " + feature); + } - final IBlockDefinition registerBlockDefinition( final IAEFeature feature ) - { - final IItemDefinition definition = this.registerItemDefinition( feature ); + final IBlockDefinition registerBlockDefinition(final IAEFeature feature) { + final IItemDefinition definition = this.registerItemDefinition(feature); - if( definition instanceof IBlockDefinition ) - { - return ( (IBlockDefinition) definition ); - } + if (definition instanceof IBlockDefinition) { + return ((IBlockDefinition) definition); + } - throw new IllegalStateException( "No block definition for " + feature ); - } + throw new IllegalStateException("No block definition for " + feature); + } - final IItemDefinition registerItemDefinition( final IAEFeature feature ) - { - final IFeatureHandler handler = feature.handler(); + final IItemDefinition registerItemDefinition(final IAEFeature feature) { + final IFeatureHandler handler = feature.handler(); - if( handler.isFeatureAvailable() ) - { - this.handlers.addFeatureHandler( handler ); - this.features.addFeature( feature ); - } + if (handler.isFeatureAvailable()) { + this.handlers.addFeatureHandler(handler); + this.features.addFeature(feature); + } - final IItemDefinition definition = handler.getDefinition(); + final IItemDefinition definition = handler.getDefinition(); - return definition; - } + return definition; + } - final AEColoredItemDefinition constructColoredDefinition( final IItemDefinition target, final int offset ) - { - final ColoredItemDefinition definition = new ColoredItemDefinition(); + final AEColoredItemDefinition constructColoredDefinition(final IItemDefinition target, final int offset) { + final ColoredItemDefinition definition = new ColoredItemDefinition(); - for( final Item targetItem : target.maybeItem().asSet() ) - { - for( final AEColor color : AEColor.VALID_COLORS ) - { - final ActivityState state = ActivityState.from( target.isEnabled() ); + for (final Item targetItem : target.maybeItem().asSet()) { + for (final AEColor color : AEColor.VALID_COLORS) { + final ActivityState state = ActivityState.from(target.isEnabled()); - definition.add( color, new ItemStackSrc( targetItem, offset + color.ordinal(), state ) ); - } - } + definition.add(color, new ItemStackSrc(targetItem, offset + color.ordinal(), state)); + } + } - return definition; - } + return definition; + } - final AEColoredItemDefinition constructColoredDefinition( final ItemMultiPart target, final PartType type ) - { - final ColoredItemDefinition definition = new ColoredItemDefinition(); + final AEColoredItemDefinition constructColoredDefinition(final ItemMultiPart target, final PartType type) { + final ColoredItemDefinition definition = new ColoredItemDefinition(); - for( final AEColor color : AEColor.values() ) - { - final ItemStackSrc multiPartSource = target.createPart( type, color ); + for (final AEColor color : AEColor.values()) { + final ItemStackSrc multiPartSource = target.createPart(type, color); - definition.add( color, multiPartSource ); - } + definition.add(color, multiPartSource); + } - return definition; - } + return definition; + } } diff --git a/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java b/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java index af040c5e18c..8f3c87cc0c8 100644 --- a/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java +++ b/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java @@ -18,7 +18,6 @@ package appeng.core.api.imc; - import appeng.api.AEApi; import appeng.core.AELog; import appeng.core.api.IIMCProcessor; @@ -26,25 +25,20 @@ import net.minecraft.block.Block; import net.minecraft.item.ItemStack; +public class IMCBlackListSpatial implements IIMCProcessor { -public class IMCBlackListSpatial implements IIMCProcessor -{ - - @Override - public void process( final IMCMessage m ) - { + @Override + public void process(final IMCMessage m) { - final ItemStack is = m.getItemStackValue(); - if( is != null ) - { - final Block blk = Block.getBlockFromItem( is.getItem() ); - if( blk != null ) - { - AEApi.instance().registries().movable().blacklistBlock( blk ); - return; - } - } + final ItemStack is = m.getItemStackValue(); + if (is != null) { + final Block blk = Block.getBlockFromItem(is.getItem()); + if (blk != null) { + AEApi.instance().registries().movable().blacklistBlock(blk); + return; + } + } - AELog.info( "Bad Block blacklisted by " + m.getSender() ); - } + AELog.info("Bad Block blacklisted by " + m.getSender()); + } } diff --git a/src/main/java/appeng/core/api/imc/IMCGrinder.java b/src/main/java/appeng/core/api/imc/IMCGrinder.java index fc9b5052363..3b6fb992ccd 100644 --- a/src/main/java/appeng/core/api/imc/IMCGrinder.java +++ b/src/main/java/appeng/core/api/imc/IMCGrinder.java @@ -18,41 +18,40 @@ /* Example: - NBTTagCompound msg = new NBTTagCompound(); - NBTTagCompound in = new NBTTagCompound(); - NBTTagCompound out = new NBTTagCompound(); +NBTTagCompound msg = new NBTTagCompound(); +NBTTagCompound in = new NBTTagCompound(); +NBTTagCompound out = new NBTTagCompound(); - new ItemStack( Blocks.iron_ore ).writeToNBT( in ); - new ItemStack( Items.iron_ingot ).writeToNBT( out ); - msg.setTag( "in", in ); - msg.setTag( "out", out ); - msg.setInteger( "turns", 8 ); +new ItemStack( Blocks.iron_ore ).writeToNBT( in ); +new ItemStack( Items.iron_ingot ).writeToNBT( out ); +msg.setTag( "in", in ); +msg.setTag( "out", out ); +msg.setInteger( "turns", 8 ); - FMLInterModComms.sendMessage( "appliedenergistics2", "add-grindable", msg ); +FMLInterModComms.sendMessage( "appliedenergistics2", "add-grindable", msg ); - -- or -- +-- or -- - NBTTagCompound msg = new NBTTagCompound(); - NBTTagCompound in = new NBTTagCompound(); - NBTTagCompound out = new NBTTagCompound(); - NBTTagCompound optional = new NBTTagCompound(); +NBTTagCompound msg = new NBTTagCompound(); +NBTTagCompound in = new NBTTagCompound(); +NBTTagCompound out = new NBTTagCompound(); +NBTTagCompound optional = new NBTTagCompound(); - new ItemStack( Blocks.iron_ore ).writeToNBT( in ); - new ItemStack( Items.iron_ingot ).writeToNBT( out ); - new ItemStack( Blocks.gravel ).writeToNBT( optional ); - msg.setTag( "in", in ); - msg.setTag( "out", out ); - msg.setTag( "optional", optional ); - msg.setFloat( "chance", 0.5 ); - msg.setInteger( "turns", 8 ); +new ItemStack( Blocks.iron_ore ).writeToNBT( in ); +new ItemStack( Items.iron_ingot ).writeToNBT( out ); +new ItemStack( Blocks.gravel ).writeToNBT( optional ); +msg.setTag( "in", in ); +msg.setTag( "out", out ); +msg.setTag( "optional", optional ); +msg.setFloat( "chance", 0.5 ); +msg.setInteger( "turns", 8 ); - FMLInterModComms.sendMessage( "appliedenergistics2", "add-grindable", msg ); +FMLInterModComms.sendMessage( "appliedenergistics2", "add-grindable", msg ); - */ +*/ package appeng.core.api.imc; - import appeng.api.AEApi; import appeng.core.AEConfig; import appeng.core.api.IIMCProcessor; @@ -61,50 +60,41 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +public class IMCGrinder implements IIMCProcessor { + @Override + public void process(final IMCMessage m) { + if (!AEConfig.instance.isFeatureEnabled(AEFeature.GrindStone)) + throw new IllegalStateException("Grindstone is disabled"); + final NBTTagCompound msg = m.getNBTValue(); + final NBTTagCompound inTag = (NBTTagCompound) msg.getTag("in"); + final NBTTagCompound outTag = (NBTTagCompound) msg.getTag("out"); + + final ItemStack in = ItemStack.loadItemStackFromNBT(inTag); + final ItemStack out = ItemStack.loadItemStackFromNBT(outTag); + + final int turns = msg.getInteger("turns"); + + if (in == null) { + throw new IllegalStateException("invalid input"); + } + + if (out == null) { + throw new IllegalStateException("invalid output"); + } + + if (msg.hasKey("optional")) { + final NBTTagCompound optionalTag = (NBTTagCompound) msg.getTag("optional"); + final ItemStack optional = ItemStack.loadItemStackFromNBT(optionalTag); + + if (optional == null) { + throw new IllegalStateException("invalid optional"); + } + + final float chance = msg.getFloat("chance"); -public class IMCGrinder implements IIMCProcessor -{ - @Override - public void process( final IMCMessage m ) - { - if ( !AEConfig.instance.isFeatureEnabled( AEFeature.GrindStone ) ) - throw new IllegalStateException( "Grindstone is disabled" ); - final NBTTagCompound msg = m.getNBTValue(); - final NBTTagCompound inTag = (NBTTagCompound) msg.getTag( "in" ); - final NBTTagCompound outTag = (NBTTagCompound) msg.getTag( "out" ); - - final ItemStack in = ItemStack.loadItemStackFromNBT( inTag ); - final ItemStack out = ItemStack.loadItemStackFromNBT( outTag ); - - final int turns = msg.getInteger( "turns" ); - - if( in == null ) - { - throw new IllegalStateException( "invalid input" ); - } - - if( out == null ) - { - throw new IllegalStateException( "invalid output" ); - } - - if( msg.hasKey( "optional" ) ) - { - final NBTTagCompound optionalTag = (NBTTagCompound) msg.getTag( "optional" ); - final ItemStack optional = ItemStack.loadItemStackFromNBT( optionalTag ); - - if( optional == null ) - { - throw new IllegalStateException( "invalid optional" ); - } - - final float chance = msg.getFloat( "chance" ); - - AEApi.instance().registries().grinder().addRecipe( in, out, optional, chance, turns ); - } - else - { - AEApi.instance().registries().grinder().addRecipe( in, out, turns ); - } - } + AEApi.instance().registries().grinder().addRecipe(in, out, optional, chance, turns); + } else { + AEApi.instance().registries().grinder().addRecipe(in, out, turns); + } + } } diff --git a/src/main/java/appeng/core/api/imc/IMCMatterCannon.java b/src/main/java/appeng/core/api/imc/IMCMatterCannon.java index cf3171caec5..8e9e42ba513 100644 --- a/src/main/java/appeng/core/api/imc/IMCMatterCannon.java +++ b/src/main/java/appeng/core/api/imc/IMCMatterCannon.java @@ -18,44 +18,39 @@ /* Example: - NBTTagCompound msg = new NBTTagCompound(); - NBTTagCompound item = new NBTTagCompound(); +NBTTagCompound msg = new NBTTagCompound(); +NBTTagCompound item = new NBTTagCompound(); - new ItemStack( Blocks.anvil ).writeToNBT( item ); - msg.setTag( "item", item ); - msg.setDouble( "weight", 32.0 ); +new ItemStack( Blocks.anvil ).writeToNBT( item ); +msg.setTag( "item", item ); +msg.setDouble( "weight", 32.0 ); - FMLInterModComms.sendMessage( "appliedenergistics2", "add-mattercannon-ammo", msg ); +FMLInterModComms.sendMessage( "appliedenergistics2", "add-mattercannon-ammo", msg ); - */ +*/ package appeng.core.api.imc; - import appeng.api.AEApi; import appeng.core.api.IIMCProcessor; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +public class IMCMatterCannon implements IIMCProcessor { -public class IMCMatterCannon implements IIMCProcessor -{ - - @Override - public void process( final IMCMessage m ) - { - final NBTTagCompound msg = m.getNBTValue(); - final NBTTagCompound item = (NBTTagCompound) msg.getTag( "item" ); + @Override + public void process(final IMCMessage m) { + final NBTTagCompound msg = m.getNBTValue(); + final NBTTagCompound item = (NBTTagCompound) msg.getTag("item"); - final ItemStack ammo = ItemStack.loadItemStackFromNBT( item ); - final double weight = msg.getDouble( "weight" ); + final ItemStack ammo = ItemStack.loadItemStackFromNBT(item); + final double weight = msg.getDouble("weight"); - if( ammo == null ) - { - throw new IllegalStateException( "invalid item in message " + m ); - } + if (ammo == null) { + throw new IllegalStateException("invalid item in message " + m); + } - AEApi.instance().registries().matterCannon().registerAmmo( ammo, weight ); - } + AEApi.instance().registries().matterCannon().registerAmmo(ammo, weight); + } } diff --git a/src/main/java/appeng/core/api/imc/IMCP2PAttunement.java b/src/main/java/appeng/core/api/imc/IMCP2PAttunement.java index c32bf22d0f8..ed49ed75652 100644 --- a/src/main/java/appeng/core/api/imc/IMCP2PAttunement.java +++ b/src/main/java/appeng/core/api/imc/IMCP2PAttunement.java @@ -18,53 +18,45 @@ /* Example: - FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-me", new ItemStack( myBlockOrItem ) ); - FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-bc-power", new ItemStack( myBlockOrItem ) ); - FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-ic2-power", new ItemStack( myBlockOrItem ) ); - FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-redstone", new ItemStack( myBlockOrItem ) ); - FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-fluid", new ItemStack( myBlockOrItem ) ); - FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-item", new ItemStack( myBlockOrItem ) ); +FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-me", new ItemStack( myBlockOrItem ) ); +FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-bc-power", new ItemStack( myBlockOrItem ) ); +FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-ic2-power", new ItemStack( myBlockOrItem ) ); +FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-redstone", new ItemStack( myBlockOrItem ) ); +FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-fluid", new ItemStack( myBlockOrItem ) ); +FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-item", new ItemStack( myBlockOrItem ) ); - */ +*/ package appeng.core.api.imc; - import appeng.api.AEApi; import appeng.api.config.TunnelType; import appeng.core.api.IIMCProcessor; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; -import net.minecraft.item.ItemStack; - import java.util.Arrays; import java.util.Locale; +import net.minecraft.item.ItemStack; - -public class IMCP2PAttunement implements IIMCProcessor -{ - - @Override - public void process( final IMCMessage m ) - { - final String key = m.key.substring( "add-p2p-attunement-".length() ).replace( '-', '_' ).toUpperCase( Locale.ENGLISH ); - - final TunnelType type = TunnelType.valueOf( key ); - - if( type != null ) - { - final ItemStack is = m.getItemStackValue(); - if( is != null ) - { - AEApi.instance().registries().p2pTunnel().addNewAttunement( is, type ); - } - else - { - throw new IllegalStateException( "invalid item in message " + m ); - } - } - else - { - throw new IllegalStateException( "invalid type in message " + m + " is not contained in " + Arrays.toString( TunnelType.values() ) ); - } - } +public class IMCP2PAttunement implements IIMCProcessor { + + @Override + public void process(final IMCMessage m) { + final String key = m.key.substring("add-p2p-attunement-".length()) + .replace('-', '_') + .toUpperCase(Locale.ENGLISH); + + final TunnelType type = TunnelType.valueOf(key); + + if (type != null) { + final ItemStack is = m.getItemStackValue(); + if (is != null) { + AEApi.instance().registries().p2pTunnel().addNewAttunement(is, type); + } else { + throw new IllegalStateException("invalid item in message " + m); + } + } else { + throw new IllegalStateException( + "invalid type in message " + m + " is not contained in " + Arrays.toString(TunnelType.values())); + } + } } diff --git a/src/main/java/appeng/core/api/imc/IMCSpatial.java b/src/main/java/appeng/core/api/imc/IMCSpatial.java index ce46885d716..f2445cdf293 100644 --- a/src/main/java/appeng/core/api/imc/IMCSpatial.java +++ b/src/main/java/appeng/core/api/imc/IMCSpatial.java @@ -18,34 +18,27 @@ /* Example: - FMLInterModComms.sendMessage( "appliedenergistics2", "whitelist-spatial", "mymod.tileentities.MyTileEntity" ); +FMLInterModComms.sendMessage( "appliedenergistics2", "whitelist-spatial", "mymod.tileentities.MyTileEntity" ); - */ +*/ package appeng.core.api.imc; - import appeng.api.AEApi; import appeng.core.AELog; import appeng.core.api.IIMCProcessor; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; +public class IMCSpatial implements IIMCProcessor { -public class IMCSpatial implements IIMCProcessor -{ - - @Override - public void process( final IMCMessage m ) - { + @Override + public void process(final IMCMessage m) { - try - { - final Class classInstance = Class.forName( m.getStringValue() ); - AEApi.instance().registries().movable().whiteListTileEntity( classInstance ); - } - catch( final ClassNotFoundException e ) - { - AELog.info( "Bad Class Registered: " + m.getStringValue() + " by " + m.getSender() ); - } - } + try { + final Class classInstance = Class.forName(m.getStringValue()); + AEApi.instance().registries().movable().whiteListTileEntity(classInstance); + } catch (final ClassNotFoundException e) { + AELog.info("Bad Class Registered: " + m.getStringValue() + " by " + m.getSender()); + } + } } diff --git a/src/main/java/appeng/core/crash/BaseCrashEnhancement.java b/src/main/java/appeng/core/crash/BaseCrashEnhancement.java index d19ed92d0a2..b710b4fa242 100644 --- a/src/main/java/appeng/core/crash/BaseCrashEnhancement.java +++ b/src/main/java/appeng/core/crash/BaseCrashEnhancement.java @@ -18,30 +18,24 @@ package appeng.core.crash; - import cpw.mods.fml.common.ICrashCallable; +abstract class BaseCrashEnhancement implements ICrashCallable { + private final String name; + private final String value; -abstract class BaseCrashEnhancement implements ICrashCallable -{ - private final String name; - private final String value; - - public BaseCrashEnhancement( final String name, final String value ) - { - this.name = name; - this.value = value; - } + public BaseCrashEnhancement(final String name, final String value) { + this.name = name; + this.value = value; + } - @Override - public final String call() throws Exception - { - return this.value; - } + @Override + public final String call() throws Exception { + return this.value; + } - @Override - public final String getLabel() - { - return this.name; - } + @Override + public final String getLabel() { + return this.name; + } } diff --git a/src/main/java/appeng/core/crash/CrashInfo.java b/src/main/java/appeng/core/crash/CrashInfo.java index 7a25618f17b..ba9a23c6b0d 100644 --- a/src/main/java/appeng/core/crash/CrashInfo.java +++ b/src/main/java/appeng/core/crash/CrashInfo.java @@ -18,8 +18,7 @@ package appeng.core.crash; - -public enum CrashInfo -{ - MOD_VERSION, INTEGRATION +public enum CrashInfo { + MOD_VERSION, + INTEGRATION } diff --git a/src/main/java/appeng/core/crash/IntegrationCrashEnhancement.java b/src/main/java/appeng/core/crash/IntegrationCrashEnhancement.java index 72cbde527d8..daa8de1252d 100644 --- a/src/main/java/appeng/core/crash/IntegrationCrashEnhancement.java +++ b/src/main/java/appeng/core/crash/IntegrationCrashEnhancement.java @@ -1,13 +1,9 @@ package appeng.core.crash; - import appeng.integration.IntegrationRegistry; - -public class IntegrationCrashEnhancement extends BaseCrashEnhancement -{ - public IntegrationCrashEnhancement() - { - super( "AE2 Integration", IntegrationRegistry.INSTANCE.getStatus() ); - } +public class IntegrationCrashEnhancement extends BaseCrashEnhancement { + public IntegrationCrashEnhancement() { + super("AE2 Integration", IntegrationRegistry.INSTANCE.getStatus()); + } } diff --git a/src/main/java/appeng/core/crash/ModCrashEnhancement.java b/src/main/java/appeng/core/crash/ModCrashEnhancement.java index 302dbbf56d6..38122ea846b 100644 --- a/src/main/java/appeng/core/crash/ModCrashEnhancement.java +++ b/src/main/java/appeng/core/crash/ModCrashEnhancement.java @@ -1,19 +1,16 @@ package appeng.core.crash; - import appeng.core.AEConfig; +public class ModCrashEnhancement extends BaseCrashEnhancement { + private static final String MOD_VERSION = AEConfig.VERSION + " for Forge " + // WHAT? + net.minecraftforge.common.ForgeVersion.majorVersion + + '.' // majorVersion + + net.minecraftforge.common.ForgeVersion.minorVersion + '.' // minorVersion + + net.minecraftforge.common.ForgeVersion.revisionVersion + '.' // revisionVersion + + net.minecraftforge.common.ForgeVersion.buildVersion; -public class ModCrashEnhancement extends BaseCrashEnhancement -{ - private static final String MOD_VERSION = AEConfig.VERSION + " for Forge " + // WHAT? - net.minecraftforge.common.ForgeVersion.majorVersion + '.' // majorVersion - + net.minecraftforge.common.ForgeVersion.minorVersion + '.' // minorVersion - + net.minecraftforge.common.ForgeVersion.revisionVersion + '.' // revisionVersion - + net.minecraftforge.common.ForgeVersion.buildVersion; - - public ModCrashEnhancement( final CrashInfo output ) - { - super( "AE2 Version", MOD_VERSION ); - } + public ModCrashEnhancement(final CrashInfo output) { + super("AE2 Version", MOD_VERSION); + } } diff --git a/src/main/java/appeng/core/features/AEBlockFeatureHandler.java b/src/main/java/appeng/core/features/AEBlockFeatureHandler.java index 73759533018..89fd6a9d40b 100644 --- a/src/main/java/appeng/core/features/AEBlockFeatureHandler.java +++ b/src/main/java/appeng/core/features/AEBlockFeatureHandler.java @@ -18,60 +18,52 @@ package appeng.core.features; - import appeng.api.definitions.IBlockDefinition; import appeng.block.AEBaseBlock; import appeng.core.CreativeTab; import com.google.common.base.Optional; import cpw.mods.fml.common.registry.GameRegistry; - import java.util.EnumSet; +public final class AEBlockFeatureHandler implements IFeatureHandler { + private final AEBaseBlock featured; + private final FeatureNameExtractor extractor; + private final boolean enabled; + private final BlockDefinition definition; -public final class AEBlockFeatureHandler implements IFeatureHandler -{ - private final AEBaseBlock featured; - private final FeatureNameExtractor extractor; - private final boolean enabled; - private final BlockDefinition definition; - - public AEBlockFeatureHandler( final EnumSet features, final AEBaseBlock featured, final Optional subName ) - { - final ActivityState state = new FeaturedActiveChecker( features ).getActivityState(); + public AEBlockFeatureHandler( + final EnumSet features, final AEBaseBlock featured, final Optional subName) { + final ActivityState state = new FeaturedActiveChecker(features).getActivityState(); - this.featured = featured; - this.extractor = new FeatureNameExtractor( featured.getClass(), subName ); - this.enabled = state == ActivityState.Enabled; - this.definition = new BlockDefinition( featured, state ); - } + this.featured = featured; + this.extractor = new FeatureNameExtractor(featured.getClass(), subName); + this.enabled = state == ActivityState.Enabled; + this.definition = new BlockDefinition(featured, state); + } - @Override - public boolean isFeatureAvailable() - { - return this.enabled; - } + @Override + public boolean isFeatureAvailable() { + return this.enabled; + } - @Override - public IBlockDefinition getDefinition() - { - return this.definition; - } + @Override + public IBlockDefinition getDefinition() { + return this.definition; + } - @Override - public void register() - { - if( this.enabled ) - { - final String name = this.extractor.get(); - this.featured.setCreativeTab( CreativeTab.instance ); - this.featured.setBlockName( /* "tile." */"appliedenergistics2." + name ); - this.featured.setBlockTextureName( "appliedenergistics2:" + name ); + @Override + public void register() { + if (this.enabled) { + final String name = this.extractor.get(); + this.featured.setCreativeTab(CreativeTab.instance); + this.featured.setBlockName(/* "tile." */ "appliedenergistics2." + name); + this.featured.setBlockTextureName("appliedenergistics2:" + name); - final String registryName = "tile." + name; + final String registryName = "tile." + name; - // Bypass the forge magic with null to register our own itemblock later. - GameRegistry.registerBlock( this.featured, null, registryName ); - GameRegistry.registerItem( this.definition.maybeItem().get(), registryName ); - } - } + // Bypass the forge magic with null to register our own itemblock later. + GameRegistry.registerBlock(this.featured, null, registryName); + GameRegistry.registerItem(this.definition.maybeItem().get(), registryName); + } + } } diff --git a/src/main/java/appeng/core/features/AECableBusFeatureHandler.java b/src/main/java/appeng/core/features/AECableBusFeatureHandler.java index dd904d4fc50..7c9349c1c13 100644 --- a/src/main/java/appeng/core/features/AECableBusFeatureHandler.java +++ b/src/main/java/appeng/core/features/AECableBusFeatureHandler.java @@ -18,7 +18,6 @@ package appeng.core.features; - import appeng.api.definitions.ITileDefinition; import appeng.block.AEBaseTileBlock; import appeng.block.networking.BlockCableBus; @@ -27,63 +26,55 @@ import appeng.util.Platform; import com.google.common.base.Optional; import cpw.mods.fml.common.registry.GameRegistry; -import net.minecraft.tileentity.TileEntity; - import java.util.EnumSet; +import net.minecraft.tileentity.TileEntity; +public final class AECableBusFeatureHandler implements IFeatureHandler { + private final AEBaseTileBlock featured; + private final FeatureNameExtractor extractor; + private final boolean enabled; + private final TileDefinition definition; -public final class AECableBusFeatureHandler implements IFeatureHandler -{ - private final AEBaseTileBlock featured; - private final FeatureNameExtractor extractor; - private final boolean enabled; - private final TileDefinition definition; - - public AECableBusFeatureHandler( final EnumSet features, final BlockCableBus featured, final Optional subName ) - { - final ActivityState state = new FeaturedActiveChecker( features ).getActivityState(); + public AECableBusFeatureHandler( + final EnumSet features, final BlockCableBus featured, final Optional subName) { + final ActivityState state = new FeaturedActiveChecker(features).getActivityState(); - this.featured = featured; - this.extractor = new FeatureNameExtractor( featured.getClass(), subName ); - this.enabled = state == ActivityState.Enabled; - this.definition = new TileDefinition( featured, state ); - } + this.featured = featured; + this.extractor = new FeatureNameExtractor(featured.getClass(), subName); + this.enabled = state == ActivityState.Enabled; + this.definition = new TileDefinition(featured, state); + } - @Override - public boolean isFeatureAvailable() - { - return this.enabled; - } + @Override + public boolean isFeatureAvailable() { + return this.enabled; + } - @Override - public ITileDefinition getDefinition() - { - return this.definition; - } + @Override + public ITileDefinition getDefinition() { + return this.definition; + } - /** - * Registration of the {@link TileEntity} will actually be handled by {@link BlockCableBus#setupTile()}. - */ - @Override - public void register() - { - if( this.enabled ) - { - final String name = this.extractor.get(); - this.featured.setCreativeTab( CreativeTab.instance ); - this.featured.setBlockName( /* "tile." */"appliedenergistics2." + name ); - this.featured.setBlockTextureName( "appliedenergistics2:" + name ); + /** + * Registration of the {@link TileEntity} will actually be handled by {@link BlockCableBus#setupTile()}. + */ + @Override + public void register() { + if (this.enabled) { + final String name = this.extractor.get(); + this.featured.setCreativeTab(CreativeTab.instance); + this.featured.setBlockName(/* "tile." */ "appliedenergistics2." + name); + this.featured.setBlockTextureName("appliedenergistics2:" + name); - if( Platform.isClient() ) - { - CommonHelper.proxy.bindTileEntitySpecialRenderer( this.featured.getTileEntityClass(), this.featured ); - } + if (Platform.isClient()) { + CommonHelper.proxy.bindTileEntitySpecialRenderer(this.featured.getTileEntityClass(), this.featured); + } - final String registryName = "tile." + name; + final String registryName = "tile." + name; - // Bypass the forge magic with null to register our own itemblock later. - GameRegistry.registerBlock( this.featured, null, registryName ); - GameRegistry.registerItem( this.definition.maybeItem().get(), registryName ); - } - } + // Bypass the forge magic with null to register our own itemblock later. + GameRegistry.registerBlock(this.featured, null, registryName); + GameRegistry.registerItem(this.definition.maybeItem().get(), registryName); + } + } } diff --git a/src/main/java/appeng/core/features/AEFeature.java b/src/main/java/appeng/core/features/AEFeature.java index 5379ec8d679..c8821e8c2af 100644 --- a/src/main/java/appeng/core/features/AEFeature.java +++ b/src/main/java/appeng/core/features/AEFeature.java @@ -18,171 +18,164 @@ package appeng.core.features; - -public enum AEFeature -{ - // stuff that has no reason for ever being turned off, or that - // is just flat out required by tons of - // important stuff. - Core( null ) - { - @Override - public boolean isVisible() - { - return false; - } - }, - - CertusQuartzWorldGen( Constants.CATEGORY_WORLD ), - MeteoriteWorldGen( Constants.CATEGORY_WORLD ), - DecorativeLights( Constants.CATEGORY_WORLD ), - DecorativeQuartzBlocks( Constants.CATEGORY_WORLD ), - SkyStoneChests( Constants.CATEGORY_WORLD ), - SpawnPressesInMeteorites( Constants.CATEGORY_WORLD ), - GrindStone( Constants.CATEGORY_WORLD ), - Flour( Constants.CATEGORY_WORLD ), - Inscriber( Constants.CATEGORY_WORLD ), - ChestLoot( Constants.CATEGORY_WORLD ), - VillagerTrading( Constants.CATEGORY_WORLD ), - TinyTNT( Constants.CATEGORY_WORLD ), - - PoweredTools( Constants.CATEGORY_TOOLS_CLASSIFICATIONS ), - CertusQuartzTools( Constants.CATEGORY_TOOLS_CLASSIFICATIONS ), - NetherQuartzTools( Constants.CATEGORY_TOOLS_CLASSIFICATIONS ), - - QuartzHoe( Constants.CATEGORY_TOOLS ), - QuartzSpade( Constants.CATEGORY_TOOLS ), - QuartzSword( Constants.CATEGORY_TOOLS ), - QuartzPickaxe( Constants.CATEGORY_TOOLS ), - QuartzAxe( Constants.CATEGORY_TOOLS ), - QuartzKnife( Constants.CATEGORY_TOOLS ), - QuartzWrench( Constants.CATEGORY_TOOLS ), - ChargedStaff( Constants.CATEGORY_TOOLS ), - EntropyManipulator( Constants.CATEGORY_TOOLS ), - MatterCannon( Constants.CATEGORY_TOOLS ), - WirelessAccessTerminal( Constants.CATEGORY_TOOLS ), - ColorApplicator( Constants.CATEGORY_TOOLS ), - MeteoriteCompass( Constants.CATEGORY_TOOLS ), - - PowerGen( Constants.CATEGORY_NETWORK_FEATURES ), - Security( Constants.CATEGORY_NETWORK_FEATURES ), - SpatialIO( Constants.CATEGORY_NETWORK_FEATURES ), - QuantumNetworkBridge( Constants.CATEGORY_NETWORK_FEATURES ), - Channels( Constants.CATEGORY_NETWORK_FEATURES ), - - LevelEmitter( Constants.CATEGORY_NETWORK_BUSES ), - CraftingTerminal( Constants.CATEGORY_NETWORK_BUSES ), - StorageMonitor( Constants.CATEGORY_NETWORK_BUSES ), - P2PTunnel( Constants.CATEGORY_NETWORK_BUSES ), - FormationPlane( Constants.CATEGORY_NETWORK_BUSES ), - AnnihilationPlane( Constants.CATEGORY_NETWORK_BUSES ), - IdentityAnnihilationPlane( Constants.CATEGORY_NETWORK_BUSES ), - ImportBus( Constants.CATEGORY_NETWORK_BUSES ), - ExportBus( Constants.CATEGORY_NETWORK_BUSES ), - StorageBus( Constants.CATEGORY_NETWORK_BUSES ), - PartConversionMonitor( Constants.CATEGORY_NETWORK_BUSES ), - - PortableCell( Constants.CATEGORY_PORTABLE_CELL ), - - StorageCells( Constants.CATEGORY_STORAGE ), - MEChest( Constants.CATEGORY_STORAGE ), - MEDrive( Constants.CATEGORY_STORAGE ), - IOPort( Constants.CATEGORY_STORAGE ), - - NetworkTool( Constants.CATEGORY_NETWORK_TOOL ), - - DenseEnergyCells( Constants.CATEGORY_HIGHER_CAPACITY ), - DenseCables( Constants.CATEGORY_HIGHER_CAPACITY ), - - P2PTunnelRF( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelME( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelItems( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelRedstone( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelEU( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelLiquids( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelLight( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelOpenComputers( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelPressure( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelGregtech( Constants.CATEGORY_P2P_TUNNELS ), - - MassCannonBlockDamage( Constants.CATEGORY_BLOCK_FEATURES ), - TinyTNTBlockDamage( Constants.CATEGORY_BLOCK_FEATURES ), - - Facades( Constants.CATEGORY_FACADES ), - - UnsupportedDeveloperTools( Constants.CATEGORY_MISC, false ), - Creative( Constants.CATEGORY_MISC ), - GrinderLogging( Constants.CATEGORY_MISC, false ), - Logging( Constants.CATEGORY_MISC ), - IntegrationLogging( Constants.CATEGORY_MISC, false ), - WebsiteRecipes( Constants.CATEGORY_MISC, false ), - LogSecurityAudits( Constants.CATEGORY_MISC, false ), - Achievements( Constants.CATEGORY_MISC ), - UpdateLogging( Constants.CATEGORY_MISC, false ), - PacketLogging( Constants.CATEGORY_MISC, false ), - CraftingLog( Constants.CATEGORY_MISC, false ), - LightDetector( Constants.CATEGORY_MISC ), - DebugLogging( Constants.CATEGORY_MISC, false ), - - EnableFacadeCrafting( Constants.CATEGORY_CRAFTING ), - InWorldSingularity( Constants.CATEGORY_CRAFTING ), - InWorldFluix( Constants.CATEGORY_CRAFTING ), - InWorldPurification( Constants.CATEGORY_CRAFTING ), - InterfaceTerminal( Constants.CATEGORY_CRAFTING ), - EnableDisassemblyCrafting( Constants.CATEGORY_CRAFTING ), - - AlphaPass( Constants.CATEGORY_RENDERING ), PaintBalls( Constants.CATEGORY_TOOLS ), - - MolecularAssembler( Constants.CATEGORY_CRAFTING_FEATURES ), - Patterns( Constants.CATEGORY_CRAFTING_FEATURES ), - CraftingCPU( Constants.CATEGORY_CRAFTING_FEATURES ), - - ChunkLoggerTrace( Constants.CATEGORY_COMMANDS, false ); - - public final String category; - public final boolean defaultValue; - - AEFeature( final String cat ) - { - this( cat, true ); - } - - AEFeature( final String cat, final boolean defaultValue ) - { - this.category = cat; - this.defaultValue = defaultValue; - } - - /** - * override to set visibility - * - * @return default true - */ - public boolean isVisible() - { - return true; - } - - private enum Constants - { - ; - - private static final String CATEGORY_MISC = "Misc"; - private static final String CATEGORY_CRAFTING = "Crafting"; - private static final String CATEGORY_WORLD = "World"; - private static final String CATEGORY_TOOLS = "Tools"; - private static final String CATEGORY_TOOLS_CLASSIFICATIONS = "ToolsClassifications"; - private static final String CATEGORY_NETWORK_BUSES = "NetworkBuses"; - private static final String CATEGORY_P2P_TUNNELS = "P2PTunnels"; - private static final String CATEGORY_BLOCK_FEATURES = "BlockFeatures"; - private static final String CATEGORY_CRAFTING_FEATURES = "CraftingFeatures"; - private static final String CATEGORY_STORAGE = "Storage"; - private static final String CATEGORY_HIGHER_CAPACITY = "HigherCapacity"; - private static final String CATEGORY_NETWORK_FEATURES = "NetworkFeatures"; - private static final String CATEGORY_COMMANDS = "Commands"; - private static final String CATEGORY_RENDERING = "Rendering"; - private static final String CATEGORY_FACADES = "Facades"; - private static final String CATEGORY_NETWORK_TOOL = "NetworkTool"; - private static final String CATEGORY_PORTABLE_CELL = "PortableCell"; - } +public enum AEFeature { + // stuff that has no reason for ever being turned off, or that + // is just flat out required by tons of + // important stuff. + Core(null) { + @Override + public boolean isVisible() { + return false; + } + }, + + CertusQuartzWorldGen(Constants.CATEGORY_WORLD), + MeteoriteWorldGen(Constants.CATEGORY_WORLD), + DecorativeLights(Constants.CATEGORY_WORLD), + DecorativeQuartzBlocks(Constants.CATEGORY_WORLD), + SkyStoneChests(Constants.CATEGORY_WORLD), + SpawnPressesInMeteorites(Constants.CATEGORY_WORLD), + GrindStone(Constants.CATEGORY_WORLD), + Flour(Constants.CATEGORY_WORLD), + Inscriber(Constants.CATEGORY_WORLD), + ChestLoot(Constants.CATEGORY_WORLD), + VillagerTrading(Constants.CATEGORY_WORLD), + TinyTNT(Constants.CATEGORY_WORLD), + + PoweredTools(Constants.CATEGORY_TOOLS_CLASSIFICATIONS), + CertusQuartzTools(Constants.CATEGORY_TOOLS_CLASSIFICATIONS), + NetherQuartzTools(Constants.CATEGORY_TOOLS_CLASSIFICATIONS), + + QuartzHoe(Constants.CATEGORY_TOOLS), + QuartzSpade(Constants.CATEGORY_TOOLS), + QuartzSword(Constants.CATEGORY_TOOLS), + QuartzPickaxe(Constants.CATEGORY_TOOLS), + QuartzAxe(Constants.CATEGORY_TOOLS), + QuartzKnife(Constants.CATEGORY_TOOLS), + QuartzWrench(Constants.CATEGORY_TOOLS), + ChargedStaff(Constants.CATEGORY_TOOLS), + EntropyManipulator(Constants.CATEGORY_TOOLS), + MatterCannon(Constants.CATEGORY_TOOLS), + WirelessAccessTerminal(Constants.CATEGORY_TOOLS), + ColorApplicator(Constants.CATEGORY_TOOLS), + MeteoriteCompass(Constants.CATEGORY_TOOLS), + + PowerGen(Constants.CATEGORY_NETWORK_FEATURES), + Security(Constants.CATEGORY_NETWORK_FEATURES), + SpatialIO(Constants.CATEGORY_NETWORK_FEATURES), + QuantumNetworkBridge(Constants.CATEGORY_NETWORK_FEATURES), + Channels(Constants.CATEGORY_NETWORK_FEATURES), + + LevelEmitter(Constants.CATEGORY_NETWORK_BUSES), + CraftingTerminal(Constants.CATEGORY_NETWORK_BUSES), + StorageMonitor(Constants.CATEGORY_NETWORK_BUSES), + P2PTunnel(Constants.CATEGORY_NETWORK_BUSES), + FormationPlane(Constants.CATEGORY_NETWORK_BUSES), + AnnihilationPlane(Constants.CATEGORY_NETWORK_BUSES), + IdentityAnnihilationPlane(Constants.CATEGORY_NETWORK_BUSES), + ImportBus(Constants.CATEGORY_NETWORK_BUSES), + ExportBus(Constants.CATEGORY_NETWORK_BUSES), + StorageBus(Constants.CATEGORY_NETWORK_BUSES), + PartConversionMonitor(Constants.CATEGORY_NETWORK_BUSES), + + PortableCell(Constants.CATEGORY_PORTABLE_CELL), + + StorageCells(Constants.CATEGORY_STORAGE), + MEChest(Constants.CATEGORY_STORAGE), + MEDrive(Constants.CATEGORY_STORAGE), + IOPort(Constants.CATEGORY_STORAGE), + + NetworkTool(Constants.CATEGORY_NETWORK_TOOL), + + DenseEnergyCells(Constants.CATEGORY_HIGHER_CAPACITY), + DenseCables(Constants.CATEGORY_HIGHER_CAPACITY), + + P2PTunnelRF(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelME(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelItems(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelRedstone(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelEU(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelLiquids(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelLight(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelOpenComputers(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelPressure(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelGregtech(Constants.CATEGORY_P2P_TUNNELS), + + MassCannonBlockDamage(Constants.CATEGORY_BLOCK_FEATURES), + TinyTNTBlockDamage(Constants.CATEGORY_BLOCK_FEATURES), + + Facades(Constants.CATEGORY_FACADES), + + UnsupportedDeveloperTools(Constants.CATEGORY_MISC, false), + Creative(Constants.CATEGORY_MISC), + GrinderLogging(Constants.CATEGORY_MISC, false), + Logging(Constants.CATEGORY_MISC), + IntegrationLogging(Constants.CATEGORY_MISC, false), + WebsiteRecipes(Constants.CATEGORY_MISC, false), + LogSecurityAudits(Constants.CATEGORY_MISC, false), + Achievements(Constants.CATEGORY_MISC), + UpdateLogging(Constants.CATEGORY_MISC, false), + PacketLogging(Constants.CATEGORY_MISC, false), + CraftingLog(Constants.CATEGORY_MISC, false), + LightDetector(Constants.CATEGORY_MISC), + DebugLogging(Constants.CATEGORY_MISC, false), + + EnableFacadeCrafting(Constants.CATEGORY_CRAFTING), + InWorldSingularity(Constants.CATEGORY_CRAFTING), + InWorldFluix(Constants.CATEGORY_CRAFTING), + InWorldPurification(Constants.CATEGORY_CRAFTING), + InterfaceTerminal(Constants.CATEGORY_CRAFTING), + EnableDisassemblyCrafting(Constants.CATEGORY_CRAFTING), + + AlphaPass(Constants.CATEGORY_RENDERING), + PaintBalls(Constants.CATEGORY_TOOLS), + + MolecularAssembler(Constants.CATEGORY_CRAFTING_FEATURES), + Patterns(Constants.CATEGORY_CRAFTING_FEATURES), + CraftingCPU(Constants.CATEGORY_CRAFTING_FEATURES), + + ChunkLoggerTrace(Constants.CATEGORY_COMMANDS, false); + + public final String category; + public final boolean defaultValue; + + AEFeature(final String cat) { + this(cat, true); + } + + AEFeature(final String cat, final boolean defaultValue) { + this.category = cat; + this.defaultValue = defaultValue; + } + + /** + * override to set visibility + * + * @return default true + */ + public boolean isVisible() { + return true; + } + + private enum Constants { + ; + + private static final String CATEGORY_MISC = "Misc"; + private static final String CATEGORY_CRAFTING = "Crafting"; + private static final String CATEGORY_WORLD = "World"; + private static final String CATEGORY_TOOLS = "Tools"; + private static final String CATEGORY_TOOLS_CLASSIFICATIONS = "ToolsClassifications"; + private static final String CATEGORY_NETWORK_BUSES = "NetworkBuses"; + private static final String CATEGORY_P2P_TUNNELS = "P2PTunnels"; + private static final String CATEGORY_BLOCK_FEATURES = "BlockFeatures"; + private static final String CATEGORY_CRAFTING_FEATURES = "CraftingFeatures"; + private static final String CATEGORY_STORAGE = "Storage"; + private static final String CATEGORY_HIGHER_CAPACITY = "HigherCapacity"; + private static final String CATEGORY_NETWORK_FEATURES = "NetworkFeatures"; + private static final String CATEGORY_COMMANDS = "Commands"; + private static final String CATEGORY_RENDERING = "Rendering"; + private static final String CATEGORY_FACADES = "Facades"; + private static final String CATEGORY_NETWORK_TOOL = "NetworkTool"; + private static final String CATEGORY_PORTABLE_CELL = "PortableCell"; + } } diff --git a/src/main/java/appeng/core/features/AETileBlockFeatureHandler.java b/src/main/java/appeng/core/features/AETileBlockFeatureHandler.java index 84e5b49d680..30199d5bc87 100644 --- a/src/main/java/appeng/core/features/AETileBlockFeatureHandler.java +++ b/src/main/java/appeng/core/features/AETileBlockFeatureHandler.java @@ -18,7 +18,6 @@ package appeng.core.features; - import appeng.api.definitions.ITileDefinition; import appeng.block.AEBaseTileBlock; import appeng.core.CommonHelper; @@ -27,61 +26,55 @@ import appeng.util.Platform; import com.google.common.base.Optional; import cpw.mods.fml.common.registry.GameRegistry; - import java.util.EnumSet; +public final class AETileBlockFeatureHandler implements IFeatureHandler { + private final AEBaseTileBlock featured; + private final FeatureNameExtractor extractor; + private final boolean enabled; + private final TileDefinition definition; -public final class AETileBlockFeatureHandler implements IFeatureHandler -{ - private final AEBaseTileBlock featured; - private final FeatureNameExtractor extractor; - private final boolean enabled; - private final TileDefinition definition; - - public AETileBlockFeatureHandler( final EnumSet features, final AEBaseTileBlock featured, final Optional subName ) - { - final ActivityState state = new FeaturedActiveChecker( features ).getActivityState(); + public AETileBlockFeatureHandler( + final EnumSet features, final AEBaseTileBlock featured, final Optional subName) { + final ActivityState state = new FeaturedActiveChecker(features).getActivityState(); - this.featured = featured; - this.extractor = new FeatureNameExtractor( featured.getClass(), subName ); - this.enabled = state == ActivityState.Enabled; - this.definition = new TileDefinition( featured, state ); - } + this.featured = featured; + this.extractor = new FeatureNameExtractor(featured.getClass(), subName); + this.enabled = state == ActivityState.Enabled; + this.definition = new TileDefinition(featured, state); + } - @Override - public boolean isFeatureAvailable() - { - return this.enabled; - } + @Override + public boolean isFeatureAvailable() { + return this.enabled; + } - @Override - public ITileDefinition getDefinition() - { - return this.definition; - } + @Override + public ITileDefinition getDefinition() { + return this.definition; + } - @Override - public void register() - { - if( this.enabled ) - { - final String name = this.extractor.get(); - this.featured.setCreativeTab( CreativeTab.instance ); - this.featured.setBlockName( /* "tile." */"appliedenergistics2." + name ); - this.featured.setBlockTextureName( "appliedenergistics2:" + name ); + @Override + public void register() { + if (this.enabled) { + final String name = this.extractor.get(); + this.featured.setCreativeTab(CreativeTab.instance); + this.featured.setBlockName(/* "tile." */ "appliedenergistics2." + name); + this.featured.setBlockTextureName("appliedenergistics2:" + name); - if( Platform.isClient() ) - { - CommonHelper.proxy.bindTileEntitySpecialRenderer( this.featured.getTileEntityClass(), this.featured ); - } + if (Platform.isClient()) { + CommonHelper.proxy.bindTileEntitySpecialRenderer(this.featured.getTileEntityClass(), this.featured); + } - final String registryName = "tile." + name; + final String registryName = "tile." + name; - // Bypass the forge magic with null to register our own itemblock later. - GameRegistry.registerBlock( this.featured, null, registryName ); - GameRegistry.registerItem( this.definition.maybeItem().get(), registryName ); - GameRegistry.registerTileEntity( this.featured.getTileEntityClass(), this.featured.toString() ); - AEBaseTile.registerTileItem( this.featured.getTileEntityClass(), new BlockStackSrc( this.featured, 0, ActivityState.from( this.isFeatureAvailable() ) ) ); - } - } + // Bypass the forge magic with null to register our own itemblock later. + GameRegistry.registerBlock(this.featured, null, registryName); + GameRegistry.registerItem(this.definition.maybeItem().get(), registryName); + GameRegistry.registerTileEntity(this.featured.getTileEntityClass(), this.featured.toString()); + AEBaseTile.registerTileItem( + this.featured.getTileEntityClass(), + new BlockStackSrc(this.featured, 0, ActivityState.from(this.isFeatureAvailable()))); + } + } } diff --git a/src/main/java/appeng/core/features/ActivityState.java b/src/main/java/appeng/core/features/ActivityState.java index 1c4f71d157b..7c25adbf739 100644 --- a/src/main/java/appeng/core/features/ActivityState.java +++ b/src/main/java/appeng/core/features/ActivityState.java @@ -18,21 +18,15 @@ package appeng.core.features; +public enum ActivityState { + Enabled, + Disabled; -public enum ActivityState -{ - Enabled, - Disabled; - - public static ActivityState from( final boolean enabled ) - { - if( enabled ) - { - return ActivityState.Enabled; - } - else - { - return ActivityState.Disabled; - } - } + public static ActivityState from(final boolean enabled) { + if (enabled) { + return ActivityState.Enabled; + } else { + return ActivityState.Disabled; + } + } } diff --git a/src/main/java/appeng/core/features/BlockDefinition.java b/src/main/java/appeng/core/features/BlockDefinition.java index 3be8f567d82..688028f4bc8 100644 --- a/src/main/java/appeng/core/features/BlockDefinition.java +++ b/src/main/java/appeng/core/features/BlockDefinition.java @@ -18,157 +18,131 @@ package appeng.core.features; - import appeng.api.definitions.IBlockDefinition; import appeng.block.AEBaseBlock; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ObjectArrays; +import java.lang.reflect.Constructor; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; -import java.lang.reflect.Constructor; - - -public class BlockDefinition extends ItemDefinition implements IBlockDefinition -{ - private static final ItemBlockTransformer ITEMBLOCK_TRANSFORMER = new ItemBlockTransformer(); - private final Optional block; - - public BlockDefinition( final Block block, final ActivityState state ) - { - super( constructItemFromBlock( block ), state ); - - Preconditions.checkNotNull( block ); - Preconditions.checkNotNull( state ); - - if( state == ActivityState.Enabled ) - { - this.block = Optional.of( block ); - } - else - { - this.block = Optional.absent(); - } - } - - /** - * Create an {@link ItemBlock} from a {@link Block} to register it later as {@link Item} - * - * @param block source block - * @return item from block - */ - private static Item constructItemFromBlock( final Block block ) - { - final Class itemclass = getItemBlockConstructor( block ); - return constructItemBlock( block, itemclass ); - } - - /** - * Returns the constructor to use. - *

- * Either {@link ItemBlock} or in case of an {@link AEBaseBlock} the class returned by - * AEBaseBlock.getItemBlockClass(). - * - * @param block the block used to determine the used constructor. - * @return a {@link Class} extending ItemBlock - */ - private static Class getItemBlockConstructor( final Block block ) - { - if( block instanceof AEBaseBlock ) - { - final AEBaseBlock aeBaseBlock = (AEBaseBlock) block; - return aeBaseBlock.getItemBlockClass(); - } - - return ItemBlock.class; - } - - /** - * Actually construct an instance of {@link Item} with the block and earlier determined constructor. - *

- * Shamelessly stolen from the forge magic. - *

- * TODO: throw an exception instead of returning null? As this could cause issue later on. - * - * @param block the block to create the {@link ItemBlock} from - * @param itemclass the class used to construct it. - * @return an {@link Item} for the block. Actually always a sub type of {@link ItemBlock} - */ - private static Item constructItemBlock( final Block block, final Class itemclass ) - { - try - { - final Object[] itemCtorArgs = {}; - final Class[] ctorArgClasses = new Class[itemCtorArgs.length + 1]; - ctorArgClasses[0] = Block.class; - for( int idx = 1; idx < ctorArgClasses.length; idx++ ) - { - ctorArgClasses[idx] = itemCtorArgs[idx - 1].getClass(); - } - - final Constructor itemCtor = itemclass.getConstructor( ctorArgClasses ); - return itemCtor.newInstance( ObjectArrays.concat( block, itemCtorArgs ) ); - } - catch( final Throwable t ) - { - return null; - } - } - - @Override - public final Optional maybeBlock() - { - return this.block; - } - - @Override - public final Optional maybeItemBlock() - { - return this.block.transform( ITEMBLOCK_TRANSFORMER ); - } - - @Override - public final Optional maybeStack( final int stackSize ) - { - return this.block.transform( new ItemStackTransformer( stackSize ) ); - } - - @Override - public final boolean isSameAs( final IBlockAccess world, final int x, final int y, final int z ) - { - return this.isEnabled() && world.getBlock( x, y, z ) == this.block.get(); - } - - private static class ItemBlockTransformer implements Function - { - @Override - public ItemBlock apply( final Block input ) - { - return new ItemBlock( input ); - } - } - - - private static class ItemStackTransformer implements Function - { - private final int stackSize; - - public ItemStackTransformer( final int stackSize ) - { - Preconditions.checkArgument( stackSize > 0 ); - - this.stackSize = stackSize; - } - - @Override - public ItemStack apply( final Block input ) - { - return new ItemStack( input, this.stackSize ); - } - } +public class BlockDefinition extends ItemDefinition implements IBlockDefinition { + private static final ItemBlockTransformer ITEMBLOCK_TRANSFORMER = new ItemBlockTransformer(); + private final Optional block; + + public BlockDefinition(final Block block, final ActivityState state) { + super(constructItemFromBlock(block), state); + + Preconditions.checkNotNull(block); + Preconditions.checkNotNull(state); + + if (state == ActivityState.Enabled) { + this.block = Optional.of(block); + } else { + this.block = Optional.absent(); + } + } + + /** + * Create an {@link ItemBlock} from a {@link Block} to register it later as {@link Item} + * + * @param block source block + * @return item from block + */ + private static Item constructItemFromBlock(final Block block) { + final Class itemclass = getItemBlockConstructor(block); + return constructItemBlock(block, itemclass); + } + + /** + * Returns the constructor to use. + *

+ * Either {@link ItemBlock} or in case of an {@link AEBaseBlock} the class returned by + * AEBaseBlock.getItemBlockClass(). + * + * @param block the block used to determine the used constructor. + * @return a {@link Class} extending ItemBlock + */ + private static Class getItemBlockConstructor(final Block block) { + if (block instanceof AEBaseBlock) { + final AEBaseBlock aeBaseBlock = (AEBaseBlock) block; + return aeBaseBlock.getItemBlockClass(); + } + + return ItemBlock.class; + } + + /** + * Actually construct an instance of {@link Item} with the block and earlier determined constructor. + *

+ * Shamelessly stolen from the forge magic. + *

+ * TODO: throw an exception instead of returning null? As this could cause issue later on. + * + * @param block the block to create the {@link ItemBlock} from + * @param itemclass the class used to construct it. + * @return an {@link Item} for the block. Actually always a sub type of {@link ItemBlock} + */ + private static Item constructItemBlock(final Block block, final Class itemclass) { + try { + final Object[] itemCtorArgs = {}; + final Class[] ctorArgClasses = new Class[itemCtorArgs.length + 1]; + ctorArgClasses[0] = Block.class; + for (int idx = 1; idx < ctorArgClasses.length; idx++) { + ctorArgClasses[idx] = itemCtorArgs[idx - 1].getClass(); + } + + final Constructor itemCtor = itemclass.getConstructor(ctorArgClasses); + return itemCtor.newInstance(ObjectArrays.concat(block, itemCtorArgs)); + } catch (final Throwable t) { + return null; + } + } + + @Override + public final Optional maybeBlock() { + return this.block; + } + + @Override + public final Optional maybeItemBlock() { + return this.block.transform(ITEMBLOCK_TRANSFORMER); + } + + @Override + public final Optional maybeStack(final int stackSize) { + return this.block.transform(new ItemStackTransformer(stackSize)); + } + + @Override + public final boolean isSameAs(final IBlockAccess world, final int x, final int y, final int z) { + return this.isEnabled() && world.getBlock(x, y, z) == this.block.get(); + } + + private static class ItemBlockTransformer implements Function { + @Override + public ItemBlock apply(final Block input) { + return new ItemBlock(input); + } + } + + private static class ItemStackTransformer implements Function { + private final int stackSize; + + public ItemStackTransformer(final int stackSize) { + Preconditions.checkArgument(stackSize > 0); + + this.stackSize = stackSize; + } + + @Override + public ItemStack apply(final Block input) { + return new ItemStack(input, this.stackSize); + } + } } diff --git a/src/main/java/appeng/core/features/BlockStackSrc.java b/src/main/java/appeng/core/features/BlockStackSrc.java index 382d3bc8fc4..93a2f1551d6 100644 --- a/src/main/java/appeng/core/features/BlockStackSrc.java +++ b/src/main/java/appeng/core/features/BlockStackSrc.java @@ -18,56 +18,47 @@ package appeng.core.features; - import com.google.common.base.Preconditions; +import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import javax.annotation.Nullable; - - -public class BlockStackSrc implements IStackSrc -{ +public class BlockStackSrc implements IStackSrc { - private final Block block; - private final int damage; - private final boolean enabled; + private final Block block; + private final int damage; + private final boolean enabled; - public BlockStackSrc( final Block block, final int damage, final ActivityState state ) - { - Preconditions.checkNotNull( block ); - Preconditions.checkArgument( damage >= 0 ); - Preconditions.checkNotNull( state ); - Preconditions.checkArgument( state == ActivityState.Enabled || state == ActivityState.Disabled ); + public BlockStackSrc(final Block block, final int damage, final ActivityState state) { + Preconditions.checkNotNull(block); + Preconditions.checkArgument(damage >= 0); + Preconditions.checkNotNull(state); + Preconditions.checkArgument(state == ActivityState.Enabled || state == ActivityState.Disabled); - this.block = block; - this.damage = damage; - this.enabled = state == ActivityState.Enabled; - } + this.block = block; + this.damage = damage; + this.enabled = state == ActivityState.Enabled; + } - @Nullable - @Override - public ItemStack stack( final int i ) - { - return new ItemStack( this.block, i, this.damage ); - } + @Nullable + @Override + public ItemStack stack(final int i) { + return new ItemStack(this.block, i, this.damage); + } - @Override - public Item getItem() - { - return null; - } + @Override + public Item getItem() { + return null; + } - @Override - public int getDamage() - { - return this.damage; - } + @Override + public int getDamage() { + return this.damage; + } - @Override - public boolean isEnabled() - { - return this.enabled; - } + @Override + public boolean isEnabled() { + return this.enabled; + } } diff --git a/src/main/java/appeng/core/features/ColoredItemDefinition.java b/src/main/java/appeng/core/features/ColoredItemDefinition.java index c685951eeaf..93b2d004577 100644 --- a/src/main/java/appeng/core/features/ColoredItemDefinition.java +++ b/src/main/java/appeng/core/features/ColoredItemDefinition.java @@ -18,7 +18,6 @@ package appeng.core.features; - import appeng.api.util.AEColor; import appeng.api.util.AEColoredItemDefinition; import net.minecraft.block.Block; @@ -26,76 +25,63 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +public final class ColoredItemDefinition implements AEColoredItemDefinition { + + private final ItemStackSrc[] colors = new ItemStackSrc[17]; + + public void add(final AEColor v, final ItemStackSrc is) { + this.colors[v.ordinal()] = is; + } + + @Override + public Block block(final AEColor color) { + return null; + } + + @Override + public Item item(final AEColor color) { + final ItemStackSrc is = this.colors[color.ordinal()]; + + if (is == null) { + return null; + } + + return is.getItem(); + } + + @Override + public Class entity(final AEColor color) { + return null; + } + + @Override + public ItemStack stack(final AEColor color, final int stackSize) { + final ItemStackSrc is = this.colors[color.ordinal()]; + + if (is == null) { + return null; + } + + return is.stack(stackSize); + } + + @Override + public ItemStack[] allStacks(final int stackSize) { + final ItemStack[] is = new ItemStack[this.colors.length]; + for (int x = 0; x < is.length; x++) { + is[x] = this.colors[x].stack(1); + } + return is; + } + + @Override + public boolean sameAs(final AEColor color, final ItemStack comparableItem) { + final ItemStackSrc is = this.colors[color.ordinal()]; + + if (comparableItem == null || is == null) { + return false; + } -public final class ColoredItemDefinition implements AEColoredItemDefinition -{ - - private final ItemStackSrc[] colors = new ItemStackSrc[17]; - - public void add( final AEColor v, final ItemStackSrc is ) - { - this.colors[v.ordinal()] = is; - } - - @Override - public Block block( final AEColor color ) - { - return null; - } - - @Override - public Item item( final AEColor color ) - { - final ItemStackSrc is = this.colors[color.ordinal()]; - - if( is == null ) - { - return null; - } - - return is.getItem(); - } - - @Override - public Class entity( final AEColor color ) - { - return null; - } - - @Override - public ItemStack stack( final AEColor color, final int stackSize ) - { - final ItemStackSrc is = this.colors[color.ordinal()]; - - if( is == null ) - { - return null; - } - - return is.stack( stackSize ); - } - - @Override - public ItemStack[] allStacks( final int stackSize ) - { - final ItemStack[] is = new ItemStack[this.colors.length]; - for( int x = 0; x < is.length; x++ ) - { - is[x] = this.colors[x].stack( 1 ); - } - return is; - } - - @Override - public boolean sameAs( final AEColor color, final ItemStack comparableItem ) - { - final ItemStackSrc is = this.colors[color.ordinal()]; - - if( comparableItem == null || is == null ) - { - return false; - } - - return comparableItem.getItem() == is.getItem() && comparableItem.getItemDamage() == is.getDamage(); - } + return comparableItem.getItem() == is.getItem() && comparableItem.getItemDamage() == is.getDamage(); + } } diff --git a/src/main/java/appeng/core/features/DamagedItemDefinition.java b/src/main/java/appeng/core/features/DamagedItemDefinition.java index 98f0cf169e5..e46b747e6eb 100644 --- a/src/main/java/appeng/core/features/DamagedItemDefinition.java +++ b/src/main/java/appeng/core/features/DamagedItemDefinition.java @@ -18,97 +18,79 @@ package appeng.core.features; - import appeng.api.definitions.IItemDefinition; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Preconditions; +import javax.annotation.Nonnull; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; -import javax.annotation.Nonnull; - - -public final class DamagedItemDefinition implements IItemDefinition -{ - private static final ItemTransformer ITEM_TRANSFORMER = new ItemTransformer(); - private final Optional source; - - public DamagedItemDefinition( @Nonnull final IStackSrc source ) - { - Preconditions.checkNotNull( source ); - - if( source.isEnabled() ) - { - this.source = Optional.of( source ); - } - else - { - this.source = Optional.absent(); - } - } - - @Override - public Optional maybeItem() - { - return this.source.transform( ITEM_TRANSFORMER ); - } - - @Override - public Optional maybeStack( final int stackSize ) - { - return this.source.transform( new ItemStackTransformer( stackSize ) ); - } - - @Override - public boolean isEnabled() - { - return this.source.isPresent(); - } - - @Override - public boolean isSameAs( final ItemStack comparableStack ) - { - if( comparableStack == null ) - { - return false; - } - - return this.isEnabled() && comparableStack.getItem() == this.source.get().getItem() && comparableStack.getItemDamage() == this.source.get().getDamage(); - } - - @Override - public boolean isSameAs( final IBlockAccess world, final int x, final int y, final int z ) - { - return false; - } - - private static class ItemTransformer implements Function - { - @Override - public Item apply( final IStackSrc input ) - { - return input.getItem(); - } - } - - - private static class ItemStackTransformer implements Function - { - private final int stackSize; - - public ItemStackTransformer( final int stackSize ) - { - Preconditions.checkArgument( stackSize > 0 ); - - this.stackSize = stackSize; - } - - @Override - public ItemStack apply( final IStackSrc input ) - { - return input.stack( this.stackSize ); - } - } +public final class DamagedItemDefinition implements IItemDefinition { + private static final ItemTransformer ITEM_TRANSFORMER = new ItemTransformer(); + private final Optional source; + + public DamagedItemDefinition(@Nonnull final IStackSrc source) { + Preconditions.checkNotNull(source); + + if (source.isEnabled()) { + this.source = Optional.of(source); + } else { + this.source = Optional.absent(); + } + } + + @Override + public Optional maybeItem() { + return this.source.transform(ITEM_TRANSFORMER); + } + + @Override + public Optional maybeStack(final int stackSize) { + return this.source.transform(new ItemStackTransformer(stackSize)); + } + + @Override + public boolean isEnabled() { + return this.source.isPresent(); + } + + @Override + public boolean isSameAs(final ItemStack comparableStack) { + if (comparableStack == null) { + return false; + } + + return this.isEnabled() + && comparableStack.getItem() == this.source.get().getItem() + && comparableStack.getItemDamage() == this.source.get().getDamage(); + } + + @Override + public boolean isSameAs(final IBlockAccess world, final int x, final int y, final int z) { + return false; + } + + private static class ItemTransformer implements Function { + @Override + public Item apply(final IStackSrc input) { + return input.getItem(); + } + } + + private static class ItemStackTransformer implements Function { + private final int stackSize; + + public ItemStackTransformer(final int stackSize) { + Preconditions.checkArgument(stackSize > 0); + + this.stackSize = stackSize; + } + + @Override + public ItemStack apply(final IStackSrc input) { + return input.stack(this.stackSize); + } + } } diff --git a/src/main/java/appeng/core/features/DefinitionConverter.java b/src/main/java/appeng/core/features/DefinitionConverter.java index 3e62abfff10..6d5b130c6b9 100644 --- a/src/main/java/appeng/core/features/DefinitionConverter.java +++ b/src/main/java/appeng/core/features/DefinitionConverter.java @@ -1,166 +1,136 @@ package appeng.core.features; - import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IComparableDefinition; import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.ITileDefinition; import appeng.api.util.AEItemDefinition; +import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; -import javax.annotation.Nullable; - - /** * @deprecated */ @Deprecated -public final class DefinitionConverter -{ - public AEItemDefinition of( final ITileDefinition definition ) - { - return new AETile( definition ); - } - - public AEItemDefinition of( final IBlockDefinition definition ) - { - return new AEBlock( definition ); - } - - public AEItemDefinition of( final IItemDefinition definition ) - { - return new AEItem( definition ); - } - - public AEItemDefinition of( final IComparableDefinition definition ) - { - return new AEComparable( definition ); - } - - private static class AEComparable implements AEItemDefinition - { - private final IComparableDefinition definition; - - public AEComparable( final IComparableDefinition definition ) - { - this.definition = definition; - } - - @Nullable - @Override - public Block block() - { - return null; - } - - @Nullable - @Override - public Item item() - { - return null; - } - - @Nullable - @Override - public Class entity() - { - return null; - } - - @Nullable - @Override - public ItemStack stack( final int stackSize ) - { - return null; - } - - @Override - public boolean sameAsStack( final ItemStack comparableItem ) - { - return this.definition.isSameAs( comparableItem ); - } - - @Override - public boolean sameAsBlock( final IBlockAccess world, final int x, final int y, final int z ) - { - return false; - } - } - - - private static class AEItem extends AEComparable - { - private final IItemDefinition definition; - - public AEItem( final IItemDefinition definition ) - { - super( definition ); - - this.definition = definition; - } - - @Nullable - @Override - public ItemStack stack( final int stackSize ) - { - return this.definition.maybeStack( stackSize ).orNull(); - } - - @Nullable - @Override - public Item item() - { - return this.definition.maybeItem().orNull(); - } - } - - - private static class AEBlock extends AEItem - { - private final IBlockDefinition definition; - - public AEBlock( final IBlockDefinition definition ) - { - super( definition ); - - this.definition = definition; - } - - @Nullable - @Override - public Block block() - { - return this.definition.maybeBlock().orNull(); - } - - @Override - public boolean sameAsBlock( final IBlockAccess world, final int x, final int y, final int z ) - { - return this.definition.isSameAs( world, x, y, z ); - } - } - - - private static class AETile extends AEBlock - { - private final ITileDefinition definition; - - public AETile( final ITileDefinition definition ) - { - super( definition ); - - this.definition = definition; - } - - @Nullable - @Override - public Class entity() - { - return this.definition.maybeEntity().orNull(); - } - } +public final class DefinitionConverter { + public AEItemDefinition of(final ITileDefinition definition) { + return new AETile(definition); + } + + public AEItemDefinition of(final IBlockDefinition definition) { + return new AEBlock(definition); + } + + public AEItemDefinition of(final IItemDefinition definition) { + return new AEItem(definition); + } + + public AEItemDefinition of(final IComparableDefinition definition) { + return new AEComparable(definition); + } + + private static class AEComparable implements AEItemDefinition { + private final IComparableDefinition definition; + + public AEComparable(final IComparableDefinition definition) { + this.definition = definition; + } + + @Nullable + @Override + public Block block() { + return null; + } + + @Nullable + @Override + public Item item() { + return null; + } + + @Nullable + @Override + public Class entity() { + return null; + } + + @Nullable + @Override + public ItemStack stack(final int stackSize) { + return null; + } + + @Override + public boolean sameAsStack(final ItemStack comparableItem) { + return this.definition.isSameAs(comparableItem); + } + + @Override + public boolean sameAsBlock(final IBlockAccess world, final int x, final int y, final int z) { + return false; + } + } + + private static class AEItem extends AEComparable { + private final IItemDefinition definition; + + public AEItem(final IItemDefinition definition) { + super(definition); + + this.definition = definition; + } + + @Nullable + @Override + public ItemStack stack(final int stackSize) { + return this.definition.maybeStack(stackSize).orNull(); + } + + @Nullable + @Override + public Item item() { + return this.definition.maybeItem().orNull(); + } + } + + private static class AEBlock extends AEItem { + private final IBlockDefinition definition; + + public AEBlock(final IBlockDefinition definition) { + super(definition); + + this.definition = definition; + } + + @Nullable + @Override + public Block block() { + return this.definition.maybeBlock().orNull(); + } + + @Override + public boolean sameAsBlock(final IBlockAccess world, final int x, final int y, final int z) { + return this.definition.isSameAs(world, x, y, z); + } + } + + private static class AETile extends AEBlock { + private final ITileDefinition definition; + + public AETile(final ITileDefinition definition) { + super(definition); + + this.definition = definition; + } + + @Nullable + @Override + public Class entity() { + return this.definition.maybeEntity().orNull(); + } + } } diff --git a/src/main/java/appeng/core/features/FeatureNameExtractor.java b/src/main/java/appeng/core/features/FeatureNameExtractor.java index ce7a06527e1..92c5b913ed8 100644 --- a/src/main/java/appeng/core/features/FeatureNameExtractor.java +++ b/src/main/java/appeng/core/features/FeatureNameExtractor.java @@ -18,61 +18,46 @@ package appeng.core.features; - import com.google.common.base.Optional; - import java.util.regex.Pattern; - -public class FeatureNameExtractor -{ - private static final Pattern PATTERN_ITEM_MULTI_PART = Pattern.compile( "ItemMultiPart", Pattern.LITERAL ); - private static final Pattern PATTERN_ITEM_MULTI_MATERIAL = Pattern.compile( "ItemMultiMaterial", Pattern.LITERAL ); - private static final Pattern PATTERN_QUARTZ = Pattern.compile( "Quartz", Pattern.LITERAL ); - - private final Class clazz; - private final Optional subName; - - public FeatureNameExtractor( final Class clazz, final Optional subName ) - { - this.clazz = clazz; - this.subName = subName; - } - - public String get() - { - String name = this.clazz.getSimpleName(); - - if( name.startsWith( "ItemMultiPart" ) ) - { - name = PATTERN_ITEM_MULTI_PART.matcher( name ).replaceAll( "ItemPart" ); - } - else if( name.startsWith( "ItemMultiMaterial" ) ) - { - name = PATTERN_ITEM_MULTI_MATERIAL.matcher( name ).replaceAll( "ItemMaterial" ); - } - - if( this.subName.isPresent() ) - { - final String subName = this.subName.get(); - // simple hack to allow me to do get nice names for these without - // mode code outside of AEBaseItem - if( subName.startsWith( "P2PTunnel" ) ) - { - return "ItemPart.P2PTunnel"; - } - else if( subName.equals( "CertusQuartzTools" ) ) - { - return PATTERN_QUARTZ.matcher( name ).replaceAll( "CertusQuartz" ); - } - else if( subName.equals( "NetherQuartzTools" ) ) - { - return PATTERN_QUARTZ.matcher( name ).replaceAll( "NetherQuartz" ); - } - - name += '.' + subName; - } - - return name; - } +public class FeatureNameExtractor { + private static final Pattern PATTERN_ITEM_MULTI_PART = Pattern.compile("ItemMultiPart", Pattern.LITERAL); + private static final Pattern PATTERN_ITEM_MULTI_MATERIAL = Pattern.compile("ItemMultiMaterial", Pattern.LITERAL); + private static final Pattern PATTERN_QUARTZ = Pattern.compile("Quartz", Pattern.LITERAL); + + private final Class clazz; + private final Optional subName; + + public FeatureNameExtractor(final Class clazz, final Optional subName) { + this.clazz = clazz; + this.subName = subName; + } + + public String get() { + String name = this.clazz.getSimpleName(); + + if (name.startsWith("ItemMultiPart")) { + name = PATTERN_ITEM_MULTI_PART.matcher(name).replaceAll("ItemPart"); + } else if (name.startsWith("ItemMultiMaterial")) { + name = PATTERN_ITEM_MULTI_MATERIAL.matcher(name).replaceAll("ItemMaterial"); + } + + if (this.subName.isPresent()) { + final String subName = this.subName.get(); + // simple hack to allow me to do get nice names for these without + // mode code outside of AEBaseItem + if (subName.startsWith("P2PTunnel")) { + return "ItemPart.P2PTunnel"; + } else if (subName.equals("CertusQuartzTools")) { + return PATTERN_QUARTZ.matcher(name).replaceAll("CertusQuartz"); + } else if (subName.equals("NetherQuartzTools")) { + return PATTERN_QUARTZ.matcher(name).replaceAll("NetherQuartz"); + } + + name += '.' + subName; + } + + return name; + } } diff --git a/src/main/java/appeng/core/features/FeaturedActiveChecker.java b/src/main/java/appeng/core/features/FeaturedActiveChecker.java index 421198a9296..15b09d8b61a 100644 --- a/src/main/java/appeng/core/features/FeaturedActiveChecker.java +++ b/src/main/java/appeng/core/features/FeaturedActiveChecker.java @@ -18,31 +18,23 @@ package appeng.core.features; - import appeng.core.AEConfig; - import java.util.Set; +public final class FeaturedActiveChecker { + private final Set features; -public final class FeaturedActiveChecker -{ - private final Set features; - - public FeaturedActiveChecker( final Set features ) - { - this.features = features; - } + public FeaturedActiveChecker(final Set features) { + this.features = features; + } - ActivityState getActivityState() - { - for( final AEFeature f : this.features ) - { - if( !AEConfig.instance.isFeatureEnabled( f ) ) - { - return ActivityState.Disabled; - } - } + ActivityState getActivityState() { + for (final AEFeature f : this.features) { + if (!AEConfig.instance.isFeatureEnabled(f)) { + return ActivityState.Disabled; + } + } - return ActivityState.Enabled; - } + return ActivityState.Enabled; + } } diff --git a/src/main/java/appeng/core/features/IAEFeature.java b/src/main/java/appeng/core/features/IAEFeature.java index c819f1e760f..6ce85f310dc 100644 --- a/src/main/java/appeng/core/features/IAEFeature.java +++ b/src/main/java/appeng/core/features/IAEFeature.java @@ -18,10 +18,8 @@ package appeng.core.features; +public interface IAEFeature { + IFeatureHandler handler(); -public interface IAEFeature -{ - IFeatureHandler handler(); - - void postInit(); + void postInit(); } diff --git a/src/main/java/appeng/core/features/IFeatureHandler.java b/src/main/java/appeng/core/features/IFeatureHandler.java index de16fc2efe9..737ff43e2d3 100644 --- a/src/main/java/appeng/core/features/IFeatureHandler.java +++ b/src/main/java/appeng/core/features/IFeatureHandler.java @@ -18,15 +18,12 @@ package appeng.core.features; - import appeng.api.definitions.IItemDefinition; +public interface IFeatureHandler { + boolean isFeatureAvailable(); -public interface IFeatureHandler -{ - boolean isFeatureAvailable(); - - IItemDefinition getDefinition(); + IItemDefinition getDefinition(); - void register(); + void register(); } diff --git a/src/main/java/appeng/core/features/IStackSrc.java b/src/main/java/appeng/core/features/IStackSrc.java index cc7e1aa24bf..89c70849707 100644 --- a/src/main/java/appeng/core/features/IStackSrc.java +++ b/src/main/java/appeng/core/features/IStackSrc.java @@ -18,19 +18,16 @@ package appeng.core.features; - import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +public interface IStackSrc { -public interface IStackSrc -{ - - ItemStack stack( int i ); + ItemStack stack(int i); - Item getItem(); + Item getItem(); - int getDamage(); + int getDamage(); - boolean isEnabled(); + boolean isEnabled(); } diff --git a/src/main/java/appeng/core/features/ItemDefinition.java b/src/main/java/appeng/core/features/ItemDefinition.java index 39d23afc7aa..169f03710a8 100644 --- a/src/main/java/appeng/core/features/ItemDefinition.java +++ b/src/main/java/appeng/core/features/ItemDefinition.java @@ -18,7 +18,6 @@ package appeng.core.features; - import appeng.api.definitions.IItemDefinition; import appeng.util.Platform; import com.google.common.base.Function; @@ -28,71 +27,58 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; - -public class ItemDefinition implements IItemDefinition -{ - private final Optional item; - - public ItemDefinition( final Item item, final ActivityState state ) - { - Preconditions.checkNotNull( item ); - Preconditions.checkNotNull( state ); - - if( state == ActivityState.Enabled ) - { - this.item = Optional.of( item ); - } - else - { - this.item = Optional.absent(); - } - } - - @Override - public final Optional maybeItem() - { - return this.item; - } - - @Override - public Optional maybeStack( final int stackSize ) - { - return this.item.transform( new ItemStackTransformer( stackSize ) ); - } - - @Override - public boolean isEnabled() - { - return this.item.isPresent(); - } - - @Override - public final boolean isSameAs( final ItemStack comparableStack ) - { - return this.isEnabled() && Platform.isSameItemType( comparableStack, this.maybeStack( 1 ).get() ); - } - - @Override - public boolean isSameAs( final IBlockAccess world, final int x, final int y, final int z ) - { - return false; - } - - private static class ItemStackTransformer implements Function - { - private final int stackSize; - - public ItemStackTransformer( final int stackSize ) - { - Preconditions.checkArgument( stackSize > 0 ); - - this.stackSize = stackSize; - } - - @Override - public ItemStack apply( final Item input ) - { - return new ItemStack( input, this.stackSize ); - } - } +public class ItemDefinition implements IItemDefinition { + private final Optional item; + + public ItemDefinition(final Item item, final ActivityState state) { + Preconditions.checkNotNull(item); + Preconditions.checkNotNull(state); + + if (state == ActivityState.Enabled) { + this.item = Optional.of(item); + } else { + this.item = Optional.absent(); + } + } + + @Override + public final Optional maybeItem() { + return this.item; + } + + @Override + public Optional maybeStack(final int stackSize) { + return this.item.transform(new ItemStackTransformer(stackSize)); + } + + @Override + public boolean isEnabled() { + return this.item.isPresent(); + } + + @Override + public final boolean isSameAs(final ItemStack comparableStack) { + return this.isEnabled() + && Platform.isSameItemType(comparableStack, this.maybeStack(1).get()); + } + + @Override + public boolean isSameAs(final IBlockAccess world, final int x, final int y, final int z) { + return false; + } + + private static class ItemStackTransformer implements Function { + private final int stackSize; + + public ItemStackTransformer(final int stackSize) { + Preconditions.checkArgument(stackSize > 0); + + this.stackSize = stackSize; + } + + @Override + public ItemStack apply(final Item input) { + return new ItemStack(input, this.stackSize); + } + } } diff --git a/src/main/java/appeng/core/features/ItemFeatureHandler.java b/src/main/java/appeng/core/features/ItemFeatureHandler.java index 1bd820fe97d..5c828e6438d 100644 --- a/src/main/java/appeng/core/features/ItemFeatureHandler.java +++ b/src/main/java/appeng/core/features/ItemFeatureHandler.java @@ -18,75 +18,64 @@ package appeng.core.features; - import appeng.api.definitions.IItemDefinition; import appeng.core.CreativeTab; import appeng.core.CreativeTabFacade; import appeng.items.parts.ItemFacade; import com.google.common.base.Optional; import cpw.mods.fml.common.registry.GameRegistry; -import net.minecraft.item.Item; - import java.util.EnumSet; +import net.minecraft.item.Item; +public final class ItemFeatureHandler implements IFeatureHandler { + private final Item item; + private final FeatureNameExtractor extractor; + private final boolean enabled; + private final ItemDefinition definition; -public final class ItemFeatureHandler implements IFeatureHandler -{ - private final Item item; - private final FeatureNameExtractor extractor; - private final boolean enabled; - private final ItemDefinition definition; - - public ItemFeatureHandler( final EnumSet features, final Item item, final IAEFeature featured, final Optional subName ) - { - final ActivityState state = new FeaturedActiveChecker( features ).getActivityState(); + public ItemFeatureHandler( + final EnumSet features, + final Item item, + final IAEFeature featured, + final Optional subName) { + final ActivityState state = new FeaturedActiveChecker(features).getActivityState(); - this.item = item; - this.extractor = new FeatureNameExtractor( featured.getClass(), subName ); - this.enabled = state == ActivityState.Enabled; - this.definition = new ItemDefinition( item, state ); - } + this.item = item; + this.extractor = new FeatureNameExtractor(featured.getClass(), subName); + this.enabled = state == ActivityState.Enabled; + this.definition = new ItemDefinition(item, state); + } - @Override - public boolean isFeatureAvailable() - { - return this.enabled; - } + @Override + public boolean isFeatureAvailable() { + return this.enabled; + } - @Override - public IItemDefinition getDefinition() - { - return this.definition; - } + @Override + public IItemDefinition getDefinition() { + return this.definition; + } - @Override - public void register() - { - if( this.enabled ) - { - String name = this.extractor.get(); - this.item.setTextureName( "appliedenergistics2:" + name ); - this.item.setUnlocalizedName( /* "item." */"appliedenergistics2." + name ); + @Override + public void register() { + if (this.enabled) { + String name = this.extractor.get(); + this.item.setTextureName("appliedenergistics2:" + name); + this.item.setUnlocalizedName(/* "item." */ "appliedenergistics2." + name); - if( this.item instanceof ItemFacade ) - { - this.item.setCreativeTab( CreativeTabFacade.instance ); - } - else - { - this.item.setCreativeTab( CreativeTab.instance ); - } + if (this.item instanceof ItemFacade) { + this.item.setCreativeTab(CreativeTabFacade.instance); + } else { + this.item.setCreativeTab(CreativeTab.instance); + } - if( name.equals( "ItemMaterial" ) ) - { - name = "ItemMultiMaterial"; - } - else if( name.equals( "ItemPart" ) ) - { - name = "ItemMultiPart"; - } + if (name.equals("ItemMaterial")) { + name = "ItemMultiMaterial"; + } else if (name.equals("ItemPart")) { + name = "ItemMultiPart"; + } - GameRegistry.registerItem( this.item, "item." + name ); - } - } + GameRegistry.registerItem(this.item, "item." + name); + } + } } diff --git a/src/main/java/appeng/core/features/ItemStackSrc.java b/src/main/java/appeng/core/features/ItemStackSrc.java index 8ec4018ecdc..732cee0a2d1 100644 --- a/src/main/java/appeng/core/features/ItemStackSrc.java +++ b/src/main/java/appeng/core/features/ItemStackSrc.java @@ -18,55 +18,46 @@ package appeng.core.features; - import com.google.common.base.Preconditions; +import javax.annotation.Nullable; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import javax.annotation.Nullable; - - -public class ItemStackSrc implements IStackSrc -{ - - private final Item item; - private final int damage; - private final boolean enabled; - - public ItemStackSrc( final Item item, final int damage, final ActivityState state ) - { - Preconditions.checkNotNull( item ); - Preconditions.checkArgument( damage >= 0 ); - Preconditions.checkNotNull( state ); - Preconditions.checkArgument( state == ActivityState.Enabled || state == ActivityState.Disabled ); - - this.item = item; - this.damage = damage; - this.enabled = state == ActivityState.Enabled; - } - - @Nullable - @Override - public ItemStack stack( final int i ) - { - return new ItemStack( this.item, i, this.damage ); - } - - @Override - public Item getItem() - { - return this.item; - } - - @Override - public int getDamage() - { - return this.damage; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } +public class ItemStackSrc implements IStackSrc { + + private final Item item; + private final int damage; + private final boolean enabled; + + public ItemStackSrc(final Item item, final int damage, final ActivityState state) { + Preconditions.checkNotNull(item); + Preconditions.checkArgument(damage >= 0); + Preconditions.checkNotNull(state); + Preconditions.checkArgument(state == ActivityState.Enabled || state == ActivityState.Disabled); + + this.item = item; + this.damage = damage; + this.enabled = state == ActivityState.Enabled; + } + + @Nullable + @Override + public ItemStack stack(final int i) { + return new ItemStack(this.item, i, this.damage); + } + + @Override + public Item getItem() { + return this.item; + } + + @Override + public int getDamage() { + return this.damage; + } + + @Override + public boolean isEnabled() { + return this.enabled; + } } diff --git a/src/main/java/appeng/core/features/MaterialStackSrc.java b/src/main/java/appeng/core/features/MaterialStackSrc.java index 6f38f452fb5..32abb81cc4c 100644 --- a/src/main/java/appeng/core/features/MaterialStackSrc.java +++ b/src/main/java/appeng/core/features/MaterialStackSrc.java @@ -18,45 +18,37 @@ package appeng.core.features; - import appeng.items.materials.MaterialType; import com.google.common.base.Preconditions; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +public class MaterialStackSrc implements IStackSrc { + private final MaterialType src; + + public MaterialStackSrc(final MaterialType src) { + Preconditions.checkNotNull(src); + + this.src = src; + } + + @Override + public ItemStack stack(final int stackSize) { + return this.src.stack(stackSize); + } + + @Override + public Item getItem() { + return this.src.getItemInstance(); + } + + @Override + public int getDamage() { + return this.src.getDamageValue(); + } -public class MaterialStackSrc implements IStackSrc -{ - private final MaterialType src; - - public MaterialStackSrc( final MaterialType src ) - { - Preconditions.checkNotNull( src ); - - this.src = src; - } - - @Override - public ItemStack stack( final int stackSize ) - { - return this.src.stack( stackSize ); - } - - @Override - public Item getItem() - { - return this.src.getItemInstance(); - } - - @Override - public int getDamage() - { - return this.src.getDamageValue(); - } - - @Override - public boolean isEnabled() - { - return true; - } + @Override + public boolean isEnabled() { + return true; + } } diff --git a/src/main/java/appeng/core/features/NameResolver.java b/src/main/java/appeng/core/features/NameResolver.java index a5969316a35..c193c1d0ab4 100644 --- a/src/main/java/appeng/core/features/NameResolver.java +++ b/src/main/java/appeng/core/features/NameResolver.java @@ -18,12 +18,9 @@ package appeng.core.features; - import appeng.items.AEBaseItem; - import java.util.regex.Pattern; - /** * This class is used to rename items to match the persistent stored items. *

@@ -33,53 +30,43 @@ * @deprecated only a temporary solution for a rename */ @Deprecated -public final class NameResolver -{ - private static final Pattern ITEM_MULTI_PART = Pattern.compile( "ItemMultiPart", Pattern.LITERAL ); - private static final Pattern ITEM_MULTI_MATERIAL = Pattern.compile( "ItemMultiMaterial", Pattern.LITERAL ); - private static final Pattern QUARTZ = Pattern.compile( "Quartz", Pattern.LITERAL ); +public final class NameResolver { + private static final Pattern ITEM_MULTI_PART = Pattern.compile("ItemMultiPart", Pattern.LITERAL); + private static final Pattern ITEM_MULTI_MATERIAL = Pattern.compile("ItemMultiMaterial", Pattern.LITERAL); + private static final Pattern QUARTZ = Pattern.compile("Quartz", Pattern.LITERAL); - private final Class withOriginalName; + private final Class withOriginalName; - public NameResolver( final Class withOriginalName ) - { - this.withOriginalName = withOriginalName; - } + public NameResolver(final Class withOriginalName) { + this.withOriginalName = withOriginalName; + } - public String getName( final String subName ) - { - String name = this.withOriginalName.getSimpleName(); + public String getName(final String subName) { + String name = this.withOriginalName.getSimpleName(); - if( name.startsWith( "ItemMultiPart" ) ) - { - name = ITEM_MULTI_PART.matcher( name ).replaceAll( "ItemPart" ); - } - else if( name.startsWith( "ItemMultiMaterial" ) ) - { - name = ITEM_MULTI_MATERIAL.matcher( name ).replaceAll( "ItemMaterial" ); - } + if (name.startsWith("ItemMultiPart")) { + name = ITEM_MULTI_PART.matcher(name).replaceAll("ItemPart"); + } else if (name.startsWith("ItemMultiMaterial")) { + name = ITEM_MULTI_MATERIAL.matcher(name).replaceAll("ItemMaterial"); + } - if( subName != null ) - { - // simple hack to allow me to do get nice names for these without - // mode code outside of AEBaseItem - if( subName.startsWith( "P2PTunnel" ) ) - { - return "ItemPart.P2PTunnel"; - } + if (subName != null) { + // simple hack to allow me to do get nice names for these without + // mode code outside of AEBaseItem + if (subName.startsWith("P2PTunnel")) { + return "ItemPart.P2PTunnel"; + } - if( subName.equals( "CertusQuartzTools" ) ) - { - return QUARTZ.matcher( name ).replaceAll( "CertusQuartz" ); - } - if( subName.equals( "NetherQuartzTools" ) ) - { - return QUARTZ.matcher( name ).replaceAll( "NetherQuartz" ); - } + if (subName.equals("CertusQuartzTools")) { + return QUARTZ.matcher(name).replaceAll("CertusQuartz"); + } + if (subName.equals("NetherQuartzTools")) { + return QUARTZ.matcher(name).replaceAll("NetherQuartz"); + } - name += '.' + subName; - } + name += '.' + subName; + } - return name; - } + return name; + } } diff --git a/src/main/java/appeng/core/features/SlabBlockFeatureHandler.java b/src/main/java/appeng/core/features/SlabBlockFeatureHandler.java index 053fa3aa0fe..cc88d190a70 100644 --- a/src/main/java/appeng/core/features/SlabBlockFeatureHandler.java +++ b/src/main/java/appeng/core/features/SlabBlockFeatureHandler.java @@ -18,53 +18,56 @@ package appeng.core.features; - import appeng.api.definitions.IBlockDefinition; import appeng.block.AEBaseItemBlockSlab; import appeng.block.AEBaseSlabBlock; import appeng.core.CreativeTab; import com.google.common.base.Optional; import cpw.mods.fml.common.registry.GameRegistry; - import java.util.EnumSet; +public class SlabBlockFeatureHandler implements IFeatureHandler { + private final AEBaseSlabBlock slabs; + private final FeatureNameExtractor extractor; + private final boolean enabled; + private final BlockDefinition definition; -public class SlabBlockFeatureHandler implements IFeatureHandler -{ - private final AEBaseSlabBlock slabs; - private final FeatureNameExtractor extractor; - private final boolean enabled; - private final BlockDefinition definition; - - public SlabBlockFeatureHandler( final EnumSet features, final AEBaseSlabBlock slabs ) - { - final ActivityState state = new FeaturedActiveChecker( features ).getActivityState(); - this.slabs = slabs; - this.extractor = new FeatureNameExtractor( slabs.getClass(), Optional.absent() ); - this.enabled = state == ActivityState.Enabled; - this.definition = new BlockDefinition( slabs, state ); - } + public SlabBlockFeatureHandler(final EnumSet features, final AEBaseSlabBlock slabs) { + final ActivityState state = new FeaturedActiveChecker(features).getActivityState(); + this.slabs = slabs; + this.extractor = new FeatureNameExtractor(slabs.getClass(), Optional.absent()); + this.enabled = state == ActivityState.Enabled; + this.definition = new BlockDefinition(slabs, state); + } - @Override - public final boolean isFeatureAvailable() - { - return this.enabled; - } + @Override + public final boolean isFeatureAvailable() { + return this.enabled; + } - @Override - public final IBlockDefinition getDefinition() - { - return this.definition; - } + @Override + public final IBlockDefinition getDefinition() { + return this.definition; + } - @Override - public final void register() - { - if( this.enabled ) - { - this.slabs.setCreativeTab( CreativeTab.instance ); - GameRegistry.registerBlock( this.slabs, AEBaseItemBlockSlab.class, "tile." + this.slabs.name(), this.slabs, this.slabs.doubleSlabs(), false ); - GameRegistry.registerBlock( this.slabs.doubleSlabs(), AEBaseItemBlockSlab.class, "tile." + this.slabs.name() + ".double", this.slabs, this.slabs.doubleSlabs(), true ); - } - } + @Override + public final void register() { + if (this.enabled) { + this.slabs.setCreativeTab(CreativeTab.instance); + GameRegistry.registerBlock( + this.slabs, + AEBaseItemBlockSlab.class, + "tile." + this.slabs.name(), + this.slabs, + this.slabs.doubleSlabs(), + false); + GameRegistry.registerBlock( + this.slabs.doubleSlabs(), + AEBaseItemBlockSlab.class, + "tile." + this.slabs.name() + ".double", + this.slabs, + this.slabs.doubleSlabs(), + true); + } + } } diff --git a/src/main/java/appeng/core/features/StairBlockFeatureHandler.java b/src/main/java/appeng/core/features/StairBlockFeatureHandler.java index 39c482733e6..1bedb511685 100644 --- a/src/main/java/appeng/core/features/StairBlockFeatureHandler.java +++ b/src/main/java/appeng/core/features/StairBlockFeatureHandler.java @@ -18,56 +18,48 @@ package appeng.core.features; - import appeng.api.definitions.IBlockDefinition; import appeng.core.CreativeTab; import com.google.common.base.Optional; import cpw.mods.fml.common.registry.GameRegistry; -import net.minecraft.block.BlockStairs; - import java.util.EnumSet; +import net.minecraft.block.BlockStairs; +public class StairBlockFeatureHandler implements IFeatureHandler { + private final BlockStairs stairs; + private final FeatureNameExtractor extractor; + private final boolean enabled; + private final BlockDefinition definition; -public class StairBlockFeatureHandler implements IFeatureHandler -{ - private final BlockStairs stairs; - private final FeatureNameExtractor extractor; - private final boolean enabled; - private final BlockDefinition definition; - - public StairBlockFeatureHandler( final EnumSet features, final BlockStairs stairs, final Optional subName ) - { - final ActivityState state = new FeaturedActiveChecker( features ).getActivityState(); + public StairBlockFeatureHandler( + final EnumSet features, final BlockStairs stairs, final Optional subName) { + final ActivityState state = new FeaturedActiveChecker(features).getActivityState(); - this.stairs = stairs; - this.extractor = new FeatureNameExtractor( stairs.getClass(), subName ); - this.enabled = state == ActivityState.Enabled; - this.definition = new BlockDefinition( stairs, state ); - } + this.stairs = stairs; + this.extractor = new FeatureNameExtractor(stairs.getClass(), subName); + this.enabled = state == ActivityState.Enabled; + this.definition = new BlockDefinition(stairs, state); + } - @Override - public final boolean isFeatureAvailable() - { - return this.enabled; - } + @Override + public final boolean isFeatureAvailable() { + return this.enabled; + } - @Override - public final IBlockDefinition getDefinition() - { - return this.definition; - } + @Override + public final IBlockDefinition getDefinition() { + return this.definition; + } - @Override - public final void register() - { - if( this.enabled ) - { - final String name = this.extractor.get(); - this.stairs.setCreativeTab( CreativeTab.instance ); - this.stairs.setBlockName( "appliedenergistics2." + name ); - this.stairs.setBlockTextureName( "appliedenergistics2:" + name ); + @Override + public final void register() { + if (this.enabled) { + final String name = this.extractor.get(); + this.stairs.setCreativeTab(CreativeTab.instance); + this.stairs.setBlockName("appliedenergistics2." + name); + this.stairs.setBlockTextureName("appliedenergistics2:" + name); - GameRegistry.registerBlock( this.stairs, "tile." + name ); - } - } + GameRegistry.registerBlock(this.stairs, "tile." + name); + } + } } diff --git a/src/main/java/appeng/core/features/TileDefinition.java b/src/main/java/appeng/core/features/TileDefinition.java index 24b06988eb4..e61a6840ec9 100644 --- a/src/main/java/appeng/core/features/TileDefinition.java +++ b/src/main/java/appeng/core/features/TileDefinition.java @@ -18,7 +18,6 @@ package appeng.core.features; - import appeng.api.definitions.ITileDefinition; import appeng.block.AEBaseTileBlock; import com.google.common.base.Function; @@ -26,44 +25,35 @@ import com.google.common.base.Preconditions; import net.minecraft.tileentity.TileEntity; - -public final class TileDefinition extends BlockDefinition implements ITileDefinition -{ - private static final TileEntityTransformer TILEENTITY_TRANSFORMER = new TileEntityTransformer(); - private final Optional block; - - public TileDefinition( final AEBaseTileBlock block, final ActivityState state ) - { - super( block, state ); - - Preconditions.checkNotNull( block ); - Preconditions.checkNotNull( state ); - Preconditions.checkNotNull( block.getTileEntityClass() ); - - if( state == ActivityState.Enabled ) - { - this.block = Optional.of( block ); - } - else - { - this.block = Optional.absent(); - } - } - - @Override - public Optional> maybeEntity() - { - return this.block.transform( TILEENTITY_TRANSFORMER ); - } - - private static class TileEntityTransformer implements Function> - { - @Override - public Class apply( final AEBaseTileBlock input ) - { - final Class entity = input.getTileEntityClass(); - - return entity; - } - } +public final class TileDefinition extends BlockDefinition implements ITileDefinition { + private static final TileEntityTransformer TILEENTITY_TRANSFORMER = new TileEntityTransformer(); + private final Optional block; + + public TileDefinition(final AEBaseTileBlock block, final ActivityState state) { + super(block, state); + + Preconditions.checkNotNull(block); + Preconditions.checkNotNull(state); + Preconditions.checkNotNull(block.getTileEntityClass()); + + if (state == ActivityState.Enabled) { + this.block = Optional.of(block); + } else { + this.block = Optional.absent(); + } + } + + @Override + public Optional> maybeEntity() { + return this.block.transform(TILEENTITY_TRANSFORMER); + } + + private static class TileEntityTransformer implements Function> { + @Override + public Class apply(final AEBaseTileBlock input) { + final Class entity = input.getTileEntityClass(); + + return entity; + } + } } diff --git a/src/main/java/appeng/core/features/WrappedDamageItemDefinition.java b/src/main/java/appeng/core/features/WrappedDamageItemDefinition.java index c4a2dcf9900..cfd83a4dc38 100644 --- a/src/main/java/appeng/core/features/WrappedDamageItemDefinition.java +++ b/src/main/java/appeng/core/features/WrappedDamageItemDefinition.java @@ -18,7 +18,6 @@ package appeng.core.features; - import appeng.api.definitions.ITileDefinition; import com.google.common.base.Function; import com.google.common.base.Optional; @@ -30,97 +29,82 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; - -public final class WrappedDamageItemDefinition implements ITileDefinition -{ - private final ITileDefinition definition; - private final int damage; - - public WrappedDamageItemDefinition( final ITileDefinition definition, final int damage ) - { - Preconditions.checkNotNull( definition ); - Preconditions.checkArgument( damage >= 0 ); - - this.definition = definition; - this.damage = damage; - } - - @Override - public Optional> maybeEntity() - { - return this.definition.maybeEntity(); - } - - @Override - public Optional maybeBlock() - { - return this.definition.maybeBlock(); - } - - @Override - public Optional maybeItemBlock() - { - return this.definition.maybeItemBlock(); - } - - @Override - public Optional maybeItem() - { - return this.definition.maybeItem(); - } - - @Override - public Optional maybeStack( final int stackSize ) - { - return this.definition.maybeBlock().transform( new BlockTransformFunction( stackSize, this.damage ) ); - } - - @Override - public boolean isEnabled() - { - return this.definition.isEnabled(); - } - - @Override - public boolean isSameAs( final ItemStack comparableStack ) - { - if( comparableStack == null ) - { - return false; - } - - final boolean sameItem = this.definition.isSameAs( new ItemStack( comparableStack.getItem() ) ); - final boolean sameDamage = comparableStack.getItemDamage() == this.damage; - - return sameItem && sameDamage; - } - - @Override - public boolean isSameAs( final IBlockAccess world, final int x, final int y, final int z ) - { - return this.definition.isSameAs( world, x, y, z ) && world.getBlockMetadata( x, y, z ) == this.damage; - } - - private static final class BlockTransformFunction implements Function - { - private final int stackSize; - private final int damage; - - public BlockTransformFunction( final int stackSize, final int damage ) - { - Preconditions.checkArgument( stackSize > 0 ); - Preconditions.checkArgument( damage >= 0 ); - - this.stackSize = stackSize; - this.damage = damage; - } - - @Override - public ItemStack apply( final Block input ) - { - Preconditions.checkNotNull( input ); - - return new ItemStack( input, this.stackSize, this.damage ); - } - } +public final class WrappedDamageItemDefinition implements ITileDefinition { + private final ITileDefinition definition; + private final int damage; + + public WrappedDamageItemDefinition(final ITileDefinition definition, final int damage) { + Preconditions.checkNotNull(definition); + Preconditions.checkArgument(damage >= 0); + + this.definition = definition; + this.damage = damage; + } + + @Override + public Optional> maybeEntity() { + return this.definition.maybeEntity(); + } + + @Override + public Optional maybeBlock() { + return this.definition.maybeBlock(); + } + + @Override + public Optional maybeItemBlock() { + return this.definition.maybeItemBlock(); + } + + @Override + public Optional maybeItem() { + return this.definition.maybeItem(); + } + + @Override + public Optional maybeStack(final int stackSize) { + return this.definition.maybeBlock().transform(new BlockTransformFunction(stackSize, this.damage)); + } + + @Override + public boolean isEnabled() { + return this.definition.isEnabled(); + } + + @Override + public boolean isSameAs(final ItemStack comparableStack) { + if (comparableStack == null) { + return false; + } + + final boolean sameItem = this.definition.isSameAs(new ItemStack(comparableStack.getItem())); + final boolean sameDamage = comparableStack.getItemDamage() == this.damage; + + return sameItem && sameDamage; + } + + @Override + public boolean isSameAs(final IBlockAccess world, final int x, final int y, final int z) { + return this.definition.isSameAs(world, x, y, z) && world.getBlockMetadata(x, y, z) == this.damage; + } + + private static final class BlockTransformFunction implements Function { + private final int stackSize; + private final int damage; + + public BlockTransformFunction(final int stackSize, final int damage) { + Preconditions.checkArgument(stackSize > 0); + Preconditions.checkArgument(damage >= 0); + + this.stackSize = stackSize; + this.damage = damage; + } + + @Override + public ItemStack apply(final Block input) { + Preconditions.checkNotNull(input); + + return new ItemStack(input, this.stackSize, this.damage); + } + } } diff --git a/src/main/java/appeng/core/features/registries/CellRegistry.java b/src/main/java/appeng/core/features/registries/CellRegistry.java index 5b8ae588b79..b067a11a571 100644 --- a/src/main/java/appeng/core/features/registries/CellRegistry.java +++ b/src/main/java/appeng/core/features/registries/CellRegistry.java @@ -18,81 +18,63 @@ package appeng.core.features.registries; - import appeng.api.storage.*; -import net.minecraft.item.ItemStack; - import java.util.ArrayList; import java.util.List; +import net.minecraft.item.ItemStack; +public class CellRegistry implements ICellRegistry { -public class CellRegistry implements ICellRegistry -{ - - private final List handlers; + private final List handlers; - public CellRegistry() - { - this.handlers = new ArrayList(); - } + public CellRegistry() { + this.handlers = new ArrayList(); + } - @Override - public void addCellHandler( final ICellHandler h ) - { - if( h != null ) - { - this.handlers.add( h ); - } - } + @Override + public void addCellHandler(final ICellHandler h) { + if (h != null) { + this.handlers.add(h); + } + } - @Override - public boolean isCellHandled( final ItemStack is ) - { - if( is == null ) - { - return false; - } - for( final ICellHandler ch : this.handlers ) - { - if( ch.isCell( is ) ) - { - return true; - } - } - return false; - } + @Override + public boolean isCellHandled(final ItemStack is) { + if (is == null) { + return false; + } + for (final ICellHandler ch : this.handlers) { + if (ch.isCell(is)) { + return true; + } + } + return false; + } - @Override - public ICellHandler getHandler( final ItemStack is ) - { - if( is == null ) - { - return null; - } - for( final ICellHandler ch : this.handlers ) - { - if( ch.isCell( is ) ) - { - return ch; - } - } - return null; - } + @Override + public ICellHandler getHandler(final ItemStack is) { + if (is == null) { + return null; + } + for (final ICellHandler ch : this.handlers) { + if (ch.isCell(is)) { + return ch; + } + } + return null; + } - @Override - public IMEInventoryHandler getCellInventory( final ItemStack is, final ISaveProvider container, final StorageChannel chan ) - { - if( is == null ) - { - return null; - } - for( final ICellHandler ch : this.handlers ) - { - if( ch.isCell( is ) ) - { - return ch.getCellInventory( is, container, chan ); - } - } - return null; - } + @Override + public IMEInventoryHandler getCellInventory( + final ItemStack is, final ISaveProvider container, final StorageChannel chan) { + if (is == null) { + return null; + } + for (final ICellHandler ch : this.handlers) { + if (ch.isCell(is)) { + return ch.getCellInventory(is, container, chan); + } + } + return null; + } } diff --git a/src/main/java/appeng/core/features/registries/ExternalStorageRegistry.java b/src/main/java/appeng/core/features/registries/ExternalStorageRegistry.java index 585f271cc6c..b2a0e357e98 100644 --- a/src/main/java/appeng/core/features/registries/ExternalStorageRegistry.java +++ b/src/main/java/appeng/core/features/registries/ExternalStorageRegistry.java @@ -18,52 +18,43 @@ package appeng.core.features.registries; - import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageHandler; import appeng.api.storage.IExternalStorageRegistry; import appeng.api.storage.StorageChannel; import appeng.core.features.registries.entries.ExternalIInv; -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.common.util.ForgeDirection; - import java.util.ArrayList; import java.util.List; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; +public class ExternalStorageRegistry implements IExternalStorageRegistry { -public class ExternalStorageRegistry implements IExternalStorageRegistry -{ - - private final List Handlers; - private final ExternalIInv lastHandler = new ExternalIInv(); + private final List Handlers; + private final ExternalIInv lastHandler = new ExternalIInv(); - public ExternalStorageRegistry() - { - this.Handlers = new ArrayList(); - } + public ExternalStorageRegistry() { + this.Handlers = new ArrayList(); + } - @Override - public void addExternalStorageInterface( final IExternalStorageHandler ei ) - { - this.Handlers.add( ei ); - } + @Override + public void addExternalStorageInterface(final IExternalStorageHandler ei) { + this.Handlers.add(ei); + } - @Override - public IExternalStorageHandler getHandler( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource mySrc ) - { - for( final IExternalStorageHandler x : this.Handlers ) - { - if( x.canHandle( te, d, chan, mySrc ) ) - { - return x; - } - } + @Override + public IExternalStorageHandler getHandler( + final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource mySrc) { + for (final IExternalStorageHandler x : this.Handlers) { + if (x.canHandle(te, d, chan, mySrc)) { + return x; + } + } - if( this.lastHandler.canHandle( te, d, chan, mySrc ) ) - { - return this.lastHandler; - } + if (this.lastHandler.canHandle(te, d, chan, mySrc)) { + return this.lastHandler; + } - return null; - } + return null; + } } diff --git a/src/main/java/appeng/core/features/registries/GridCacheRegistry.java b/src/main/java/appeng/core/features/registries/GridCacheRegistry.java index 58a2bf45eee..50911c22e77 100644 --- a/src/main/java/appeng/core/features/registries/GridCacheRegistry.java +++ b/src/main/java/appeng/core/features/registries/GridCacheRegistry.java @@ -18,69 +18,56 @@ package appeng.core.features.registries; - import appeng.api.networking.IGrid; import appeng.api.networking.IGridCache; import appeng.api.networking.IGridCacheRegistry; import appeng.core.AELog; - import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; +public final class GridCacheRegistry implements IGridCacheRegistry { + private final Map, Class> caches = + new HashMap, Class>(); -public final class GridCacheRegistry implements IGridCacheRegistry -{ - private final Map, Class> caches = new HashMap, Class>(); - - @Override - public void registerGridCache( final Class iface, final Class implementation ) - { - if( iface.isAssignableFrom( implementation ) ) - { - this.caches.put( iface, implementation ); - } - else - { - throw new IllegalArgumentException( "Invalid setup, grid cache must either be the same class, or an interface that the implementation implements. Gotten: " + iface + " and " + implementation ); - } - } + @Override + public void registerGridCache( + final Class iface, final Class implementation) { + if (iface.isAssignableFrom(implementation)) { + this.caches.put(iface, implementation); + } else { + throw new IllegalArgumentException( + "Invalid setup, grid cache must either be the same class, or an interface that the implementation implements. Gotten: " + + iface + " and " + implementation); + } + } - @Override - public HashMap, IGridCache> createCacheInstance( final IGrid g ) - { - final HashMap, IGridCache> map = new HashMap, IGridCache>(); + @Override + public HashMap, IGridCache> createCacheInstance(final IGrid g) { + final HashMap, IGridCache> map = + new HashMap, IGridCache>(); - for( final Class iface : this.caches.keySet() ) - { - try - { - final Constructor c = this.caches.get( iface ).getConstructor( IGrid.class ); - map.put( iface, c.newInstance( g ) ); - } - catch( final NoSuchMethodException e ) - { - AELog.error( "Grid Caches must have a constructor with IGrid as the single param." ); - throw new IllegalArgumentException( e ); - } - catch( final InvocationTargetException e ) - { - AELog.error( "Grid Caches must have a constructor with IGrid as the single param." ); - throw new IllegalStateException( e ); - } - catch( final InstantiationException e ) - { - AELog.error( "Grid Caches must have a constructor with IGrid as the single param." ); - throw new IllegalStateException( e ); - } - catch( final IllegalAccessException e ) - { - AELog.error( "Grid Caches must have a constructor with IGrid as the single param." ); - throw new IllegalStateException( e ); - } - } + for (final Class iface : this.caches.keySet()) { + try { + final Constructor c = + this.caches.get(iface).getConstructor(IGrid.class); + map.put(iface, c.newInstance(g)); + } catch (final NoSuchMethodException e) { + AELog.error("Grid Caches must have a constructor with IGrid as the single param."); + throw new IllegalArgumentException(e); + } catch (final InvocationTargetException e) { + AELog.error("Grid Caches must have a constructor with IGrid as the single param."); + throw new IllegalStateException(e); + } catch (final InstantiationException e) { + AELog.error("Grid Caches must have a constructor with IGrid as the single param."); + throw new IllegalStateException(e); + } catch (final IllegalAccessException e) { + AELog.error("Grid Caches must have a constructor with IGrid as the single param."); + throw new IllegalStateException(e); + } + } - return map; - } + return map; + } } diff --git a/src/main/java/appeng/core/features/registries/GrinderRecipeManager.java b/src/main/java/appeng/core/features/registries/GrinderRecipeManager.java index 74819f32657..b17e1624427 100644 --- a/src/main/java/appeng/core/features/registries/GrinderRecipeManager.java +++ b/src/main/java/appeng/core/features/registries/GrinderRecipeManager.java @@ -18,7 +18,6 @@ package appeng.core.features.registries; - import appeng.api.features.IGrinderEntry; import appeng.api.features.IGrinderRegistry; import appeng.core.AEConfig; @@ -27,272 +26,237 @@ import appeng.recipes.ores.IOreListener; import appeng.recipes.ores.OreDictionaryHandler; import appeng.util.Platform; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; - -public final class GrinderRecipeManager implements IGrinderRegistry, IOreListener -{ - private final List recipes; - private final Map ores; - private final Map ingots; - private final Map dusts; - - public GrinderRecipeManager() - { - this.recipes = new ArrayList(); - this.ores = new HashMap(); - this.ingots = new HashMap(); - this.dusts = new HashMap(); - - this.addOre( "Coal", new ItemStack( Items.coal ) ); - this.addOre( "Charcoal", new ItemStack( Items.coal, 1, 1 ) ); - - this.addOre( "NetherQuartz", new ItemStack( Blocks.quartz_ore ) ); - this.addIngot( "NetherQuartz", new ItemStack( Items.quartz ) ); - - this.addOre( "Gold", new ItemStack( Blocks.gold_ore ) ); - this.addIngot( "Gold", new ItemStack( Items.gold_ingot ) ); - - this.addOre( "Iron", new ItemStack( Blocks.iron_ore ) ); - this.addIngot( "Iron", new ItemStack( Items.iron_ingot ) ); - - this.addOre( "Obsidian", new ItemStack( Blocks.obsidian ) ); - - this.addIngot( "Ender", new ItemStack( Items.ender_pearl ) ); - this.addIngot( "EnderPearl", new ItemStack( Items.ender_pearl ) ); - - this.addIngot( "Wheat", new ItemStack( Items.wheat ) ); - - OreDictionaryHandler.INSTANCE.observe( this ); - } - - @Override - public List getRecipes() - { - this.log( "API - getRecipes" ); - return this.recipes; - } - - @Override - public void addRecipe( final ItemStack in, final ItemStack out, final int cost ) - { - if( in == null || out == null ) - { - this.log( "Invalid Grinder Recipe Specified." ); - return; - } - - this.log( "Allow Grinding of " + Platform.getItemDisplayName( in ) + " to " + Platform.getItemDisplayName( out ) + " for " + cost ); - this.injectRecipe( new AppEngGrinderRecipe( this.copy( in ), this.copy( out ), cost ) ); - } - - @Override - public void addRecipe( final ItemStack in, final ItemStack out, final ItemStack optional, final float chance, final int cost ) - { - if( in == null || ( optional == null && out == null ) ) - { - this.log( "Invalid Grinder Recipe Specified." ); - return; - } - - this.log( "Allow Grinding of " + Platform.getItemDisplayName( in ) + " to " + Platform.getItemDisplayName( out ) + " with optional " + Platform.getItemDisplayName( optional ) + " for " + cost ); - this.injectRecipe( new AppEngGrinderRecipe( this.copy( in ), this.copy( out ), this.copy( optional ), chance, cost ) ); - } - - @Override - public void addRecipe( final ItemStack in, final ItemStack out, final ItemStack optional, final float chance, final ItemStack optional2, final float chance2, final int cost ) - { - if( in == null || ( optional == null && out == null && optional2 == null ) ) - { - this.log( "Invalid Grinder Recipe Specified." ); - return; - } - - this.log( "Allow Grinding of " + Platform.getItemDisplayName( in ) + " to " + Platform.getItemDisplayName( out ) + " with optional " + Platform.getItemDisplayName( optional ) + " for " + cost ); - this.injectRecipe( new AppEngGrinderRecipe( this.copy( in ), this.copy( out ), this.copy( optional ), this.copy( optional2 ), chance, chance2, cost ) ); - } - - private void injectRecipe( final AppEngGrinderRecipe appEngGrinderRecipe ) - { - for( final IGrinderEntry gr : this.recipes ) - { - if( Platform.isSameItemPrecise( gr.getInput(), appEngGrinderRecipe.getInput() ) ) - { - return; - } - } - - this.recipes.add( appEngGrinderRecipe ); - } - - private ItemStack copy( final ItemStack is ) - { - if( is != null ) - { - return is.copy(); - } - return null; - } - - @Override - public IGrinderEntry getRecipeForInput( final ItemStack input ) - { - this.log( "Looking up recipe for " + Platform.getItemDisplayName( input ) ); - if( input != null ) - { - for( final IGrinderEntry r : this.recipes ) - { - if( Platform.isSameItem( input, r.getInput() ) ) - { - this.log( "Recipe for " + input.getUnlocalizedName() + " found " + Platform.getItemDisplayName( r.getOutput() ) ); - return r; - } - } - - this.log( "Could not find recipe for " + Platform.getItemDisplayName( input ) ); - } - - return null; - } - - private void log( final String o ) - { - AELog.grinder( o ); - } - - private int getDustToOreRatio( final String name ) - { - if( name.equals( "Obsidian" ) ) - { - return 1; - } - if( name.equals( "Charcoal" ) ) - { - return 1; - } - if( name.equals( "Coal" ) ) - { - return 1; - } - return 2; - } - - private void addOre( final String name, final ItemStack item ) - { - if( item == null ) - { - return; - } - this.log( "Adding Ore - " + name + " : " + Platform.getItemDisplayName( item ) ); - - this.ores.put( item, name ); - - if( this.dusts.containsKey( name ) ) - { - final ItemStack is = this.dusts.get( name ).copy(); - final int ratio = this.getDustToOreRatio( name ); - if( ratio > 1 ) - { - final ItemStack extra = is.copy(); - extra.stackSize = ratio - 1; - this.addRecipe( item, is, extra, (float) ( AEConfig.instance.oreDoublePercentage / 100.0 ), 8 ); - } - else - { - this.addRecipe( item, is, 8 ); - } - } - } - - private void addIngot( final String name, final ItemStack item ) - { - if( item == null ) - { - return; - } - this.log( "Adding Ingot - " + name + " : " + Platform.getItemDisplayName( item ) ); - - this.ingots.put( item, name ); - - if( this.dusts.containsKey( name ) ) - { - this.addRecipe( item, this.dusts.get( name ), 4 ); - } - } - - private void addDust( final String name, final ItemStack item ) - { - if( item == null ) - { - return; - } - if( this.dusts.containsKey( name ) ) - { - this.log( "Rejecting Dust - " + name + " : " + Platform.getItemDisplayName( item ) ); - return; - } - - this.log( "Adding Dust - " + name + " : " + Platform.getItemDisplayName( item ) ); - - this.dusts.put( name, item ); - - for( final Entry d : this.ores.entrySet() ) - { - if( name.equals( d.getValue() ) ) - { - final ItemStack is = item.copy(); - is.stackSize = 1; - final int ratio = this.getDustToOreRatio( name ); - if( ratio > 1 ) - { - final ItemStack extra = is.copy(); - extra.stackSize = ratio - 1; - this.addRecipe( d.getKey(), is, extra, (float) ( AEConfig.instance.oreDoublePercentage / 100.0 ), 8 ); - } - else - { - this.addRecipe( d.getKey(), is, 8 ); - } - } - } - - for( final Entry d : this.ingots.entrySet() ) - { - if( name.equals( d.getValue() ) ) - { - this.addRecipe( d.getKey(), item, 4 ); - } - } - } - - @Override - public void oreRegistered( final String name, final ItemStack item ) - { - if( name.startsWith( "ore" ) || name.startsWith( "crystal" ) || name.startsWith( "gem" ) || name.startsWith( "ingot" ) || name.startsWith( "dust" ) ) - { - for( final String ore : AEConfig.instance.grinderOres ) - { - if( name.equals( "ore" + ore ) ) - { - this.addOre( ore, item ); - } - else if( name.equals( "crystal" + ore ) || name.equals( "ingot" + ore ) || name.equals( "gem" + ore ) ) - { - this.addIngot( ore, item ); - } - else if( name.equals( "dust" + ore ) ) - { - this.addDust( ore, item ); - } - } - } - } +public final class GrinderRecipeManager implements IGrinderRegistry, IOreListener { + private final List recipes; + private final Map ores; + private final Map ingots; + private final Map dusts; + + public GrinderRecipeManager() { + this.recipes = new ArrayList(); + this.ores = new HashMap(); + this.ingots = new HashMap(); + this.dusts = new HashMap(); + + this.addOre("Coal", new ItemStack(Items.coal)); + this.addOre("Charcoal", new ItemStack(Items.coal, 1, 1)); + + this.addOre("NetherQuartz", new ItemStack(Blocks.quartz_ore)); + this.addIngot("NetherQuartz", new ItemStack(Items.quartz)); + + this.addOre("Gold", new ItemStack(Blocks.gold_ore)); + this.addIngot("Gold", new ItemStack(Items.gold_ingot)); + + this.addOre("Iron", new ItemStack(Blocks.iron_ore)); + this.addIngot("Iron", new ItemStack(Items.iron_ingot)); + + this.addOre("Obsidian", new ItemStack(Blocks.obsidian)); + + this.addIngot("Ender", new ItemStack(Items.ender_pearl)); + this.addIngot("EnderPearl", new ItemStack(Items.ender_pearl)); + + this.addIngot("Wheat", new ItemStack(Items.wheat)); + + OreDictionaryHandler.INSTANCE.observe(this); + } + + @Override + public List getRecipes() { + this.log("API - getRecipes"); + return this.recipes; + } + + @Override + public void addRecipe(final ItemStack in, final ItemStack out, final int cost) { + if (in == null || out == null) { + this.log("Invalid Grinder Recipe Specified."); + return; + } + + this.log("Allow Grinding of " + Platform.getItemDisplayName(in) + " to " + Platform.getItemDisplayName(out) + + " for " + cost); + this.injectRecipe(new AppEngGrinderRecipe(this.copy(in), this.copy(out), cost)); + } + + @Override + public void addRecipe( + final ItemStack in, final ItemStack out, final ItemStack optional, final float chance, final int cost) { + if (in == null || (optional == null && out == null)) { + this.log("Invalid Grinder Recipe Specified."); + return; + } + + this.log("Allow Grinding of " + Platform.getItemDisplayName(in) + " to " + Platform.getItemDisplayName(out) + + " with optional " + Platform.getItemDisplayName(optional) + " for " + cost); + this.injectRecipe(new AppEngGrinderRecipe(this.copy(in), this.copy(out), this.copy(optional), chance, cost)); + } + + @Override + public void addRecipe( + final ItemStack in, + final ItemStack out, + final ItemStack optional, + final float chance, + final ItemStack optional2, + final float chance2, + final int cost) { + if (in == null || (optional == null && out == null && optional2 == null)) { + this.log("Invalid Grinder Recipe Specified."); + return; + } + + this.log("Allow Grinding of " + Platform.getItemDisplayName(in) + " to " + Platform.getItemDisplayName(out) + + " with optional " + Platform.getItemDisplayName(optional) + " for " + cost); + this.injectRecipe(new AppEngGrinderRecipe( + this.copy(in), this.copy(out), this.copy(optional), this.copy(optional2), chance, chance2, cost)); + } + + private void injectRecipe(final AppEngGrinderRecipe appEngGrinderRecipe) { + for (final IGrinderEntry gr : this.recipes) { + if (Platform.isSameItemPrecise(gr.getInput(), appEngGrinderRecipe.getInput())) { + return; + } + } + + this.recipes.add(appEngGrinderRecipe); + } + + private ItemStack copy(final ItemStack is) { + if (is != null) { + return is.copy(); + } + return null; + } + + @Override + public IGrinderEntry getRecipeForInput(final ItemStack input) { + this.log("Looking up recipe for " + Platform.getItemDisplayName(input)); + if (input != null) { + for (final IGrinderEntry r : this.recipes) { + if (Platform.isSameItem(input, r.getInput())) { + this.log("Recipe for " + input.getUnlocalizedName() + " found " + + Platform.getItemDisplayName(r.getOutput())); + return r; + } + } + + this.log("Could not find recipe for " + Platform.getItemDisplayName(input)); + } + + return null; + } + + private void log(final String o) { + AELog.grinder(o); + } + + private int getDustToOreRatio(final String name) { + if (name.equals("Obsidian")) { + return 1; + } + if (name.equals("Charcoal")) { + return 1; + } + if (name.equals("Coal")) { + return 1; + } + return 2; + } + + private void addOre(final String name, final ItemStack item) { + if (item == null) { + return; + } + this.log("Adding Ore - " + name + " : " + Platform.getItemDisplayName(item)); + + this.ores.put(item, name); + + if (this.dusts.containsKey(name)) { + final ItemStack is = this.dusts.get(name).copy(); + final int ratio = this.getDustToOreRatio(name); + if (ratio > 1) { + final ItemStack extra = is.copy(); + extra.stackSize = ratio - 1; + this.addRecipe(item, is, extra, (float) (AEConfig.instance.oreDoublePercentage / 100.0), 8); + } else { + this.addRecipe(item, is, 8); + } + } + } + + private void addIngot(final String name, final ItemStack item) { + if (item == null) { + return; + } + this.log("Adding Ingot - " + name + " : " + Platform.getItemDisplayName(item)); + + this.ingots.put(item, name); + + if (this.dusts.containsKey(name)) { + this.addRecipe(item, this.dusts.get(name), 4); + } + } + + private void addDust(final String name, final ItemStack item) { + if (item == null) { + return; + } + if (this.dusts.containsKey(name)) { + this.log("Rejecting Dust - " + name + " : " + Platform.getItemDisplayName(item)); + return; + } + + this.log("Adding Dust - " + name + " : " + Platform.getItemDisplayName(item)); + + this.dusts.put(name, item); + + for (final Entry d : this.ores.entrySet()) { + if (name.equals(d.getValue())) { + final ItemStack is = item.copy(); + is.stackSize = 1; + final int ratio = this.getDustToOreRatio(name); + if (ratio > 1) { + final ItemStack extra = is.copy(); + extra.stackSize = ratio - 1; + this.addRecipe(d.getKey(), is, extra, (float) (AEConfig.instance.oreDoublePercentage / 100.0), 8); + } else { + this.addRecipe(d.getKey(), is, 8); + } + } + } + + for (final Entry d : this.ingots.entrySet()) { + if (name.equals(d.getValue())) { + this.addRecipe(d.getKey(), item, 4); + } + } + } + + @Override + public void oreRegistered(final String name, final ItemStack item) { + if (name.startsWith("ore") + || name.startsWith("crystal") + || name.startsWith("gem") + || name.startsWith("ingot") + || name.startsWith("dust")) { + for (final String ore : AEConfig.instance.grinderOres) { + if (name.equals("ore" + ore)) { + this.addOre(ore, item); + } else if (name.equals("crystal" + ore) || name.equals("ingot" + ore) || name.equals("gem" + ore)) { + this.addIngot(ore, item); + } else if (name.equals("dust" + ore)) { + this.addDust(ore, item); + } + } + } + } } diff --git a/src/main/java/appeng/core/features/registries/InscriberRegistry.java b/src/main/java/appeng/core/features/registries/InscriberRegistry.java index ac2bbd841a4..b39684892f4 100644 --- a/src/main/java/appeng/core/features/registries/InscriberRegistry.java +++ b/src/main/java/appeng/core/features/registries/InscriberRegistry.java @@ -18,177 +18,151 @@ package appeng.core.features.registries; - import appeng.api.features.IInscriberRecipe; import appeng.api.features.IInscriberRecipeBuilder; import appeng.api.features.IInscriberRegistry; import appeng.api.features.InscriberProcessType; import appeng.core.features.registries.entries.InscriberRecipe; -import net.minecraft.item.ItemStack; - -import javax.annotation.Nonnull; import java.util.*; - +import javax.annotation.Nonnull; +import net.minecraft.item.ItemStack; /** * @author thatsIch * @version rv3 * @since rv2 */ -public final class InscriberRegistry implements IInscriberRegistry -{ - private final Set recipes; - private final Set optionals; - private final Set inputs; - - public InscriberRegistry() - { - this.inputs = new HashSet(); - this.optionals = new HashSet(); - this.recipes = new HashSet(); - } - - @Nonnull - @Override - public Collection getRecipes() - { - return Collections.unmodifiableCollection( this.recipes ); - } - - @Nonnull - @Override - public Set getOptionals() - { - return this.optionals; - } - - @Nonnull - @Override - public Set getInputs() - { - return this.inputs; - } - - @Nonnull - @Override - public IInscriberRecipeBuilder builder() - { - return new Builder(); - } - - @Override - public void addRecipe( final IInscriberRecipe recipe ) - { - if( recipe == null ) - { - throw new IllegalArgumentException( "Tried to add an invalid (null) inscriber recipe to the registry." ); - } - - this.recipes.add( recipe ); - - this.optionals.addAll( recipe.getTopOptional().asSet() ); - this.optionals.addAll( recipe.getBottomOptional().asSet() ); - - this.inputs.addAll( recipe.getInputs() ); - } - - @Override - public void removeRecipe( final IInscriberRecipe toBeRemovedRecipe ) - { - for( final Iterator iterator = this.recipes.iterator(); iterator.hasNext(); ) - { - final IInscriberRecipe recipe = iterator.next(); - if( recipe.equals( toBeRemovedRecipe ) ) - { - iterator.remove(); - } - } - } - - /** - * Internal {@link IInscriberRecipeBuilder} implementation. - * Needs to be adapted to represent a correct {@link IInscriberRecipe} - */ - private static final class Builder implements IInscriberRecipeBuilder - { - private List inputs; - private ItemStack output; - private ItemStack topOptional; - private ItemStack bottomOptional; - private InscriberProcessType type; - - @Nonnull - @Override - public Builder withInputs( @Nonnull final Collection inputs ) - { - this.inputs = new ArrayList( inputs.size() ); - this.inputs.addAll( inputs ); - - return this; - } - - @Nonnull - @Override - public Builder withOutput( @Nonnull final ItemStack output ) - { - this.output = output; - - return this; - } - - @Nonnull - @Override - public Builder withTopOptional( @Nonnull final ItemStack topOptional ) - { - this.topOptional = topOptional; - - return this; - } - - @Nonnull - @Override - public Builder withBottomOptional( @Nonnull final ItemStack bottomOptional ) - { - this.bottomOptional = bottomOptional; - - return this; - } - - @Nonnull - @Override - public Builder withProcessType( @Nonnull final InscriberProcessType type ) - { - this.type = type; - - return this; - } - - @Nonnull - @Override - public IInscriberRecipe build() - { - if( this.inputs == null ) - { - throw new IllegalStateException( "Input must be defined." ); - } - if( this.inputs.isEmpty() ) - { - throw new IllegalStateException( "Input must have a size." ); - } - if( this.output == null ) - { - throw new IllegalStateException( "Output must be defined." ); - } - if( this.topOptional == null && this.bottomOptional == null ) - { - throw new IllegalStateException( "One optional must be defined." ); - } - if( this.type == null ) - { - throw new IllegalStateException( "Process type must be defined." ); - } - - return new InscriberRecipe( this.inputs, this.output, this.topOptional, this.bottomOptional, this.type ); - } - } +public final class InscriberRegistry implements IInscriberRegistry { + private final Set recipes; + private final Set optionals; + private final Set inputs; + + public InscriberRegistry() { + this.inputs = new HashSet(); + this.optionals = new HashSet(); + this.recipes = new HashSet(); + } + + @Nonnull + @Override + public Collection getRecipes() { + return Collections.unmodifiableCollection(this.recipes); + } + + @Nonnull + @Override + public Set getOptionals() { + return this.optionals; + } + + @Nonnull + @Override + public Set getInputs() { + return this.inputs; + } + + @Nonnull + @Override + public IInscriberRecipeBuilder builder() { + return new Builder(); + } + + @Override + public void addRecipe(final IInscriberRecipe recipe) { + if (recipe == null) { + throw new IllegalArgumentException("Tried to add an invalid (null) inscriber recipe to the registry."); + } + + this.recipes.add(recipe); + + this.optionals.addAll(recipe.getTopOptional().asSet()); + this.optionals.addAll(recipe.getBottomOptional().asSet()); + + this.inputs.addAll(recipe.getInputs()); + } + + @Override + public void removeRecipe(final IInscriberRecipe toBeRemovedRecipe) { + for (final Iterator iterator = this.recipes.iterator(); iterator.hasNext(); ) { + final IInscriberRecipe recipe = iterator.next(); + if (recipe.equals(toBeRemovedRecipe)) { + iterator.remove(); + } + } + } + + /** + * Internal {@link IInscriberRecipeBuilder} implementation. + * Needs to be adapted to represent a correct {@link IInscriberRecipe} + */ + private static final class Builder implements IInscriberRecipeBuilder { + private List inputs; + private ItemStack output; + private ItemStack topOptional; + private ItemStack bottomOptional; + private InscriberProcessType type; + + @Nonnull + @Override + public Builder withInputs(@Nonnull final Collection inputs) { + this.inputs = new ArrayList(inputs.size()); + this.inputs.addAll(inputs); + + return this; + } + + @Nonnull + @Override + public Builder withOutput(@Nonnull final ItemStack output) { + this.output = output; + + return this; + } + + @Nonnull + @Override + public Builder withTopOptional(@Nonnull final ItemStack topOptional) { + this.topOptional = topOptional; + + return this; + } + + @Nonnull + @Override + public Builder withBottomOptional(@Nonnull final ItemStack bottomOptional) { + this.bottomOptional = bottomOptional; + + return this; + } + + @Nonnull + @Override + public Builder withProcessType(@Nonnull final InscriberProcessType type) { + this.type = type; + + return this; + } + + @Nonnull + @Override + public IInscriberRecipe build() { + if (this.inputs == null) { + throw new IllegalStateException("Input must be defined."); + } + if (this.inputs.isEmpty()) { + throw new IllegalStateException("Input must have a size."); + } + if (this.output == null) { + throw new IllegalStateException("Output must be defined."); + } + if (this.topOptional == null && this.bottomOptional == null) { + throw new IllegalStateException("One optional must be defined."); + } + if (this.type == null) { + throw new IllegalStateException("Process type must be defined."); + } + + return new InscriberRecipe(this.inputs, this.output, this.topOptional, this.bottomOptional, this.type); + } + } } diff --git a/src/main/java/appeng/core/features/registries/LocatableRegistry.java b/src/main/java/appeng/core/features/registries/LocatableRegistry.java index d0e069e11b2..e241efa8182 100644 --- a/src/main/java/appeng/core/features/registries/LocatableRegistry.java +++ b/src/main/java/appeng/core/features/registries/LocatableRegistry.java @@ -18,60 +18,48 @@ package appeng.core.features.registries; - import appeng.api.events.LocatableEventAnnounce; import appeng.api.events.LocatableEventAnnounce.LocatableEvent; import appeng.api.features.ILocatable; import appeng.api.features.ILocatableRegistry; import appeng.util.Platform; import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.common.MinecraftForge; - import java.util.HashMap; import java.util.Map; +import net.minecraftforge.common.MinecraftForge; +public final class LocatableRegistry implements ILocatableRegistry { + private final Map set; -public final class LocatableRegistry implements ILocatableRegistry -{ - private final Map set; - - public LocatableRegistry() - { - this.set = new HashMap(); - MinecraftForge.EVENT_BUS.register( this ); - } + public LocatableRegistry() { + this.set = new HashMap(); + MinecraftForge.EVENT_BUS.register(this); + } - @SubscribeEvent - public void updateLocatable( final LocatableEventAnnounce e ) - { - if( Platform.isClient() ) - { - return; // IGNORE! - } + @SubscribeEvent + public void updateLocatable(final LocatableEventAnnounce e) { + if (Platform.isClient()) { + return; // IGNORE! + } - if( e.change == LocatableEvent.Register ) - { - this.set.put( e.target.getLocatableSerial(), e.target ); - } - else if( e.change == LocatableEvent.Unregister ) - { - this.set.remove( e.target.getLocatableSerial() ); - } - } + if (e.change == LocatableEvent.Register) { + this.set.put(e.target.getLocatableSerial(), e.target); + } else if (e.change == LocatableEvent.Unregister) { + this.set.remove(e.target.getLocatableSerial()); + } + } - /** - * Find a locate-able object by its serial. - */ - @Override - @Deprecated - public Object findLocatableBySerial( final long ser ) - { - return this.set.get( ser ); - } + /** + * Find a locate-able object by its serial. + */ + @Override + @Deprecated + public Object findLocatableBySerial(final long ser) { + return this.set.get(ser); + } - @Override - public ILocatable getLocatableBy( final long serial ) - { - return this.set.get( serial ); - } + @Override + public ILocatable getLocatableBy(final long serial) { + return this.set.get(serial); + } } diff --git a/src/main/java/appeng/core/features/registries/MatterCannonAmmoRegistry.java b/src/main/java/appeng/core/features/registries/MatterCannonAmmoRegistry.java index 9ff3af34c6e..f3b060c6449 100644 --- a/src/main/java/appeng/core/features/registries/MatterCannonAmmoRegistry.java +++ b/src/main/java/appeng/core/features/registries/MatterCannonAmmoRegistry.java @@ -18,133 +18,120 @@ package appeng.core.features.registries; - import appeng.api.features.IMatterCannonAmmoRegistry; import appeng.recipes.ores.IOreListener; import appeng.recipes.ores.OreDictionaryHandler; import appeng.util.Platform; +import java.util.HashMap; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; -import java.util.HashMap; - - -public class MatterCannonAmmoRegistry implements IOreListener, IMatterCannonAmmoRegistry -{ +public class MatterCannonAmmoRegistry implements IOreListener, IMatterCannonAmmoRegistry { - private final HashMap DamageModifiers = new HashMap(); + private final HashMap DamageModifiers = new HashMap(); - public MatterCannonAmmoRegistry() - { - OreDictionaryHandler.INSTANCE.observe( this ); - this.registerAmmo( new ItemStack( Items.gold_nugget ), 196.96655 ); - } + public MatterCannonAmmoRegistry() { + OreDictionaryHandler.INSTANCE.observe(this); + this.registerAmmo(new ItemStack(Items.gold_nugget), 196.96655); + } - @Override - public void registerAmmo( final ItemStack ammo, final double weight ) - { - this.DamageModifiers.put( ammo, weight ); - } + @Override + public void registerAmmo(final ItemStack ammo, final double weight) { + this.DamageModifiers.put(ammo, weight); + } - @Override - public float getPenetration( final ItemStack is ) - { - for( final ItemStack o : this.DamageModifiers.keySet() ) - { - if( Platform.isSameItem( o, is ) ) - { - return this.DamageModifiers.get( o ).floatValue(); - } - } - return 0; - } + @Override + public float getPenetration(final ItemStack is) { + for (final ItemStack o : this.DamageModifiers.keySet()) { + if (Platform.isSameItem(o, is)) { + return this.DamageModifiers.get(o).floatValue(); + } + } + return 0; + } - @Override - public void oreRegistered( final String name, final ItemStack item ) - { - if( !( name.startsWith( "berry" ) || name.startsWith( "nugget" ) ) ) - { - return; - } + @Override + public void oreRegistered(final String name, final ItemStack item) { + if (!(name.startsWith("berry") || name.startsWith("nugget"))) { + return; + } - // addNugget( "Cobble", 18 ); // ? - this.considerItem( name, item, "MeatRaw", 32 ); - this.considerItem( name, item, "MeatCooked", 32 ); - this.considerItem( name, item, "Meat", 32 ); - this.considerItem( name, item, "Chicken", 32 ); - this.considerItem( name, item, "Beef", 32 ); - this.considerItem( name, item, "Sheep", 32 ); - this.considerItem( name, item, "Fish", 32 ); + // addNugget( "Cobble", 18 ); // ? + this.considerItem(name, item, "MeatRaw", 32); + this.considerItem(name, item, "MeatCooked", 32); + this.considerItem(name, item, "Meat", 32); + this.considerItem(name, item, "Chicken", 32); + this.considerItem(name, item, "Beef", 32); + this.considerItem(name, item, "Sheep", 32); + this.considerItem(name, item, "Fish", 32); - // real world... - this.considerItem( name, item, "Lithium", 6.941 ); - this.considerItem( name, item, "Beryllium", 9.0122 ); - this.considerItem( name, item, "Boron", 10.811 ); - this.considerItem( name, item, "Carbon", 12.0107 ); - this.considerItem( name, item, "Coal", 12.0107 ); - this.considerItem( name, item, "Charcoal", 12.0107 ); - this.considerItem( name, item, "Sodium", 22.9897 ); - this.considerItem( name, item, "Magnesium", 24.305 ); - this.considerItem( name, item, "Aluminum", 26.9815 ); - this.considerItem( name, item, "Silicon", 28.0855 ); - this.considerItem( name, item, "Phosphorus", 30.9738 ); - this.considerItem( name, item, "Sulfur", 32.065 ); - this.considerItem( name, item, "Potassium", 39.0983 ); - this.considerItem( name, item, "Calcium", 40.078 ); - this.considerItem( name, item, "Scandium", 44.9559 ); - this.considerItem( name, item, "Titanium", 47.867 ); - this.considerItem( name, item, "Vanadium", 50.9415 ); - this.considerItem( name, item, "Manganese", 54.938 ); - this.considerItem( name, item, "Iron", 55.845 ); - this.considerItem( name, item, "Nickel", 58.6934 ); - this.considerItem( name, item, "Cobalt", 58.9332 ); - this.considerItem( name, item, "Copper", 63.546 ); - this.considerItem( name, item, "Zinc", 65.39 ); - this.considerItem( name, item, "Gallium", 69.723 ); - this.considerItem( name, item, "Germanium", 72.64 ); - this.considerItem( name, item, "Bromine", 79.904 ); - this.considerItem( name, item, "Krypton", 83.8 ); - this.considerItem( name, item, "Rubidium", 85.4678 ); - this.considerItem( name, item, "Strontium", 87.62 ); - this.considerItem( name, item, "Yttrium", 88.9059 ); - this.considerItem( name, item, "Zirconiumm", 91.224 ); - this.considerItem( name, item, "Niobiumm", 92.9064 ); - this.considerItem( name, item, "Technetium", 98 ); - this.considerItem( name, item, "Ruthenium", 101.07 ); - this.considerItem( name, item, "Rhodium", 102.9055 ); - this.considerItem( name, item, "Palladium", 106.42 ); - this.considerItem( name, item, "Silver", 107.8682 ); - this.considerItem( name, item, "Cadmium", 112.411 ); - this.considerItem( name, item, "Indium", 114.818 ); - this.considerItem( name, item, "Tin", 118.71 ); - this.considerItem( name, item, "Antimony", 121.76 ); - this.considerItem( name, item, "Iodine", 126.9045 ); - this.considerItem( name, item, "Tellurium", 127.6 ); - this.considerItem( name, item, "Xenon", 131.293 ); - this.considerItem( name, item, "Cesium", 132.9055 ); - this.considerItem( name, item, "Barium", 137.327 ); - this.considerItem( name, item, "Lanthanum", 138.9055 ); - this.considerItem( name, item, "Cerium", 140.116 ); - this.considerItem( name, item, "Tantalum", 180.9479 ); - this.considerItem( name, item, "Tungsten", 183.84 ); - this.considerItem( name, item, "Osmium", 190.23 ); - this.considerItem( name, item, "Iridium", 192.217 ); - this.considerItem( name, item, "Platinum", 195.078 ); - this.considerItem( name, item, "Lead", 207.2 ); - this.considerItem( name, item, "Bismuth", 208.9804 ); - this.considerItem( name, item, "Uranium", 238.0289 ); - this.considerItem( name, item, "Plutonium", 244 ); + // real world... + this.considerItem(name, item, "Lithium", 6.941); + this.considerItem(name, item, "Beryllium", 9.0122); + this.considerItem(name, item, "Boron", 10.811); + this.considerItem(name, item, "Carbon", 12.0107); + this.considerItem(name, item, "Coal", 12.0107); + this.considerItem(name, item, "Charcoal", 12.0107); + this.considerItem(name, item, "Sodium", 22.9897); + this.considerItem(name, item, "Magnesium", 24.305); + this.considerItem(name, item, "Aluminum", 26.9815); + this.considerItem(name, item, "Silicon", 28.0855); + this.considerItem(name, item, "Phosphorus", 30.9738); + this.considerItem(name, item, "Sulfur", 32.065); + this.considerItem(name, item, "Potassium", 39.0983); + this.considerItem(name, item, "Calcium", 40.078); + this.considerItem(name, item, "Scandium", 44.9559); + this.considerItem(name, item, "Titanium", 47.867); + this.considerItem(name, item, "Vanadium", 50.9415); + this.considerItem(name, item, "Manganese", 54.938); + this.considerItem(name, item, "Iron", 55.845); + this.considerItem(name, item, "Nickel", 58.6934); + this.considerItem(name, item, "Cobalt", 58.9332); + this.considerItem(name, item, "Copper", 63.546); + this.considerItem(name, item, "Zinc", 65.39); + this.considerItem(name, item, "Gallium", 69.723); + this.considerItem(name, item, "Germanium", 72.64); + this.considerItem(name, item, "Bromine", 79.904); + this.considerItem(name, item, "Krypton", 83.8); + this.considerItem(name, item, "Rubidium", 85.4678); + this.considerItem(name, item, "Strontium", 87.62); + this.considerItem(name, item, "Yttrium", 88.9059); + this.considerItem(name, item, "Zirconiumm", 91.224); + this.considerItem(name, item, "Niobiumm", 92.9064); + this.considerItem(name, item, "Technetium", 98); + this.considerItem(name, item, "Ruthenium", 101.07); + this.considerItem(name, item, "Rhodium", 102.9055); + this.considerItem(name, item, "Palladium", 106.42); + this.considerItem(name, item, "Silver", 107.8682); + this.considerItem(name, item, "Cadmium", 112.411); + this.considerItem(name, item, "Indium", 114.818); + this.considerItem(name, item, "Tin", 118.71); + this.considerItem(name, item, "Antimony", 121.76); + this.considerItem(name, item, "Iodine", 126.9045); + this.considerItem(name, item, "Tellurium", 127.6); + this.considerItem(name, item, "Xenon", 131.293); + this.considerItem(name, item, "Cesium", 132.9055); + this.considerItem(name, item, "Barium", 137.327); + this.considerItem(name, item, "Lanthanum", 138.9055); + this.considerItem(name, item, "Cerium", 140.116); + this.considerItem(name, item, "Tantalum", 180.9479); + this.considerItem(name, item, "Tungsten", 183.84); + this.considerItem(name, item, "Osmium", 190.23); + this.considerItem(name, item, "Iridium", 192.217); + this.considerItem(name, item, "Platinum", 195.078); + this.considerItem(name, item, "Lead", 207.2); + this.considerItem(name, item, "Bismuth", 208.9804); + this.considerItem(name, item, "Uranium", 238.0289); + this.considerItem(name, item, "Plutonium", 244); - // TE stuff... - this.considerItem( name, item, "Invar", ( 58.6934 + 55.845 + 55.845 ) / 3.0 ); - this.considerItem( name, item, "Electrum", ( 107.8682 + 196.96655 ) / 2.0 ); - } + // TE stuff... + this.considerItem(name, item, "Invar", (58.6934 + 55.845 + 55.845) / 3.0); + this.considerItem(name, item, "Electrum", (107.8682 + 196.96655) / 2.0); + } - private void considerItem( final String ore, final ItemStack item, final String name, final double weight ) - { - if( ore.equals( "berry" + name ) || ore.equals( "nugget" + name ) ) - { - this.registerAmmo( item, weight ); - } - } + private void considerItem(final String ore, final ItemStack item, final String name, final double weight) { + if (ore.equals("berry" + name) || ore.equals("nugget" + name)) { + this.registerAmmo(item, weight); + } + } } diff --git a/src/main/java/appeng/core/features/registries/MovableTileRegistry.java b/src/main/java/appeng/core/features/registries/MovableTileRegistry.java index 337415e64ab..a70395b69e7 100644 --- a/src/main/java/appeng/core/features/registries/MovableTileRegistry.java +++ b/src/main/java/appeng/core/features/registries/MovableTileRegistry.java @@ -18,149 +18,127 @@ package appeng.core.features.registries; - import appeng.api.exceptions.AppEngException; import appeng.api.movable.IMovableHandler; import appeng.api.movable.IMovableRegistry; import appeng.api.movable.IMovableTile; import appeng.spatial.DefaultSpatialHandler; -import net.minecraft.block.Block; -import net.minecraft.tileentity.TileEntity; - import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; +import net.minecraft.block.Block; +import net.minecraft.tileentity.TileEntity; - -public class MovableTileRegistry implements IMovableRegistry -{ - - private final HashSet blacklisted = new HashSet(); - - private final HashMap, IMovableHandler> Valid = new HashMap, IMovableHandler>(); - private final LinkedList> test = new LinkedList>(); - private final LinkedList handlers = new LinkedList(); - private final DefaultSpatialHandler dsh = new DefaultSpatialHandler(); - - private final IMovableHandler nullHandler = new DefaultSpatialHandler(); - - @Override - public void blacklistBlock( final Block blk ) - { - this.blacklisted.add( blk ); - } - - @Override - public void whiteListTileEntity( final Class c ) - { - if( c.getName().equals( TileEntity.class.getName() ) ) - { - throw new IllegalArgumentException( new AppEngException( "Someone tried to make all tiles movable with " + c + ", this is a clear violation of the purpose of the white list." ) ); - } - - this.test.add( c ); - } - - @Override - public boolean askToMove( final TileEntity te ) - { - final Class myClass = te.getClass(); - IMovableHandler canMove = this.Valid.get( myClass ); - - if( canMove == null ) - { - canMove = this.testClass( myClass, te ); - } - - if( canMove != this.nullHandler ) - { - if( te instanceof IMovableTile ) - { - ( (IMovableTile) te ).prepareToMove(); - } - - te.invalidate(); - return true; - } - - return false; - } - - private IMovableHandler testClass( final Class myClass, final TileEntity te ) - { - IMovableHandler handler = null; - - // ask handlers... - for( final IMovableHandler han : this.handlers ) - { - if( han.canHandle( myClass, te ) ) - { - handler = han; - break; - } - } - - // if you have a handler your opted in - if( handler != null ) - { - this.Valid.put( myClass, handler ); - return handler; - } - - // if your movable our opted in - if( te instanceof IMovableTile ) - { - this.Valid.put( myClass, this.dsh ); - return this.dsh; - } - - // if you are on the white list your opted in. - for( final Class testClass : this.test ) - { - if( testClass.isAssignableFrom( myClass ) ) - { - this.Valid.put( myClass, this.dsh ); - return this.dsh; - } - } - - this.Valid.put( myClass, this.nullHandler ); - return this.nullHandler; - } - - @Override - public void doneMoving( final TileEntity te ) - { - if( te instanceof IMovableTile ) - { - final IMovableTile mt = (IMovableTile) te; - mt.doneMoving(); - } - } - - @Override - public void addHandler( final IMovableHandler han ) - { - this.handlers.add( han ); - } - - @Override - public IMovableHandler getHandler( final TileEntity te ) - { - final Class myClass = te.getClass(); - final IMovableHandler h = this.Valid.get( myClass ); - return h == null ? this.dsh : h; - } - - @Override - public IMovableHandler getDefaultHandler() - { - return this.dsh; - } - - @Override - public boolean isBlacklisted( final Block blk ) - { - return this.blacklisted.contains( blk ); - } +public class MovableTileRegistry implements IMovableRegistry { + + private final HashSet blacklisted = new HashSet(); + + private final HashMap, IMovableHandler> Valid = + new HashMap, IMovableHandler>(); + private final LinkedList> test = new LinkedList>(); + private final LinkedList handlers = new LinkedList(); + private final DefaultSpatialHandler dsh = new DefaultSpatialHandler(); + + private final IMovableHandler nullHandler = new DefaultSpatialHandler(); + + @Override + public void blacklistBlock(final Block blk) { + this.blacklisted.add(blk); + } + + @Override + public void whiteListTileEntity(final Class c) { + if (c.getName().equals(TileEntity.class.getName())) { + throw new IllegalArgumentException(new AppEngException("Someone tried to make all tiles movable with " + c + + ", this is a clear violation of the purpose of the white list.")); + } + + this.test.add(c); + } + + @Override + public boolean askToMove(final TileEntity te) { + final Class myClass = te.getClass(); + IMovableHandler canMove = this.Valid.get(myClass); + + if (canMove == null) { + canMove = this.testClass(myClass, te); + } + + if (canMove != this.nullHandler) { + if (te instanceof IMovableTile) { + ((IMovableTile) te).prepareToMove(); + } + + te.invalidate(); + return true; + } + + return false; + } + + private IMovableHandler testClass(final Class myClass, final TileEntity te) { + IMovableHandler handler = null; + + // ask handlers... + for (final IMovableHandler han : this.handlers) { + if (han.canHandle(myClass, te)) { + handler = han; + break; + } + } + + // if you have a handler your opted in + if (handler != null) { + this.Valid.put(myClass, handler); + return handler; + } + + // if your movable our opted in + if (te instanceof IMovableTile) { + this.Valid.put(myClass, this.dsh); + return this.dsh; + } + + // if you are on the white list your opted in. + for (final Class testClass : this.test) { + if (testClass.isAssignableFrom(myClass)) { + this.Valid.put(myClass, this.dsh); + return this.dsh; + } + } + + this.Valid.put(myClass, this.nullHandler); + return this.nullHandler; + } + + @Override + public void doneMoving(final TileEntity te) { + if (te instanceof IMovableTile) { + final IMovableTile mt = (IMovableTile) te; + mt.doneMoving(); + } + } + + @Override + public void addHandler(final IMovableHandler han) { + this.handlers.add(han); + } + + @Override + public IMovableHandler getHandler(final TileEntity te) { + final Class myClass = te.getClass(); + final IMovableHandler h = this.Valid.get(myClass); + return h == null ? this.dsh : h; + } + + @Override + public IMovableHandler getDefaultHandler() { + return this.dsh; + } + + @Override + public boolean isBlacklisted(final Block blk) { + return this.blacklisted.contains(blk); + } } diff --git a/src/main/java/appeng/core/features/registries/P2PTunnelRegistry.java b/src/main/java/appeng/core/features/registries/P2PTunnelRegistry.java index b1fc0952d4b..b234cf37328 100644 --- a/src/main/java/appeng/core/features/registries/P2PTunnelRegistry.java +++ b/src/main/java/appeng/core/features/registries/P2PTunnelRegistry.java @@ -18,7 +18,6 @@ package appeng.core.features.registries; - import appeng.api.AEApi; import appeng.api.config.TunnelType; import appeng.api.definitions.IBlocks; @@ -29,152 +28,139 @@ import appeng.api.util.AEColor; import appeng.util.Platform; import cpw.mods.fml.common.registry.GameRegistry; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.oredict.OreDictionary; -import javax.annotation.Nullable; -import java.util.HashMap; -import java.util.Map; - - -public final class P2PTunnelRegistry implements IP2PTunnelRegistry -{ - private static final int INITIAL_CAPACITY = 40; - - private final Map tunnels = new HashMap( INITIAL_CAPACITY ); - - public void configure() - { - /** - * light! - */ - this.addNewAttunement( new ItemStack( Blocks.torch ), TunnelType.LIGHT ); - this.addNewAttunement( new ItemStack( Blocks.glowstone ), TunnelType.LIGHT ); - - /** - * attune based on most redstone base items. - */ - this.addNewAttunement( new ItemStack( Items.redstone ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Items.repeater ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.redstone_lamp ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.unpowered_comparator ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.powered_comparator ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.powered_repeater ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.unpowered_repeater ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.daylight_detector ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.redstone_wire ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.redstone_block ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.lever ), TunnelType.REDSTONE ); - this.addNewAttunement( this.getModItem( "EnderIO", "itemRedstoneConduit", OreDictionary.WILDCARD_VALUE ), TunnelType.REDSTONE ); - - /** - * attune based on lots of random item related stuff - */ - final IDefinitions definitions = AEApi.instance().definitions(); - final IBlocks blocks = definitions.blocks(); - final IParts parts = definitions.parts(); - - this.addNewAttunement( blocks.iface(), TunnelType.ITEM ); - this.addNewAttunement( parts.iface(), TunnelType.ITEM ); - this.addNewAttunement( parts.storageBus(), TunnelType.ITEM ); - this.addNewAttunement( parts.importBus(), TunnelType.ITEM ); - this.addNewAttunement( parts.exportBus(), TunnelType.ITEM ); - - this.addNewAttunement( new ItemStack( Blocks.hopper ), TunnelType.ITEM ); - this.addNewAttunement( new ItemStack( Blocks.chest ), TunnelType.ITEM ); - this.addNewAttunement( new ItemStack( Blocks.trapped_chest ), TunnelType.ITEM ); - this.addNewAttunement( this.getModItem( "ExtraUtilities", "extractor_base", 0 ), TunnelType.ITEM ); - this.addNewAttunement( this.getModItem( "Mekanism", "PartTransmitter", 9 ), TunnelType.ITEM ); - this.addNewAttunement( this.getModItem( "EnderIO", "itemItemConduit", OreDictionary.WILDCARD_VALUE ), TunnelType.ITEM ); - this.addNewAttunement( this.getModItem( "ThermalDynamics", "ThermalDynamics_32", 0 ), TunnelType.ITEM ); - - /** - * attune based on lots of random item related stuff - */ - this.addNewAttunement( new ItemStack( Items.bucket ), TunnelType.FLUID ); - this.addNewAttunement( new ItemStack( Items.lava_bucket ), TunnelType.FLUID ); - this.addNewAttunement( new ItemStack( Items.milk_bucket ), TunnelType.FLUID ); - this.addNewAttunement( new ItemStack( Items.water_bucket ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "Mekanism", "MachineBlock2", 11 ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "Mekanism", "PartTransmitter", 4 ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "ExtraUtilities", "extractor_base", 6 ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "ExtraUtilities", "drum", OreDictionary.WILDCARD_VALUE ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "EnderIO", "itemLiquidConduit", OreDictionary.WILDCARD_VALUE ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "ThermalDynamics", "ThermalDynamics_16", 0 ), TunnelType.FLUID ); - - for( final AEColor c : AEColor.values() ) - { - this.addNewAttunement( parts.cableGlass().stack( c, 1 ), TunnelType.ME ); - this.addNewAttunement( parts.cableCovered().stack( c, 1 ), TunnelType.ME ); - this.addNewAttunement( parts.cableSmart().stack( c, 1 ), TunnelType.ME ); - this.addNewAttunement( parts.cableDense().stack( c, 1 ), TunnelType.ME ); - this.addNewAttunement( parts.cableDenseCovered().stack( c, 1 ), TunnelType.ME ); - this.addNewAttunement( parts.cableUltraDenseCovered().stack( c, 1 ), TunnelType.ME ); - this.addNewAttunement( parts.cableUltraDenseSmart().stack( c, 1 ), TunnelType.ME ); - } - } - - @Override - public void addNewAttunement( @Nullable final ItemStack trigger, @Nullable final TunnelType type ) - { - if( type == null || trigger == null ) - { - return; - } - - this.tunnels.put( trigger, type ); - } - - @Nullable - @Override - public TunnelType getTunnelTypeByItem( final ItemStack trigger ) - { - if( trigger != null ) - { - if( FluidContainerRegistry.isContainer( trigger ) ) - { - return TunnelType.FLUID; - } - - for( final ItemStack is : this.tunnels.keySet() ) - { - if( is.getItem() == trigger.getItem() && is.getItemDamage() == OreDictionary.WILDCARD_VALUE ) - { - return this.tunnels.get( is ); - } - - if( Platform.isSameItem( is, trigger ) ) - { - return this.tunnels.get( is ); - } - } - } - - return null; - } - - @Nullable - private ItemStack getModItem( final String modID, final String name, final int meta ) - { - final ItemStack myItemStack = GameRegistry.findItemStack( modID, name, 1 ); - - if( myItemStack == null ) - { - return null; - } - - myItemStack.setItemDamage( meta ); - return myItemStack; - } - - private void addNewAttunement( final IItemDefinition definition, final TunnelType type ) - { - for( final ItemStack definitionStack : definition.maybeStack( 1 ).asSet() ) - { - this.addNewAttunement( definitionStack, type ); - } - } +public final class P2PTunnelRegistry implements IP2PTunnelRegistry { + private static final int INITIAL_CAPACITY = 40; + + private final Map tunnels = new HashMap(INITIAL_CAPACITY); + + public void configure() { + /** + * light! + */ + this.addNewAttunement(new ItemStack(Blocks.torch), TunnelType.LIGHT); + this.addNewAttunement(new ItemStack(Blocks.glowstone), TunnelType.LIGHT); + + /** + * attune based on most redstone base items. + */ + this.addNewAttunement(new ItemStack(Items.redstone), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Items.repeater), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.redstone_lamp), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.unpowered_comparator), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.powered_comparator), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.powered_repeater), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.unpowered_repeater), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.daylight_detector), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.redstone_wire), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.redstone_block), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.lever), TunnelType.REDSTONE); + this.addNewAttunement( + this.getModItem("EnderIO", "itemRedstoneConduit", OreDictionary.WILDCARD_VALUE), TunnelType.REDSTONE); + + /** + * attune based on lots of random item related stuff + */ + final IDefinitions definitions = AEApi.instance().definitions(); + final IBlocks blocks = definitions.blocks(); + final IParts parts = definitions.parts(); + + this.addNewAttunement(blocks.iface(), TunnelType.ITEM); + this.addNewAttunement(parts.iface(), TunnelType.ITEM); + this.addNewAttunement(parts.storageBus(), TunnelType.ITEM); + this.addNewAttunement(parts.importBus(), TunnelType.ITEM); + this.addNewAttunement(parts.exportBus(), TunnelType.ITEM); + + this.addNewAttunement(new ItemStack(Blocks.hopper), TunnelType.ITEM); + this.addNewAttunement(new ItemStack(Blocks.chest), TunnelType.ITEM); + this.addNewAttunement(new ItemStack(Blocks.trapped_chest), TunnelType.ITEM); + this.addNewAttunement(this.getModItem("ExtraUtilities", "extractor_base", 0), TunnelType.ITEM); + this.addNewAttunement(this.getModItem("Mekanism", "PartTransmitter", 9), TunnelType.ITEM); + this.addNewAttunement( + this.getModItem("EnderIO", "itemItemConduit", OreDictionary.WILDCARD_VALUE), TunnelType.ITEM); + this.addNewAttunement(this.getModItem("ThermalDynamics", "ThermalDynamics_32", 0), TunnelType.ITEM); + + /** + * attune based on lots of random item related stuff + */ + this.addNewAttunement(new ItemStack(Items.bucket), TunnelType.FLUID); + this.addNewAttunement(new ItemStack(Items.lava_bucket), TunnelType.FLUID); + this.addNewAttunement(new ItemStack(Items.milk_bucket), TunnelType.FLUID); + this.addNewAttunement(new ItemStack(Items.water_bucket), TunnelType.FLUID); + this.addNewAttunement(this.getModItem("Mekanism", "MachineBlock2", 11), TunnelType.FLUID); + this.addNewAttunement(this.getModItem("Mekanism", "PartTransmitter", 4), TunnelType.FLUID); + this.addNewAttunement(this.getModItem("ExtraUtilities", "extractor_base", 6), TunnelType.FLUID); + this.addNewAttunement( + this.getModItem("ExtraUtilities", "drum", OreDictionary.WILDCARD_VALUE), TunnelType.FLUID); + this.addNewAttunement( + this.getModItem("EnderIO", "itemLiquidConduit", OreDictionary.WILDCARD_VALUE), TunnelType.FLUID); + this.addNewAttunement(this.getModItem("ThermalDynamics", "ThermalDynamics_16", 0), TunnelType.FLUID); + + for (final AEColor c : AEColor.values()) { + this.addNewAttunement(parts.cableGlass().stack(c, 1), TunnelType.ME); + this.addNewAttunement(parts.cableCovered().stack(c, 1), TunnelType.ME); + this.addNewAttunement(parts.cableSmart().stack(c, 1), TunnelType.ME); + this.addNewAttunement(parts.cableDense().stack(c, 1), TunnelType.ME); + this.addNewAttunement(parts.cableDenseCovered().stack(c, 1), TunnelType.ME); + this.addNewAttunement(parts.cableUltraDenseCovered().stack(c, 1), TunnelType.ME); + this.addNewAttunement(parts.cableUltraDenseSmart().stack(c, 1), TunnelType.ME); + } + } + + @Override + public void addNewAttunement(@Nullable final ItemStack trigger, @Nullable final TunnelType type) { + if (type == null || trigger == null) { + return; + } + + this.tunnels.put(trigger, type); + } + + @Nullable + @Override + public TunnelType getTunnelTypeByItem(final ItemStack trigger) { + if (trigger != null) { + if (FluidContainerRegistry.isContainer(trigger)) { + return TunnelType.FLUID; + } + + for (final ItemStack is : this.tunnels.keySet()) { + if (is.getItem() == trigger.getItem() && is.getItemDamage() == OreDictionary.WILDCARD_VALUE) { + return this.tunnels.get(is); + } + + if (Platform.isSameItem(is, trigger)) { + return this.tunnels.get(is); + } + } + } + + return null; + } + + @Nullable + private ItemStack getModItem(final String modID, final String name, final int meta) { + final ItemStack myItemStack = GameRegistry.findItemStack(modID, name, 1); + + if (myItemStack == null) { + return null; + } + + myItemStack.setItemDamage(meta); + return myItemStack; + } + + private void addNewAttunement(final IItemDefinition definition, final TunnelType type) { + for (final ItemStack definitionStack : definition.maybeStack(1).asSet()) { + this.addNewAttunement(definitionStack, type); + } + } } diff --git a/src/main/java/appeng/core/features/registries/PlayerRegistry.java b/src/main/java/appeng/core/features/registries/PlayerRegistry.java index 16c2b0ed107..b56c6316e2a 100644 --- a/src/main/java/appeng/core/features/registries/PlayerRegistry.java +++ b/src/main/java/appeng/core/features/registries/PlayerRegistry.java @@ -18,39 +18,31 @@ package appeng.core.features.registries; - import appeng.api.features.IPlayerRegistry; import appeng.core.worlddata.WorldData; import com.mojang.authlib.GameProfile; -import net.minecraft.entity.player.EntityPlayer; - import javax.annotation.Nullable; +import net.minecraft.entity.player.EntityPlayer; +public class PlayerRegistry implements IPlayerRegistry { -public class PlayerRegistry implements IPlayerRegistry -{ - - @Override - public int getID( final GameProfile username ) - { - if( username == null || !username.isComplete() ) - { - return -1; - } + @Override + public int getID(final GameProfile username) { + if (username == null || !username.isComplete()) { + return -1; + } - return WorldData.instance().playerData().getPlayerID( username ); - } + return WorldData.instance().playerData().getPlayerID(username); + } - @Override - public int getID( final EntityPlayer player ) - { - return this.getID( player.getGameProfile() ); - } + @Override + public int getID(final EntityPlayer player) { + return this.getID(player.getGameProfile()); + } - @Nullable - @Override - public EntityPlayer findPlayer( final int playerID ) - { - return WorldData.instance().playerData().getPlayerFromID( playerID ); - } + @Nullable + @Override + public EntityPlayer findPlayer(final int playerID) { + return WorldData.instance().playerData().getPlayerFromID(playerID); + } } diff --git a/src/main/java/appeng/core/features/registries/RecipeHandlerRegistry.java b/src/main/java/appeng/core/features/registries/RecipeHandlerRegistry.java index 2a90128daef..800d0e4501c 100644 --- a/src/main/java/appeng/core/features/registries/RecipeHandlerRegistry.java +++ b/src/main/java/appeng/core/features/registries/RecipeHandlerRegistry.java @@ -18,17 +18,14 @@ package appeng.core.features.registries; - import appeng.api.features.IRecipeHandlerRegistry; import appeng.api.recipes.ICraftHandler; import appeng.api.recipes.IRecipeHandler; import appeng.api.recipes.ISubItemResolver; import appeng.core.AELog; import appeng.recipes.RecipeHandler; - -import javax.annotation.Nullable; import java.util.*; - +import javax.annotation.Nullable; /** * @author AlgorithmX2 @@ -36,76 +33,62 @@ * @version rv3 - 10.08.2015 * @since rv0 */ -public class RecipeHandlerRegistry implements IRecipeHandlerRegistry -{ - private final Map> handlers = new HashMap>( 20 ); - private final Collection resolvers = new LinkedList(); - - @Override - public void addNewCraftHandler( final String name, final Class handler ) - { - this.handlers.put( name.toLowerCase( Locale.ENGLISH ), handler ); - } - - @Override - public void addNewSubItemResolver( final ISubItemResolver sir ) - { - this.resolvers.add( sir ); - } - - @Nullable - @Override - public ICraftHandler getCraftHandlerFor( final String name ) - { - final Class clz = this.handlers.get( name ); - if( clz == null ) - { - return null; - } - try - { - return clz.newInstance(); - } - catch( final Throwable e ) - { - AELog.error( "Error Caused when trying to construct " + clz.getName() ); - AELog.debug( e ); - - this.handlers.put( name, null ); // clear it.. - - return null; - } - } - - @Override - public IRecipeHandler createNewRecipehandler() - { - return new RecipeHandler(); - } - - @Nullable - @Override - public Object resolveItem( final String nameSpace, final String itemName ) - { - for( final ISubItemResolver sir : this.resolvers ) - { - Object rr = null; - - try - { - rr = sir.resolveItemByName( nameSpace, itemName ); - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - - if( rr != null ) - { - return rr; - } - } - - return null; - } +public class RecipeHandlerRegistry implements IRecipeHandlerRegistry { + private final Map> handlers = + new HashMap>(20); + private final Collection resolvers = new LinkedList(); + + @Override + public void addNewCraftHandler(final String name, final Class handler) { + this.handlers.put(name.toLowerCase(Locale.ENGLISH), handler); + } + + @Override + public void addNewSubItemResolver(final ISubItemResolver sir) { + this.resolvers.add(sir); + } + + @Nullable + @Override + public ICraftHandler getCraftHandlerFor(final String name) { + final Class clz = this.handlers.get(name); + if (clz == null) { + return null; + } + try { + return clz.newInstance(); + } catch (final Throwable e) { + AELog.error("Error Caused when trying to construct " + clz.getName()); + AELog.debug(e); + + this.handlers.put(name, null); // clear it.. + + return null; + } + } + + @Override + public IRecipeHandler createNewRecipehandler() { + return new RecipeHandler(); + } + + @Nullable + @Override + public Object resolveItem(final String nameSpace, final String itemName) { + for (final ISubItemResolver sir : this.resolvers) { + Object rr = null; + + try { + rr = sir.resolveItemByName(nameSpace, itemName); + } catch (final Throwable t) { + AELog.debug(t); + } + + if (rr != null) { + return rr; + } + } + + return null; + } } diff --git a/src/main/java/appeng/core/features/registries/RegistryContainer.java b/src/main/java/appeng/core/features/registries/RegistryContainer.java index 195c7263a30..ffea120c86f 100644 --- a/src/main/java/appeng/core/features/registries/RegistryContainer.java +++ b/src/main/java/appeng/core/features/registries/RegistryContainer.java @@ -18,14 +18,12 @@ package appeng.core.features.registries; - import appeng.api.features.*; import appeng.api.movable.IMovableRegistry; import appeng.api.networking.IGridCacheRegistry; import appeng.api.storage.ICellRegistry; import appeng.api.storage.IExternalStorageRegistry; - /** * represents all registries * @@ -34,103 +32,88 @@ * @version rv2 * @since rv0 */ -public class RegistryContainer implements IRegistryContainer -{ - private final IGrinderRegistry grinder = new GrinderRecipeManager(); - private final IInscriberRegistry inscriber = new InscriberRegistry(); - private final IExternalStorageRegistry storage = new ExternalStorageRegistry(); - private final ICellRegistry cell = new CellRegistry(); - private final ILocatableRegistry locatable = new LocatableRegistry(); - private final ISpecialComparisonRegistry comparison = new SpecialComparisonRegistry(); - private final IWirelessTermRegistry wireless = new WirelessRegistry(); - private final IGridCacheRegistry gridCache = new GridCacheRegistry(); - private final IP2PTunnelRegistry p2pTunnel = new P2PTunnelRegistry(); - private final IMovableRegistry movable = new MovableTileRegistry(); - private final IMatterCannonAmmoRegistry matterCannonReg = new MatterCannonAmmoRegistry(); - private final IPlayerRegistry playerRegistry = new PlayerRegistry(); - private final IRecipeHandlerRegistry recipeReg = new RecipeHandlerRegistry(); - - @Override - public IMovableRegistry movable() - { - return this.movable; - } - - @Override - public IGridCacheRegistry gridCache() - { - return this.gridCache; - } - - @Override - public IExternalStorageRegistry externalStorage() - { - return this.storage; - } - - @Override - public ISpecialComparisonRegistry specialComparison() - { - return this.comparison; - } - - @Override - public IWirelessTermRegistry wireless() - { - return this.wireless; - } - - @Override - public ICellRegistry cell() - { - return this.cell; - } - - @Override - public IGrinderRegistry grinder() - { - return this.grinder; - } - - @Override - public IInscriberRegistry inscriber() - { - return this.inscriber; - } - - @Override - public ILocatableRegistry locatable() - { - return this.locatable; - } - - @Override - public IP2PTunnelRegistry p2pTunnel() - { - return this.p2pTunnel; - } - - @Override - public IMatterCannonAmmoRegistry matterCannon() - { - return this.matterCannonReg; - } - - @Override - public IPlayerRegistry players() - { - return this.playerRegistry; - } - - @Override - public IRecipeHandlerRegistry recipes() - { - return this.recipeReg; - } - - @Override - public IWorldGen worldgen() - { - return WorldGenRegistry.INSTANCE; - } +public class RegistryContainer implements IRegistryContainer { + private final IGrinderRegistry grinder = new GrinderRecipeManager(); + private final IInscriberRegistry inscriber = new InscriberRegistry(); + private final IExternalStorageRegistry storage = new ExternalStorageRegistry(); + private final ICellRegistry cell = new CellRegistry(); + private final ILocatableRegistry locatable = new LocatableRegistry(); + private final ISpecialComparisonRegistry comparison = new SpecialComparisonRegistry(); + private final IWirelessTermRegistry wireless = new WirelessRegistry(); + private final IGridCacheRegistry gridCache = new GridCacheRegistry(); + private final IP2PTunnelRegistry p2pTunnel = new P2PTunnelRegistry(); + private final IMovableRegistry movable = new MovableTileRegistry(); + private final IMatterCannonAmmoRegistry matterCannonReg = new MatterCannonAmmoRegistry(); + private final IPlayerRegistry playerRegistry = new PlayerRegistry(); + private final IRecipeHandlerRegistry recipeReg = new RecipeHandlerRegistry(); + + @Override + public IMovableRegistry movable() { + return this.movable; + } + + @Override + public IGridCacheRegistry gridCache() { + return this.gridCache; + } + + @Override + public IExternalStorageRegistry externalStorage() { + return this.storage; + } + + @Override + public ISpecialComparisonRegistry specialComparison() { + return this.comparison; + } + + @Override + public IWirelessTermRegistry wireless() { + return this.wireless; + } + + @Override + public ICellRegistry cell() { + return this.cell; + } + + @Override + public IGrinderRegistry grinder() { + return this.grinder; + } + + @Override + public IInscriberRegistry inscriber() { + return this.inscriber; + } + + @Override + public ILocatableRegistry locatable() { + return this.locatable; + } + + @Override + public IP2PTunnelRegistry p2pTunnel() { + return this.p2pTunnel; + } + + @Override + public IMatterCannonAmmoRegistry matterCannon() { + return this.matterCannonReg; + } + + @Override + public IPlayerRegistry players() { + return this.playerRegistry; + } + + @Override + public IRecipeHandlerRegistry recipes() { + return this.recipeReg; + } + + @Override + public IWorldGen worldgen() { + return WorldGenRegistry.INSTANCE; + } } diff --git a/src/main/java/appeng/core/features/registries/SpecialComparisonRegistry.java b/src/main/java/appeng/core/features/registries/SpecialComparisonRegistry.java index 4563351bf07..395f5329817 100644 --- a/src/main/java/appeng/core/features/registries/SpecialComparisonRegistry.java +++ b/src/main/java/appeng/core/features/registries/SpecialComparisonRegistry.java @@ -18,44 +18,35 @@ package appeng.core.features.registries; - import appeng.api.features.IItemComparison; import appeng.api.features.IItemComparisonProvider; import appeng.api.features.ISpecialComparisonRegistry; -import net.minecraft.item.ItemStack; - import java.util.ArrayList; import java.util.List; +import net.minecraft.item.ItemStack; + +public class SpecialComparisonRegistry implements ISpecialComparisonRegistry { + + private final List CompRegistry; + + public SpecialComparisonRegistry() { + this.CompRegistry = new ArrayList(); + } + + @Override + public IItemComparison getSpecialComparison(final ItemStack stack) { + for (final IItemComparisonProvider i : this.CompRegistry) { + final IItemComparison comp = i.getComparison(stack); + if (comp != null) { + return comp; + } + } + return null; + } -public class SpecialComparisonRegistry implements ISpecialComparisonRegistry -{ - - private final List CompRegistry; - - public SpecialComparisonRegistry() - { - this.CompRegistry = new ArrayList(); - } - - @Override - public IItemComparison getSpecialComparison( final ItemStack stack ) - { - for( final IItemComparisonProvider i : this.CompRegistry ) - { - final IItemComparison comp = i.getComparison( stack ); - if( comp != null ) - { - return comp; - } - } - - return null; - } - - @Override - public void addComparisonProvider( final IItemComparisonProvider prov ) - { - this.CompRegistry.add( prov ); - } + @Override + public void addComparisonProvider(final IItemComparisonProvider prov) { + this.CompRegistry.add(prov); + } } diff --git a/src/main/java/appeng/core/features/registries/WirelessRegistry.java b/src/main/java/appeng/core/features/registries/WirelessRegistry.java index 4b93d2c8d22..7a5028a31cd 100644 --- a/src/main/java/appeng/core/features/registries/WirelessRegistry.java +++ b/src/main/java/appeng/core/features/registries/WirelessRegistry.java @@ -18,7 +18,6 @@ package appeng.core.features.registries; - import appeng.api.AEApi; import appeng.api.features.ILocatable; import appeng.api.features.IWirelessTermHandler; @@ -26,95 +25,76 @@ import appeng.core.localization.PlayerMessages; import appeng.core.sync.GuiBridge; import appeng.util.Platform; +import java.util.ArrayList; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import java.util.ArrayList; -import java.util.List; - - -public final class WirelessRegistry implements IWirelessTermRegistry -{ - private final List handlers; +public final class WirelessRegistry implements IWirelessTermRegistry { + private final List handlers; - public WirelessRegistry() - { - this.handlers = new ArrayList(); - } + public WirelessRegistry() { + this.handlers = new ArrayList(); + } - @Override - public void registerWirelessHandler( final IWirelessTermHandler handler ) - { - if( handler != null ) - { - this.handlers.add( handler ); - } - } + @Override + public void registerWirelessHandler(final IWirelessTermHandler handler) { + if (handler != null) { + this.handlers.add(handler); + } + } - @Override - public boolean isWirelessTerminal( final ItemStack is ) - { - for( final IWirelessTermHandler h : this.handlers ) - { - if( h.canHandle( is ) ) - { - return true; - } - } - return false; - } + @Override + public boolean isWirelessTerminal(final ItemStack is) { + for (final IWirelessTermHandler h : this.handlers) { + if (h.canHandle(is)) { + return true; + } + } + return false; + } - @Override - public IWirelessTermHandler getWirelessTerminalHandler( final ItemStack is ) - { - for( final IWirelessTermHandler h : this.handlers ) - { - if( h.canHandle( is ) ) - { - return h; - } - } - return null; - } + @Override + public IWirelessTermHandler getWirelessTerminalHandler(final ItemStack is) { + for (final IWirelessTermHandler h : this.handlers) { + if (h.canHandle(is)) { + return h; + } + } + return null; + } - @Override - public void openWirelessTerminalGui( final ItemStack item, final World w, final EntityPlayer player ) - { - if( Platform.isClient() ) - { - return; - } + @Override + public void openWirelessTerminalGui(final ItemStack item, final World w, final EntityPlayer player) { + if (Platform.isClient()) { + return; + } - if( !this.isWirelessTerminal( item ) ) - { - player.addChatMessage( PlayerMessages.DeviceNotWirelessTerminal.get() ); - return; - } + if (!this.isWirelessTerminal(item)) { + player.addChatMessage(PlayerMessages.DeviceNotWirelessTerminal.get()); + return; + } - final IWirelessTermHandler handler = this.getWirelessTerminalHandler( item ); - final String unparsedKey = handler.getEncryptionKey( item ); - if( unparsedKey.isEmpty() ) - { - player.addChatMessage( PlayerMessages.DeviceNotLinked.get() ); - return; - } + final IWirelessTermHandler handler = this.getWirelessTerminalHandler(item); + final String unparsedKey = handler.getEncryptionKey(item); + if (unparsedKey.isEmpty()) { + player.addChatMessage(PlayerMessages.DeviceNotLinked.get()); + return; + } - final long parsedKey = Long.parseLong( unparsedKey ); - final ILocatable securityStation = AEApi.instance().registries().locatable().getLocatableBy( parsedKey ); - if( securityStation == null ) - { - player.addChatMessage( PlayerMessages.StationCanNotBeLocated.get() ); - return; - } + final long parsedKey = Long.parseLong(unparsedKey); + final ILocatable securityStation = + AEApi.instance().registries().locatable().getLocatableBy(parsedKey); + if (securityStation == null) { + player.addChatMessage(PlayerMessages.StationCanNotBeLocated.get()); + return; + } - if( handler.hasPower( player, 0.5, item ) ) - { - Platform.openGUI( player, null, null, GuiBridge.GUI_WIRELESS_TERM ); - } - else - { - player.addChatMessage( PlayerMessages.DeviceNotPowered.get() ); - } - } + if (handler.hasPower(player, 0.5, item)) { + Platform.openGUI(player, null, null, GuiBridge.GUI_WIRELESS_TERM); + } else { + player.addChatMessage(PlayerMessages.DeviceNotPowered.get()); + } + } } diff --git a/src/main/java/appeng/core/features/registries/WorldGenRegistry.java b/src/main/java/appeng/core/features/registries/WorldGenRegistry.java index a33859a914c..589f0d47c3f 100644 --- a/src/main/java/appeng/core/features/registries/WorldGenRegistry.java +++ b/src/main/java/appeng/core/features/registries/WorldGenRegistry.java @@ -18,99 +18,81 @@ package appeng.core.features.registries; - import appeng.api.features.IWorldGen; +import java.util.HashSet; import net.minecraft.world.World; import net.minecraft.world.WorldProvider; -import java.util.HashSet; +public final class WorldGenRegistry implements IWorldGen { + + public static final WorldGenRegistry INSTANCE = new WorldGenRegistry(); + private final TypeSet[] types; + + private WorldGenRegistry() { + + this.types = new TypeSet[WorldGenType.values().length]; + + for (final WorldGenType type : WorldGenType.values()) { + this.types[type.ordinal()] = new TypeSet(); + } + } + + @Override + public void disableWorldGenForProviderID(final WorldGenType type, final Class provider) { + if (type == null) { + throw new IllegalArgumentException("Bad Type Passed"); + } + + if (provider == null) { + throw new IllegalArgumentException("Bad Provider Passed"); + } + + this.types[type.ordinal()].badProviders.add(provider); + } + + @Override + public void enableWorldGenForDimension(final WorldGenType type, final int dimensionID) { + if (type == null) { + throw new IllegalArgumentException("Bad Type Passed"); + } + + this.types[type.ordinal()].enabledDimensions.add(dimensionID); + } + + @Override + public void disableWorldGenForDimension(final WorldGenType type, final int dimensionID) { + if (type == null) { + throw new IllegalArgumentException("Bad Type Passed"); + } + + this.types[type.ordinal()].badDimensions.add(dimensionID); + } + + @Override + public boolean isWorldGenEnabled(final WorldGenType type, final World w) { + if (type == null) { + throw new IllegalArgumentException("Bad Type Passed"); + } + + if (w == null) { + throw new IllegalArgumentException("Bad Provider Passed"); + } + + final boolean isBadProvider = this.types[type.ordinal()].badProviders.contains(w.provider.getClass()); + final boolean isBadDimension = this.types[type.ordinal()].badDimensions.contains(w.provider.dimensionId); + final boolean isGoodDimension = this.types[type.ordinal()].enabledDimensions.contains(w.provider.dimensionId); + + if (isBadProvider || isBadDimension) { + return false; + } + + return !(!isGoodDimension && type == WorldGenType.Meteorites); + } + private static class TypeSet { -public final class WorldGenRegistry implements IWorldGen -{ - - public static final WorldGenRegistry INSTANCE = new WorldGenRegistry(); - private final TypeSet[] types; - - private WorldGenRegistry() - { - - this.types = new TypeSet[WorldGenType.values().length]; - - for( final WorldGenType type : WorldGenType.values() ) - { - this.types[type.ordinal()] = new TypeSet(); - } - } - - @Override - public void disableWorldGenForProviderID( final WorldGenType type, final Class provider ) - { - if( type == null ) - { - throw new IllegalArgumentException( "Bad Type Passed" ); - } - - if( provider == null ) - { - throw new IllegalArgumentException( "Bad Provider Passed" ); - } - - this.types[type.ordinal()].badProviders.add( provider ); - } - - @Override - public void enableWorldGenForDimension( final WorldGenType type, final int dimensionID ) - { - if( type == null ) - { - throw new IllegalArgumentException( "Bad Type Passed" ); - } - - this.types[type.ordinal()].enabledDimensions.add( dimensionID ); - } - - @Override - public void disableWorldGenForDimension( final WorldGenType type, final int dimensionID ) - { - if( type == null ) - { - throw new IllegalArgumentException( "Bad Type Passed" ); - } - - this.types[type.ordinal()].badDimensions.add( dimensionID ); - } - - @Override - public boolean isWorldGenEnabled( final WorldGenType type, final World w ) - { - if( type == null ) - { - throw new IllegalArgumentException( "Bad Type Passed" ); - } - - if( w == null ) - { - throw new IllegalArgumentException( "Bad Provider Passed" ); - } - - final boolean isBadProvider = this.types[type.ordinal()].badProviders.contains( w.provider.getClass() ); - final boolean isBadDimension = this.types[type.ordinal()].badDimensions.contains( w.provider.dimensionId ); - final boolean isGoodDimension = this.types[type.ordinal()].enabledDimensions.contains( w.provider.dimensionId ); - - if( isBadProvider || isBadDimension ) - { - return false; - } - - return !( !isGoodDimension && type == WorldGenType.Meteorites ); - } - - private static class TypeSet - { - - final HashSet> badProviders = new HashSet>(); - final HashSet badDimensions = new HashSet(); - final HashSet enabledDimensions = new HashSet(); - } + final HashSet> badProviders = new HashSet>(); + final HashSet badDimensions = new HashSet(); + final HashSet enabledDimensions = new HashSet(); + } } diff --git a/src/main/java/appeng/core/features/registries/entries/AppEngGrinderRecipe.java b/src/main/java/appeng/core/features/registries/entries/AppEngGrinderRecipe.java index c4554457a49..b24bcf5fdfa 100644 --- a/src/main/java/appeng/core/features/registries/entries/AppEngGrinderRecipe.java +++ b/src/main/java/appeng/core/features/registries/entries/AppEngGrinderRecipe.java @@ -18,128 +18,118 @@ package appeng.core.features.registries.entries; - import appeng.api.features.IGrinderEntry; import net.minecraft.item.ItemStack; - -public class AppEngGrinderRecipe implements IGrinderEntry -{ - - private ItemStack in; - private ItemStack out; - - private float optionalChance; - private ItemStack optionalOutput; - - private float optionalChance2; - private ItemStack optionalOutput2; - - private int energy; - - public AppEngGrinderRecipe( final ItemStack a, final ItemStack b, final int cost ) - { - this.in = a; - this.out = b; - this.energy = cost; - } - - public AppEngGrinderRecipe( final ItemStack a, final ItemStack b, final ItemStack c, final float chance, final int cost ) - { - this.in = a; - this.out = b; - - this.optionalOutput = c; - this.optionalChance = chance; - - this.energy = cost; - } - - public AppEngGrinderRecipe( final ItemStack a, final ItemStack b, final ItemStack c, final ItemStack d, final float chance, final float chance2, final int cost ) - { - this.in = a; - this.out = b; - - this.optionalOutput = c; - this.optionalChance = chance; - - this.optionalOutput2 = d; - this.optionalChance2 = chance2; - - this.energy = cost; - } - - @Override - public ItemStack getInput() - { - return this.in; - } - - @Override - public void setInput( final ItemStack i ) - { - this.in = i.copy(); - } - - @Override - public ItemStack getOutput() - { - return this.out; - } - - @Override - public void setOutput( final ItemStack o ) - { - this.out = o.copy(); - } - - @Override - public ItemStack getOptionalOutput() - { - return this.optionalOutput; - } - - @Override - public ItemStack getSecondOptionalOutput() - { - return this.optionalOutput2; - } - - @Override - public void setOptionalOutput( final ItemStack output, final float chance ) - { - this.optionalOutput = output.copy(); - this.optionalChance = chance; - } - - @Override - public float getOptionalChance() - { - return this.optionalChance; - } - - @Override - public void setSecondOptionalOutput( final ItemStack output, final float chance ) - { - this.optionalChance2 = chance; - this.optionalOutput2 = output.copy(); - } - - @Override - public float getSecondOptionalChance() - { - return this.optionalChance2; - } - - @Override - public int getEnergyCost() - { - return this.energy; - } - - @Override - public void setEnergyCost( final int c ) - { - this.energy = c; - } +public class AppEngGrinderRecipe implements IGrinderEntry { + + private ItemStack in; + private ItemStack out; + + private float optionalChance; + private ItemStack optionalOutput; + + private float optionalChance2; + private ItemStack optionalOutput2; + + private int energy; + + public AppEngGrinderRecipe(final ItemStack a, final ItemStack b, final int cost) { + this.in = a; + this.out = b; + this.energy = cost; + } + + public AppEngGrinderRecipe( + final ItemStack a, final ItemStack b, final ItemStack c, final float chance, final int cost) { + this.in = a; + this.out = b; + + this.optionalOutput = c; + this.optionalChance = chance; + + this.energy = cost; + } + + public AppEngGrinderRecipe( + final ItemStack a, + final ItemStack b, + final ItemStack c, + final ItemStack d, + final float chance, + final float chance2, + final int cost) { + this.in = a; + this.out = b; + + this.optionalOutput = c; + this.optionalChance = chance; + + this.optionalOutput2 = d; + this.optionalChance2 = chance2; + + this.energy = cost; + } + + @Override + public ItemStack getInput() { + return this.in; + } + + @Override + public void setInput(final ItemStack i) { + this.in = i.copy(); + } + + @Override + public ItemStack getOutput() { + return this.out; + } + + @Override + public void setOutput(final ItemStack o) { + this.out = o.copy(); + } + + @Override + public ItemStack getOptionalOutput() { + return this.optionalOutput; + } + + @Override + public ItemStack getSecondOptionalOutput() { + return this.optionalOutput2; + } + + @Override + public void setOptionalOutput(final ItemStack output, final float chance) { + this.optionalOutput = output.copy(); + this.optionalChance = chance; + } + + @Override + public float getOptionalChance() { + return this.optionalChance; + } + + @Override + public void setSecondOptionalOutput(final ItemStack output, final float chance) { + this.optionalChance2 = chance; + this.optionalOutput2 = output.copy(); + } + + @Override + public float getSecondOptionalChance() { + return this.optionalChance2; + } + + @Override + public int getEnergyCost() { + return this.energy; + } + + @Override + public void setEnergyCost(final int c) { + this.energy = c; + } } diff --git a/src/main/java/appeng/core/features/registries/entries/BasicCellHandler.java b/src/main/java/appeng/core/features/registries/entries/BasicCellHandler.java index 096d043cebf..68cee45b70e 100644 --- a/src/main/java/appeng/core/features/registries/entries/BasicCellHandler.java +++ b/src/main/java/appeng/core/features/registries/entries/BasicCellHandler.java @@ -18,7 +18,6 @@ package appeng.core.features.registries.entries; - import appeng.api.implementations.tiles.IChestOrDrive; import appeng.api.storage.*; import appeng.client.texture.ExtraBlockTextures; @@ -31,65 +30,60 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; +public class BasicCellHandler implements ICellHandler { -public class BasicCellHandler implements ICellHandler -{ - - @Override - public boolean isCell( final ItemStack is ) - { - return CellInventory.isCell( is ); - } + @Override + public boolean isCell(final ItemStack is) { + return CellInventory.isCell(is); + } - @Override - public IMEInventoryHandler getCellInventory( final ItemStack is, final ISaveProvider container, final StorageChannel channel ) - { - if( channel == StorageChannel.ITEMS ) - { - return CellInventory.getCell( is, container ); - } - return null; - } + @Override + public IMEInventoryHandler getCellInventory( + final ItemStack is, final ISaveProvider container, final StorageChannel channel) { + if (channel == StorageChannel.ITEMS) { + return CellInventory.getCell(is, container); + } + return null; + } - @Override - public IIcon getTopTexture_Light() - { - return ExtraBlockTextures.BlockMEChestItems_Light.getIcon(); - } + @Override + public IIcon getTopTexture_Light() { + return ExtraBlockTextures.BlockMEChestItems_Light.getIcon(); + } - @Override - public IIcon getTopTexture_Medium() - { - return ExtraBlockTextures.BlockMEChestItems_Medium.getIcon(); - } + @Override + public IIcon getTopTexture_Medium() { + return ExtraBlockTextures.BlockMEChestItems_Medium.getIcon(); + } - @Override - public IIcon getTopTexture_Dark() - { - return ExtraBlockTextures.BlockMEChestItems_Dark.getIcon(); - } + @Override + public IIcon getTopTexture_Dark() { + return ExtraBlockTextures.BlockMEChestItems_Dark.getIcon(); + } - @Override - public void openChestGui( final EntityPlayer player, final IChestOrDrive chest, final ICellHandler cellHandler, final IMEInventoryHandler inv, final ItemStack is, final StorageChannel chan ) - { - Platform.openGUI( player, (TileEntity) chest, chest.getUp(), GuiBridge.GUI_ME ); - } + @Override + public void openChestGui( + final EntityPlayer player, + final IChestOrDrive chest, + final ICellHandler cellHandler, + final IMEInventoryHandler inv, + final ItemStack is, + final StorageChannel chan) { + Platform.openGUI(player, (TileEntity) chest, chest.getUp(), GuiBridge.GUI_ME); + } - @Override - public int getStatusForCell( final ItemStack is, final IMEInventory handler ) - { - if( handler instanceof CellInventoryHandler ) - { - final CellInventoryHandler ci = (CellInventoryHandler) handler; - return ci.getStatusForCell(); - } - return 0; - } + @Override + public int getStatusForCell(final ItemStack is, final IMEInventory handler) { + if (handler instanceof CellInventoryHandler) { + final CellInventoryHandler ci = (CellInventoryHandler) handler; + return ci.getStatusForCell(); + } + return 0; + } - @Override - public double cellIdleDrain( final ItemStack is, final IMEInventory handler ) - { - final ICellInventory inv = ( (ICellInventoryHandler) handler ).getCellInv(); - return inv.getIdleDrain(); - } + @Override + public double cellIdleDrain(final ItemStack is, final IMEInventory handler) { + final ICellInventory inv = ((ICellInventoryHandler) handler).getCellInv(); + return inv.getIdleDrain(); + } } diff --git a/src/main/java/appeng/core/features/registries/entries/CreativeCellHandler.java b/src/main/java/appeng/core/features/registries/entries/CreativeCellHandler.java index 9e6e2ecfb22..c8794fbc981 100644 --- a/src/main/java/appeng/core/features/registries/entries/CreativeCellHandler.java +++ b/src/main/java/appeng/core/features/registries/entries/CreativeCellHandler.java @@ -18,7 +18,6 @@ package appeng.core.features.registries.entries; - import appeng.api.implementations.tiles.IChestOrDrive; import appeng.api.storage.*; import appeng.client.texture.ExtraBlockTextures; @@ -31,59 +30,55 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; +public class CreativeCellHandler implements ICellHandler { -public class CreativeCellHandler implements ICellHandler -{ - - @Override - public boolean isCell( final ItemStack is ) - { - return is != null && is.getItem() instanceof ItemCreativeStorageCell; - } + @Override + public boolean isCell(final ItemStack is) { + return is != null && is.getItem() instanceof ItemCreativeStorageCell; + } - @Override - public IMEInventoryHandler getCellInventory( final ItemStack is, final ISaveProvider container, final StorageChannel channel ) - { - if( channel == StorageChannel.ITEMS && is != null && is.getItem() instanceof ItemCreativeStorageCell ) - { - return CreativeCellInventory.getCell( is ); - } - return null; - } + @Override + public IMEInventoryHandler getCellInventory( + final ItemStack is, final ISaveProvider container, final StorageChannel channel) { + if (channel == StorageChannel.ITEMS && is != null && is.getItem() instanceof ItemCreativeStorageCell) { + return CreativeCellInventory.getCell(is); + } + return null; + } - @Override - public IIcon getTopTexture_Light() - { - return ExtraBlockTextures.BlockMEChestItems_Light.getIcon(); - } + @Override + public IIcon getTopTexture_Light() { + return ExtraBlockTextures.BlockMEChestItems_Light.getIcon(); + } - @Override - public IIcon getTopTexture_Medium() - { - return ExtraBlockTextures.BlockMEChestItems_Medium.getIcon(); - } + @Override + public IIcon getTopTexture_Medium() { + return ExtraBlockTextures.BlockMEChestItems_Medium.getIcon(); + } - @Override - public IIcon getTopTexture_Dark() - { - return ExtraBlockTextures.BlockMEChestItems_Dark.getIcon(); - } + @Override + public IIcon getTopTexture_Dark() { + return ExtraBlockTextures.BlockMEChestItems_Dark.getIcon(); + } - @Override - public void openChestGui( final EntityPlayer player, final IChestOrDrive chest, final ICellHandler cellHandler, final IMEInventoryHandler inv, final ItemStack is, final StorageChannel chan ) - { - Platform.openGUI( player, (TileEntity) chest, chest.getUp(), GuiBridge.GUI_ME ); - } + @Override + public void openChestGui( + final EntityPlayer player, + final IChestOrDrive chest, + final ICellHandler cellHandler, + final IMEInventoryHandler inv, + final ItemStack is, + final StorageChannel chan) { + Platform.openGUI(player, (TileEntity) chest, chest.getUp(), GuiBridge.GUI_ME); + } - @Override - public int getStatusForCell( final ItemStack is, final IMEInventory handler ) - { - return 2; - } + @Override + public int getStatusForCell(final ItemStack is, final IMEInventory handler) { + return 2; + } - @Override - public double cellIdleDrain( final ItemStack is, final IMEInventory handler ) - { - return 0; - } + @Override + public double cellIdleDrain(final ItemStack is, final IMEInventory handler) { + return 0; + } } diff --git a/src/main/java/appeng/core/features/registries/entries/ExternalIInv.java b/src/main/java/appeng/core/features/registries/entries/ExternalIInv.java index 399b461d419..955ef3c6f9a 100644 --- a/src/main/java/appeng/core/features/registries/entries/ExternalIInv.java +++ b/src/main/java/appeng/core/features/registries/entries/ExternalIInv.java @@ -18,7 +18,6 @@ package appeng.core.features.registries.entries; - import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageHandler; import appeng.api.storage.IMEInventory; @@ -29,26 +28,23 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +public class ExternalIInv implements IExternalStorageHandler { -public class ExternalIInv implements IExternalStorageHandler -{ - - @Override - public boolean canHandle( final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource mySrc ) - { - return channel == StorageChannel.ITEMS && te instanceof IInventory; - } + @Override + public boolean canHandle( + final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource mySrc) { + return channel == StorageChannel.ITEMS && te instanceof IInventory; + } - @Override - public IMEInventory getInventory( final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource src ) - { - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, d ); + @Override + public IMEInventory getInventory( + final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource src) { + final InventoryAdaptor ad = InventoryAdaptor.getAdaptor(te, d); - if( channel == StorageChannel.ITEMS && ad != null ) - { - return new MEMonitorIInventory( ad ); - } + if (channel == StorageChannel.ITEMS && ad != null) { + return new MEMonitorIInventory(ad); + } - return null; - } + return null; + } } diff --git a/src/main/java/appeng/core/features/registries/entries/InscriberInscribeRecipe.java b/src/main/java/appeng/core/features/registries/entries/InscriberInscribeRecipe.java index c3d4bc3299e..ea4b2455928 100644 --- a/src/main/java/appeng/core/features/registries/entries/InscriberInscribeRecipe.java +++ b/src/main/java/appeng/core/features/registries/entries/InscriberInscribeRecipe.java @@ -1,13 +1,10 @@ package appeng.core.features.registries.entries; - import appeng.api.features.InscriberProcessType; -import net.minecraft.item.ItemStack; - +import java.util.Collection; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.Collection; - +import net.minecraft.item.ItemStack; /** * inscribe recipes do not use up the provided optional upon craft @@ -16,10 +13,12 @@ * @version rv2 * @since rv2 */ -public class InscriberInscribeRecipe extends InscriberRecipe -{ - public InscriberInscribeRecipe( @Nonnull final Collection inputs, @Nonnull final ItemStack output, @Nullable final ItemStack top, @Nullable final ItemStack bot ) - { - super( inputs, output, top, bot, InscriberProcessType.Inscribe ); - } +public class InscriberInscribeRecipe extends InscriberRecipe { + public InscriberInscribeRecipe( + @Nonnull final Collection inputs, + @Nonnull final ItemStack output, + @Nullable final ItemStack top, + @Nullable final ItemStack bot) { + super(inputs, output, top, bot, InscriberProcessType.Inscribe); + } } diff --git a/src/main/java/appeng/core/features/registries/entries/InscriberRecipe.java b/src/main/java/appeng/core/features/registries/entries/InscriberRecipe.java index 8508d8c3837..85f5df95134 100644 --- a/src/main/java/appeng/core/features/registries/entries/InscriberRecipe.java +++ b/src/main/java/appeng/core/features/registries/entries/InscriberRecipe.java @@ -1,17 +1,14 @@ package appeng.core.features.registries.entries; - import appeng.api.features.IInscriberRecipe; import appeng.api.features.InscriberProcessType; import com.google.common.base.Optional; -import net.minecraft.item.ItemStack; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.List; - +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import net.minecraft.item.ItemStack; /** * Basic inscriber recipe @@ -20,111 +17,101 @@ * @version rv2 * @since rv2 */ -public class InscriberRecipe implements IInscriberRecipe -{ - @Nonnull - private final List inputs; - - @Nonnull - private final ItemStack output; - - @Nonnull - private final Optional maybeTop; - - @Nonnull - private final Optional maybeBot; - - @Nonnull - private final InscriberProcessType type; - - public InscriberRecipe( @Nonnull final Collection inputs, @Nonnull final ItemStack output, @Nullable final ItemStack top, @Nullable final ItemStack bot, @Nonnull final InscriberProcessType type ) - { - this.inputs = new ArrayList( inputs.size() ); - this.inputs.addAll( inputs ); - - this.output = output; - this.maybeTop = Optional.fromNullable( top ); - this.maybeBot = Optional.fromNullable( bot ); - - this.type = type; - } - - @Nonnull - @Override - public final List getInputs() - { - return this.inputs; - } - - @Nonnull - @Override - public final ItemStack getOutput() - { - return this.output; - } - - @Nonnull - @Override - public final Optional getTopOptional() - { - return this.maybeTop; - } - - @Nonnull - @Override - public final Optional getBottomOptional() - { - return this.maybeBot; - } - - @Nonnull - @Override - public final InscriberProcessType getProcessType() - { - return this.type; - } - - @Override - public boolean equals( final Object o ) - { - if( this == o ) - { - return true; - } - if( !( o instanceof IInscriberRecipe ) ) - { - return false; - } - - final IInscriberRecipe that = (IInscriberRecipe) o; - - if( !this.inputs.equals( that.getInputs() ) ) - { - return false; - } - if( !this.output.equals( that.getOutput() ) ) - { - return false; - } - if( !this.maybeTop.equals( that.getTopOptional() ) ) - { - return false; - } - if( !this.maybeBot.equals( that.getBottomOptional() ) ) - { - return false; - } - return this.type == that.getProcessType(); - } - - @Override - public int hashCode() - { - int result = this.inputs.hashCode(); - result = 31 * result + this.output.hashCode(); - result = 31 * result + this.maybeTop.hashCode(); - result = 31 * result + this.maybeBot.hashCode(); - result = 31 * result + this.type.hashCode(); - return result; - } +public class InscriberRecipe implements IInscriberRecipe { + @Nonnull + private final List inputs; + + @Nonnull + private final ItemStack output; + + @Nonnull + private final Optional maybeTop; + + @Nonnull + private final Optional maybeBot; + + @Nonnull + private final InscriberProcessType type; + + public InscriberRecipe( + @Nonnull final Collection inputs, + @Nonnull final ItemStack output, + @Nullable final ItemStack top, + @Nullable final ItemStack bot, + @Nonnull final InscriberProcessType type) { + this.inputs = new ArrayList(inputs.size()); + this.inputs.addAll(inputs); + + this.output = output; + this.maybeTop = Optional.fromNullable(top); + this.maybeBot = Optional.fromNullable(bot); + + this.type = type; + } + + @Nonnull + @Override + public final List getInputs() { + return this.inputs; + } + + @Nonnull + @Override + public final ItemStack getOutput() { + return this.output; + } + + @Nonnull + @Override + public final Optional getTopOptional() { + return this.maybeTop; + } + + @Nonnull + @Override + public final Optional getBottomOptional() { + return this.maybeBot; + } + + @Nonnull + @Override + public final InscriberProcessType getProcessType() { + return this.type; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (!(o instanceof IInscriberRecipe)) { + return false; + } + + final IInscriberRecipe that = (IInscriberRecipe) o; + + if (!this.inputs.equals(that.getInputs())) { + return false; + } + if (!this.output.equals(that.getOutput())) { + return false; + } + if (!this.maybeTop.equals(that.getTopOptional())) { + return false; + } + if (!this.maybeBot.equals(that.getBottomOptional())) { + return false; + } + return this.type == that.getProcessType(); + } + + @Override + public int hashCode() { + int result = this.inputs.hashCode(); + result = 31 * result + this.output.hashCode(); + result = 31 * result + this.maybeTop.hashCode(); + result = 31 * result + this.maybeBot.hashCode(); + result = 31 * result + this.type.hashCode(); + return result; + } } diff --git a/src/main/java/appeng/core/localization/ButtonToolTips.java b/src/main/java/appeng/core/localization/ButtonToolTips.java index 84c1feac31e..e1d307568ca 100644 --- a/src/main/java/appeng/core/localization/ButtonToolTips.java +++ b/src/main/java/appeng/core/localization/ButtonToolTips.java @@ -18,100 +18,174 @@ package appeng.core.localization; - -import appeng.api.config.InsertionMode; -import appeng.api.config.SchedulingMode; import net.minecraft.util.StatCollector; - -public enum ButtonToolTips -{ - PowerUnits, IOMode, CondenserOutput, RedstoneMode, MatchingFuzzy, - - MatchingMode, TransferDirection, SortOrder, SortBy, View, - - PartitionStorage, Clear, FuzzyMode, OperationMode, TrashController, - - InterfaceBlockingMode, InterfaceCraftingMode, Trash, MatterBalls, - - Singularity, Read, Write, ReadWrite, AlwaysActive, - - ActiveWithoutSignal, ActiveWithSignal, ActiveOnPulse, - - EmitLevelsBelow, EmitLevelAbove, MatchingExact, TransferToNetwork, - - TransferToStorageCell, ToggleSortDirection, SearchMode_Auto, - - SearchMode_Standard, SearchMode_NEIAuto, SearchMode_NEIStandard, - - SearchMode, ItemName, NumberOfItems, PartitionStorageHint, - - ClearSettings, StoredItems, StoredCraftable, Craftable, - - FZPercent_25, FZPercent_50, FZPercent_75, FZPercent_99, FZIgnoreAll, - - MoveWhenEmpty, MoveWhenWorkIsDone, MoveWhenFull, Disabled, Enable, - - Blocking, NonBlocking, - - LevelType, LevelType_Energy, LevelType_Item, InventoryTweaks, TerminalStyle, TerminalStyle_Full, TerminalStyle_Tall, TerminalStyle_Small, - - Stash, StashDesc, Encode, EncodeDescription, Substitutions, PatternSlotConfigTitle, PatternSlotConfigInfo, SubstitutionsDescEnabled, SubstitutionsDescDisabled, CraftOnly, CraftEither, - - Craft, Mod, DoesntDespawn, EmitterMode, CraftViaRedstone, EmitWhenCrafting, ReportInaccessibleItems, ReportInaccessibleItemsYes, ReportInaccessibleItemsNo, - - BlockPlacement, BlockPlacementYes, BlockPlacementNo, - - // Used in the tooltips of the items in the terminal, when moused over - ItemsStored,ItemCount, ItemsRequestable, P2PFrequency, SearchStringTooltip, - - SchedulingMode, SchedulingModeDefault, SchedulingModeRoundRobin, SchedulingModeRandom, OreFilter, OreFilterHint, DoublePattern, DoublePatternHint, - - SaveSearchString, SaveSearchStringYes, SaveSearchStringNo, - CraftingStatus, CraftingStatusDesc, - ToggleMolecularAssemblers, - ToggleMolecularAssemblersDescOn, - ToggleMolecularAssemblersDescOff, - ToggleShowFullInterfaces, - ToggleShowFullInterfacesOnDesc, - ToggleShowFullInterfacesOffDesc, - ToggleShowOnlyInvalidInterface, - ToggleShowOnlyInvalidInterfaceOnDesc, - ToggleShowOnlyInvalidInterfaceOffDesc, - HighlightInterface, - HighlightInterfaceDesc, - SearchFieldInputs, - SearchFieldOutputs, - SearchFieldNames, - - InsertionModeDefault, - InsertionModeDefaultDesc, - InsertionModePreferEmpty, - InsertionModePreferEmptyDesc, - InsertionModeOnlyEmpty, - InsertionModeOnlyEmptyDesc, - ; - - private final String root; - - ButtonToolTips() - { - this.root = "gui.tooltips.appliedenergistics2"; - } - - ButtonToolTips( final String r ) - { - this.root = r; - } - - public String getLocal() - { - return StatCollector.translateToLocal( this.getUnlocalized() ); - } - - public String getUnlocalized() - { - return this.root + '.' + this.toString(); - } - +public enum ButtonToolTips { + PowerUnits, + IOMode, + CondenserOutput, + RedstoneMode, + MatchingFuzzy, + + MatchingMode, + TransferDirection, + SortOrder, + SortBy, + View, + + PartitionStorage, + Clear, + FuzzyMode, + OperationMode, + TrashController, + + InterfaceBlockingMode, + InterfaceCraftingMode, + Trash, + MatterBalls, + + Singularity, + Read, + Write, + ReadWrite, + AlwaysActive, + + ActiveWithoutSignal, + ActiveWithSignal, + ActiveOnPulse, + + EmitLevelsBelow, + EmitLevelAbove, + MatchingExact, + TransferToNetwork, + + TransferToStorageCell, + ToggleSortDirection, + SearchMode_Auto, + + SearchMode_Standard, + SearchMode_NEIAuto, + SearchMode_NEIStandard, + + SearchMode, + ItemName, + NumberOfItems, + PartitionStorageHint, + + ClearSettings, + StoredItems, + StoredCraftable, + Craftable, + + FZPercent_25, + FZPercent_50, + FZPercent_75, + FZPercent_99, + FZIgnoreAll, + + MoveWhenEmpty, + MoveWhenWorkIsDone, + MoveWhenFull, + Disabled, + Enable, + + Blocking, + NonBlocking, + + LevelType, + LevelType_Energy, + LevelType_Item, + InventoryTweaks, + TerminalStyle, + TerminalStyle_Full, + TerminalStyle_Tall, + TerminalStyle_Small, + + Stash, + StashDesc, + Encode, + EncodeDescription, + Substitutions, + PatternSlotConfigTitle, + PatternSlotConfigInfo, + SubstitutionsDescEnabled, + SubstitutionsDescDisabled, + CraftOnly, + CraftEither, + + Craft, + Mod, + DoesntDespawn, + EmitterMode, + CraftViaRedstone, + EmitWhenCrafting, + ReportInaccessibleItems, + ReportInaccessibleItemsYes, + ReportInaccessibleItemsNo, + + BlockPlacement, + BlockPlacementYes, + BlockPlacementNo, + + // Used in the tooltips of the items in the terminal, when moused over + ItemsStored, + ItemCount, + ItemsRequestable, + P2PFrequency, + SearchStringTooltip, + + SchedulingMode, + SchedulingModeDefault, + SchedulingModeRoundRobin, + SchedulingModeRandom, + OreFilter, + OreFilterHint, + DoublePattern, + DoublePatternHint, + + SaveSearchString, + SaveSearchStringYes, + SaveSearchStringNo, + CraftingStatus, + CraftingStatusDesc, + ToggleMolecularAssemblers, + ToggleMolecularAssemblersDescOn, + ToggleMolecularAssemblersDescOff, + ToggleShowFullInterfaces, + ToggleShowFullInterfacesOnDesc, + ToggleShowFullInterfacesOffDesc, + ToggleShowOnlyInvalidInterface, + ToggleShowOnlyInvalidInterfaceOnDesc, + ToggleShowOnlyInvalidInterfaceOffDesc, + HighlightInterface, + HighlightInterfaceDesc, + SearchFieldInputs, + SearchFieldOutputs, + SearchFieldNames, + + InsertionModeDefault, + InsertionModeDefaultDesc, + InsertionModePreferEmpty, + InsertionModePreferEmptyDesc, + InsertionModeOnlyEmpty, + InsertionModeOnlyEmptyDesc, + ; + + private final String root; + + ButtonToolTips() { + this.root = "gui.tooltips.appliedenergistics2"; + } + + ButtonToolTips(final String r) { + this.root = r; + } + + public String getLocal() { + return StatCollector.translateToLocal(this.getUnlocalized()); + } + + public String getUnlocalized() { + return this.root + '.' + this.toString(); + } } diff --git a/src/main/java/appeng/core/localization/GuiColors.java b/src/main/java/appeng/core/localization/GuiColors.java index 7b978be22ad..32728b6c87a 100644 --- a/src/main/java/appeng/core/localization/GuiColors.java +++ b/src/main/java/appeng/core/localization/GuiColors.java @@ -21,169 +21,159 @@ import appeng.core.AELog; import net.minecraft.util.StatCollector; -public enum GuiColors -{ - //ARGB Colors: Name and default value - SearchboxFocused (0x6E000000), - SearchboxUnfocused (0x00000000), +public enum GuiColors { + // ARGB Colors: Name and default value + SearchboxFocused(0x6E000000), + SearchboxUnfocused(0x00000000), - ItemSlotOverlayUnpowered (0x66111111), - ItemSlotOverlayInvalid (0x66ff6666), + ItemSlotOverlayUnpowered(0x66111111), + ItemSlotOverlayInvalid(0x66ff6666), - CraftConfirmMissingItem (0x1AFF0000), + CraftConfirmMissingItem(0x1AFF0000), - CraftingCPUActive (0x5A45A021), - CraftingCPUInactive (0x5AFFF7AA), + CraftingCPUActive(0x5A45A021), + CraftingCPUInactive(0x5AFFF7AA), - InterfaceTerminalMatch (0x2A00FF00), - - //RGB Colors: Name and default value - SearchboxText (0xFFFFFF), + InterfaceTerminalMatch(0x2A00FF00), - CraftingCPUTitle (0x404040), - CraftingCPUStored (0x404040), - CraftingCPUAmount (0x404040), - CraftingCPUScheduled (0x404040), + // RGB Colors: Name and default value + SearchboxText(0xFFFFFF), - CraftingStatusCPUName (0x202020), - CraftingStatusCPUStorage (0x202020), - CraftingStatusCPUAmount (0x202020), + CraftingCPUTitle(0x404040), + CraftingCPUStored(0x404040), + CraftingCPUAmount(0x404040), + CraftingCPUScheduled(0x404040), - CraftAmountToCraft (0xFFFFFF), - CraftAmountSelectAmount (0x404040), + CraftingStatusCPUName(0x202020), + CraftingStatusCPUStorage(0x202020), + CraftingStatusCPUAmount(0x202020), - LevelEmitterValue (0xFFFFFF), + CraftAmountToCraft(0xFFFFFF), + CraftAmountSelectAmount(0x404040), - PriorityTitle (0x404040), - PriorityValue (0xFFFFFF), + LevelEmitterValue(0xFFFFFF), - ChestTitle (0x404040), - ChestInventory (0x404040), + PriorityTitle(0x404040), + PriorityValue(0xFFFFFF), - CondenserTitle (0x404040), - CondenserInventory (0x404040), + ChestTitle(0x404040), + ChestInventory(0x404040), - CraftConfirmCraftingPlan (0x404040), - CraftConfirmSimulation (0x404040), - CraftConfirmFromStorage (0x404040), - CraftConfirmMissing (0x404040), - CraftConfirmToCraft (0x404040), + CondenserTitle(0x404040), + CondenserInventory(0x404040), - CraftingTerminalTitle (0x404040), + CraftConfirmCraftingPlan(0x404040), + CraftConfirmSimulation(0x404040), + CraftConfirmFromStorage(0x404040), + CraftConfirmMissing(0x404040), + CraftConfirmToCraft(0x404040), - DriveTitle (0x404040), - DriveInventory (0x404040), + CraftingTerminalTitle(0x404040), - FormationPlaneTitle (0x404040), - FormationPlaneInventory (0x404040), - - GrindStoneTitle (0x404040), - GrindStoneInventory (0x404040), - - InscriberTitle (0x404040), - InscriberInventory (0x404040), - - InterfaceTitle (0x404040), - - InterfaceTerminalTitle (0x404040), - InterfaceTerminalInventory (0x404040), - InterfaceTerminalName (0x404040), - - IOPortTitle (0x404040), - IOPortInventory (0x404040), - - NetworkStatusDetails (0x404040), - NetworkStatusStoredPower (0x404040), - NetworkStatusMaxPower (0x404040), - NetworkStatusPowerInputRate (0x404040), - NetworkStatusPowerUsageRate (0x404040), - NetworkStatusItemCount (0x404040), - - NetworkToolTitle (0x404040), - NetworkToolInventory (0x404040), - - OreFilterLabel (0x404040), - - PatternTerminalTitle (0x404040), - PatternTerminalEx (0x404040), - - QuantumLinkChamberTitle (0x404040), - QuantumLinkChamberInventory (0x404040), - - QuartzCuttingKnifeTitle (0x404040), - QuartzCuttingKnifeInventory (0x404040), - - RenamerTitle (0x404040), - - SecurityCardEditorTitle (0x404040), - - SkyChestTitle (0x404040), - SkyChestInventory (0x404040), - - SpatialIOTitle (0x404040), - SpatialIOInventory (0x404040), - SpatialIOStoredPower (0x404040), - SpatialIOMaxPower (0x404040), - SpatialIORequiredPower (0x404040), - SpatialIOEfficiency (0x404040), - - StorageBusTitle (0x404040), - StorageBusInventory (0x404040), - - UpgradableTitle (0x404040), - UpgradableInventory (0x404040), - - VibrationChamberTitle (0x404040), - VibrationChamberInventory (0x404040), - - WirelessTitle (0x404040), - WirelessInventory (0x404040), - WirelessRange (0x404040), - WirelessPowerUsageRate (0x404040), - - NEIGrindstoneRecipeChance (0x000000), - NEIGrindstoneNoSecondOutput (0x000000), - - MEMonitorableTitle (0x404040), - MEMonitorableInventory (0x404040) - ; - - private final String root; - private final int color; - - GuiColors() - { - this.root = "gui.color.appliedenergistics2"; - this.color = 0x000000; - } - - GuiColors( final int hex ) - { - this.root = "gui.color.appliedenergistics2"; - this.color = hex; - } - - public int getColor() - { - String hex = StatCollector.translateToLocal( this.getUnlocalized() ); - int color = this.color; - - if ( hex.length() <= 8 ) - { - try - { - color = Integer.parseUnsignedInt( hex, 16 ); - } - catch ( final NumberFormatException e ) - { - AELog.warn( "Couldn't format color correctly for: " + this.root + " -> " + hex); - } - } - return color; - } - - public String getUnlocalized() - { - return this.root + '.' + this.toString(); - } + DriveTitle(0x404040), + DriveInventory(0x404040), + + FormationPlaneTitle(0x404040), + FormationPlaneInventory(0x404040), + + GrindStoneTitle(0x404040), + GrindStoneInventory(0x404040), + + InscriberTitle(0x404040), + InscriberInventory(0x404040), + + InterfaceTitle(0x404040), + + InterfaceTerminalTitle(0x404040), + InterfaceTerminalInventory(0x404040), + InterfaceTerminalName(0x404040), + + IOPortTitle(0x404040), + IOPortInventory(0x404040), + + NetworkStatusDetails(0x404040), + NetworkStatusStoredPower(0x404040), + NetworkStatusMaxPower(0x404040), + NetworkStatusPowerInputRate(0x404040), + NetworkStatusPowerUsageRate(0x404040), + NetworkStatusItemCount(0x404040), + + NetworkToolTitle(0x404040), + NetworkToolInventory(0x404040), + + OreFilterLabel(0x404040), + + PatternTerminalTitle(0x404040), + PatternTerminalEx(0x404040), + + QuantumLinkChamberTitle(0x404040), + QuantumLinkChamberInventory(0x404040), + + QuartzCuttingKnifeTitle(0x404040), + QuartzCuttingKnifeInventory(0x404040), + + RenamerTitle(0x404040), + + SecurityCardEditorTitle(0x404040), + + SkyChestTitle(0x404040), + SkyChestInventory(0x404040), + + SpatialIOTitle(0x404040), + SpatialIOInventory(0x404040), + SpatialIOStoredPower(0x404040), + SpatialIOMaxPower(0x404040), + SpatialIORequiredPower(0x404040), + SpatialIOEfficiency(0x404040), + + StorageBusTitle(0x404040), + StorageBusInventory(0x404040), + + UpgradableTitle(0x404040), + UpgradableInventory(0x404040), + + VibrationChamberTitle(0x404040), + VibrationChamberInventory(0x404040), + + WirelessTitle(0x404040), + WirelessInventory(0x404040), + WirelessRange(0x404040), + WirelessPowerUsageRate(0x404040), + + NEIGrindstoneRecipeChance(0x000000), + NEIGrindstoneNoSecondOutput(0x000000), + + MEMonitorableTitle(0x404040), + MEMonitorableInventory(0x404040); + + private final String root; + private final int color; + + GuiColors() { + this.root = "gui.color.appliedenergistics2"; + this.color = 0x000000; + } + + GuiColors(final int hex) { + this.root = "gui.color.appliedenergistics2"; + this.color = hex; + } + + public int getColor() { + String hex = StatCollector.translateToLocal(this.getUnlocalized()); + int color = this.color; + + if (hex.length() <= 8) { + try { + color = Integer.parseUnsignedInt(hex, 16); + } catch (final NumberFormatException e) { + AELog.warn("Couldn't format color correctly for: " + this.root + " -> " + hex); + } + } + return color; + } + + public String getUnlocalized() { + return this.root + '.' + this.toString(); + } } diff --git a/src/main/java/appeng/core/localization/GuiText.java b/src/main/java/appeng/core/localization/GuiText.java index 1803f2a22df..99ca8bffc02 100644 --- a/src/main/java/appeng/core/localization/GuiText.java +++ b/src/main/java/appeng/core/localization/GuiText.java @@ -18,113 +18,201 @@ package appeng.core.localization; - import net.minecraft.util.StatCollector; - -public enum GuiText -{ - inventory( "container" ), // mc's default Inventory localization. - - Chest, StoredEnergy, Of, Condenser, Drive, GrindStone, SkyChest, - - VibrationChamber, SpatialIOPort, LevelEmitter, Terminal, - - Interface, Config, StoredItems, Patterns, ImportBus, ExportBus, - - CellWorkbench, NetworkDetails, StorageCells, IOBuses, - - IOPort, BytesUsed, Types, QuantumLinkChamber, PortableCell, - - NetworkTool, PowerUsageRate, PowerInputRate, Installed, EnergyDrain, - - StorageBus, Priority, Security, Encoded, Blank, Unlinked, Linked, - - SecurityCardEditor, NoPermissions, WirelessTerminal, Wireless, - - CraftingTerminal, FormationPlane, Inscriber, QuartzCuttingKnife, - - // tunnel names - METunnel, ItemTunnel, RedstoneTunnel, EUTunnel, FluidTunnel, OCTunnel, LightTunnel, RFTunnel, PressureTunnel, GTTunnel, - - StoredSize, CopyMode, CopyModeDesc, PatternTerminal, - - // Pattern tooltips - CraftingPattern, - ProcessingPattern, - Crafts, - Creates, - And, - With, - Substitute, - Yes, - No, - - MolecularAssembler, - - StoredPower, MaxPower, RequiredPower, Efficiency, InWorldCrafting, - - inWorldFluix, inWorldPurificationCertus, inWorldPurificationNether, - - inWorldPurificationFluix, inWorldSingularity, ChargedQuartz, - - NoSecondOutput, - OfSecondOutput, - MultipleOutputs, - - Stores, Next, SelectAmount, Lumen, Empty, - - ConfirmCrafting, Stored, Crafting, Scheduled, CraftingStatus, Cancel, ETA, ETAFormat, - - FromStorage, ToCraft, CraftingPlan, CalculatingWait, Start, Bytes,Set, - - CraftingCPU, Automatic, CoProcessors, Simulation, Missing, - - InterfaceTerminal, NoCraftingCPUs, Clean, InvalidPattern, UnknownItem, - - InterfaceTerminalHint, Range, TransparentFacades, TransparentFacadesHint, - - NoCraftingJobs, CPUs, FacadeCrafting, inWorldCraftingPresses, ChargedQuartzFind, - - Included, Excluded, Partitioned, PartitionedOre, Precise, Fuzzy, Filter, - - // Used in a terminal to indicate that an item is craftable - SmallFontCraft, LargeFontCraft, - - // processing pattern terminal - PatternTerminalEx, - - // renaming GUI label - Renamer, - - // oredictionary filter GUI label - OreFilterLabel, - - HoldShiftForTooltip, - - // Used in a ME Interface when no appropriate TileEntity was detected near it - Nothing; - - private final String root; - - GuiText() - { - this.root = "gui.appliedenergistics2"; - } - - GuiText( final String r ) - { - this.root = r; - } - - public String getLocal() - { - return StatCollector.translateToLocal( this.getUnlocalized() ); - } - - public String getUnlocalized() - { - return this.root + '.' + this.toString(); - } - +public enum GuiText { + inventory("container"), // mc's default Inventory localization. + + Chest, + StoredEnergy, + Of, + Condenser, + Drive, + GrindStone, + SkyChest, + + VibrationChamber, + SpatialIOPort, + LevelEmitter, + Terminal, + + Interface, + Config, + StoredItems, + Patterns, + ImportBus, + ExportBus, + + CellWorkbench, + NetworkDetails, + StorageCells, + IOBuses, + + IOPort, + BytesUsed, + Types, + QuantumLinkChamber, + PortableCell, + + NetworkTool, + PowerUsageRate, + PowerInputRate, + Installed, + EnergyDrain, + + StorageBus, + Priority, + Security, + Encoded, + Blank, + Unlinked, + Linked, + + SecurityCardEditor, + NoPermissions, + WirelessTerminal, + Wireless, + + CraftingTerminal, + FormationPlane, + Inscriber, + QuartzCuttingKnife, + + // tunnel names + METunnel, + ItemTunnel, + RedstoneTunnel, + EUTunnel, + FluidTunnel, + OCTunnel, + LightTunnel, + RFTunnel, + PressureTunnel, + GTTunnel, + + StoredSize, + CopyMode, + CopyModeDesc, + PatternTerminal, + + // Pattern tooltips + CraftingPattern, + ProcessingPattern, + Crafts, + Creates, + And, + With, + Substitute, + Yes, + No, + + MolecularAssembler, + + StoredPower, + MaxPower, + RequiredPower, + Efficiency, + InWorldCrafting, + + inWorldFluix, + inWorldPurificationCertus, + inWorldPurificationNether, + + inWorldPurificationFluix, + inWorldSingularity, + ChargedQuartz, + + NoSecondOutput, + OfSecondOutput, + MultipleOutputs, + + Stores, + Next, + SelectAmount, + Lumen, + Empty, + + ConfirmCrafting, + Stored, + Crafting, + Scheduled, + CraftingStatus, + Cancel, + ETA, + ETAFormat, + + FromStorage, + ToCraft, + CraftingPlan, + CalculatingWait, + Start, + Bytes, + Set, + + CraftingCPU, + Automatic, + CoProcessors, + Simulation, + Missing, + + InterfaceTerminal, + NoCraftingCPUs, + Clean, + InvalidPattern, + UnknownItem, + + InterfaceTerminalHint, + Range, + TransparentFacades, + TransparentFacadesHint, + + NoCraftingJobs, + CPUs, + FacadeCrafting, + inWorldCraftingPresses, + ChargedQuartzFind, + + Included, + Excluded, + Partitioned, + PartitionedOre, + Precise, + Fuzzy, + Filter, + + // Used in a terminal to indicate that an item is craftable + SmallFontCraft, + LargeFontCraft, + + // processing pattern terminal + PatternTerminalEx, + + // renaming GUI label + Renamer, + + // oredictionary filter GUI label + OreFilterLabel, + + HoldShiftForTooltip, + + // Used in a ME Interface when no appropriate TileEntity was detected near it + Nothing; + + private final String root; + + GuiText() { + this.root = "gui.appliedenergistics2"; + } + + GuiText(final String r) { + this.root = r; + } + + public String getLocal() { + return StatCollector.translateToLocal(this.getUnlocalized()); + } + + public String getUnlocalized() { + return this.root + '.' + this.toString(); + } } diff --git a/src/main/java/appeng/core/localization/PlayerMessages.java b/src/main/java/appeng/core/localization/PlayerMessages.java index 53216a37eac..3af443b7ee6 100644 --- a/src/main/java/appeng/core/localization/PlayerMessages.java +++ b/src/main/java/appeng/core/localization/PlayerMessages.java @@ -18,31 +18,38 @@ package appeng.core.localization; - import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; - -public enum PlayerMessages -{ - ChestCannotReadStorageCell, InvalidMachine, LoadedSettings, SavedSettings, MachineNotPowered, - - isNowLocked, isNowUnlocked, - AmmoDepleted, - CommunicationError, OutOfRange, DeviceNotPowered, DeviceNotWirelessTerminal, DeviceNotLinked, StationCanNotBeLocated, - SettingCleared, - TunnelNotConnected, TunnelInputIsAt, TunnelHasNoOutputs, TunnelOutputsAreAt, - InterfaceInOtherDim, InterfaceHighlighted - ; - - public IChatComponent get() - { - return new ChatComponentTranslation( this.getName() ); - } - - public String getName() - { - return "chat.appliedenergistics2." + this.toString(); - } - +public enum PlayerMessages { + ChestCannotReadStorageCell, + InvalidMachine, + LoadedSettings, + SavedSettings, + MachineNotPowered, + + isNowLocked, + isNowUnlocked, + AmmoDepleted, + CommunicationError, + OutOfRange, + DeviceNotPowered, + DeviceNotWirelessTerminal, + DeviceNotLinked, + StationCanNotBeLocated, + SettingCleared, + TunnelNotConnected, + TunnelInputIsAt, + TunnelHasNoOutputs, + TunnelOutputsAreAt, + InterfaceInOtherDim, + InterfaceHighlighted; + + public IChatComponent get() { + return new ChatComponentTranslation(this.getName()); + } + + public String getName() { + return "chat.appliedenergistics2." + this.toString(); + } } diff --git a/src/main/java/appeng/core/localization/WailaText.java b/src/main/java/appeng/core/localization/WailaText.java index d34c0db7124..fa1193fc514 100644 --- a/src/main/java/appeng/core/localization/WailaText.java +++ b/src/main/java/appeng/core/localization/WailaText.java @@ -18,42 +18,43 @@ package appeng.core.localization; - import net.minecraft.util.StatCollector; +public enum WailaText { + Crafting, -public enum WailaText -{ - Crafting, - - DeviceOnline, DeviceOffline, DeviceMissingChannel, - - P2PUnlinked, P2PInputOneOutput, P2PInputManyOutputs, P2POutput, + DeviceOnline, + DeviceOffline, + DeviceMissingChannel, - Locked, Unlocked, Showing, + P2PUnlinked, + P2PInputOneOutput, + P2PInputManyOutputs, + P2POutput, - Contains, Channels, Booting; + Locked, + Unlocked, + Showing, - private final String root; + Contains, + Channels, + Booting; - WailaText() - { - this.root = "waila.appliedenergistics2"; - } + private final String root; - WailaText( final String r ) - { - this.root = r; - } + WailaText() { + this.root = "waila.appliedenergistics2"; + } - public String getLocal() - { - return StatCollector.translateToLocal( this.getUnlocalized() ); - } + WailaText(final String r) { + this.root = r; + } - public String getUnlocalized() - { - return this.root + '.' + this.toString(); - } + public String getLocal() { + return StatCollector.translateToLocal(this.getUnlocalized()); + } + public String getUnlocalized() { + return this.root + '.' + this.toString(); + } } diff --git a/src/main/java/appeng/core/settings/TickRates.java b/src/main/java/appeng/core/settings/TickRates.java index bc440898e20..405b6159cb9 100644 --- a/src/main/java/appeng/core/settings/TickRates.java +++ b/src/main/java/appeng/core/settings/TickRates.java @@ -18,73 +18,64 @@ package appeng.core.settings; - import appeng.core.AEConfig; +public enum TickRates { + Interface(5, 120), -public enum TickRates -{ - - Interface( 5, 120 ), - - ImportBus( 5, 40 ), - - ExportBus( 5, 60 ), + ImportBus(5, 40), - AnnihilationPlane( 2, 120 ), + ExportBus(5, 60), - METunnel( 5, 20 ), + AnnihilationPlane(2, 120), - Inscriber( 1, 1 ), + METunnel(5, 20), - IOPort( 1, 5 ), + Inscriber(1, 1), - VibrationChamber( 10, 40 ), + IOPort(1, 5), - StorageBus( 5, 60 ), + VibrationChamber(10, 40), - ItemTunnel( 5, 60 ), + StorageBus(5, 60), - LightTunnel( 5, 120 ), + ItemTunnel(5, 60), - OpenComputersTunnel( 1, 5 ), + LightTunnel(5, 120), - PressureTunnel( 1, 120 ); + OpenComputersTunnel(1, 5), - private int min; - private int max; + PressureTunnel(1, 120); - TickRates( final int min, final int max ) - { - this.setMin( min ); - this.setMax( max ); - } + private int min; + private int max; - public void Load( final AEConfig config ) - { - config.addCustomCategoryComment( "TickRates", " Min / Max Tickrates for dynamic ticking, most of these components also use sleeping, to prevent constant ticking, adjust with care, non standard rates are not supported or tested." ); - this.setMin( config.get( "TickRates", this.name() + ".min", this.getMin() ).getInt( this.getMin() ) ); - this.setMax( config.get( "TickRates", this.name() + ".max", this.getMax() ).getInt( this.getMax() ) ); - } + TickRates(final int min, final int max) { + this.setMin(min); + this.setMax(max); + } - public int getMax() - { - return this.max; - } + public void Load(final AEConfig config) { + config.addCustomCategoryComment( + "TickRates", + " Min / Max Tickrates for dynamic ticking, most of these components also use sleeping, to prevent constant ticking, adjust with care, non standard rates are not supported or tested."); + this.setMin(config.get("TickRates", this.name() + ".min", this.getMin()).getInt(this.getMin())); + this.setMax(config.get("TickRates", this.name() + ".max", this.getMax()).getInt(this.getMax())); + } - public void setMax( final int max ) - { - this.max = max; - } + public int getMax() { + return this.max; + } - public int getMin() - { - return this.min; - } + public void setMax(final int max) { + this.max = max; + } - public void setMin( final int min ) - { - this.min = min; - } + public int getMin() { + return this.min; + } + public void setMin(final int min) { + this.min = min; + } } diff --git a/src/main/java/appeng/core/stats/AchievementCraftingHandler.java b/src/main/java/appeng/core/stats/AchievementCraftingHandler.java index 650623e94e5..21be0856149 100644 --- a/src/main/java/appeng/core/stats/AchievementCraftingHandler.java +++ b/src/main/java/appeng/core/stats/AchievementCraftingHandler.java @@ -18,12 +18,10 @@ package appeng.core.stats; - import appeng.util.Platform; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; - /** * handles the achievement when an {@link net.minecraft.item.Item} is crafted by a player. * The achievement is only added if its a real {@link net.minecraft.entity.player.EntityPlayer}. @@ -31,42 +29,36 @@ * @author thatsIch * @since rv2 */ -public class AchievementCraftingHandler -{ - private final PlayerDifferentiator differentiator; +public class AchievementCraftingHandler { + private final PlayerDifferentiator differentiator; - public AchievementCraftingHandler( final PlayerDifferentiator differentiator ) - { - this.differentiator = differentiator; - } + public AchievementCraftingHandler(final PlayerDifferentiator differentiator) { + this.differentiator = differentiator; + } - @SubscribeEvent - public void onPlayerCraftingEvent( final PlayerEvent.ItemCraftedEvent event ) - { - if( this.differentiator.isNoPlayer( event.player ) || event.crafting == null ) - { - return; - } + @SubscribeEvent + public void onPlayerCraftingEvent(final PlayerEvent.ItemCraftedEvent event) { + if (this.differentiator.isNoPlayer(event.player) || event.crafting == null) { + return; + } - for( final Achievements achievement : Achievements.values() ) - { - switch( achievement.getType() ) - { - case Craft: - if( Platform.isSameItemPrecise( achievement.getStack(), event.crafting ) ) - { - achievement.addToPlayer( event.player ); - return; - } - break; - case CraftItem: - if( achievement.getStack() != null && achievement.getStack().getItem().getClass() == event.crafting.getItem().getClass() ) - { - achievement.addToPlayer( event.player ); - return; - } - default: - } - } - } + for (final Achievements achievement : Achievements.values()) { + switch (achievement.getType()) { + case Craft: + if (Platform.isSameItemPrecise(achievement.getStack(), event.crafting)) { + achievement.addToPlayer(event.player); + return; + } + break; + case CraftItem: + if (achievement.getStack() != null + && achievement.getStack().getItem().getClass() + == event.crafting.getItem().getClass()) { + achievement.addToPlayer(event.player); + return; + } + default: + } + } + } } diff --git a/src/main/java/appeng/core/stats/AchievementHierarchy.java b/src/main/java/appeng/core/stats/AchievementHierarchy.java index cb8df680460..d99d42d8900 100644 --- a/src/main/java/appeng/core/stats/AchievementHierarchy.java +++ b/src/main/java/appeng/core/stats/AchievementHierarchy.java @@ -18,44 +18,41 @@ package appeng.core.stats; - /** * Hierarchy of the AE2 achievements * * @author thatsIch * @since rv2 */ -public class AchievementHierarchy -{ - /** - * Setup hierarchy through assigning parents. - */ - void registerAchievementHierarchy() - { - Achievements.Presses.setParent( Achievements.Compass ); +public class AchievementHierarchy { + /** + * Setup hierarchy through assigning parents. + */ + void registerAchievementHierarchy() { + Achievements.Presses.setParent(Achievements.Compass); - Achievements.Fluix.setParent( Achievements.ChargedQuartz ); + Achievements.Fluix.setParent(Achievements.ChargedQuartz); - Achievements.Charger.setParent( Achievements.Fluix ); + Achievements.Charger.setParent(Achievements.Fluix); - Achievements.CrystalGrowthAccelerator.setParent( Achievements.Charger ); + Achievements.CrystalGrowthAccelerator.setParent(Achievements.Charger); - Achievements.GlassCable.setParent( Achievements.Charger ); + Achievements.GlassCable.setParent(Achievements.Charger); - Achievements.SpatialIOExplorer.setParent( Achievements.SpatialIO ); + Achievements.SpatialIOExplorer.setParent(Achievements.SpatialIO); - Achievements.IOPort.setParent( Achievements.StorageCell ); + Achievements.IOPort.setParent(Achievements.StorageCell); - Achievements.PatternTerminal.setParent( Achievements.CraftingTerminal ); + Achievements.PatternTerminal.setParent(Achievements.CraftingTerminal); - Achievements.Controller.setParent( Achievements.Networking1 ); + Achievements.Controller.setParent(Achievements.Networking1); - Achievements.Networking2.setParent( Achievements.Controller ); + Achievements.Networking2.setParent(Achievements.Controller); - Achievements.Networking3.setParent( Achievements.Networking2 ); + Achievements.Networking3.setParent(Achievements.Networking2); - Achievements.P2P.setParent( Achievements.Controller ); + Achievements.P2P.setParent(Achievements.Controller); - Achievements.Recursive.setParent( Achievements.Controller ); - } + Achievements.Recursive.setParent(Achievements.Controller); + } } diff --git a/src/main/java/appeng/core/stats/AchievementPickupHandler.java b/src/main/java/appeng/core/stats/AchievementPickupHandler.java index 3f60e1c65de..9031a13e25c 100644 --- a/src/main/java/appeng/core/stats/AchievementPickupHandler.java +++ b/src/main/java/appeng/core/stats/AchievementPickupHandler.java @@ -18,13 +18,11 @@ package appeng.core.stats; - import appeng.util.Platform; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import net.minecraft.item.ItemStack; - /** * handles the achievement when an {@link net.minecraft.item.Item} is picked up by a player. * The achievement is only added if its a real {@link net.minecraft.entity.player.EntityPlayer}. @@ -32,32 +30,29 @@ * @author thatsIch * @since rv2 */ -public class AchievementPickupHandler -{ - private final PlayerDifferentiator differentiator; - - public AchievementPickupHandler( final PlayerDifferentiator differentiator ) - { - this.differentiator = differentiator; - } - - @SubscribeEvent - public void onItemPickUp( final PlayerEvent.ItemPickupEvent event ) - { - if( this.differentiator.isNoPlayer( event.player ) || event.pickedUp == null || event.pickedUp.getEntityItem() == null ) - { - return; - } - - final ItemStack is = event.pickedUp.getEntityItem(); - - for( final Achievements achievement : Achievements.values() ) - { - if( achievement.getType() == AchievementType.Pickup && Platform.isSameItemPrecise( achievement.getStack(), is ) ) - { - achievement.addToPlayer( event.player ); - return; - } - } - } +public class AchievementPickupHandler { + private final PlayerDifferentiator differentiator; + + public AchievementPickupHandler(final PlayerDifferentiator differentiator) { + this.differentiator = differentiator; + } + + @SubscribeEvent + public void onItemPickUp(final PlayerEvent.ItemPickupEvent event) { + if (this.differentiator.isNoPlayer(event.player) + || event.pickedUp == null + || event.pickedUp.getEntityItem() == null) { + return; + } + + final ItemStack is = event.pickedUp.getEntityItem(); + + for (final Achievements achievement : Achievements.values()) { + if (achievement.getType() == AchievementType.Pickup + && Platform.isSameItemPrecise(achievement.getStack(), is)) { + achievement.addToPlayer(event.player); + return; + } + } + } } diff --git a/src/main/java/appeng/core/stats/AchievementType.java b/src/main/java/appeng/core/stats/AchievementType.java index 2e90ba9cada..d8ec67f1571 100644 --- a/src/main/java/appeng/core/stats/AchievementType.java +++ b/src/main/java/appeng/core/stats/AchievementType.java @@ -18,10 +18,9 @@ package appeng.core.stats; - -public enum AchievementType -{ - - Craft, CraftItem, Pickup, Custom - +public enum AchievementType { + Craft, + CraftItem, + Pickup, + Custom } diff --git a/src/main/java/appeng/core/stats/Achievements.java b/src/main/java/appeng/core/stats/Achievements.java index a5ba3b1badb..bcf4e2d636d 100644 --- a/src/main/java/appeng/core/stats/Achievements.java +++ b/src/main/java/appeng/core/stats/Achievements.java @@ -18,7 +18,6 @@ package appeng.core.stats; - import appeng.api.AEApi; import appeng.api.definitions.IItemDefinition; import appeng.api.util.AEColor; @@ -27,145 +26,145 @@ import net.minecraft.item.ItemStack; import net.minecraft.stats.Achievement; +public enum Achievements { + // done + Compass(-2, -4, AEApi.instance().definitions().blocks().skyCompass(), AchievementType.Craft), -public enum Achievements -{ - // done - Compass( -2, -4, AEApi.instance().definitions().blocks().skyCompass(), AchievementType.Craft ), - - // done - Presses( -2, -2, AEApi.instance().definitions().materials().logicProcessorPress(), AchievementType.Custom ), - - // done - SpatialIO( -4, -4, AEApi.instance().definitions().blocks().spatialIOPort(), AchievementType.Craft ), - - // done - SpatialIOExplorer( -4, -2, AEApi.instance().definitions().items().spatialCell128(), AchievementType.Custom ), - - // done - StorageCell( -6, -4, AEApi.instance().definitions().items().cell64k(), AchievementType.CraftItem ), - - // done - IOPort( -6, -2, AEApi.instance().definitions().blocks().iOPort(), AchievementType.Craft ), - - // done - CraftingTerminal( -8, -4, AEApi.instance().definitions().parts().craftingTerminal(), AchievementType.Craft ), + // done + Presses(-2, -2, AEApi.instance().definitions().materials().logicProcessorPress(), AchievementType.Custom), - // done - PatternTerminal( -8, -2, AEApi.instance().definitions().parts().patternTerminal(), AchievementType.Craft ), + // done + SpatialIO(-4, -4, AEApi.instance().definitions().blocks().spatialIOPort(), AchievementType.Craft), - // done - ChargedQuartz( 0, -4, AEApi.instance().definitions().materials().certusQuartzCrystalCharged(), AchievementType.Pickup ), + // done + SpatialIOExplorer(-4, -2, AEApi.instance().definitions().items().spatialCell128(), AchievementType.Custom), - // done - Fluix( 0, -2, AEApi.instance().definitions().materials().fluixCrystal(), AchievementType.Pickup ), + // done + StorageCell(-6, -4, AEApi.instance().definitions().items().cell64k(), AchievementType.CraftItem), - // done - Charger( 0, 0, AEApi.instance().definitions().blocks().charger(), AchievementType.Craft ), + // done + IOPort(-6, -2, AEApi.instance().definitions().blocks().iOPort(), AchievementType.Craft), - // done - CrystalGrowthAccelerator( -2, 0, AEApi.instance().definitions().blocks().quartzGrowthAccelerator(), AchievementType.Craft ), + // done + CraftingTerminal(-8, -4, AEApi.instance().definitions().parts().craftingTerminal(), AchievementType.Craft), - // done - GlassCable( 2, 0, AEApi.instance().definitions().parts().cableGlass(), AchievementType.Craft ), + // done + PatternTerminal(-8, -2, AEApi.instance().definitions().parts().patternTerminal(), AchievementType.Craft), - // done - Networking1( 4, -6, AEApi.instance().definitions().parts().cableCovered(), AchievementType.Custom ), + // done + ChargedQuartz( + 0, -4, AEApi.instance().definitions().materials().certusQuartzCrystalCharged(), AchievementType.Pickup), - // done - Controller( 4, -4, AEApi.instance().definitions().blocks().controller(), AchievementType.Craft ), + // done + Fluix(0, -2, AEApi.instance().definitions().materials().fluixCrystal(), AchievementType.Pickup), - // done - Networking2( 4, 0, AEApi.instance().definitions().parts().cableSmart(), AchievementType.Custom ), + // done + Charger(0, 0, AEApi.instance().definitions().blocks().charger(), AchievementType.Craft), - // done - Networking3( 4, 2, AEApi.instance().definitions().parts().cableDense(), AchievementType.Custom ),//todo achievement for dense covered cables + // done + CrystalGrowthAccelerator( + -2, 0, AEApi.instance().definitions().blocks().quartzGrowthAccelerator(), AchievementType.Craft), - // done - P2P( 2, -2, AEApi.instance().definitions().parts().p2PTunnelME(), AchievementType.Craft ), + // done + GlassCable(2, 0, AEApi.instance().definitions().parts().cableGlass(), AchievementType.Craft), - // done - Recursive( 6, -2, AEApi.instance().definitions().blocks().iface(), AchievementType.Craft ), + // done + Networking1(4, -6, AEApi.instance().definitions().parts().cableCovered(), AchievementType.Custom), - // done - CraftingCPU( 6, 0, AEApi.instance().definitions().blocks().craftingStorage64k(), AchievementType.CraftItem ), + // done + Controller(4, -4, AEApi.instance().definitions().blocks().controller(), AchievementType.Craft), - // done - Facade( 6, 2, AEApi.instance().definitions().items().facade(), AchievementType.CraftItem ), + // done + Networking2(4, 0, AEApi.instance().definitions().parts().cableSmart(), AchievementType.Custom), - // done - NetworkTool( 8, 0, AEApi.instance().definitions().items().networkTool(), AchievementType.Craft ), + // done + Networking3( + 4, + 2, + AEApi.instance().definitions().parts().cableDense(), + AchievementType.Custom), // todo achievement for dense covered cables - // done - PortableCell( 8, 2, AEApi.instance().definitions().items().portableCell(), AchievementType.Craft ), + // done + P2P(2, -2, AEApi.instance().definitions().parts().p2PTunnelME(), AchievementType.Craft), - // done - StorageBus( 10, 0, AEApi.instance().definitions().parts().storageBus(), AchievementType.Craft ), + // done + Recursive(6, -2, AEApi.instance().definitions().blocks().iface(), AchievementType.Craft), - // done - QNB( 10, 2, AEApi.instance().definitions().blocks().quantumLink(), AchievementType.Craft ); + // done + CraftingCPU(6, 0, AEApi.instance().definitions().blocks().craftingStorage64k(), AchievementType.CraftItem), - private final ItemStack stack; - private final AchievementType type; - private final int x; - private final int y; + // done + Facade(6, 2, AEApi.instance().definitions().items().facade(), AchievementType.CraftItem), - private Achievement parent; - private Achievement stat; + // done + NetworkTool(8, 0, AEApi.instance().definitions().items().networkTool(), AchievementType.Craft), - Achievements( final int x, final int y, final AEColoredItemDefinition which, final AchievementType type ) - { - this.stack = ( which != null ) ? which.stack( AEColor.Transparent, 1 ) : null; - this.type = type; - this.x = x; - this.y = y; - } + // done + PortableCell(8, 2, AEApi.instance().definitions().items().portableCell(), AchievementType.Craft), - Achievements( final int x, final int y, final IItemDefinition which, final AchievementType type ) - { - this.stack = which.maybeStack( 1 ).orNull(); - this.type = type; - this.x = x; - this.y = y; - } + // done + StorageBus(10, 0, AEApi.instance().definitions().parts().storageBus(), AchievementType.Craft), - Achievements( final int x, final int y, final ItemStack which, final AchievementType type ) - { - this.stack = which; - this.type = type; - this.x = x; - this.y = y; - } + // done + QNB(10, 2, AEApi.instance().definitions().blocks().quantumLink(), AchievementType.Craft); - void setParent( final Achievements parent ) - { - this.parent = parent.getAchievement(); - } + private final ItemStack stack; + private final AchievementType type; + private final int x; + private final int y; - public Achievement getAchievement() - { - if( this.stat == null && this.getStack() != null ) - { - this.stat = new Achievement( "achievement.ae2." + this.name(), "ae2." + this.name(), this.x, this.y, this.getStack(), this.parent ); - this.stat.registerStat(); - } + private Achievement parent; + private Achievement stat; - return this.stat; - } + Achievements(final int x, final int y, final AEColoredItemDefinition which, final AchievementType type) { + this.stack = (which != null) ? which.stack(AEColor.Transparent, 1) : null; + this.type = type; + this.x = x; + this.y = y; + } - public void addToPlayer( final EntityPlayer player ) - { - player.addStat( this.getAchievement(), 1 ); - } + Achievements(final int x, final int y, final IItemDefinition which, final AchievementType type) { + this.stack = which.maybeStack(1).orNull(); + this.type = type; + this.x = x; + this.y = y; + } - AchievementType getType() - { - return this.type; - } + Achievements(final int x, final int y, final ItemStack which, final AchievementType type) { + this.stack = which; + this.type = type; + this.x = x; + this.y = y; + } - ItemStack getStack() - { - return this.stack; - } + void setParent(final Achievements parent) { + this.parent = parent.getAchievement(); + } + public Achievement getAchievement() { + if (this.stat == null && this.getStack() != null) { + this.stat = new Achievement( + "achievement.ae2." + this.name(), + "ae2." + this.name(), + this.x, + this.y, + this.getStack(), + this.parent); + this.stat.registerStat(); + } + + return this.stat; + } + + public void addToPlayer(final EntityPlayer player) { + player.addStat(this.getAchievement(), 1); + } + + AchievementType getType() { + return this.type; + } + + ItemStack getStack() { + return this.stack; + } } diff --git a/src/main/java/appeng/core/stats/PlayerDifferentiator.java b/src/main/java/appeng/core/stats/PlayerDifferentiator.java index 75d18bf6db4..a9b502ea907 100644 --- a/src/main/java/appeng/core/stats/PlayerDifferentiator.java +++ b/src/main/java/appeng/core/stats/PlayerDifferentiator.java @@ -18,31 +18,27 @@ package appeng.core.stats; - import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.common.util.FakePlayer; - /** * Can differentiate if a {@link net.minecraft.entity.player.EntityPlayer} is a real player or not * * @author thatsIch * @since rv2 */ -public class PlayerDifferentiator -{ - /** - * Can determine if an {@link net.minecraft.entity.player.EntityPlayer} is not a real player. - * This is based on if the {@param player} is: - * - null - * - dead - * - fake - * - * @param player to be checked player - * @return true if {@param player} is not a real player - */ - boolean isNoPlayer( final EntityPlayer player ) - { - return player == null || player.isDead || player instanceof FakePlayer; - } +public class PlayerDifferentiator { + /** + * Can determine if an {@link net.minecraft.entity.player.EntityPlayer} is not a real player. + * This is based on if the {@param player} is: + * - null + * - dead + * - fake + * + * @param player to be checked player + * @return true if {@param player} is not a real player + */ + boolean isNoPlayer(final EntityPlayer player) { + return player == null || player.isDead || player instanceof FakePlayer; + } } diff --git a/src/main/java/appeng/core/stats/PlayerStatsRegistration.java b/src/main/java/appeng/core/stats/PlayerStatsRegistration.java index eccedaa090e..22c918fe8c7 100644 --- a/src/main/java/appeng/core/stats/PlayerStatsRegistration.java +++ b/src/main/java/appeng/core/stats/PlayerStatsRegistration.java @@ -18,97 +18,86 @@ package appeng.core.stats; - import appeng.core.AEConfig; import appeng.core.features.AEFeature; import cpw.mods.fml.common.eventhandler.EventBus; +import java.util.ArrayList; import net.minecraft.stats.Achievement; import net.minecraftforge.common.AchievementPage; -import java.util.ArrayList; - - /** * Registers any items a player is picking up or is crafting. * Registered items are added to the player stats. * This will only happen if the {@link AEFeature#Achievements} feature is enabled. */ -public class PlayerStatsRegistration -{ - /** - * {@link cpw.mods.fml.common.eventhandler.EventBus} to which the handlers might get posted to depending if the - * feature is enabled - */ - private final EventBus bus; +public class PlayerStatsRegistration { + /** + * {@link cpw.mods.fml.common.eventhandler.EventBus} to which the handlers might get posted to depending if the + * feature is enabled + */ + private final EventBus bus; - /** - * is true if the {@link appeng.core.features.AEFeature#Achievements} is enabled in the - */ - private final boolean isAchievementFeatureEnabled; + /** + * is true if the {@link appeng.core.features.AEFeature#Achievements} is enabled in the + */ + private final boolean isAchievementFeatureEnabled; - /** - * Constructs this with an {@link cpw.mods.fml.common.eventhandler.EventBus} and {@link appeng.core.AEConfig}. - * - * @param bus {@see #bus} - * @param config {@link appeng.core.AEConfig} which is used to determine if the - * {@link appeng.core.features.AEFeature#Achievements} is enabled - */ - public PlayerStatsRegistration( final EventBus bus, final AEConfig config ) - { - this.bus = bus; - this.isAchievementFeatureEnabled = config.isFeatureEnabled( AEFeature.Achievements ); - } + /** + * Constructs this with an {@link cpw.mods.fml.common.eventhandler.EventBus} and {@link appeng.core.AEConfig}. + * + * @param bus {@see #bus} + * @param config {@link appeng.core.AEConfig} which is used to determine if the + * {@link appeng.core.features.AEFeature#Achievements} is enabled + */ + public PlayerStatsRegistration(final EventBus bus, final AEConfig config) { + this.bus = bus; + this.isAchievementFeatureEnabled = config.isFeatureEnabled(AEFeature.Achievements); + } - /** - * Registers the {@link appeng.core.stats.AchievementCraftingHandler} and - * {@link appeng.core.stats.AchievementPickupHandler} to the {@link #bus} if {@link #isAchievementFeatureEnabled} is - * true. - */ - public void registerAchievementHandlers() - { - if( this.isAchievementFeatureEnabled ) - { - final PlayerDifferentiator differentiator = new PlayerDifferentiator(); - final AchievementCraftingHandler craftingHandler = new AchievementCraftingHandler( differentiator ); - final AchievementPickupHandler pickupHandler = new AchievementPickupHandler( differentiator ); + /** + * Registers the {@link appeng.core.stats.AchievementCraftingHandler} and + * {@link appeng.core.stats.AchievementPickupHandler} to the {@link #bus} if {@link #isAchievementFeatureEnabled} is + * true. + */ + public void registerAchievementHandlers() { + if (this.isAchievementFeatureEnabled) { + final PlayerDifferentiator differentiator = new PlayerDifferentiator(); + final AchievementCraftingHandler craftingHandler = new AchievementCraftingHandler(differentiator); + final AchievementPickupHandler pickupHandler = new AchievementPickupHandler(differentiator); - this.bus.register( craftingHandler ); - this.bus.register( pickupHandler ); - } - } + this.bus.register(craftingHandler); + this.bus.register(pickupHandler); + } + } - /** - * Registers the {@link appeng.core.stats.AchievementHierarchy} and adds all {@link appeng.core.stats.Achievements} - * to a new {@link net.minecraftforge.common.AchievementPage}. - */ - public void registerAchievements() - { - if( this.isAchievementFeatureEnabled ) - { - final AchievementHierarchy hierarchy = new AchievementHierarchy(); - hierarchy.registerAchievementHierarchy(); + /** + * Registers the {@link appeng.core.stats.AchievementHierarchy} and adds all {@link appeng.core.stats.Achievements} + * to a new {@link net.minecraftforge.common.AchievementPage}. + */ + public void registerAchievements() { + if (this.isAchievementFeatureEnabled) { + final AchievementHierarchy hierarchy = new AchievementHierarchy(); + hierarchy.registerAchievementHierarchy(); - for( final Stats s : Stats.values() ) - { - s.getStat(); - } + for (final Stats s : Stats.values()) { + s.getStat(); + } - /** - * register - */ - final ArrayList list = new ArrayList(); + /** + * register + */ + final ArrayList list = new ArrayList(); - for( final Achievements a : Achievements.values() ) - { - final Achievement ach = a.getAchievement(); - if( ach != null ) - { - list.add( ach ); - } - } + for (final Achievements a : Achievements.values()) { + final Achievement ach = a.getAchievement(); + if (ach != null) { + list.add(ach); + } + } - final AchievementPage ae2AchievementPage = new AchievementPage( "Applied Energistics 2", list.toArray( new Achievement[list.size()] ) ); - AchievementPage.registerAchievementPage( ae2AchievementPage ); - } - } + final AchievementPage ae2AchievementPage = + new AchievementPage("Applied Energistics 2", list.toArray(new Achievement[list.size()])); + AchievementPage.registerAchievementPage(ae2AchievementPage); + } + } } diff --git a/src/main/java/appeng/core/stats/Stats.java b/src/main/java/appeng/core/stats/Stats.java index a3fd1546d2e..b4787e8afbc 100644 --- a/src/main/java/appeng/core/stats/Stats.java +++ b/src/main/java/appeng/core/stats/Stats.java @@ -18,44 +18,36 @@ package appeng.core.stats; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.stats.StatBasic; import net.minecraft.util.ChatComponentTranslation; +public enum Stats { -public enum Stats -{ - - // done - ItemsInserted, - - // done - ItemsExtracted, + // done + ItemsInserted, - // done - TurnedCranks; + // done + ItemsExtracted, - private StatBasic stat; + // done + TurnedCranks; - Stats() - { - } + private StatBasic stat; - public void addToPlayer( final EntityPlayer player, final int howMany ) - { - player.addStat( this.getStat(), howMany ); - } + Stats() {} - StatBasic getStat() - { - if( this.stat == null ) - { - this.stat = new StatBasic( "stat.ae2." + this.name(), new ChatComponentTranslation( "stat.ae2." + this.name() ) ); - this.stat.registerStat(); - } + public void addToPlayer(final EntityPlayer player, final int howMany) { + player.addStat(this.getStat(), howMany); + } - return this.stat; - } + StatBasic getStat() { + if (this.stat == null) { + this.stat = + new StatBasic("stat.ae2." + this.name(), new ChatComponentTranslation("stat.ae2." + this.name())); + this.stat.registerStat(); + } + return this.stat; + } } diff --git a/src/main/java/appeng/core/sync/AppEngPacket.java b/src/main/java/appeng/core/sync/AppEngPacket.java index 30d590b9e8e..e04195b742b 100644 --- a/src/main/java/appeng/core/sync/AppEngPacket.java +++ b/src/main/java/appeng/core/sync/AppEngPacket.java @@ -18,7 +18,6 @@ package appeng.core.sync; - import appeng.core.AEConfig; import appeng.core.AELog; import appeng.core.features.AEFeature; @@ -28,53 +27,47 @@ import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayer; +public abstract class AppEngPacket { -public abstract class AppEngPacket -{ - - private AppEngPacketHandlerBase.PacketTypes id; - private ByteBuf p; + private AppEngPacketHandlerBase.PacketTypes id; + private ByteBuf p; - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - throw new UnsupportedOperationException( "This packet ( " + this.getPacketID() + " does not implement a server side handler." ); - } + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + throw new UnsupportedOperationException( + "This packet ( " + this.getPacketID() + " does not implement a server side handler."); + } - public final int getPacketID() - { - return AppEngPacketHandlerBase.PacketTypes.getID( this.getClass() ).ordinal(); - } + public final int getPacketID() { + return AppEngPacketHandlerBase.PacketTypes.getID(this.getClass()).ordinal(); + } - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - throw new UnsupportedOperationException( "This packet ( " + this.getPacketID() + " does not implement a client side handler." ); - } + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + throw new UnsupportedOperationException( + "This packet ( " + this.getPacketID() + " does not implement a client side handler."); + } - protected void configureWrite( final ByteBuf data ) - { - data.capacity( data.readableBytes() ); - this.p = data; - } + protected void configureWrite(final ByteBuf data) { + data.capacity(data.readableBytes()); + this.p = data; + } - public int size() - { - return this.p.array().length; - } + public int size() { + return this.p.array().length; + } - public FMLProxyPacket getProxy() - { - if( this.p.array().length > 2 * 1024 * 1024 ) // 2k walking room :) - { - throw new IllegalArgumentException( "Sorry AE2 made a " + this.p.array().length + " byte packet by accident!" ); - } + public FMLProxyPacket getProxy() { + if (this.p.array().length > 2 * 1024 * 1024) // 2k walking room :) + { + throw new IllegalArgumentException( + "Sorry AE2 made a " + this.p.array().length + " byte packet by accident!"); + } - final FMLProxyPacket pp = new FMLProxyPacket( this.p, NetworkHandler.instance.getChannel() ); + final FMLProxyPacket pp = new FMLProxyPacket(this.p, NetworkHandler.instance.getChannel()); - if( AEConfig.instance.isFeatureEnabled( AEFeature.PacketLogging ) ) - { - AELog.info( this.getClass().getName() + " : " + pp.payload().readableBytes() ); - } + if (AEConfig.instance.isFeatureEnabled(AEFeature.PacketLogging)) { + AELog.info(this.getClass().getName() + " : " + pp.payload().readableBytes()); + } - return pp; - } + return pp; + } } diff --git a/src/main/java/appeng/core/sync/AppEngPacketHandlerBase.java b/src/main/java/appeng/core/sync/AppEngPacketHandlerBase.java index 377b4021121..535406c1a42 100644 --- a/src/main/java/appeng/core/sync/AppEngPacketHandlerBase.java +++ b/src/main/java/appeng/core/sync/AppEngPacketHandlerBase.java @@ -18,116 +18,104 @@ package appeng.core.sync; - import appeng.core.sync.packets.*; import io.netty.buffer.ByteBuf; - import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; +public class AppEngPacketHandlerBase { + private static final Map, PacketTypes> REVERSE_LOOKUP = new HashMap<>(); -public class AppEngPacketHandlerBase -{ - private static final Map, PacketTypes> REVERSE_LOOKUP = new HashMap<>(); - - - public enum PacketTypes - { - PACKET_COMPASS_REQUEST( PacketCompassRequest.class ), + public enum PacketTypes { + PACKET_COMPASS_REQUEST(PacketCompassRequest.class), - PACKET_COMPASS_RESPONSE( PacketCompassResponse.class ), + PACKET_COMPASS_RESPONSE(PacketCompassResponse.class), - PACKET_INVENTORY_ACTION( PacketInventoryAction.class ), + PACKET_INVENTORY_ACTION(PacketInventoryAction.class), - PACKET_ME_INVENTORY_UPDATE( PacketMEInventoryUpdate.class ), + PACKET_ME_INVENTORY_UPDATE(PacketMEInventoryUpdate.class), - PACKET_CONFIG_BUTTON( PacketConfigButton.class ), + PACKET_CONFIG_BUTTON(PacketConfigButton.class), - PACKET_MULTIPART( PacketMultiPart.class ), + PACKET_MULTIPART(PacketMultiPart.class), - PACKET_PART_PLACEMENT( PacketPartPlacement.class ), + PACKET_PART_PLACEMENT(PacketPartPlacement.class), - PACKET_LIGHTNING( PacketLightning.class ), + PACKET_LIGHTNING(PacketLightning.class), - PACKET_MATTER_CANNON( PacketMatterCannon.class ), + PACKET_MATTER_CANNON(PacketMatterCannon.class), - PACKET_MOCK_EXPLOSION( PacketMockExplosion.class ), + PACKET_MOCK_EXPLOSION(PacketMockExplosion.class), - PACKET_VALUE_CONFIG( PacketValueConfig.class ), + PACKET_VALUE_CONFIG(PacketValueConfig.class), - PACKET_TRANSITION_EFFECT( PacketTransitionEffect.class ), + PACKET_TRANSITION_EFFECT(PacketTransitionEffect.class), - PACKET_PROGRESS_VALUE( PacketProgressBar.class ), + PACKET_PROGRESS_VALUE(PacketProgressBar.class), - PACKET_CLICK( PacketClick.class ), + PACKET_CLICK(PacketClick.class), - PACKET_NEW_STORAGE_DIMENSION( PacketNewStorageDimension.class ), + PACKET_NEW_STORAGE_DIMENSION(PacketNewStorageDimension.class), - PACKET_SWITCH_GUIS( PacketSwitchGuis.class ), + PACKET_SWITCH_GUIS(PacketSwitchGuis.class), - PACKET_SWAP_SLOTS( PacketSwapSlots.class ), + PACKET_SWAP_SLOTS(PacketSwapSlots.class), - PACKET_PATTERN_SLOT( PacketPatternSlot.class ), + PACKET_PATTERN_SLOT(PacketPatternSlot.class), - PACKET_RECIPE_NEI( PacketNEIRecipe.class ), + PACKET_RECIPE_NEI(PacketNEIRecipe.class), - PACKET_PARTIAL_ITEM( PacketPartialItem.class ), + PACKET_PARTIAL_ITEM(PacketPartialItem.class), - PACKET_CRAFTING_REQUEST( PacketCraftRequest.class ), + PACKET_CRAFTING_REQUEST(PacketCraftRequest.class), - PACKET_ASSEMBLER_ANIMATION( PacketAssemblerAnimation.class ), + PACKET_ASSEMBLER_ANIMATION(PacketAssemblerAnimation.class), - PACKET_COMPRESSED_NBT( PacketCompressedNBT.class ), + PACKET_COMPRESSED_NBT(PacketCompressedNBT.class), - PACKET_PAINTED_ENTITY( PacketPaintedEntity.class ), + PACKET_PAINTED_ENTITY(PacketPaintedEntity.class), - PACKET_CRAFTING_CPUS_UPDATE( PacketCraftingCPUsUpdate.class ), + PACKET_CRAFTING_CPUS_UPDATE(PacketCraftingCPUsUpdate.class), - PACKET_NEI_DRAG( PacketNEIDragClick.class ), + PACKET_NEI_DRAG(PacketNEIDragClick.class), - PACKET_PATTERN_VALUE( PacketPatternValueSet.class ); + PACKET_PATTERN_VALUE(PacketPatternValueSet.class); - private final Class packetClass; - private final Constructor packetConstructor; + private final Class packetClass; + private final Constructor packetConstructor; - PacketTypes( final Class c ) - { - this.packetClass = c; + PacketTypes(final Class c) { + this.packetClass = c; - Constructor x = null; - try - { - x = this.packetClass.getConstructor( ByteBuf.class ); - } - catch( final NoSuchMethodException | SecurityException ignored ) - { - } + Constructor x = null; + try { + x = this.packetClass.getConstructor(ByteBuf.class); + } catch (final NoSuchMethodException | SecurityException ignored) { + } this.packetConstructor = x; - REVERSE_LOOKUP.put( this.packetClass, this ); - - if( this.packetConstructor == null ) - { - throw new IllegalStateException( "Invalid Packet Class " + c + ", must be constructable on DataInputStream" ); - } - } - - public static PacketTypes getPacket( final int id ) - { - return ( values() )[id]; - } - - static PacketTypes getID( final Class c ) - { - return REVERSE_LOOKUP.get( c ); - } - - public AppEngPacket parsePacket( final ByteBuf in ) - throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException - { - return this.packetConstructor.newInstance( in ); - } - } + REVERSE_LOOKUP.put(this.packetClass, this); + + if (this.packetConstructor == null) { + throw new IllegalStateException( + "Invalid Packet Class " + c + ", must be constructable on DataInputStream"); + } + } + + public static PacketTypes getPacket(final int id) { + return (values())[id]; + } + + static PacketTypes getID(final Class c) { + return REVERSE_LOOKUP.get(c); + } + + public AppEngPacket parsePacket(final ByteBuf in) + throws InstantiationException, IllegalAccessException, IllegalArgumentException, + InvocationTargetException { + return this.packetConstructor.newInstance(in); + } + } } diff --git a/src/main/java/appeng/core/sync/GuiBridge.java b/src/main/java/appeng/core/sync/GuiBridge.java index daef2745201..1c0a022045b 100644 --- a/src/main/java/appeng/core/sync/GuiBridge.java +++ b/src/main/java/appeng/core/sync/GuiBridge.java @@ -18,7 +18,6 @@ package appeng.core.sync; - import appeng.api.AEApi; import appeng.api.config.SecurityPermissions; import appeng.api.definitions.IComparableDefinition; @@ -68,6 +67,8 @@ import com.google.common.collect.Lists; import cpw.mods.fml.common.network.IGuiHandler; import cpw.mods.fml.relauncher.ReflectionHelper; +import java.lang.reflect.Constructor; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; @@ -76,476 +77,429 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.lang.reflect.Constructor; -import java.util.List; - - -public enum GuiBridge implements IGuiHandler -{ - GUI_Handler(), - - GUI_GRINDER( ContainerGrinder.class, TileGrinder.class, GuiHostType.WORLD, null ), - - GUI_QNB( ContainerQNB.class, TileQuantumBridge.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), - - GUI_SKYCHEST( ContainerSkyChest.class, TileSkyChest.class, GuiHostType.WORLD, null ), +public enum GuiBridge implements IGuiHandler { + GUI_Handler(), - GUI_CHEST( ContainerChest.class, TileChest.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_GRINDER(ContainerGrinder.class, TileGrinder.class, GuiHostType.WORLD, null), - GUI_WIRELESS( ContainerWireless.class, TileWireless.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_QNB(ContainerQNB.class, TileQuantumBridge.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_ME( ContainerMEMonitorable.class, ITerminalHost.class, GuiHostType.WORLD, null ), + GUI_SKYCHEST(ContainerSkyChest.class, TileSkyChest.class, GuiHostType.WORLD, null), - GUI_PORTABLE_CELL( ContainerMEPortableCell.class, IPortableCell.class, GuiHostType.ITEM, null ), + GUI_CHEST(ContainerChest.class, TileChest.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_WIRELESS_TERM( ContainerWirelessTerm.class, WirelessTerminalGuiObject.class, GuiHostType.ITEM, null ), + GUI_WIRELESS(ContainerWireless.class, TileWireless.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_NETWORK_STATUS( ContainerNetworkStatus.class, INetworkTool.class, GuiHostType.ITEM, null ), + GUI_ME(ContainerMEMonitorable.class, ITerminalHost.class, GuiHostType.WORLD, null), - GUI_CRAFTING_CPU( ContainerCraftingCPU.class, TileCraftingTile.class, GuiHostType.WORLD, SecurityPermissions.CRAFT ), + GUI_PORTABLE_CELL(ContainerMEPortableCell.class, IPortableCell.class, GuiHostType.ITEM, null), - GUI_NETWORK_TOOL( ContainerNetworkTool.class, INetworkTool.class, GuiHostType.ITEM, null ), + GUI_WIRELESS_TERM(ContainerWirelessTerm.class, WirelessTerminalGuiObject.class, GuiHostType.ITEM, null), - GUI_QUARTZ_KNIFE( ContainerQuartzKnife.class, QuartzKnifeObj.class, GuiHostType.ITEM, null ), + GUI_NETWORK_STATUS(ContainerNetworkStatus.class, INetworkTool.class, GuiHostType.ITEM, null), - GUI_DRIVE( ContainerDrive.class, TileDrive.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_CRAFTING_CPU(ContainerCraftingCPU.class, TileCraftingTile.class, GuiHostType.WORLD, SecurityPermissions.CRAFT), - GUI_VIBRATION_CHAMBER( ContainerVibrationChamber.class, TileVibrationChamber.class, GuiHostType.WORLD, null ), + GUI_NETWORK_TOOL(ContainerNetworkTool.class, INetworkTool.class, GuiHostType.ITEM, null), - GUI_CONDENSER( ContainerCondenser.class, TileCondenser.class, GuiHostType.WORLD, null ), + GUI_QUARTZ_KNIFE(ContainerQuartzKnife.class, QuartzKnifeObj.class, GuiHostType.ITEM, null), - GUI_INTERFACE( ContainerInterface.class, IInterfaceHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_DRIVE(ContainerDrive.class, TileDrive.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_BUS( ContainerUpgradeable.class, IUpgradeableHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_VIBRATION_CHAMBER(ContainerVibrationChamber.class, TileVibrationChamber.class, GuiHostType.WORLD, null), - GUI_IOPORT( ContainerIOPort.class, TileIOPort.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_CONDENSER(ContainerCondenser.class, TileCondenser.class, GuiHostType.WORLD, null), - GUI_STORAGEBUS( ContainerStorageBus.class, PartStorageBus.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_INTERFACE(ContainerInterface.class, IInterfaceHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_FORMATION_PLANE( ContainerFormationPlane.class, PartFormationPlane.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_BUS(ContainerUpgradeable.class, IUpgradeableHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_PRIORITY( ContainerPriority.class, IPriorityHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_IOPORT(ContainerIOPort.class, TileIOPort.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_SECURITY( ContainerSecurity.class, TileSecurity.class, GuiHostType.WORLD, SecurityPermissions.SECURITY ), + GUI_STORAGEBUS(ContainerStorageBus.class, PartStorageBus.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_CRAFTING_TERMINAL( ContainerCraftingTerm.class, PartCraftingTerminal.class, GuiHostType.WORLD, SecurityPermissions.CRAFT ), + GUI_FORMATION_PLANE( + ContainerFormationPlane.class, PartFormationPlane.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_PATTERN_TERMINAL( ContainerPatternTerm.class, PartPatternTerminal.class, GuiHostType.WORLD, SecurityPermissions.CRAFT ), + GUI_PRIORITY(ContainerPriority.class, IPriorityHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_PATTERN_TERMINAL_EX( ContainerPatternTermEx.class, PartPatternTerminalEx.class, GuiHostType.WORLD, SecurityPermissions.CRAFT ), + GUI_SECURITY(ContainerSecurity.class, TileSecurity.class, GuiHostType.WORLD, SecurityPermissions.SECURITY), - // extends (Container/Gui) + Bus - GUI_LEVEL_EMITTER( ContainerLevelEmitter.class, PartLevelEmitter.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_CRAFTING_TERMINAL( + ContainerCraftingTerm.class, PartCraftingTerminal.class, GuiHostType.WORLD, SecurityPermissions.CRAFT), - GUI_SPATIAL_IO_PORT( ContainerSpatialIOPort.class, TileSpatialIOPort.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_PATTERN_TERMINAL( + ContainerPatternTerm.class, PartPatternTerminal.class, GuiHostType.WORLD, SecurityPermissions.CRAFT), - GUI_INSCRIBER( ContainerInscriber.class, TileInscriber.class, GuiHostType.WORLD, null ), + GUI_PATTERN_TERMINAL_EX( + ContainerPatternTermEx.class, PartPatternTerminalEx.class, GuiHostType.WORLD, SecurityPermissions.CRAFT), - GUI_CELL_WORKBENCH( ContainerCellWorkbench.class, TileCellWorkbench.class, GuiHostType.WORLD, null ), + // extends (Container/Gui) + Bus + GUI_LEVEL_EMITTER( + ContainerLevelEmitter.class, PartLevelEmitter.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_MAC( ContainerMAC.class, TileMolecularAssembler.class, GuiHostType.WORLD, null ), + GUI_SPATIAL_IO_PORT( + ContainerSpatialIOPort.class, TileSpatialIOPort.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GUI_CRAFTING_AMOUNT( ContainerCraftAmount.class, ITerminalHost.class, GuiHostType.ITEM_OR_WORLD, SecurityPermissions.CRAFT ), + GUI_INSCRIBER(ContainerInscriber.class, TileInscriber.class, GuiHostType.WORLD, null), - GUI_PATTERN_VALUE_AMOUNT( ContainerPatternValueAmount.class, ITerminalHost.class, GuiHostType.WORLD, SecurityPermissions.CRAFT ), + GUI_CELL_WORKBENCH(ContainerCellWorkbench.class, TileCellWorkbench.class, GuiHostType.WORLD, null), - GUI_CRAFTING_CONFIRM( ContainerCraftConfirm.class, ITerminalHost.class, GuiHostType.ITEM_OR_WORLD, SecurityPermissions.CRAFT ), + GUI_MAC(ContainerMAC.class, TileMolecularAssembler.class, GuiHostType.WORLD, null), - GUI_INTERFACE_TERMINAL( ContainerInterfaceTerminal.class, PartInterfaceTerminal.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_CRAFTING_AMOUNT( + ContainerCraftAmount.class, ITerminalHost.class, GuiHostType.ITEM_OR_WORLD, SecurityPermissions.CRAFT), - GUI_CRAFTING_STATUS( ContainerCraftingStatus.class, ITerminalHost.class, GuiHostType.ITEM_OR_WORLD, SecurityPermissions.CRAFT ), + GUI_PATTERN_VALUE_AMOUNT( + ContainerPatternValueAmount.class, ITerminalHost.class, GuiHostType.WORLD, SecurityPermissions.CRAFT), - GUI_RENAMER( ContainerRenamer.class, ICustomNameObject.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), + GUI_CRAFTING_CONFIRM( + ContainerCraftConfirm.class, ITerminalHost.class, GuiHostType.ITEM_OR_WORLD, SecurityPermissions.CRAFT), - GUI_ORE_FILTER( ContainerOreFilter.class, IOreFilterable.class, GuiHostType.ITEM_OR_WORLD, null ); + GUI_INTERFACE_TERMINAL( + ContainerInterfaceTerminal.class, + PartInterfaceTerminal.class, + GuiHostType.WORLD, + SecurityPermissions.BUILD), - private final Class tileClass; - private final Class containerClass; - private Class guiClass; - private GuiHostType type; - private SecurityPermissions requiredPermission; + GUI_CRAFTING_STATUS( + ContainerCraftingStatus.class, ITerminalHost.class, GuiHostType.ITEM_OR_WORLD, SecurityPermissions.CRAFT), - GuiBridge() - { - this.tileClass = null; - this.guiClass = null; - this.containerClass = null; - } + GUI_RENAMER(ContainerRenamer.class, ICustomNameObject.class, GuiHostType.WORLD, SecurityPermissions.BUILD), - GuiBridge( final Class containerClass, final SecurityPermissions requiredPermission ) - { - this.requiredPermission = requiredPermission; - this.containerClass = containerClass; - this.tileClass = null; - this.getGui(); - } - - /** - * I honestly wish I could just use the GuiClass Names myself, but I can't access them without MC's Server - * Exploding. - */ - private void getGui() - { - if( Platform.isClient() ) - { - final String start = this.containerClass.getName(); - final String guiClass = start.replaceFirst( "container.", "client.gui." ).replace( ".Container", ".Gui" ); - - if( start.equals( guiClass ) ) - { - throw new IllegalStateException( "Unable to find gui class" ); - } - this.guiClass = ReflectionHelper.getClass( this.getClass().getClassLoader(), guiClass ); - if( this.guiClass == null ) - { - throw new IllegalStateException( "Cannot Load class: " + guiClass ); - } - } - } - - GuiBridge( final Class containerClass, final Class tileClass, final GuiHostType type, final SecurityPermissions requiredPermission ) - { - this.requiredPermission = requiredPermission; - this.containerClass = containerClass; - this.type = type; - this.tileClass = tileClass; - this.getGui(); - } - - @Override - public Object getServerGuiElement( final int ordinal, final EntityPlayer player, final World w, final int x, final int y, final int z ) - { - final ForgeDirection side = ForgeDirection.getOrientation( ordinal & 0x07 ); - final GuiBridge ID = values()[ordinal >> 5]; - final boolean stem = ( ( ordinal >> 3 ) & 1 ) == 1; - final boolean xIsSlotIndex = ( ( ordinal >> 4 ) & 1 ) == 1; - if( ID.type.isItem() ) - { - ItemStack it = null; - if( stem ) - { - it = player.inventory.getCurrentItem(); - } - else if( xIsSlotIndex && x >= 0 && x < player.inventory.mainInventory.length ) - { - it = player.inventory.getStackInSlot( x ); - } - final Object myItem = this.getGuiObject( it, player, w, x, y, z ); - if( myItem != null && ID.CorrectTileOrPart( myItem ) ) - { - return this.updateGui( ID.ConstructContainer( player.inventory, side, myItem ), w, x, y, z, side, myItem ); - } - } - if( ID.type.isTile() ) - { - final TileEntity TE = w.getTileEntity( x, y, z ); - if( TE instanceof IPartHost ) - { - ( (IPartHost) TE ).getPart( side ); - final IPart part = ( (IPartHost) TE ).getPart( side ); - if( ID.CorrectTileOrPart( part ) ) - { - return this.updateGui( ID.ConstructContainer( player.inventory, side, part ), w, x, y, z, side, part ); - } - } - else - { - if( ID.CorrectTileOrPart( TE ) ) - { - return this.updateGui( ID.ConstructContainer( player.inventory, side, TE ), w, x, y, z, side, TE ); - } - } - } - return new ContainerNull(); - } - - private Object getGuiObject( final ItemStack it, final EntityPlayer player, final World w, final int x, final int y, final int z ) - { - if( it != null ) - { - if( it.getItem() instanceof IGuiItem ) - { - return ( (IGuiItem) it.getItem() ).getGuiObject( it, w, x, y, z ); - } - - final IWirelessTermHandler wh = AEApi.instance().registries().wireless().getWirelessTerminalHandler( it ); - if( wh != null ) - { - return new WirelessTerminalGuiObject( wh, it, player, w, x, y, z ); - } - } - - return null; - } - - public boolean CorrectTileOrPart( final Object tE ) - { - if( this.tileClass == null ) - { - throw new IllegalArgumentException( "This Gui Cannot use the standard Handler." ); - } - - return this.tileClass.isInstance( tE ); - } - - private Object updateGui( final Object newContainer, final World w, final int x, final int y, final int z, final ForgeDirection side, final Object myItem ) - { - if( newContainer instanceof AEBaseContainer ) - { - final AEBaseContainer bc = (AEBaseContainer) newContainer; - bc.setOpenContext( new ContainerOpenContext( myItem ) ); - bc.getOpenContext().setWorld( w ); - bc.getOpenContext().setX( x ); - bc.getOpenContext().setY( y ); - bc.getOpenContext().setZ( z ); - bc.getOpenContext().setSide( side ); - } - - return newContainer; - } - - public Object ConstructContainer( final InventoryPlayer inventory, final ForgeDirection side, final Object tE ) - { - try - { - final Constructor[] c = this.containerClass.getConstructors(); - if( c.length == 0 ) - { - throw new AppEngException( "Invalid Gui Class" ); - } - - final Constructor target = this.findConstructor( c, inventory, tE ); - - if( target == null ) - { - throw new IllegalStateException( "Cannot find " + this.containerClass.getName() + "( " + this.typeName( inventory ) + ", " + this.typeName( tE ) + " )" ); - } - - final Object o = target.newInstance( inventory, tE ); - - /** - * triggers achievement when the player sees presses. - */ - if( o instanceof AEBaseContainer ) - { - final AEBaseContainer bc = (AEBaseContainer) o; - for( final Object so : bc.inventorySlots ) - { - if( so instanceof Slot ) - { - final ItemStack is = ( (Slot) so ).getStack(); - - final IMaterials materials = AEApi.instance().definitions().materials(); - this.addPressAchievementToPlayer( is, materials, inventory.player ); - } - } - } - - return o; - } - catch( final Throwable t ) - { - throw new IllegalStateException( t ); - } - } - - private Constructor findConstructor( final Constructor[] c, final InventoryPlayer inventory, final Object tE ) - { - for( final Constructor con : c ) - { - final Class[] types = con.getParameterTypes(); - if( types.length == 2 ) - { - if( types[0].isAssignableFrom( inventory.getClass() ) && types[1].isAssignableFrom( tE.getClass() ) ) - { - return con; - } - } - } - return null; - } - - private String typeName( final Object inventory ) - { - if( inventory == null ) - { - return "NULL"; - } - - return inventory.getClass().getName(); - } - - private void addPressAchievementToPlayer( final ItemStack newItem, final IMaterials possibleMaterials, final EntityPlayer player ) - { - final IComparableDefinition logic = possibleMaterials.logicProcessorPress(); - final IComparableDefinition eng = possibleMaterials.engProcessorPress(); - final IComparableDefinition calc = possibleMaterials.calcProcessorPress(); - final IComparableDefinition silicon = possibleMaterials.siliconPress(); - - final List presses = Lists.newArrayList( logic, eng, calc, silicon ); - - for( final IComparableDefinition press : presses ) - { - if( press.isSameAs( newItem ) ) - { - Achievements.Presses.addToPlayer( player ); - - return; - } - } - } - - @Override - public Object getClientGuiElement( final int ordinal, final EntityPlayer player, final World w, final int x, final int y, final int z ) - { - final ForgeDirection side = ForgeDirection.getOrientation( ordinal & 0x07 ); - final GuiBridge ID = values()[ordinal >> 5]; - final boolean stem = ( ( ordinal >> 3 ) & 1 ) == 1; - final boolean xIsSlotIndex = ( ( ordinal >> 4 ) & 1 ) == 1; - if( ID.type.isItem() ) - { - ItemStack it = null; - if( stem ) - { - it = player.inventory.getCurrentItem(); - } - else if (xIsSlotIndex && x >= 0 && x < player.inventory.mainInventory.length ) - { - it = player.inventory.getStackInSlot( x ); - } - final Object myItem = this.getGuiObject( it, player, w, x, y, z ); - if( myItem != null && ID.CorrectTileOrPart( myItem ) ) - { - return ID.ConstructGui( player.inventory, side, myItem ); - } - } - if( ID.type.isTile() ) - { - final TileEntity TE = w.getTileEntity( x, y, z ); - if( TE instanceof IPartHost ) - { - ( (IPartHost) TE ).getPart( side ); - final IPart part = ( (IPartHost) TE ).getPart( side ); - if( ID.CorrectTileOrPart( part ) ) - { - return ID.ConstructGui( player.inventory, side, part ); - } - } - else - { - if( ID.CorrectTileOrPart( TE ) ) - { - return ID.ConstructGui( player.inventory, side, TE ); - } - } - } - return new GuiNull( new ContainerNull() ); - } - - public Object ConstructGui( final InventoryPlayer inventory, final ForgeDirection side, final Object tE ) - { - try - { - final Constructor[] c = this.guiClass.getConstructors(); - if( c.length == 0 ) - { - throw new AppEngException( "Invalid Gui Class" ); - } - - final Constructor target = this.findConstructor( c, inventory, tE ); - - if( target == null ) - { - throw new IllegalStateException( "Cannot find " + this.containerClass.getName() + "( " + this.typeName( inventory ) + ", " + this.typeName( tE ) + " )" ); - } - - return target.newInstance( inventory, tE ); - } - catch( final Throwable t ) - { - throw new IllegalStateException( t ); - } - } - - public boolean hasPermissions( final TileEntity te, final int x, final int y, final int z, final ForgeDirection side, final EntityPlayer player ) - { - final World w = player.getEntityWorld(); - - if( Platform.hasPermissions( te != null ? new DimensionalCoord( te ) : new DimensionalCoord( player.worldObj, x, y, z ), player ) ) - { - if( this.type.isItem() ) - { - final ItemStack it = player.inventory.getCurrentItem(); - if( it != null && it.getItem() instanceof IGuiItem ) - { - final Object myItem = ( (IGuiItem) it.getItem() ).getGuiObject( it, w, x, y, z ); - if( this.CorrectTileOrPart( myItem ) ) - { - return true; - } - } - } - - if( this.type.isTile() ) - { - final TileEntity TE = w.getTileEntity( x, y, z ); - if( TE instanceof IPartHost ) - { - ( (IPartHost) TE ).getPart( side ); - final IPart part = ( (IPartHost) TE ).getPart( side ); - if( this.CorrectTileOrPart( part ) ) - { - return this.securityCheck( part, player ); - } - } - else - { - if( this.CorrectTileOrPart( TE ) ) - { - return this.securityCheck( TE, player ); - } - } - } - } - return false; - } - - private boolean securityCheck( final Object te, final EntityPlayer player ) - { - if( te instanceof IActionHost && this.requiredPermission != null ) - { - final IGridNode gn = ( (IActionHost) te ).getActionableNode(); - if( gn != null ) - { - final IGrid g = gn.getGrid(); - if( g != null ) - { - final boolean requirePower = false; - if( requirePower ) - { - final IEnergyGrid eg = g.getCache( IEnergyGrid.class ); - if( !eg.isNetworkPowered() ) - { - return false; - } - } - - final ISecurityGrid sg = g.getCache( ISecurityGrid.class ); - if( sg.hasPermission( player, this.requiredPermission ) ) - { - return true; - } - } - } - - return false; - } - return true; - } - - public GuiHostType getType() - { - return this.type; - } + GUI_ORE_FILTER(ContainerOreFilter.class, IOreFilterable.class, GuiHostType.ITEM_OR_WORLD, null); + + private final Class tileClass; + private final Class containerClass; + private Class guiClass; + private GuiHostType type; + private SecurityPermissions requiredPermission; + GuiBridge() { + this.tileClass = null; + this.guiClass = null; + this.containerClass = null; + } + + GuiBridge(final Class containerClass, final SecurityPermissions requiredPermission) { + this.requiredPermission = requiredPermission; + this.containerClass = containerClass; + this.tileClass = null; + this.getGui(); + } + + /** + * I honestly wish I could just use the GuiClass Names myself, but I can't access them without MC's Server + * Exploding. + */ + private void getGui() { + if (Platform.isClient()) { + final String start = this.containerClass.getName(); + final String guiClass = + start.replaceFirst("container.", "client.gui.").replace(".Container", ".Gui"); + + if (start.equals(guiClass)) { + throw new IllegalStateException("Unable to find gui class"); + } + this.guiClass = ReflectionHelper.getClass(this.getClass().getClassLoader(), guiClass); + if (this.guiClass == null) { + throw new IllegalStateException("Cannot Load class: " + guiClass); + } + } + } + + GuiBridge( + final Class containerClass, + final Class tileClass, + final GuiHostType type, + final SecurityPermissions requiredPermission) { + this.requiredPermission = requiredPermission; + this.containerClass = containerClass; + this.type = type; + this.tileClass = tileClass; + this.getGui(); + } + + @Override + public Object getServerGuiElement( + final int ordinal, final EntityPlayer player, final World w, final int x, final int y, final int z) { + final ForgeDirection side = ForgeDirection.getOrientation(ordinal & 0x07); + final GuiBridge ID = values()[ordinal >> 5]; + final boolean stem = ((ordinal >> 3) & 1) == 1; + final boolean xIsSlotIndex = ((ordinal >> 4) & 1) == 1; + if (ID.type.isItem()) { + ItemStack it = null; + if (stem) { + it = player.inventory.getCurrentItem(); + } else if (xIsSlotIndex && x >= 0 && x < player.inventory.mainInventory.length) { + it = player.inventory.getStackInSlot(x); + } + final Object myItem = this.getGuiObject(it, player, w, x, y, z); + if (myItem != null && ID.CorrectTileOrPart(myItem)) { + return this.updateGui(ID.ConstructContainer(player.inventory, side, myItem), w, x, y, z, side, myItem); + } + } + if (ID.type.isTile()) { + final TileEntity TE = w.getTileEntity(x, y, z); + if (TE instanceof IPartHost) { + ((IPartHost) TE).getPart(side); + final IPart part = ((IPartHost) TE).getPart(side); + if (ID.CorrectTileOrPart(part)) { + return this.updateGui(ID.ConstructContainer(player.inventory, side, part), w, x, y, z, side, part); + } + } else { + if (ID.CorrectTileOrPart(TE)) { + return this.updateGui(ID.ConstructContainer(player.inventory, side, TE), w, x, y, z, side, TE); + } + } + } + return new ContainerNull(); + } + + private Object getGuiObject( + final ItemStack it, final EntityPlayer player, final World w, final int x, final int y, final int z) { + if (it != null) { + if (it.getItem() instanceof IGuiItem) { + return ((IGuiItem) it.getItem()).getGuiObject(it, w, x, y, z); + } + + final IWirelessTermHandler wh = + AEApi.instance().registries().wireless().getWirelessTerminalHandler(it); + if (wh != null) { + return new WirelessTerminalGuiObject(wh, it, player, w, x, y, z); + } + } + + return null; + } + + public boolean CorrectTileOrPart(final Object tE) { + if (this.tileClass == null) { + throw new IllegalArgumentException("This Gui Cannot use the standard Handler."); + } + + return this.tileClass.isInstance(tE); + } + + private Object updateGui( + final Object newContainer, + final World w, + final int x, + final int y, + final int z, + final ForgeDirection side, + final Object myItem) { + if (newContainer instanceof AEBaseContainer) { + final AEBaseContainer bc = (AEBaseContainer) newContainer; + bc.setOpenContext(new ContainerOpenContext(myItem)); + bc.getOpenContext().setWorld(w); + bc.getOpenContext().setX(x); + bc.getOpenContext().setY(y); + bc.getOpenContext().setZ(z); + bc.getOpenContext().setSide(side); + } + + return newContainer; + } + + public Object ConstructContainer(final InventoryPlayer inventory, final ForgeDirection side, final Object tE) { + try { + final Constructor[] c = this.containerClass.getConstructors(); + if (c.length == 0) { + throw new AppEngException("Invalid Gui Class"); + } + + final Constructor target = this.findConstructor(c, inventory, tE); + + if (target == null) { + throw new IllegalStateException("Cannot find " + this.containerClass.getName() + "( " + + this.typeName(inventory) + ", " + this.typeName(tE) + " )"); + } + + final Object o = target.newInstance(inventory, tE); + + /** + * triggers achievement when the player sees presses. + */ + if (o instanceof AEBaseContainer) { + final AEBaseContainer bc = (AEBaseContainer) o; + for (final Object so : bc.inventorySlots) { + if (so instanceof Slot) { + final ItemStack is = ((Slot) so).getStack(); + + final IMaterials materials = + AEApi.instance().definitions().materials(); + this.addPressAchievementToPlayer(is, materials, inventory.player); + } + } + } + + return o; + } catch (final Throwable t) { + throw new IllegalStateException(t); + } + } + + private Constructor findConstructor(final Constructor[] c, final InventoryPlayer inventory, final Object tE) { + for (final Constructor con : c) { + final Class[] types = con.getParameterTypes(); + if (types.length == 2) { + if (types[0].isAssignableFrom(inventory.getClass()) && types[1].isAssignableFrom(tE.getClass())) { + return con; + } + } + } + return null; + } + + private String typeName(final Object inventory) { + if (inventory == null) { + return "NULL"; + } + + return inventory.getClass().getName(); + } + + private void addPressAchievementToPlayer( + final ItemStack newItem, final IMaterials possibleMaterials, final EntityPlayer player) { + final IComparableDefinition logic = possibleMaterials.logicProcessorPress(); + final IComparableDefinition eng = possibleMaterials.engProcessorPress(); + final IComparableDefinition calc = possibleMaterials.calcProcessorPress(); + final IComparableDefinition silicon = possibleMaterials.siliconPress(); + + final List presses = Lists.newArrayList(logic, eng, calc, silicon); + + for (final IComparableDefinition press : presses) { + if (press.isSameAs(newItem)) { + Achievements.Presses.addToPlayer(player); + + return; + } + } + } + + @Override + public Object getClientGuiElement( + final int ordinal, final EntityPlayer player, final World w, final int x, final int y, final int z) { + final ForgeDirection side = ForgeDirection.getOrientation(ordinal & 0x07); + final GuiBridge ID = values()[ordinal >> 5]; + final boolean stem = ((ordinal >> 3) & 1) == 1; + final boolean xIsSlotIndex = ((ordinal >> 4) & 1) == 1; + if (ID.type.isItem()) { + ItemStack it = null; + if (stem) { + it = player.inventory.getCurrentItem(); + } else if (xIsSlotIndex && x >= 0 && x < player.inventory.mainInventory.length) { + it = player.inventory.getStackInSlot(x); + } + final Object myItem = this.getGuiObject(it, player, w, x, y, z); + if (myItem != null && ID.CorrectTileOrPart(myItem)) { + return ID.ConstructGui(player.inventory, side, myItem); + } + } + if (ID.type.isTile()) { + final TileEntity TE = w.getTileEntity(x, y, z); + if (TE instanceof IPartHost) { + ((IPartHost) TE).getPart(side); + final IPart part = ((IPartHost) TE).getPart(side); + if (ID.CorrectTileOrPart(part)) { + return ID.ConstructGui(player.inventory, side, part); + } + } else { + if (ID.CorrectTileOrPart(TE)) { + return ID.ConstructGui(player.inventory, side, TE); + } + } + } + return new GuiNull(new ContainerNull()); + } + + public Object ConstructGui(final InventoryPlayer inventory, final ForgeDirection side, final Object tE) { + try { + final Constructor[] c = this.guiClass.getConstructors(); + if (c.length == 0) { + throw new AppEngException("Invalid Gui Class"); + } + + final Constructor target = this.findConstructor(c, inventory, tE); + + if (target == null) { + throw new IllegalStateException("Cannot find " + this.containerClass.getName() + "( " + + this.typeName(inventory) + ", " + this.typeName(tE) + " )"); + } + + return target.newInstance(inventory, tE); + } catch (final Throwable t) { + throw new IllegalStateException(t); + } + } + + public boolean hasPermissions( + final TileEntity te, + final int x, + final int y, + final int z, + final ForgeDirection side, + final EntityPlayer player) { + final World w = player.getEntityWorld(); + + if (Platform.hasPermissions( + te != null ? new DimensionalCoord(te) : new DimensionalCoord(player.worldObj, x, y, z), player)) { + if (this.type.isItem()) { + final ItemStack it = player.inventory.getCurrentItem(); + if (it != null && it.getItem() instanceof IGuiItem) { + final Object myItem = ((IGuiItem) it.getItem()).getGuiObject(it, w, x, y, z); + if (this.CorrectTileOrPart(myItem)) { + return true; + } + } + } + + if (this.type.isTile()) { + final TileEntity TE = w.getTileEntity(x, y, z); + if (TE instanceof IPartHost) { + ((IPartHost) TE).getPart(side); + final IPart part = ((IPartHost) TE).getPart(side); + if (this.CorrectTileOrPart(part)) { + return this.securityCheck(part, player); + } + } else { + if (this.CorrectTileOrPart(TE)) { + return this.securityCheck(TE, player); + } + } + } + } + return false; + } + + private boolean securityCheck(final Object te, final EntityPlayer player) { + if (te instanceof IActionHost && this.requiredPermission != null) { + final IGridNode gn = ((IActionHost) te).getActionableNode(); + if (gn != null) { + final IGrid g = gn.getGrid(); + if (g != null) { + final boolean requirePower = false; + if (requirePower) { + final IEnergyGrid eg = g.getCache(IEnergyGrid.class); + if (!eg.isNetworkPowered()) { + return false; + } + } + + final ISecurityGrid sg = g.getCache(ISecurityGrid.class); + if (sg.hasPermission(player, this.requiredPermission)) { + return true; + } + } + } + + return false; + } + return true; + } + + public GuiHostType getType() { + return this.type; + } } diff --git a/src/main/java/appeng/core/sync/GuiHostType.java b/src/main/java/appeng/core/sync/GuiHostType.java index ac780028519..35041153428 100644 --- a/src/main/java/appeng/core/sync/GuiHostType.java +++ b/src/main/java/appeng/core/sync/GuiHostType.java @@ -18,18 +18,16 @@ package appeng.core.sync; +public enum GuiHostType { + ITEM_OR_WORLD, + ITEM, + WORLD; -public enum GuiHostType -{ - ITEM_OR_WORLD, ITEM, WORLD; + public boolean isItem() { + return this != WORLD; + } - public boolean isItem() - { - return this != WORLD; - } - - boolean isTile() - { - return this != ITEM; - } + boolean isTile() { + return this != ITEM; + } } diff --git a/src/main/java/appeng/core/sync/network/AppEngClientPacketHandler.java b/src/main/java/appeng/core/sync/network/AppEngClientPacketHandler.java index 5aac2000c9f..04e6f965779 100644 --- a/src/main/java/appeng/core/sync/network/AppEngClientPacketHandler.java +++ b/src/main/java/appeng/core/sync/network/AppEngClientPacketHandler.java @@ -18,49 +18,35 @@ package appeng.core.sync.network; - import appeng.core.AELog; import appeng.core.sync.AppEngPacket; import appeng.core.sync.AppEngPacketHandlerBase; import cpw.mods.fml.common.network.internal.FMLProxyPacket; import io.netty.buffer.ByteBuf; +import java.lang.reflect.InvocationTargetException; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; -import java.lang.reflect.InvocationTargetException; - - -public class AppEngClientPacketHandler extends AppEngPacketHandlerBase implements IPacketHandler -{ - - @Override - public void onPacketData( final INetworkInfo network, final FMLProxyPacket packet, EntityPlayer player ) - { - final ByteBuf stream = packet.payload(); - - player = Minecraft.getMinecraft().thePlayer; - - try - { - final int packetType = stream.readInt(); - final AppEngPacket pack = PacketTypes.getPacket( packetType ).parsePacket( stream ); - pack.clientPacketData( network, pack, player ); - } - catch( final InstantiationException e ) - { - AELog.debug( e ); - } - catch( final IllegalAccessException e ) - { - AELog.debug( e ); - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - catch( final InvocationTargetException e ) - { - AELog.debug( e ); - } - } +public class AppEngClientPacketHandler extends AppEngPacketHandlerBase implements IPacketHandler { + + @Override + public void onPacketData(final INetworkInfo network, final FMLProxyPacket packet, EntityPlayer player) { + final ByteBuf stream = packet.payload(); + + player = Minecraft.getMinecraft().thePlayer; + + try { + final int packetType = stream.readInt(); + final AppEngPacket pack = PacketTypes.getPacket(packetType).parsePacket(stream); + pack.clientPacketData(network, pack, player); + } catch (final InstantiationException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final InvocationTargetException e) { + AELog.debug(e); + } + } } diff --git a/src/main/java/appeng/core/sync/network/AppEngServerPacketHandler.java b/src/main/java/appeng/core/sync/network/AppEngServerPacketHandler.java index 62e6b98d492..76e9c5f3e0e 100644 --- a/src/main/java/appeng/core/sync/network/AppEngServerPacketHandler.java +++ b/src/main/java/appeng/core/sync/network/AppEngServerPacketHandler.java @@ -18,46 +18,32 @@ package appeng.core.sync.network; - import appeng.core.AELog; import appeng.core.sync.AppEngPacket; import appeng.core.sync.AppEngPacketHandlerBase; import cpw.mods.fml.common.network.internal.FMLProxyPacket; import io.netty.buffer.ByteBuf; -import net.minecraft.entity.player.EntityPlayer; - import java.lang.reflect.InvocationTargetException; +import net.minecraft.entity.player.EntityPlayer; - -public final class AppEngServerPacketHandler extends AppEngPacketHandlerBase implements IPacketHandler -{ - - @Override - public void onPacketData( final INetworkInfo manager, final FMLProxyPacket packet, final EntityPlayer player ) - { - final ByteBuf stream = packet.payload(); - - try - { - final int packetType = stream.readInt(); - final AppEngPacket pack = PacketTypes.getPacket( packetType ).parsePacket( stream ); - pack.serverPacketData( manager, pack, player ); - } - catch( final InstantiationException e ) - { - AELog.debug( e ); - } - catch( final IllegalAccessException e ) - { - AELog.debug( e ); - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - catch( final InvocationTargetException e ) - { - AELog.debug( e ); - } - } +public final class AppEngServerPacketHandler extends AppEngPacketHandlerBase implements IPacketHandler { + + @Override + public void onPacketData(final INetworkInfo manager, final FMLProxyPacket packet, final EntityPlayer player) { + final ByteBuf stream = packet.payload(); + + try { + final int packetType = stream.readInt(); + final AppEngPacket pack = PacketTypes.getPacket(packetType).parsePacket(stream); + pack.serverPacketData(manager, pack, player); + } catch (final InstantiationException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final InvocationTargetException e) { + AELog.debug(e); + } + } } diff --git a/src/main/java/appeng/core/sync/network/INetworkInfo.java b/src/main/java/appeng/core/sync/network/INetworkInfo.java index 51766b76c1e..c2f914b3ad5 100644 --- a/src/main/java/appeng/core/sync/network/INetworkInfo.java +++ b/src/main/java/appeng/core/sync/network/INetworkInfo.java @@ -18,8 +18,4 @@ package appeng.core.sync.network; - -public interface INetworkInfo -{ - -} +public interface INetworkInfo {} diff --git a/src/main/java/appeng/core/sync/network/IPacketHandler.java b/src/main/java/appeng/core/sync/network/IPacketHandler.java index d1b2756d4e0..479b01ef796 100644 --- a/src/main/java/appeng/core/sync/network/IPacketHandler.java +++ b/src/main/java/appeng/core/sync/network/IPacketHandler.java @@ -18,13 +18,10 @@ package appeng.core.sync.network; - import cpw.mods.fml.common.network.internal.FMLProxyPacket; import net.minecraft.entity.player.EntityPlayer; +public interface IPacketHandler { -public interface IPacketHandler -{ - - void onPacketData( INetworkInfo manager, FMLProxyPacket packet, EntityPlayer player ); + void onPacketData(INetworkInfo manager, FMLProxyPacket packet, EntityPlayer player); } diff --git a/src/main/java/appeng/core/sync/network/NetworkHandler.java b/src/main/java/appeng/core/sync/network/NetworkHandler.java index 7f326985461..6e0ed36d9cb 100644 --- a/src/main/java/appeng/core/sync/network/NetworkHandler.java +++ b/src/main/java/appeng/core/sync/network/NetworkHandler.java @@ -18,7 +18,6 @@ package appeng.core.sync.network; - import appeng.core.sync.AppEngPacket; import appeng.core.worlddata.WorldData; import cpw.mods.fml.common.FMLCommonHandler; @@ -32,113 +31,89 @@ import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.NetHandlerPlayServer; - -public class NetworkHandler -{ - - public static NetworkHandler instance; - - private final FMLEventChannel ec; - private final String myChannelName; - - private final IPacketHandler clientHandler; - private final IPacketHandler serveHandler; - - public NetworkHandler( final String channelName ) - { - FMLCommonHandler.instance().bus().register( this ); - this.ec = NetworkRegistry.INSTANCE.newEventDrivenChannel( this.myChannelName = channelName ); - this.ec.register( this ); - - this.clientHandler = this.createClientSide(); - this.serveHandler = this.createServerSide(); - } - - private IPacketHandler createClientSide() - { - try - { - return new AppEngClientPacketHandler(); - } - catch( final Throwable t ) - { - return null; - } - } - - private IPacketHandler createServerSide() - { - try - { - return new AppEngServerPacketHandler(); - } - catch( final Throwable t ) - { - return null; - } - } - - @SubscribeEvent - public void newConnection( final ServerConnectionFromClientEvent ev ) - { - WorldData.instance().dimensionData().sendToPlayer( ev.manager ); - } - - @SubscribeEvent - public void newConnection( final PlayerLoggedInEvent loginEvent ) - { - if( loginEvent.player instanceof EntityPlayerMP ) - { - WorldData.instance().dimensionData().sendToPlayer( null ); - } - } - - @SubscribeEvent - public void serverPacket( final ServerCustomPacketEvent ev ) - { - final NetHandlerPlayServer srv = (NetHandlerPlayServer) ev.packet.handler(); - if( this.serveHandler != null ) - { - this.serveHandler.onPacketData( null, ev.packet, srv.playerEntity ); - } - } - - @SubscribeEvent - public void clientPacket( final ClientCustomPacketEvent ev ) - { - if( this.clientHandler != null ) - { - this.clientHandler.onPacketData( null, ev.packet, null ); - } - } - - public String getChannel() - { - return this.myChannelName; - } - - public void sendToAll( final AppEngPacket message ) - { - this.ec.sendToAll( message.getProxy() ); - } - - public void sendTo( final AppEngPacket message, final EntityPlayerMP player ) - { - this.ec.sendTo( message.getProxy(), player ); - } - - public void sendToAllAround( final AppEngPacket message, final NetworkRegistry.TargetPoint point ) - { - this.ec.sendToAllAround( message.getProxy(), point ); - } - - public void sendToDimension( final AppEngPacket message, final int dimensionId ) - { - this.ec.sendToDimension( message.getProxy(), dimensionId ); - } - - public void sendToServer( final AppEngPacket message ) - { - this.ec.sendToServer( message.getProxy() ); - } +public class NetworkHandler { + + public static NetworkHandler instance; + + private final FMLEventChannel ec; + private final String myChannelName; + + private final IPacketHandler clientHandler; + private final IPacketHandler serveHandler; + + public NetworkHandler(final String channelName) { + FMLCommonHandler.instance().bus().register(this); + this.ec = NetworkRegistry.INSTANCE.newEventDrivenChannel(this.myChannelName = channelName); + this.ec.register(this); + + this.clientHandler = this.createClientSide(); + this.serveHandler = this.createServerSide(); + } + + private IPacketHandler createClientSide() { + try { + return new AppEngClientPacketHandler(); + } catch (final Throwable t) { + return null; + } + } + + private IPacketHandler createServerSide() { + try { + return new AppEngServerPacketHandler(); + } catch (final Throwable t) { + return null; + } + } + + @SubscribeEvent + public void newConnection(final ServerConnectionFromClientEvent ev) { + WorldData.instance().dimensionData().sendToPlayer(ev.manager); + } + + @SubscribeEvent + public void newConnection(final PlayerLoggedInEvent loginEvent) { + if (loginEvent.player instanceof EntityPlayerMP) { + WorldData.instance().dimensionData().sendToPlayer(null); + } + } + + @SubscribeEvent + public void serverPacket(final ServerCustomPacketEvent ev) { + final NetHandlerPlayServer srv = (NetHandlerPlayServer) ev.packet.handler(); + if (this.serveHandler != null) { + this.serveHandler.onPacketData(null, ev.packet, srv.playerEntity); + } + } + + @SubscribeEvent + public void clientPacket(final ClientCustomPacketEvent ev) { + if (this.clientHandler != null) { + this.clientHandler.onPacketData(null, ev.packet, null); + } + } + + public String getChannel() { + return this.myChannelName; + } + + public void sendToAll(final AppEngPacket message) { + this.ec.sendToAll(message.getProxy()); + } + + public void sendTo(final AppEngPacket message, final EntityPlayerMP player) { + this.ec.sendTo(message.getProxy(), player); + } + + public void sendToAllAround(final AppEngPacket message, final NetworkRegistry.TargetPoint point) { + this.ec.sendToAllAround(message.getProxy(), point); + } + + public void sendToDimension(final AppEngPacket message, final int dimensionId) { + this.ec.sendToDimension(message.getProxy(), dimensionId); + } + + public void sendToServer(final AppEngPacket message) { + this.ec.sendToServer(message.getProxy()); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketAssemblerAnimation.java b/src/main/java/appeng/core/sync/packets/PacketAssemblerAnimation.java index f9123de70b6..9a3e28cec8c 100644 --- a/src/main/java/appeng/core/sync/packets/PacketAssemblerAnimation.java +++ b/src/main/java/appeng/core/sync/packets/PacketAssemblerAnimation.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.api.storage.data.IAEItemStack; import appeng.client.EffectType; import appeng.core.CommonHelper; @@ -29,55 +28,51 @@ import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; -import net.minecraft.entity.player.EntityPlayer; - import java.io.IOException; +import net.minecraft.entity.player.EntityPlayer; +public class PacketAssemblerAnimation extends AppEngPacket { -public class PacketAssemblerAnimation extends AppEngPacket -{ - - private final int x; - private final int y; - private final int z; - public final byte rate; - public final IAEItemStack is; + private final int x; + private final int y; + private final int z; + public final byte rate; + public final IAEItemStack is; - // automatic. - public PacketAssemblerAnimation( final ByteBuf stream ) throws IOException - { - this.x = stream.readInt(); - this.y = stream.readInt(); - this.z = stream.readInt(); - this.rate = stream.readByte(); - this.is = AEItemStack.loadItemStackFromPacket( stream ); - } + // automatic. + public PacketAssemblerAnimation(final ByteBuf stream) throws IOException { + this.x = stream.readInt(); + this.y = stream.readInt(); + this.z = stream.readInt(); + this.rate = stream.readByte(); + this.is = AEItemStack.loadItemStackFromPacket(stream); + } - // api - public PacketAssemblerAnimation( final int x, final int y, final int z, final byte rate, final IAEItemStack is ) throws IOException - { + // api + public PacketAssemblerAnimation(final int x, final int y, final int z, final byte rate, final IAEItemStack is) + throws IOException { - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( this.x = x ); - data.writeInt( this.y = y ); - data.writeInt( this.z = z ); - data.writeByte( this.rate = rate ); - is.writeToPacket( data ); - this.is = is; + data.writeInt(this.getPacketID()); + data.writeInt(this.x = x); + data.writeInt(this.y = y); + data.writeInt(this.z = z); + data.writeByte(this.rate = rate); + is.writeToPacket(data); + this.is = is; - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final double d0 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); - final double d1 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); - final double d2 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final double d0 = 0.5d; // + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); + final double d1 = 0.5d; // + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); + final double d2 = 0.5d; // + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); - CommonHelper.proxy.spawnEffect( EffectType.Assembler, player.getEntityWorld(), this.x + d0, this.y + d1, this.z + d2, this ); - } + CommonHelper.proxy.spawnEffect( + EffectType.Assembler, player.getEntityWorld(), this.x + d0, this.y + d1, this.z + d2, this); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketClick.java b/src/main/java/appeng/core/sync/packets/PacketClick.java index 02f24920016..72b16ab68de 100644 --- a/src/main/java/appeng/core/sync/packets/PacketClick.java +++ b/src/main/java/appeng/core/sync/packets/PacketClick.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.api.AEApi; import appeng.api.definitions.IComparableDefinition; import appeng.api.definitions.IItems; @@ -33,76 +32,80 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; +public class PacketClick extends AppEngPacket { -public class PacketClick extends AppEngPacket -{ - - private final int x; - private final int y; - private final int z; - private final int side; - private final float hitX; - private final float hitY; - private final float hitZ; - - // automatic. - public PacketClick( final ByteBuf stream ) - { - this.x = stream.readInt(); - this.y = stream.readInt(); - this.z = stream.readInt(); - this.side = stream.readInt(); - this.hitX = stream.readFloat(); - this.hitY = stream.readFloat(); - this.hitZ = stream.readFloat(); - } - - // api - public PacketClick( final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { + private final int x; + private final int y; + private final int z; + private final int side; + private final float hitX; + private final float hitY; + private final float hitZ; - final ByteBuf data = Unpooled.buffer(); + // automatic. + public PacketClick(final ByteBuf stream) { + this.x = stream.readInt(); + this.y = stream.readInt(); + this.z = stream.readInt(); + this.side = stream.readInt(); + this.hitX = stream.readFloat(); + this.hitY = stream.readFloat(); + this.hitZ = stream.readFloat(); + } - data.writeInt( this.getPacketID() ); - data.writeInt( this.x = x ); - data.writeInt( this.y = y ); - data.writeInt( this.z = z ); - data.writeInt( this.side = side ); - data.writeFloat( this.hitX = hitX ); - data.writeFloat( this.hitY = hitY ); - data.writeFloat( this.hitZ = hitZ ); + // api + public PacketClick( + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { - this.configureWrite( data ); - } + final ByteBuf data = Unpooled.buffer(); - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final ItemStack is = player.inventory.getCurrentItem(); - final IItems items = AEApi.instance().definitions().items(); - final IComparableDefinition maybeMemoryCard = items.memoryCard(); - final IComparableDefinition maybeColorApplicator = items.colorApplicator(); + data.writeInt(this.getPacketID()); + data.writeInt(this.x = x); + data.writeInt(this.y = y); + data.writeInt(this.z = z); + data.writeInt(this.side = side); + data.writeFloat(this.hitX = hitX); + data.writeFloat(this.hitY = hitY); + data.writeFloat(this.hitZ = hitZ); - if( is != null ) - { - if( is.getItem() instanceof ToolNetworkTool ) - { - final ToolNetworkTool tnt = (ToolNetworkTool) is.getItem(); - tnt.serverSideToolLogic( is, player, player.worldObj, this.x, this.y, this.z, this.side, this.hitX, this.hitY, this.hitZ ); - } + this.configureWrite(data); + } - else if( maybeMemoryCard.isSameAs( is ) ) - { - final IMemoryCard mem = (IMemoryCard) is.getItem(); - mem.notifyUser( player, MemoryCardMessages.SETTINGS_CLEARED ); - is.setTagCompound( null ); - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final ItemStack is = player.inventory.getCurrentItem(); + final IItems items = AEApi.instance().definitions().items(); + final IComparableDefinition maybeMemoryCard = items.memoryCard(); + final IComparableDefinition maybeColorApplicator = items.colorApplicator(); - else if( maybeColorApplicator.isSameAs( is ) ) - { - final ToolColorApplicator mem = (ToolColorApplicator) is.getItem(); - mem.cycleColors( is, mem.getColor( is ), 1 ); - } - } - } + if (is != null) { + if (is.getItem() instanceof ToolNetworkTool) { + final ToolNetworkTool tnt = (ToolNetworkTool) is.getItem(); + tnt.serverSideToolLogic( + is, + player, + player.worldObj, + this.x, + this.y, + this.z, + this.side, + this.hitX, + this.hitY, + this.hitZ); + } else if (maybeMemoryCard.isSameAs(is)) { + final IMemoryCard mem = (IMemoryCard) is.getItem(); + mem.notifyUser(player, MemoryCardMessages.SETTINGS_CLEARED); + is.setTagCompound(null); + } else if (maybeColorApplicator.isSameAs(is)) { + final ToolColorApplicator mem = (ToolColorApplicator) is.getItem(); + mem.cycleColors(is, mem.getColor(is), 1); + } + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketCompassRequest.java b/src/main/java/appeng/core/sync/packets/PacketCompassRequest.java index a9e76ad82b3..aefe319f9c6 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCompassRequest.java +++ b/src/main/java/appeng/core/sync/packets/PacketCompassRequest.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.api.util.DimensionalCoord; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -30,53 +29,49 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; +public class PacketCompassRequest extends AppEngPacket implements ICompassCallback { -public class PacketCompassRequest extends AppEngPacket implements ICompassCallback -{ - - final long attunement; - final int cx; - final int cz; - final int cdy; + final long attunement; + final int cx; + final int cz; + final int cdy; - private EntityPlayer talkBackTo; + private EntityPlayer talkBackTo; - // automatic. - public PacketCompassRequest( final ByteBuf stream ) - { - this.attunement = stream.readLong(); - this.cx = stream.readInt(); - this.cz = stream.readInt(); - this.cdy = stream.readInt(); - } + // automatic. + public PacketCompassRequest(final ByteBuf stream) { + this.attunement = stream.readLong(); + this.cx = stream.readInt(); + this.cz = stream.readInt(); + this.cdy = stream.readInt(); + } - // api - public PacketCompassRequest( final long attunement, final int cx, final int cz, final int cdy ) - { + // api + public PacketCompassRequest(final long attunement, final int cx, final int cz, final int cdy) { - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeLong( this.attunement = attunement ); - data.writeInt( this.cx = cx ); - data.writeInt( this.cz = cz ); - data.writeInt( this.cdy = cdy ); + data.writeInt(this.getPacketID()); + data.writeLong(this.attunement = attunement); + data.writeInt(this.cx = cx); + data.writeInt(this.cz = cz); + data.writeInt(this.cdy = cdy); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void calculatedDirection( final boolean hasResult, final boolean spin, final double radians, final double dist ) - { - NetworkHandler.instance.sendTo( new PacketCompassResponse( this, hasResult, spin, radians ), (EntityPlayerMP) this.talkBackTo ); - } + @Override + public void calculatedDirection( + final boolean hasResult, final boolean spin, final double radians, final double dist) { + NetworkHandler.instance.sendTo( + new PacketCompassResponse(this, hasResult, spin, radians), (EntityPlayerMP) this.talkBackTo); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - this.talkBackTo = player; + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + this.talkBackTo = player; - final DimensionalCoord loc = new DimensionalCoord( player.worldObj, this.cx << 4, this.cdy << 5, this.cz << 4 ); - WorldData.instance().compassData().service().getCompassDirection( loc, 174, this ); - } + final DimensionalCoord loc = new DimensionalCoord(player.worldObj, this.cx << 4, this.cdy << 5, this.cz << 4); + WorldData.instance().compassData().service().getCompassDirection(loc, 174, this); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketCompassResponse.java b/src/main/java/appeng/core/sync/packets/PacketCompassResponse.java index 6daf805b344..3e06af88241 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCompassResponse.java +++ b/src/main/java/appeng/core/sync/packets/PacketCompassResponse.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.hooks.CompassManager; @@ -27,50 +26,46 @@ import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; +public class PacketCompassResponse extends AppEngPacket { -public class PacketCompassResponse extends AppEngPacket -{ - - private final long attunement; - private final int cx; - private final int cz; - private final int cdy; + private final long attunement; + private final int cx; + private final int cz; + private final int cdy; - private CompassResult cr; + private CompassResult cr; - // automatic. - public PacketCompassResponse( final ByteBuf stream ) - { - this.attunement = stream.readLong(); - this.cx = stream.readInt(); - this.cz = stream.readInt(); - this.cdy = stream.readInt(); + // automatic. + public PacketCompassResponse(final ByteBuf stream) { + this.attunement = stream.readLong(); + this.cx = stream.readInt(); + this.cz = stream.readInt(); + this.cdy = stream.readInt(); - this.cr = new CompassResult( stream.readBoolean(), stream.readBoolean(), stream.readDouble() ); - } + this.cr = new CompassResult(stream.readBoolean(), stream.readBoolean(), stream.readDouble()); + } - // api - public PacketCompassResponse( final PacketCompassRequest req, final boolean hasResult, final boolean spin, final double radians ) - { + // api + public PacketCompassResponse( + final PacketCompassRequest req, final boolean hasResult, final boolean spin, final double radians) { - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeLong( this.attunement = req.attunement ); - data.writeInt( this.cx = req.cx ); - data.writeInt( this.cz = req.cz ); - data.writeInt( this.cdy = req.cdy ); + data.writeInt(this.getPacketID()); + data.writeLong(this.attunement = req.attunement); + data.writeInt(this.cx = req.cx); + data.writeInt(this.cz = req.cz); + data.writeInt(this.cdy = req.cdy); - data.writeBoolean( hasResult ); - data.writeBoolean( spin ); - data.writeDouble( radians ); + data.writeBoolean(hasResult); + data.writeBoolean(spin); + data.writeDouble(radians); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - CompassManager.INSTANCE.postResult( this.attunement, this.cx << 4, this.cdy << 5, this.cz << 4, this.cr ); - } -} \ No newline at end of file + @Override + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + CompassManager.INSTANCE.postResult(this.attunement, this.cx << 4, this.cdy << 5, this.cz << 4, this.cr); + } +} diff --git a/src/main/java/appeng/core/sync/packets/PacketCompressedNBT.java b/src/main/java/appeng/core/sync/packets/PacketCompressedNBT.java index 84e610cf33f..b81d3678d2a 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCompressedNBT.java +++ b/src/main/java/appeng/core/sync/packets/PacketCompressedNBT.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.client.gui.implementations.GuiInterfaceTerminal; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -26,86 +25,74 @@ import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import java.io.*; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; -import java.io.*; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; +public class PacketCompressedNBT extends AppEngPacket { + + // input. + private final NBTTagCompound in; + // output... + private final ByteBuf data; + private final GZIPOutputStream compressFrame; + + // automatic. + public PacketCompressedNBT(final ByteBuf stream) throws IOException { + this.data = null; + this.compressFrame = null; + + final GZIPInputStream gzReader = new GZIPInputStream(new InputStream() { + + @Override + public int read() throws IOException { + if (stream.readableBytes() <= 0) { + return -1; + } + + return stream.readByte() & 0xff; + } + }); + + final DataInputStream inStream = new DataInputStream(gzReader); + this.in = CompressedStreamTools.read(inStream); + inStream.close(); + } + + // api + public PacketCompressedNBT(final NBTTagCompound din) throws IOException { + + this.data = Unpooled.buffer(2048); + this.data.writeInt(this.getPacketID()); + + this.in = din; + + this.compressFrame = new GZIPOutputStream(new OutputStream() { + + @Override + public void write(final int value) throws IOException { + PacketCompressedNBT.this.data.writeByte(value); + } + }); + + CompressedStreamTools.write(din, new DataOutputStream(this.compressFrame)); + this.compressFrame.close(); + + this.configureWrite(this.data); + } + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final GuiScreen gs = Minecraft.getMinecraft().currentScreen; -public class PacketCompressedNBT extends AppEngPacket -{ - - // input. - private final NBTTagCompound in; - // output... - private final ByteBuf data; - private final GZIPOutputStream compressFrame; - - // automatic. - public PacketCompressedNBT( final ByteBuf stream ) throws IOException - { - this.data = null; - this.compressFrame = null; - - final GZIPInputStream gzReader = new GZIPInputStream( new InputStream() - { - - @Override - public int read() throws IOException - { - if( stream.readableBytes() <= 0 ) - { - return -1; - } - - return stream.readByte() & 0xff; - } - } ); - - final DataInputStream inStream = new DataInputStream( gzReader ); - this.in = CompressedStreamTools.read( inStream ); - inStream.close(); - } - - // api - public PacketCompressedNBT( final NBTTagCompound din ) throws IOException - { - - this.data = Unpooled.buffer( 2048 ); - this.data.writeInt( this.getPacketID() ); - - this.in = din; - - this.compressFrame = new GZIPOutputStream( new OutputStream() - { - - @Override - public void write( final int value ) throws IOException - { - PacketCompressedNBT.this.data.writeByte( value ); - } - } ); - - CompressedStreamTools.write( din, new DataOutputStream( this.compressFrame ) ); - this.compressFrame.close(); - - this.configureWrite( this.data ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final GuiScreen gs = Minecraft.getMinecraft().currentScreen; - - if( gs instanceof GuiInterfaceTerminal ) - { - ( (GuiInterfaceTerminal) gs ).postUpdate( this.in ); - } - } + if (gs instanceof GuiInterfaceTerminal) { + ((GuiInterfaceTerminal) gs).postUpdate(this.in); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketConfigButton.java b/src/main/java/appeng/core/sync/packets/PacketConfigButton.java index db9e2bba033..9e15f52c36f 100644 --- a/src/main/java/appeng/core/sync/packets/PacketConfigButton.java +++ b/src/main/java/appeng/core/sync/packets/PacketConfigButton.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.api.config.Settings; import appeng.api.util.IConfigManager; import appeng.api.util.IConfigurableObject; @@ -32,48 +31,42 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; +public final class PacketConfigButton extends AppEngPacket { + private final Settings option; + private final boolean rotationDirection; -public final class PacketConfigButton extends AppEngPacket -{ - private final Settings option; - private final boolean rotationDirection; - - // automatic. - @Reflected - public PacketConfigButton( final ByteBuf stream ) - { - this.option = Settings.values()[stream.readInt()]; - this.rotationDirection = stream.readBoolean(); - } + // automatic. + @Reflected + public PacketConfigButton(final ByteBuf stream) { + this.option = Settings.values()[stream.readInt()]; + this.rotationDirection = stream.readBoolean(); + } - // api - public PacketConfigButton( final Settings option, final boolean rotationDirection ) - { - this.option = option; - this.rotationDirection = rotationDirection; + // api + public PacketConfigButton(final Settings option, final boolean rotationDirection) { + this.option = option; + this.rotationDirection = rotationDirection; - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( option.ordinal() ); - data.writeBoolean( rotationDirection ); + data.writeInt(this.getPacketID()); + data.writeInt(option.ordinal()); + data.writeBoolean(rotationDirection); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final EntityPlayerMP sender = (EntityPlayerMP) player; - if( sender.openContainer instanceof AEBaseContainer ) - { - final AEBaseContainer baseContainer = (AEBaseContainer) sender.openContainer; - if( baseContainer.getTarget() instanceof IConfigurableObject ) - { - final IConfigManager cm = ( (IConfigurableObject) baseContainer.getTarget() ).getConfigManager(); - final Enum newState = Platform.rotateEnum( cm.getSetting( this.option ), this.rotationDirection, this.option.getPossibleValues() ); - cm.putSetting( this.option, newState ); - } - } - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final EntityPlayerMP sender = (EntityPlayerMP) player; + if (sender.openContainer instanceof AEBaseContainer) { + final AEBaseContainer baseContainer = (AEBaseContainer) sender.openContainer; + if (baseContainer.getTarget() instanceof IConfigurableObject) { + final IConfigManager cm = ((IConfigurableObject) baseContainer.getTarget()).getConfigManager(); + final Enum newState = Platform.rotateEnum( + cm.getSetting(this.option), this.rotationDirection, this.option.getPossibleValues()); + cm.putSetting(this.option, newState); + } + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketCraftRequest.java b/src/main/java/appeng/core/sync/packets/PacketCraftRequest.java index b0bbbd19e6b..d1a9fb2a2d3 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCraftRequest.java +++ b/src/main/java/appeng/core/sync/packets/PacketCraftRequest.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; @@ -29,99 +28,82 @@ import appeng.container.implementations.ContainerCraftConfirm; import appeng.core.AELog; import appeng.core.sync.AppEngPacket; -import appeng.core.sync.GuiBridge; import appeng.core.sync.network.INetworkInfo; -import appeng.util.Platform; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import java.util.concurrent.Future; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.concurrent.Future; - - -public class PacketCraftRequest extends AppEngPacket -{ - - private final long amount; - private final boolean heldShift; - - // automatic. - public PacketCraftRequest( final ByteBuf stream ) - { - this.heldShift = stream.readBoolean(); - this.amount = stream.readLong(); - } - - public PacketCraftRequest( final int craftAmt, final boolean shift ) - { - this.amount = craftAmt; - this.heldShift = shift; - - final ByteBuf data = Unpooled.buffer(); - - data.writeInt( this.getPacketID() ); - data.writeBoolean( shift ); - data.writeLong( this.amount ); - - this.configureWrite( data ); - } - - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - if( player.openContainer instanceof ContainerCraftAmount ) - { - final ContainerCraftAmount cca = (ContainerCraftAmount) player.openContainer; - final Object target = cca.getTarget(); - if( target instanceof IGridHost ) - { - final IGridHost gh = (IGridHost) target; - final IGridNode gn = gh.getGridNode( ForgeDirection.UNKNOWN ); - if( gn == null ) - { - return; - } - - final IGrid g = gn.getGrid(); - if( g == null || cca.getItemToCraft() == null ) - { - return; - } - - cca.getItemToCraft().setStackSize( this.amount ); - - Future futureJob = null; - try - { - final ICraftingGrid cg = g.getCache( ICraftingGrid.class ); - futureJob = cg.beginCraftingJob( cca.getWorld(), cca.getGrid(), cca.getActionSrc(), cca.getItemToCraft(), null ); - - final ContainerOpenContext context = cca.getOpenContext(); - if( context != null ) - { - final TileEntity te = context.getTile(); - cca.openConfirmationGUI( player, te ); - - if( player.openContainer instanceof ContainerCraftConfirm ) - { - final ContainerCraftConfirm ccc = (ContainerCraftConfirm) player.openContainer; - ccc.setAutoStart( this.heldShift ); - ccc.setJob( futureJob ); - cca.detectAndSendChanges(); - } - } - } - catch( final Throwable e ) - { - if( futureJob != null ) - { - futureJob.cancel( true ); - } - AELog.debug( e ); - } - } - } - } +public class PacketCraftRequest extends AppEngPacket { + + private final long amount; + private final boolean heldShift; + + // automatic. + public PacketCraftRequest(final ByteBuf stream) { + this.heldShift = stream.readBoolean(); + this.amount = stream.readLong(); + } + + public PacketCraftRequest(final int craftAmt, final boolean shift) { + this.amount = craftAmt; + this.heldShift = shift; + + final ByteBuf data = Unpooled.buffer(); + + data.writeInt(this.getPacketID()); + data.writeBoolean(shift); + data.writeLong(this.amount); + + this.configureWrite(data); + } + + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + if (player.openContainer instanceof ContainerCraftAmount) { + final ContainerCraftAmount cca = (ContainerCraftAmount) player.openContainer; + final Object target = cca.getTarget(); + if (target instanceof IGridHost) { + final IGridHost gh = (IGridHost) target; + final IGridNode gn = gh.getGridNode(ForgeDirection.UNKNOWN); + if (gn == null) { + return; + } + + final IGrid g = gn.getGrid(); + if (g == null || cca.getItemToCraft() == null) { + return; + } + + cca.getItemToCraft().setStackSize(this.amount); + + Future futureJob = null; + try { + final ICraftingGrid cg = g.getCache(ICraftingGrid.class); + futureJob = cg.beginCraftingJob( + cca.getWorld(), cca.getGrid(), cca.getActionSrc(), cca.getItemToCraft(), null); + + final ContainerOpenContext context = cca.getOpenContext(); + if (context != null) { + final TileEntity te = context.getTile(); + cca.openConfirmationGUI(player, te); + + if (player.openContainer instanceof ContainerCraftConfirm) { + final ContainerCraftConfirm ccc = (ContainerCraftConfirm) player.openContainer; + ccc.setAutoStart(this.heldShift); + ccc.setJob(futureJob); + cca.detectAndSendChanges(); + } + } + } catch (final Throwable e) { + if (futureJob != null) { + futureJob.cancel(true); + } + AELog.debug(e); + } + } + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketCraftingCPUsUpdate.java b/src/main/java/appeng/core/sync/packets/PacketCraftingCPUsUpdate.java index f0370834222..93a58f63791 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCraftingCPUsUpdate.java +++ b/src/main/java/appeng/core/sync/packets/PacketCraftingCPUsUpdate.java @@ -1,64 +1,51 @@ package appeng.core.sync.packets; -import appeng.client.gui.implementations.GuiCraftingStatus; import appeng.client.gui.widgets.ICraftingCPUTableHolder; import appeng.container.implementations.CraftingCPUStatus; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import java.io.IOException; +import java.util.Collection; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; -import java.io.IOException; -import java.util.Collection; - -public class PacketCraftingCPUsUpdate extends AppEngPacket -{ +public class PacketCraftingCPUsUpdate extends AppEngPacket { private final CraftingCPUStatus[] cpus; - public PacketCraftingCPUsUpdate( final ByteBuf stream ) - { + public PacketCraftingCPUsUpdate(final ByteBuf stream) { int count = stream.readInt(); cpus = new CraftingCPUStatus[count]; - for( int i = 0; i < count; i++ ) - { - try - { - cpus[i] = new CraftingCPUStatus( stream ); - } - catch( IOException e ) - { - cpus[i] = new CraftingCPUStatus( ); + for (int i = 0; i < count; i++) { + try { + cpus[i] = new CraftingCPUStatus(stream); + } catch (IOException e) { + cpus[i] = new CraftingCPUStatus(); } } } - public PacketCraftingCPUsUpdate( final Collection cpus ) throws IOException - { - this.cpus = cpus.toArray( new CraftingCPUStatus[0] ); + public PacketCraftingCPUsUpdate(final Collection cpus) throws IOException { + this.cpus = cpus.toArray(new CraftingCPUStatus[0]); final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( this.cpus.length ); - for( CraftingCPUStatus cpu : this.cpus ) - { - cpu.writeToPacket( data ); + data.writeInt(this.getPacketID()); + data.writeInt(this.cpus.length); + for (CraftingCPUStatus cpu : this.cpus) { + cpu.writeToPacket(data); } - this.configureWrite( data ); + this.configureWrite(data); } @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { final GuiScreen gs = Minecraft.getMinecraft().currentScreen; - if( gs instanceof ICraftingCPUTableHolder ) - { + if (gs instanceof ICraftingCPUTableHolder) { ICraftingCPUTableHolder gui = (ICraftingCPUTableHolder) gs; - gui.getCPUTable().getContainer().handleCPUUpdate( this.cpus ); + gui.getCPUTable().getContainer().handleCPUUpdate(this.cpus); } - } } diff --git a/src/main/java/appeng/core/sync/packets/PacketInventoryAction.java b/src/main/java/appeng/core/sync/packets/PacketInventoryAction.java index 3f92e154e28..5527bbdb17a 100644 --- a/src/main/java/appeng/core/sync/packets/PacketInventoryAction.java +++ b/src/main/java/appeng/core/sync/packets/PacketInventoryAction.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.api.storage.data.IAEItemStack; import appeng.client.ClientHelper; import appeng.container.AEBaseContainer; @@ -33,159 +32,133 @@ import appeng.util.item.AEItemStack; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.tileentity.TileEntity; -import java.io.IOException; +public class PacketInventoryAction extends AppEngPacket { + + private final InventoryAction action; + private final int slot; + private final long id; + private final IAEItemStack slotItem; + + // automatic. + public PacketInventoryAction(final ByteBuf stream) throws IOException { + this.action = InventoryAction.values()[stream.readInt()]; + this.slot = stream.readInt(); + this.id = stream.readLong(); + final boolean hasItem = stream.readBoolean(); + if (hasItem) { + this.slotItem = AEItemStack.loadItemStackFromPacket(stream); + } else { + this.slotItem = null; + } + } + + // api + public PacketInventoryAction(final InventoryAction action, final int slot, final IAEItemStack slotItem) + throws IOException { + + if (Platform.isClient()) { + throw new IllegalStateException("invalid packet, client cannot post inv actions with stacks."); + } + + this.action = action; + this.slot = slot; + this.id = 0; + this.slotItem = slotItem; + + final ByteBuf data = Unpooled.buffer(); + + data.writeInt(this.getPacketID()); + data.writeInt(action.ordinal()); + data.writeInt(slot); + data.writeLong(this.id); + + if (slotItem == null) { + data.writeBoolean(false); + } else { + data.writeBoolean(true); + slotItem.writeToPacket(data); + } + + this.configureWrite(data); + } + + // api + public PacketInventoryAction(final InventoryAction action, final int slot, final long id) { + this.action = action; + this.slot = slot; + this.id = id; + this.slotItem = null; + + final ByteBuf data = Unpooled.buffer(); + + data.writeInt(this.getPacketID()); + data.writeInt(action.ordinal()); + data.writeInt(slot); + data.writeLong(id); + data.writeBoolean(false); + + this.configureWrite(data); + } + + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final EntityPlayerMP sender = (EntityPlayerMP) player; + if (sender.openContainer instanceof AEBaseContainer) { + final AEBaseContainer baseContainer = (AEBaseContainer) sender.openContainer; + if (this.action == InventoryAction.AUTO_CRAFT) { + final ContainerOpenContext context = baseContainer.getOpenContext(); + if (context != null) { + final TileEntity te = context.getTile(); + Platform.openGUI( + sender, te, baseContainer.getOpenContext().getSide(), GuiBridge.GUI_CRAFTING_AMOUNT); + if (sender.openContainer instanceof ContainerCraftAmount) { + final ContainerCraftAmount cca = (ContainerCraftAmount) sender.openContainer; -public class PacketInventoryAction extends AppEngPacket -{ - - private final InventoryAction action; - private final int slot; - private final long id; - private final IAEItemStack slotItem; - - // automatic. - public PacketInventoryAction( final ByteBuf stream ) throws IOException - { - this.action = InventoryAction.values()[stream.readInt()]; - this.slot = stream.readInt(); - this.id = stream.readLong(); - final boolean hasItem = stream.readBoolean(); - if( hasItem ) - { - this.slotItem = AEItemStack.loadItemStackFromPacket( stream ); - } - else - { - this.slotItem = null; - } - } - - // api - public PacketInventoryAction( final InventoryAction action, final int slot, final IAEItemStack slotItem ) throws IOException - { - - if( Platform.isClient() ) - { - throw new IllegalStateException( "invalid packet, client cannot post inv actions with stacks." ); - } - - this.action = action; - this.slot = slot; - this.id = 0; - this.slotItem = slotItem; - - final ByteBuf data = Unpooled.buffer(); - - data.writeInt( this.getPacketID() ); - data.writeInt( action.ordinal() ); - data.writeInt( slot ); - data.writeLong( this.id ); - - if( slotItem == null ) - { - data.writeBoolean( false ); - } - else - { - data.writeBoolean( true ); - slotItem.writeToPacket( data ); - } - - this.configureWrite( data ); - } - - // api - public PacketInventoryAction( final InventoryAction action, final int slot, final long id ) - { - this.action = action; - this.slot = slot; - this.id = id; - this.slotItem = null; - - final ByteBuf data = Unpooled.buffer(); - - data.writeInt( this.getPacketID() ); - data.writeInt( action.ordinal() ); - data.writeInt( slot ); - data.writeLong( id ); - data.writeBoolean( false ); - - this.configureWrite( data ); - } - - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final EntityPlayerMP sender = (EntityPlayerMP) player; - if( sender.openContainer instanceof AEBaseContainer ) - { - final AEBaseContainer baseContainer = (AEBaseContainer) sender.openContainer; - if( this.action == InventoryAction.AUTO_CRAFT ) - { - final ContainerOpenContext context = baseContainer.getOpenContext(); - if( context != null ) - { - final TileEntity te = context.getTile(); - Platform.openGUI( sender, te, baseContainer.getOpenContext().getSide(), GuiBridge.GUI_CRAFTING_AMOUNT ); - - if( sender.openContainer instanceof ContainerCraftAmount ) - { - final ContainerCraftAmount cca = (ContainerCraftAmount) sender.openContainer; - - if( baseContainer.getTargetStack() != null ) - { - cca.getCraftingItem().putStack( baseContainer.getTargetStack().getItemStack() ); - cca.setItemToCraft( baseContainer.getTargetStack() ); - } - - cca.detectAndSendChanges(); - } - } - } - else if( this.action == InventoryAction.SET_PATTERN_VALUE ) - { + if (baseContainer.getTargetStack() != null) { + cca.getCraftingItem() + .putStack(baseContainer.getTargetStack().getItemStack()); + cca.setItemToCraft(baseContainer.getTargetStack()); + } + + cca.detectAndSendChanges(); + } + } + } else if (this.action == InventoryAction.SET_PATTERN_VALUE) { final ContainerOpenContext context = baseContainer.getOpenContext(); - if( context != null ) - { + if (context != null) { final TileEntity te = context.getTile(); - Platform.openGUI( sender, te, baseContainer.getOpenContext().getSide(), GuiBridge.GUI_PATTERN_VALUE_AMOUNT ); - if( sender.openContainer instanceof ContainerPatternValueAmount ) - { + Platform.openGUI( + sender, te, baseContainer.getOpenContext().getSide(), GuiBridge.GUI_PATTERN_VALUE_AMOUNT); + if (sender.openContainer instanceof ContainerPatternValueAmount) { final ContainerPatternValueAmount cpv = (ContainerPatternValueAmount) sender.openContainer; - if( baseContainer.getTargetStack() != null ) - { - cpv.setValueIndex( this.slot ); - cpv.getPatternValue().putStack( baseContainer.getTargetStack().getItemStack() ); + if (baseContainer.getTargetStack() != null) { + cpv.setValueIndex(this.slot); + cpv.getPatternValue() + .putStack(baseContainer.getTargetStack().getItemStack()); } cpv.detectAndSendChanges(); } } + } else { + baseContainer.doAction(sender, this.action, this.slot, this.id); + } + } + } + + @Override + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + if (this.action == InventoryAction.UPDATE_HAND) { + if (this.slotItem == null) { + ClientHelper.proxy.getPlayers().get(0).inventory.setItemStack(null); + } else { + ClientHelper.proxy.getPlayers().get(0).inventory.setItemStack(this.slotItem.getItemStack()); } - else - { - baseContainer.doAction( sender, this.action, this.slot, this.id ); - } - } - } - - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - if( this.action == InventoryAction.UPDATE_HAND ) - { - if( this.slotItem == null ) - { - ClientHelper.proxy.getPlayers().get( 0 ).inventory.setItemStack( null ); - } - else - { - ClientHelper.proxy.getPlayers().get( 0 ).inventory.setItemStack( this.slotItem.getItemStack() ); - } - } - } + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketLightning.java b/src/main/java/appeng/core/sync/packets/PacketLightning.java index e17414c0f2c..d81582ee72e 100644 --- a/src/main/java/appeng/core/sync/packets/PacketLightning.java +++ b/src/main/java/appeng/core/sync/packets/PacketLightning.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.client.ClientHelper; import appeng.client.render.effects.LightningFX; import appeng.core.AEConfig; @@ -32,53 +31,45 @@ import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; +public class PacketLightning extends AppEngPacket { -public class PacketLightning extends AppEngPacket -{ - - private final double x; - private final double y; - private final double z; + private final double x; + private final double y; + private final double z; - // automatic. - public PacketLightning( final ByteBuf stream ) - { - this.x = stream.readFloat(); - this.y = stream.readFloat(); - this.z = stream.readFloat(); - } + // automatic. + public PacketLightning(final ByteBuf stream) { + this.x = stream.readFloat(); + this.y = stream.readFloat(); + this.z = stream.readFloat(); + } - // api - public PacketLightning( final double x, final double y, final double z ) - { - this.x = x; - this.y = y; - this.z = z; + // api + public PacketLightning(final double x, final double y, final double z) { + this.x = x; + this.y = y; + this.z = z; - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeFloat( (float) x ); - data.writeFloat( (float) y ); - data.writeFloat( (float) z ); + data.writeInt(this.getPacketID()); + data.writeFloat((float) x); + data.writeFloat((float) y); + data.writeFloat((float) z); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - try - { - if( Platform.isClient() && AEConfig.instance.enableEffects ) - { - final LightningFX fx = new LightningFX( ClientHelper.proxy.getWorld(), this.x, this.y, this.z, 0.0f, 0.0f, 0.0f ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - catch( final Exception ignored ) - { - } - } + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + try { + if (Platform.isClient() && AEConfig.instance.enableEffects) { + final LightningFX fx = + new LightningFX(ClientHelper.proxy.getWorld(), this.x, this.y, this.z, 0.0f, 0.0f, 0.0f); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } catch (final Exception ignored) { + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketMEInventoryUpdate.java b/src/main/java/appeng/core/sync/packets/PacketMEInventoryUpdate.java index df24cf19b00..ce697965ed9 100644 --- a/src/main/java/appeng/core/sync/packets/PacketMEInventoryUpdate.java +++ b/src/main/java/appeng/core/sync/packets/PacketMEInventoryUpdate.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.api.storage.data.IAEItemStack; import appeng.client.gui.implementations.GuiCraftConfirm; import appeng.client.gui.implementations.GuiCraftingCPU; @@ -33,11 +32,6 @@ import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.entity.player.EntityPlayer; - -import javax.annotation.Nullable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -46,173 +40,150 @@ import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; +import javax.annotation.Nullable; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.entity.player.EntityPlayer; - -public class PacketMEInventoryUpdate extends AppEngPacket -{ - private static final int UNCOMPRESSED_PACKET_BYTE_LIMIT = 16 * 1024 * 1024; - private static final int OPERATION_BYTE_LIMIT = 2 * 1024; - private static final int TEMP_BUFFER_SIZE = 1024; - private static final int STREAM_MASK = 0xff; - - // input. - @Nullable - private final List list; - // output... - private final byte ref; - - @Nullable - private final ByteBuf data; - @Nullable - private final GZIPOutputStream compressFrame; - - private int writtenBytes = 0; - private boolean empty = true; - - // automatic. - public PacketMEInventoryUpdate( final ByteBuf stream ) throws IOException - { - this.data = null; - this.compressFrame = null; - this.list = new LinkedList(); - this.ref = stream.readByte(); - - // int originalBytes = stream.readableBytes(); - - final GZIPInputStream gzReader = new GZIPInputStream( new InputStream() - { - @Override - public int read() throws IOException - { - if( stream.readableBytes() <= 0 ) - { - return -1; - } - - return stream.readByte() & STREAM_MASK; - } - } ); - - final ByteBuf uncompressed = Unpooled.buffer( stream.readableBytes() ); - final byte[] tmp = new byte[TEMP_BUFFER_SIZE]; - while( gzReader.available() != 0 ) - { - final int bytes = gzReader.read( tmp ); - if( bytes > 0 ) - { - uncompressed.writeBytes( tmp, 0, bytes ); - } - } - gzReader.close(); - - // int uncompressedBytes = uncompressed.readableBytes(); - // AELog.info( "Receiver: " + originalBytes + " -> " + uncompressedBytes ); - - while( uncompressed.readableBytes() > 0 ) - { - this.list.add( AEItemStack.loadItemStackFromPacket( uncompressed ) ); - } - - this.empty = this.list.isEmpty(); - } - - // api - public PacketMEInventoryUpdate() throws IOException - { - this( (byte) 0 ); - } - - // api - public PacketMEInventoryUpdate( final byte ref ) throws IOException - { - this.ref = ref; - this.data = Unpooled.buffer( OPERATION_BYTE_LIMIT ); - this.data.writeInt( this.getPacketID() ); - this.data.writeByte( this.ref ); - - this.compressFrame = new GZIPOutputStream( new OutputStream() - { - @Override - public void write( final int value ) throws IOException - { - PacketMEInventoryUpdate.this.data.writeByte( value ); - } - } ); - - this.list = null; - } - - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final GuiScreen gs = Minecraft.getMinecraft().currentScreen; - - if( gs instanceof GuiCraftConfirm ) - { - ( (GuiCraftConfirm) gs ).postUpdate( this.list, this.ref ); - } - - if( gs instanceof GuiCraftingCPU ) - { - ( (GuiCraftingCPU) gs ).postUpdate( this.list, this.ref ); - } - - if( gs instanceof GuiMEMonitorable ) - { - ( (GuiMEMonitorable) gs ).postUpdate( this.list ); - } - - if( gs instanceof GuiNetworkStatus ) - { - ( (GuiNetworkStatus) gs ).postUpdate( this.list ); - } - } - - @Nullable - @Override - public FMLProxyPacket getProxy() - { - try - { - this.compressFrame.close(); - - this.configureWrite( this.data ); - return super.getProxy(); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - - return null; - } - - public void appendItem( final IAEItemStack is ) throws IOException, BufferOverflowException - { - final ByteBuf tmp = Unpooled.buffer( OPERATION_BYTE_LIMIT ); - is.writeToPacket( tmp ); - - this.compressFrame.flush(); - if( this.writtenBytes + tmp.readableBytes() > UNCOMPRESSED_PACKET_BYTE_LIMIT ) - { - throw new BufferOverflowException(); - } - else - { - this.writtenBytes += tmp.readableBytes(); - this.compressFrame.write( tmp.array(), 0, tmp.readableBytes() ); - this.empty = false; - } - } - - public int getLength() - { - return this.data.readableBytes(); - } - - public boolean isEmpty() - { - return this.empty; - } +public class PacketMEInventoryUpdate extends AppEngPacket { + private static final int UNCOMPRESSED_PACKET_BYTE_LIMIT = 16 * 1024 * 1024; + private static final int OPERATION_BYTE_LIMIT = 2 * 1024; + private static final int TEMP_BUFFER_SIZE = 1024; + private static final int STREAM_MASK = 0xff; + + // input. + @Nullable + private final List list; + // output... + private final byte ref; + + @Nullable + private final ByteBuf data; + + @Nullable + private final GZIPOutputStream compressFrame; + + private int writtenBytes = 0; + private boolean empty = true; + + // automatic. + public PacketMEInventoryUpdate(final ByteBuf stream) throws IOException { + this.data = null; + this.compressFrame = null; + this.list = new LinkedList(); + this.ref = stream.readByte(); + + // int originalBytes = stream.readableBytes(); + + final GZIPInputStream gzReader = new GZIPInputStream(new InputStream() { + @Override + public int read() throws IOException { + if (stream.readableBytes() <= 0) { + return -1; + } + + return stream.readByte() & STREAM_MASK; + } + }); + + final ByteBuf uncompressed = Unpooled.buffer(stream.readableBytes()); + final byte[] tmp = new byte[TEMP_BUFFER_SIZE]; + while (gzReader.available() != 0) { + final int bytes = gzReader.read(tmp); + if (bytes > 0) { + uncompressed.writeBytes(tmp, 0, bytes); + } + } + gzReader.close(); + + // int uncompressedBytes = uncompressed.readableBytes(); + // AELog.info( "Receiver: " + originalBytes + " -> " + uncompressedBytes ); + + while (uncompressed.readableBytes() > 0) { + this.list.add(AEItemStack.loadItemStackFromPacket(uncompressed)); + } + + this.empty = this.list.isEmpty(); + } + + // api + public PacketMEInventoryUpdate() throws IOException { + this((byte) 0); + } + + // api + public PacketMEInventoryUpdate(final byte ref) throws IOException { + this.ref = ref; + this.data = Unpooled.buffer(OPERATION_BYTE_LIMIT); + this.data.writeInt(this.getPacketID()); + this.data.writeByte(this.ref); + + this.compressFrame = new GZIPOutputStream(new OutputStream() { + @Override + public void write(final int value) throws IOException { + PacketMEInventoryUpdate.this.data.writeByte(value); + } + }); + + this.list = null; + } + + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final GuiScreen gs = Minecraft.getMinecraft().currentScreen; + + if (gs instanceof GuiCraftConfirm) { + ((GuiCraftConfirm) gs).postUpdate(this.list, this.ref); + } + + if (gs instanceof GuiCraftingCPU) { + ((GuiCraftingCPU) gs).postUpdate(this.list, this.ref); + } + + if (gs instanceof GuiMEMonitorable) { + ((GuiMEMonitorable) gs).postUpdate(this.list); + } + + if (gs instanceof GuiNetworkStatus) { + ((GuiNetworkStatus) gs).postUpdate(this.list); + } + } + + @Nullable + @Override + public FMLProxyPacket getProxy() { + try { + this.compressFrame.close(); + + this.configureWrite(this.data); + return super.getProxy(); + } catch (final IOException e) { + AELog.debug(e); + } + + return null; + } + + public void appendItem(final IAEItemStack is) throws IOException, BufferOverflowException { + final ByteBuf tmp = Unpooled.buffer(OPERATION_BYTE_LIMIT); + is.writeToPacket(tmp); + + this.compressFrame.flush(); + if (this.writtenBytes + tmp.readableBytes() > UNCOMPRESSED_PACKET_BYTE_LIMIT) { + throw new BufferOverflowException(); + } else { + this.writtenBytes += tmp.readableBytes(); + this.compressFrame.write(tmp.array(), 0, tmp.readableBytes()); + this.empty = false; + } + } + + public int getLength() { + return this.data.readableBytes(); + } + + public boolean isEmpty() { + return this.empty; + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java b/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java index 79e9ed3a578..5ae84c65248 100644 --- a/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java +++ b/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.client.render.effects.MatterCannonFX; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -32,75 +31,74 @@ import net.minecraft.init.Items; import net.minecraft.world.World; +public class PacketMatterCannon extends AppEngPacket { -public class PacketMatterCannon extends AppEngPacket -{ - - private final double x; - private final double y; - private final double z; - private final double dx; - private final double dy; - private final double dz; - private final byte len; + private final double x; + private final double y; + private final double z; + private final double dx; + private final double dy; + private final double dz; + private final byte len; - // automatic. - public PacketMatterCannon( final ByteBuf stream ) - { - this.x = stream.readFloat(); - this.y = stream.readFloat(); - this.z = stream.readFloat(); - this.dx = stream.readFloat(); - this.dy = stream.readFloat(); - this.dz = stream.readFloat(); - this.len = stream.readByte(); - } + // automatic. + public PacketMatterCannon(final ByteBuf stream) { + this.x = stream.readFloat(); + this.y = stream.readFloat(); + this.z = stream.readFloat(); + this.dx = stream.readFloat(); + this.dy = stream.readFloat(); + this.dz = stream.readFloat(); + this.len = stream.readByte(); + } - // api - public PacketMatterCannon( final double x, final double y, final double z, final float dx, final float dy, final float dz, final byte len ) - { - final float dl = dx * dx + dy * dy + dz * dz; - final float dlz = (float) Math.sqrt( dl ); + // api + public PacketMatterCannon( + final double x, + final double y, + final double z, + final float dx, + final float dy, + final float dz, + final byte len) { + final float dl = dx * dx + dy * dy + dz * dz; + final float dlz = (float) Math.sqrt(dl); - this.x = x; - this.y = y; - this.z = z; - this.dx = dx / dlz; - this.dy = dy / dlz; - this.dz = dz / dlz; - this.len = len; + this.x = x; + this.y = y; + this.z = z; + this.dx = dx / dlz; + this.dy = dy / dlz; + this.dz = dz / dlz; + this.len = len; - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeFloat( (float) x ); - data.writeFloat( (float) y ); - data.writeFloat( (float) z ); - data.writeFloat( (float) this.dx ); - data.writeFloat( (float) this.dy ); - data.writeFloat( (float) this.dz ); - data.writeByte( len ); + data.writeInt(this.getPacketID()); + data.writeFloat((float) x); + data.writeFloat((float) y); + data.writeFloat((float) z); + data.writeFloat((float) this.dx); + data.writeFloat((float) this.dy); + data.writeFloat((float) this.dz); + data.writeByte(len); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - try - { + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + try { - final World world = FMLClientHandler.instance().getClient().theWorld; - for( int a = 1; a < this.len; a++ ) - { - final MatterCannonFX fx = new MatterCannonFX( world, this.x + this.dx * a, this.y + this.dy * a, this.z + this.dz * a, Items.diamond ); + final World world = FMLClientHandler.instance().getClient().theWorld; + for (int a = 1; a < this.len; a++) { + final MatterCannonFX fx = new MatterCannonFX( + world, this.x + this.dx * a, this.y + this.dy * a, this.z + this.dz * a, Items.diamond); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - catch( final Exception ignored ) - { - } - } + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } catch (final Exception ignored) { + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketMockExplosion.java b/src/main/java/appeng/core/sync/packets/PacketMockExplosion.java index f9e1893c5a6..da31415a713 100644 --- a/src/main/java/appeng/core/sync/packets/PacketMockExplosion.java +++ b/src/main/java/appeng/core/sync/packets/PacketMockExplosion.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.core.CommonHelper; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -29,44 +28,39 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; +public class PacketMockExplosion extends AppEngPacket { -public class PacketMockExplosion extends AppEngPacket -{ - - private final double x; - private final double y; - private final double z; + private final double x; + private final double y; + private final double z; - // automatic. - public PacketMockExplosion( final ByteBuf stream ) - { - this.x = stream.readDouble(); - this.y = stream.readDouble(); - this.z = stream.readDouble(); - } + // automatic. + public PacketMockExplosion(final ByteBuf stream) { + this.x = stream.readDouble(); + this.y = stream.readDouble(); + this.z = stream.readDouble(); + } - // api - public PacketMockExplosion( final double x, final double y, final double z ) - { - this.x = x; - this.y = y; - this.z = z; + // api + public PacketMockExplosion(final double x, final double y, final double z) { + this.x = x; + this.y = y; + this.z = z; - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeDouble( x ); - data.writeDouble( y ); - data.writeDouble( z ); + data.writeInt(this.getPacketID()); + data.writeDouble(x); + data.writeDouble(y); + data.writeDouble(z); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final World world = CommonHelper.proxy.getWorld(); - world.spawnParticle( "largeexplode", this.x, this.y, this.z, 1.0D, 0.0D, 0.0D ); - } + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final World world = CommonHelper.proxy.getWorld(); + world.spawnParticle("largeexplode", this.x, this.y, this.z, 1.0D, 0.0D, 0.0D); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketMultiPart.java b/src/main/java/appeng/core/sync/packets/PacketMultiPart.java index 8bb90b26bb5..9ca2e667d2a 100644 --- a/src/main/java/appeng/core/sync/packets/PacketMultiPart.java +++ b/src/main/java/appeng/core/sync/packets/PacketMultiPart.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.integration.IntegrationRegistry; @@ -30,33 +29,26 @@ import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.common.MinecraftForge; +public class PacketMultiPart extends AppEngPacket { -public class PacketMultiPart extends AppEngPacket -{ - - // automatic. - public PacketMultiPart( final ByteBuf stream ) - { - } + // automatic. + public PacketMultiPart(final ByteBuf stream) {} - // api - public PacketMultiPart() - { - final ByteBuf data = Unpooled.buffer(); + // api + public PacketMultiPart() { + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); + data.writeInt(this.getPacketID()); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final IFMP fmp = (IFMP) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.FMP ); - if( fmp != null ) - { - final EntityPlayerMP sender = (EntityPlayerMP) player; - MinecraftForge.EVENT_BUS.post( fmp.newFMPPacketEvent( sender ) ); // when received it just posts this event. - } - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final IFMP fmp = (IFMP) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.FMP); + if (fmp != null) { + final EntityPlayerMP sender = (EntityPlayerMP) player; + MinecraftForge.EVENT_BUS.post(fmp.newFMPPacketEvent(sender)); // when received it just posts this event. + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketNEIDragClick.java b/src/main/java/appeng/core/sync/packets/PacketNEIDragClick.java index 5a5105a78f5..cdc955de351 100644 --- a/src/main/java/appeng/core/sync/packets/PacketNEIDragClick.java +++ b/src/main/java/appeng/core/sync/packets/PacketNEIDragClick.java @@ -10,54 +10,43 @@ import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; -public class PacketNEIDragClick extends AppEngPacket -{ +public class PacketNEIDragClick extends AppEngPacket { private final ItemStack dragItem; private final int slotIndex; - public PacketNEIDragClick( ItemStack dragItem, int slotIndex ) - { + public PacketNEIDragClick(ItemStack dragItem, int slotIndex) { this.dragItem = dragItem; this.slotIndex = slotIndex; final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); + data.writeInt(this.getPacketID()); - if( this.dragItem != null ) - { - data.writeBoolean( true ); - ByteBufUtils.writeItemStack( data, this.dragItem ); - } - else - { - data.writeBoolean( false ); + if (this.dragItem != null) { + data.writeBoolean(true); + ByteBufUtils.writeItemStack(data, this.dragItem); + } else { + data.writeBoolean(false); } - data.writeInt( this.slotIndex ); - this.configureWrite( data ); + data.writeInt(this.slotIndex); + this.configureWrite(data); } - public PacketNEIDragClick( final ByteBuf stream ) - { - if( stream.readBoolean() ) - { - this.dragItem = ByteBufUtils.readItemStack( stream ); - } - else - { + public PacketNEIDragClick(final ByteBuf stream) { + if (stream.readBoolean()) { + this.dragItem = ByteBufUtils.readItemStack(stream); + } else { this.dragItem = null; } this.slotIndex = stream.readInt(); } @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { final Container c = player.openContainer; - Slot slot = c.getSlot( slotIndex ); - slot.putStack( dragItem ); + Slot slot = c.getSlot(slotIndex); + slot.putStack(dragItem); } - } diff --git a/src/main/java/appeng/core/sync/packets/PacketNEIRecipe.java b/src/main/java/appeng/core/sync/packets/PacketNEIRecipe.java index c3bf32d2140..bfa18a0b217 100644 --- a/src/main/java/appeng/core/sync/packets/PacketNEIRecipe.java +++ b/src/main/java/appeng/core/sync/packets/PacketNEIRecipe.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.api.config.Actionable; import appeng.api.config.FuzzyMode; import appeng.api.config.SecurityPermissions; @@ -41,6 +40,10 @@ import appeng.util.prioitylist.IPartitionList; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Container; @@ -54,219 +57,195 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.oredict.OreDictionary; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; - - -public class PacketNEIRecipe extends AppEngPacket -{ - - private ItemStack[][] recipe; - - // automatic. - public PacketNEIRecipe( final ByteBuf stream ) throws IOException - { - final ByteArrayInputStream bytes = new ByteArrayInputStream( stream.array() ); - bytes.skip( stream.readerIndex() ); - final NBTTagCompound comp = CompressedStreamTools.readCompressed( bytes ); - if( comp != null ) - { - this.recipe = new ItemStack[9][]; - for( int x = 0; x < this.recipe.length; x++ ) - { - final NBTTagList list = comp.getTagList( "#" + x, 10 ); - if( list.tagCount() > 0 ) - { - this.recipe[x] = new ItemStack[list.tagCount()]; - for( int y = 0; y < list.tagCount(); y++ ) - { - this.recipe[x][y] = ItemStack.loadItemStackFromNBT( list.getCompoundTagAt( y ) ); - } - } - } - } - } - - // api - public PacketNEIRecipe( final NBTTagCompound recipe ) throws IOException - { - final ByteBuf data = Unpooled.buffer(); - - final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - final DataOutputStream outputStream = new DataOutputStream( bytes ); - - data.writeInt( this.getPacketID() ); - - CompressedStreamTools.writeCompressed( recipe, outputStream ); - data.writeBytes( bytes.toByteArray() ); - - this.configureWrite( data ); - } - - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final EntityPlayerMP pmp = (EntityPlayerMP) player; - final Container con = pmp.openContainer; - - if( con instanceof IContainerCraftingPacket ) - { - final IContainerCraftingPacket cct = (IContainerCraftingPacket) con; - final IGridNode node = cct.getNetworkNode(); - if( node != null ) - { - final IGrid grid = node.getGrid(); - if( grid == null ) - { - return; - } - - final IStorageGrid inv = grid.getCache( IStorageGrid.class ); - final IEnergyGrid energy = grid.getCache( IEnergyGrid.class ); - final ISecurityGrid security = grid.getCache( ISecurityGrid.class ); - final IInventory craftMatrix = cct.getInventoryByName( "crafting" ); - final IInventory playerInventory = cct.getInventoryByName( "player" ); - - final Actionable realForFake = cct.useRealItems() ? Actionable.MODULATE : Actionable.SIMULATE; - - if( inv != null && this.recipe != null && security != null ) - { - final InventoryCrafting testInv = new InventoryCrafting( new ContainerNull(), 3, 3 ); - for( int x = 0; x < 9; x++ ) - { - if( this.recipe[x] != null && this.recipe[x].length > 0 ) - { - testInv.setInventorySlotContents( x, this.recipe[x][0] ); - } - } - - final IRecipe r = Platform.findMatchingRecipe( testInv, pmp.worldObj ); - - if( r != null && security.hasPermission( player, SecurityPermissions.EXTRACT ) ) - { - final ItemStack is = r.getCraftingResult( testInv ); - - if( is != null ) - { - final IMEMonitor storage = inv.getItemInventory(); - final IItemList all = storage.getStorageList(); - final IPartitionList filter = ItemViewCell.createFilter( cct.getViewCells() ); - - for( int x = 0; x < craftMatrix.getSizeInventory(); x++ ) - { - final ItemStack patternItem = testInv.getStackInSlot( x ); - - ItemStack currentItem = craftMatrix.getStackInSlot( x ); - if( currentItem != null ) - { - testInv.setInventorySlotContents( x, currentItem ); - final ItemStack newItemStack = r.matches( testInv, pmp.worldObj ) ? r.getCraftingResult( testInv ) : null; - testInv.setInventorySlotContents( x, patternItem ); - - if( newItemStack == null || !Platform.isSameItemPrecise( newItemStack, is ) ) - { - final IAEItemStack in = AEItemStack.create( currentItem ); - if( in != null ) - { - final IAEItemStack out = realForFake == Actionable.SIMULATE ? null : Platform.poweredInsert( energy, storage, in, cct.getActionSource() ); - if( out != null ) - { - craftMatrix.setInventorySlotContents( x, out.getItemStack() ); - } - else - { - craftMatrix.setInventorySlotContents( x, null ); - } - - currentItem = craftMatrix.getStackInSlot( x ); - } - } - } - - // True if we need to fetch an item for the recipe - if( patternItem != null && currentItem == null ) - { - // Grab from network by recipe - ItemStack whichItem = Platform.extractItemsByRecipe( energy, cct.getActionSource(), storage, player.worldObj, r, is, testInv, patternItem, x, all, realForFake, filter ); - - // If that doesn't get it, grab exact items from network (?) - // TODO see if this code is necessary - if( whichItem == null ) - { - for( int y = 0; y < this.recipe[x].length; y++ ) - { - final IAEItemStack request = AEItemStack.create( this.recipe[x][y] ); - if( request != null ) - { - if( filter == null || filter.isListed( request ) ) - { - request.setStackSize( 1 ); - final IAEItemStack out = Platform.poweredExtraction( energy, storage, request, cct.getActionSource() ); - if( out != null ) - { - whichItem = out.getItemStack(); - break; - } - } - } - } - } - - // If that doesn't work, grab from the player's inventory - if( whichItem == null && playerInventory != null ) - { - whichItem = this.extractItemFromPlayerInventory( player, realForFake, patternItem ); - } - - craftMatrix.setInventorySlotContents( x, whichItem ); - } - } - con.onCraftMatrixChanged( craftMatrix ); - } - } - } - } - } - } - - /** - * Tries to extract an item from the player inventory. Does account for fuzzy items. - * - * @param player the {@link EntityPlayer} to extract from - * @param mode the {@link Actionable} to simulate or modulate the operation - * @param patternItem which {@link ItemStack} to extract - * @return null or a found {@link ItemStack} - */ - private ItemStack extractItemFromPlayerInventory( final EntityPlayer player, final Actionable mode, final ItemStack patternItem ) - { - final InventoryAdaptor ia = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); - final AEItemStack request = AEItemStack.create( patternItem ); - final boolean isSimulated = mode == Actionable.SIMULATE; - final boolean checkFuzzy = request.isOre() || patternItem.getItemDamage() == OreDictionary.WILDCARD_VALUE || patternItem.hasTagCompound() || patternItem.isItemStackDamageable(); - - if( !checkFuzzy ) - { - if( isSimulated ) - { - return ia.simulateRemove( 1, patternItem, null ); - } - else - { - return ia.removeItems( 1, patternItem, null ); - } - } - else - { - if( isSimulated ) - { - return ia.simulateSimilarRemove( 1, patternItem, FuzzyMode.IGNORE_ALL, null ); - } - else - { - return ia.removeSimilarItems( 1, patternItem, FuzzyMode.IGNORE_ALL, null ); - } - } - } +public class PacketNEIRecipe extends AppEngPacket { + + private ItemStack[][] recipe; + + // automatic. + public PacketNEIRecipe(final ByteBuf stream) throws IOException { + final ByteArrayInputStream bytes = new ByteArrayInputStream(stream.array()); + bytes.skip(stream.readerIndex()); + final NBTTagCompound comp = CompressedStreamTools.readCompressed(bytes); + if (comp != null) { + this.recipe = new ItemStack[9][]; + for (int x = 0; x < this.recipe.length; x++) { + final NBTTagList list = comp.getTagList("#" + x, 10); + if (list.tagCount() > 0) { + this.recipe[x] = new ItemStack[list.tagCount()]; + for (int y = 0; y < list.tagCount(); y++) { + this.recipe[x][y] = ItemStack.loadItemStackFromNBT(list.getCompoundTagAt(y)); + } + } + } + } + } + + // api + public PacketNEIRecipe(final NBTTagCompound recipe) throws IOException { + final ByteBuf data = Unpooled.buffer(); + + final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + final DataOutputStream outputStream = new DataOutputStream(bytes); + + data.writeInt(this.getPacketID()); + + CompressedStreamTools.writeCompressed(recipe, outputStream); + data.writeBytes(bytes.toByteArray()); + + this.configureWrite(data); + } + + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final EntityPlayerMP pmp = (EntityPlayerMP) player; + final Container con = pmp.openContainer; + + if (con instanceof IContainerCraftingPacket) { + final IContainerCraftingPacket cct = (IContainerCraftingPacket) con; + final IGridNode node = cct.getNetworkNode(); + if (node != null) { + final IGrid grid = node.getGrid(); + if (grid == null) { + return; + } + + final IStorageGrid inv = grid.getCache(IStorageGrid.class); + final IEnergyGrid energy = grid.getCache(IEnergyGrid.class); + final ISecurityGrid security = grid.getCache(ISecurityGrid.class); + final IInventory craftMatrix = cct.getInventoryByName("crafting"); + final IInventory playerInventory = cct.getInventoryByName("player"); + + final Actionable realForFake = cct.useRealItems() ? Actionable.MODULATE : Actionable.SIMULATE; + + if (inv != null && this.recipe != null && security != null) { + final InventoryCrafting testInv = new InventoryCrafting(new ContainerNull(), 3, 3); + for (int x = 0; x < 9; x++) { + if (this.recipe[x] != null && this.recipe[x].length > 0) { + testInv.setInventorySlotContents(x, this.recipe[x][0]); + } + } + + final IRecipe r = Platform.findMatchingRecipe(testInv, pmp.worldObj); + + if (r != null && security.hasPermission(player, SecurityPermissions.EXTRACT)) { + final ItemStack is = r.getCraftingResult(testInv); + + if (is != null) { + final IMEMonitor storage = inv.getItemInventory(); + final IItemList all = storage.getStorageList(); + final IPartitionList filter = ItemViewCell.createFilter(cct.getViewCells()); + + for (int x = 0; x < craftMatrix.getSizeInventory(); x++) { + final ItemStack patternItem = testInv.getStackInSlot(x); + + ItemStack currentItem = craftMatrix.getStackInSlot(x); + if (currentItem != null) { + testInv.setInventorySlotContents(x, currentItem); + final ItemStack newItemStack = + r.matches(testInv, pmp.worldObj) ? r.getCraftingResult(testInv) : null; + testInv.setInventorySlotContents(x, patternItem); + + if (newItemStack == null || !Platform.isSameItemPrecise(newItemStack, is)) { + final IAEItemStack in = AEItemStack.create(currentItem); + if (in != null) { + final IAEItemStack out = realForFake == Actionable.SIMULATE + ? null + : Platform.poweredInsert( + energy, storage, in, cct.getActionSource()); + if (out != null) { + craftMatrix.setInventorySlotContents(x, out.getItemStack()); + } else { + craftMatrix.setInventorySlotContents(x, null); + } + + currentItem = craftMatrix.getStackInSlot(x); + } + } + } + + // True if we need to fetch an item for the recipe + if (patternItem != null && currentItem == null) { + // Grab from network by recipe + ItemStack whichItem = Platform.extractItemsByRecipe( + energy, + cct.getActionSource(), + storage, + player.worldObj, + r, + is, + testInv, + patternItem, + x, + all, + realForFake, + filter); + + // If that doesn't get it, grab exact items from network (?) + // TODO see if this code is necessary + if (whichItem == null) { + for (int y = 0; y < this.recipe[x].length; y++) { + final IAEItemStack request = AEItemStack.create(this.recipe[x][y]); + if (request != null) { + if (filter == null || filter.isListed(request)) { + request.setStackSize(1); + final IAEItemStack out = Platform.poweredExtraction( + energy, storage, request, cct.getActionSource()); + if (out != null) { + whichItem = out.getItemStack(); + break; + } + } + } + } + } + + // If that doesn't work, grab from the player's inventory + if (whichItem == null && playerInventory != null) { + whichItem = + this.extractItemFromPlayerInventory(player, realForFake, patternItem); + } + + craftMatrix.setInventorySlotContents(x, whichItem); + } + } + con.onCraftMatrixChanged(craftMatrix); + } + } + } + } + } + } + + /** + * Tries to extract an item from the player inventory. Does account for fuzzy items. + * + * @param player the {@link EntityPlayer} to extract from + * @param mode the {@link Actionable} to simulate or modulate the operation + * @param patternItem which {@link ItemStack} to extract + * @return null or a found {@link ItemStack} + */ + private ItemStack extractItemFromPlayerInventory( + final EntityPlayer player, final Actionable mode, final ItemStack patternItem) { + final InventoryAdaptor ia = InventoryAdaptor.getAdaptor(player, ForgeDirection.UNKNOWN); + final AEItemStack request = AEItemStack.create(patternItem); + final boolean isSimulated = mode == Actionable.SIMULATE; + final boolean checkFuzzy = request.isOre() + || patternItem.getItemDamage() == OreDictionary.WILDCARD_VALUE + || patternItem.hasTagCompound() + || patternItem.isItemStackDamageable(); + + if (!checkFuzzy) { + if (isSimulated) { + return ia.simulateRemove(1, patternItem, null); + } else { + return ia.removeItems(1, patternItem, null); + } + } else { + if (isSimulated) { + return ia.simulateSimilarRemove(1, patternItem, FuzzyMode.IGNORE_ALL, null); + } else { + return ia.removeSimilarItems(1, patternItem, FuzzyMode.IGNORE_ALL, null); + } + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketNewStorageDimension.java b/src/main/java/appeng/core/sync/packets/PacketNewStorageDimension.java index 29e911ba820..b191d017453 100644 --- a/src/main/java/appeng/core/sync/packets/PacketNewStorageDimension.java +++ b/src/main/java/appeng/core/sync/packets/PacketNewStorageDimension.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.core.AEConfig; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -29,42 +28,34 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.common.DimensionManager; +public class PacketNewStorageDimension extends AppEngPacket { -public class PacketNewStorageDimension extends AppEngPacket -{ - - private final int newDim; + private final int newDim; - // automatic. - public PacketNewStorageDimension( final ByteBuf stream ) - { - this.newDim = stream.readInt(); - } + // automatic. + public PacketNewStorageDimension(final ByteBuf stream) { + this.newDim = stream.readInt(); + } - // api - public PacketNewStorageDimension( final int newDim ) - { - this.newDim = newDim; + // api + public PacketNewStorageDimension(final int newDim) { + this.newDim = newDim; - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( newDim ); + data.writeInt(this.getPacketID()); + data.writeInt(newDim); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - try - { - DimensionManager.registerDimension( this.newDim, AEConfig.instance.storageProviderID ); - } - catch( final IllegalArgumentException iae ) - { - // ok! - } - } + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + try { + DimensionManager.registerDimension(this.newDim, AEConfig.instance.storageProviderID); + } catch (final IllegalArgumentException iae) { + // ok! + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketPaintedEntity.java b/src/main/java/appeng/core/sync/packets/PacketPaintedEntity.java index 78ff4387811..4b844c28a53 100644 --- a/src/main/java/appeng/core/sync/packets/PacketPaintedEntity.java +++ b/src/main/java/appeng/core/sync/packets/PacketPaintedEntity.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.api.util.AEColor; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -28,40 +27,35 @@ import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; +public class PacketPaintedEntity extends AppEngPacket { -public class PacketPaintedEntity extends AppEngPacket -{ - - private final AEColor myColor; - private final int entityId; - private int ticks; + private final AEColor myColor; + private final int entityId; + private int ticks; - // automatic. - public PacketPaintedEntity( final ByteBuf stream ) - { - this.entityId = stream.readInt(); - this.myColor = AEColor.values()[stream.readByte()]; - this.ticks = stream.readInt(); - } + // automatic. + public PacketPaintedEntity(final ByteBuf stream) { + this.entityId = stream.readInt(); + this.myColor = AEColor.values()[stream.readByte()]; + this.ticks = stream.readInt(); + } - // api - public PacketPaintedEntity( final int myEntity, final AEColor myColor, final int ticksLeft ) - { + // api + public PacketPaintedEntity(final int myEntity, final AEColor myColor, final int ticksLeft) { - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( this.entityId = myEntity ); - data.writeByte( ( this.myColor = myColor ).ordinal() ); - data.writeInt( ticksLeft ); + data.writeInt(this.getPacketID()); + data.writeInt(this.entityId = myEntity); + data.writeByte((this.myColor = myColor).ordinal()); + data.writeInt(ticksLeft); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final PlayerColor pc = new PlayerColor( this.entityId, this.myColor, this.ticks ); - TickHandler.INSTANCE.getPlayerColors().put( this.entityId, pc ); - } + @Override + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final PlayerColor pc = new PlayerColor(this.entityId, this.myColor, this.ticks); + TickHandler.INSTANCE.getPlayerColors().put(this.entityId, pc); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketPartPlacement.java b/src/main/java/appeng/core/sync/packets/PacketPartPlacement.java index 3a6f3557fc5..25b0fcf191d 100644 --- a/src/main/java/appeng/core/sync/packets/PacketPartPlacement.java +++ b/src/main/java/appeng/core/sync/packets/PacketPartPlacement.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.core.CommonHelper; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -28,48 +27,52 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; +public class PacketPartPlacement extends AppEngPacket { -public class PacketPartPlacement extends AppEngPacket -{ - - private int x; - private int y; - private int z; - private int face; - private float eyeHeight; + private int x; + private int y; + private int z; + private int face; + private float eyeHeight; - // automatic. - public PacketPartPlacement( final ByteBuf stream ) - { - this.x = stream.readInt(); - this.y = stream.readInt(); - this.z = stream.readInt(); - this.face = stream.readByte(); - this.eyeHeight = stream.readFloat(); - } + // automatic. + public PacketPartPlacement(final ByteBuf stream) { + this.x = stream.readInt(); + this.y = stream.readInt(); + this.z = stream.readInt(); + this.face = stream.readByte(); + this.eyeHeight = stream.readFloat(); + } - // api - public PacketPartPlacement( final int x, final int y, final int z, final int face, final float eyeHeight ) - { - final ByteBuf data = Unpooled.buffer(); + // api + public PacketPartPlacement(final int x, final int y, final int z, final int face, final float eyeHeight) { + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( x ); - data.writeInt( y ); - data.writeInt( z ); - data.writeByte( face ); - data.writeFloat( eyeHeight ); + data.writeInt(this.getPacketID()); + data.writeInt(x); + data.writeInt(y); + data.writeInt(z); + data.writeByte(face); + data.writeFloat(eyeHeight); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final EntityPlayerMP sender = (EntityPlayerMP) player; - CommonHelper.proxy.updateRenderMode( sender ); - PartPlacement.setEyeHeight( this.eyeHeight ); - PartPlacement.place( sender.getHeldItem(), this.x, this.y, this.z, this.face, sender, sender.worldObj, PartPlacement.PlaceType.INTERACT_FIRST_PASS, 0 ); - CommonHelper.proxy.updateRenderMode( null ); - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final EntityPlayerMP sender = (EntityPlayerMP) player; + CommonHelper.proxy.updateRenderMode(sender); + PartPlacement.setEyeHeight(this.eyeHeight); + PartPlacement.place( + sender.getHeldItem(), + this.x, + this.y, + this.z, + this.face, + sender, + sender.worldObj, + PartPlacement.PlaceType.INTERACT_FIRST_PASS, + 0); + CommonHelper.proxy.updateRenderMode(null); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketPartialItem.java b/src/main/java/appeng/core/sync/packets/PacketPartialItem.java index 1fd9e0fcf3b..4af81b6dc1a 100644 --- a/src/main/java/appeng/core/sync/packets/PacketPartialItem.java +++ b/src/main/java/appeng/core/sync/packets/PacketPartialItem.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.container.AEBaseContainer; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -26,57 +25,48 @@ import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; +public class PacketPartialItem extends AppEngPacket { -public class PacketPartialItem extends AppEngPacket -{ - - private final short pageNum; - private final byte[] data; + private final short pageNum; + private final byte[] data; - // automatic. - public PacketPartialItem( final ByteBuf stream ) - { - this.pageNum = stream.readShort(); - stream.readBytes( this.data = new byte[stream.readableBytes()] ); - } + // automatic. + public PacketPartialItem(final ByteBuf stream) { + this.pageNum = stream.readShort(); + stream.readBytes(this.data = new byte[stream.readableBytes()]); + } - // api - public PacketPartialItem( final int page, final int maxPages, final byte[] buf ) - { + // api + public PacketPartialItem(final int page, final int maxPages, final byte[] buf) { - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - this.pageNum = (short) ( page | ( maxPages << 8 ) ); - this.data = buf; - data.writeInt( this.getPacketID() ); - data.writeShort( this.pageNum ); - data.writeBytes( buf ); + this.pageNum = (short) (page | (maxPages << 8)); + this.data = buf; + data.writeInt(this.getPacketID()); + data.writeShort(this.pageNum); + data.writeBytes(buf); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - if( player.openContainer instanceof AEBaseContainer ) - { - ( (AEBaseContainer) player.openContainer ).postPartial( this ); - } - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + if (player.openContainer instanceof AEBaseContainer) { + ((AEBaseContainer) player.openContainer).postPartial(this); + } + } - public int getPageCount() - { - return this.pageNum >> 8; - } + public int getPageCount() { + return this.pageNum >> 8; + } - public int getSize() - { - return this.data.length; - } + public int getSize() { + return this.data.length; + } - public int write( final byte[] buffer, final int cursor ) - { - System.arraycopy( this.data, 0, buffer, cursor, this.data.length ); - return cursor + this.data.length; - } + public int write(final byte[] buffer, final int cursor) { + System.arraycopy(this.data, 0, buffer, cursor, this.data.length); + return cursor + this.data.length; + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketPatternSlot.java b/src/main/java/appeng/core/sync/packets/PacketPatternSlot.java index 02a2dfa6b70..6879b0a967b 100644 --- a/src/main/java/appeng/core/sync/packets/PacketPatternSlot.java +++ b/src/main/java/appeng/core/sync/packets/PacketPatternSlot.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.api.AEApi; import appeng.api.storage.data.IAEItemStack; import appeng.container.implementations.ContainerPatternTerm; @@ -27,92 +26,78 @@ import appeng.util.item.AEItemStack; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.IInventory; -import java.io.IOException; - - -public class PacketPatternSlot extends AppEngPacket -{ +public class PacketPatternSlot extends AppEngPacket { - public final IAEItemStack slotItem; + public final IAEItemStack slotItem; - public final IAEItemStack[] pattern = new IAEItemStack[9]; + public final IAEItemStack[] pattern = new IAEItemStack[9]; - public final boolean shift; + public final boolean shift; - // automatic. - public PacketPatternSlot( final ByteBuf stream ) throws IOException - { + // automatic. + public PacketPatternSlot(final ByteBuf stream) throws IOException { - this.shift = stream.readBoolean(); + this.shift = stream.readBoolean(); - this.slotItem = this.readItem( stream ); + this.slotItem = this.readItem(stream); - for( int x = 0; x < 9; x++ ) - { - this.pattern[x] = this.readItem( stream ); - } - } + for (int x = 0; x < 9; x++) { + this.pattern[x] = this.readItem(stream); + } + } - private IAEItemStack readItem( final ByteBuf stream ) throws IOException - { - final boolean hasItem = stream.readBoolean(); + private IAEItemStack readItem(final ByteBuf stream) throws IOException { + final boolean hasItem = stream.readBoolean(); - if( hasItem ) - { - return AEItemStack.loadItemStackFromPacket( stream ); - } + if (hasItem) { + return AEItemStack.loadItemStackFromPacket(stream); + } - return null; - } + return null; + } - // api - public PacketPatternSlot( final IInventory pat, final IAEItemStack slotItem, final boolean shift ) throws IOException - { + // api + public PacketPatternSlot(final IInventory pat, final IAEItemStack slotItem, final boolean shift) + throws IOException { - this.slotItem = slotItem; - this.shift = shift; + this.slotItem = slotItem; + this.shift = shift; - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); + data.writeInt(this.getPacketID()); - data.writeBoolean( shift ); + data.writeBoolean(shift); - this.writeItem( slotItem, data ); - for( int x = 0; x < 9; x++ ) - { - this.pattern[x] = AEApi.instance().storage().createItemStack( pat.getStackInSlot( x ) ); - this.writeItem( this.pattern[x], data ); - } + this.writeItem(slotItem, data); + for (int x = 0; x < 9; x++) { + this.pattern[x] = AEApi.instance().storage().createItemStack(pat.getStackInSlot(x)); + this.writeItem(this.pattern[x], data); + } - this.configureWrite( data ); - } + this.configureWrite(data); + } - private void writeItem( final IAEItemStack slotItem, final ByteBuf data ) throws IOException - { - if( slotItem == null ) - { - data.writeBoolean( false ); - } - else - { - data.writeBoolean( true ); - slotItem.writeToPacket( data ); - } - } + private void writeItem(final IAEItemStack slotItem, final ByteBuf data) throws IOException { + if (slotItem == null) { + data.writeBoolean(false); + } else { + data.writeBoolean(true); + slotItem.writeToPacket(data); + } + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final EntityPlayerMP sender = (EntityPlayerMP) player; - if( sender.openContainer instanceof ContainerPatternTerm ) - { - final ContainerPatternTerm patternTerminal = (ContainerPatternTerm) sender.openContainer; - patternTerminal.craftOrGetItem( this ); - } - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final EntityPlayerMP sender = (EntityPlayerMP) player; + if (sender.openContainer instanceof ContainerPatternTerm) { + final ContainerPatternTerm patternTerminal = (ContainerPatternTerm) sender.openContainer; + patternTerminal.craftOrGetItem(this); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketPatternValueSet.java b/src/main/java/appeng/core/sync/packets/PacketPatternValueSet.java index 9bb22365c18..a0005e78f27 100644 --- a/src/main/java/appeng/core/sync/packets/PacketPatternValueSet.java +++ b/src/main/java/appeng/core/sync/packets/PacketPatternValueSet.java @@ -16,56 +16,47 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -public class PacketPatternValueSet extends AppEngPacket -{ +public class PacketPatternValueSet extends AppEngPacket { private final GuiBridge originGui; private final int amount; private final int valueIndex; - public PacketPatternValueSet( final ByteBuf stream ) - { + public PacketPatternValueSet(final ByteBuf stream) { this.originGui = GuiBridge.values()[stream.readInt()]; this.amount = stream.readInt(); this.valueIndex = stream.readInt(); } - public PacketPatternValueSet( int originalGui, int amount, int valueIndex ) - { + public PacketPatternValueSet(int originalGui, int amount, int valueIndex) { this.originGui = GuiBridge.values()[originalGui]; this.amount = amount; this.valueIndex = valueIndex; final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( originalGui ); - data.writeInt( this.amount ); - data.writeInt( this.valueIndex ); - - this.configureWrite( data ); + data.writeInt(this.getPacketID()); + data.writeInt(originalGui); + data.writeInt(this.amount); + data.writeInt(this.valueIndex); + this.configureWrite(data); } @Override - public void serverPacketData( INetworkInfo manager, AppEngPacket packet, EntityPlayer player ) - { - if( player.openContainer instanceof ContainerPatternValueAmount ) - { + public void serverPacketData(INetworkInfo manager, AppEngPacket packet, EntityPlayer player) { + if (player.openContainer instanceof ContainerPatternValueAmount) { ContainerPatternValueAmount cpv = (ContainerPatternValueAmount) player.openContainer; final Object target = cpv.getTarget(); - if( target instanceof IGridHost ) - { + if (target instanceof IGridHost) { final ContainerOpenContext context = cpv.getOpenContext(); - if( context != null ) - { + if (context != null) { final TileEntity te = context.getTile(); - Platform.openGUI( player, te, cpv.getOpenContext().getSide(), originGui ); - if( player.openContainer instanceof ContainerPatternTerm || player.openContainer instanceof ContainerPatternTermEx ) - { - Slot slot = player.openContainer.getSlot( valueIndex ); - if( slot != null && slot.getHasStack() ) - { + Platform.openGUI(player, te, cpv.getOpenContext().getSide(), originGui); + if (player.openContainer instanceof ContainerPatternTerm + || player.openContainer instanceof ContainerPatternTermEx) { + Slot slot = player.openContainer.getSlot(valueIndex); + if (slot != null && slot.getHasStack()) { ItemStack nextStack = slot.getStack().copy(); nextStack.stackSize = amount; slot.putStack(nextStack); diff --git a/src/main/java/appeng/core/sync/packets/PacketProgressBar.java b/src/main/java/appeng/core/sync/packets/PacketProgressBar.java index 4c0ec163cab..205766a59dc 100644 --- a/src/main/java/appeng/core/sync/packets/PacketProgressBar.java +++ b/src/main/java/appeng/core/sync/packets/PacketProgressBar.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.container.AEBaseContainer; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -27,52 +26,44 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; +public class PacketProgressBar extends AppEngPacket { -public class PacketProgressBar extends AppEngPacket -{ - - private final short id; - private final long value; + private final short id; + private final long value; - // automatic. - public PacketProgressBar( final ByteBuf stream ) - { - this.id = stream.readShort(); - this.value = stream.readLong(); - } + // automatic. + public PacketProgressBar(final ByteBuf stream) { + this.id = stream.readShort(); + this.value = stream.readLong(); + } - // api - public PacketProgressBar( final int shortID, final long value ) - { - this.id = (short) shortID; - this.value = value; + // api + public PacketProgressBar(final int shortID, final long value) { + this.id = (short) shortID; + this.value = value; - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeShort( shortID ); - data.writeLong( value ); + data.writeInt(this.getPacketID()); + data.writeShort(shortID); + data.writeLong(value); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; - if( c instanceof AEBaseContainer ) - { - ( (AEBaseContainer) c ).updateFullProgressBar( this.id, this.value ); - } - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final Container c = player.openContainer; + if (c instanceof AEBaseContainer) { + ((AEBaseContainer) c).updateFullProgressBar(this.id, this.value); + } + } - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; - if( c instanceof AEBaseContainer ) - { - ( (AEBaseContainer) c ).updateFullProgressBar( this.id, this.value ); - } - } + @Override + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final Container c = player.openContainer; + if (c instanceof AEBaseContainer) { + ((AEBaseContainer) c).updateFullProgressBar(this.id, this.value); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketSwapSlots.java b/src/main/java/appeng/core/sync/packets/PacketSwapSlots.java index d8aff31a3c9..a9b6f3e6c34 100644 --- a/src/main/java/appeng/core/sync/packets/PacketSwapSlots.java +++ b/src/main/java/appeng/core/sync/packets/PacketSwapSlots.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.container.AEBaseContainer; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -26,38 +25,32 @@ import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; +public class PacketSwapSlots extends AppEngPacket { -public class PacketSwapSlots extends AppEngPacket -{ - - private final int slotA; - private final int slotB; + private final int slotA; + private final int slotB; - // automatic. - public PacketSwapSlots( final ByteBuf stream ) - { - this.slotA = stream.readInt(); - this.slotB = stream.readInt(); - } + // automatic. + public PacketSwapSlots(final ByteBuf stream) { + this.slotA = stream.readInt(); + this.slotB = stream.readInt(); + } - // api - public PacketSwapSlots( final int slotA, final int slotB ) - { - final ByteBuf data = Unpooled.buffer(); + // api + public PacketSwapSlots(final int slotA, final int slotB) { + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( this.slotA = slotA ); - data.writeInt( this.slotB = slotB ); + data.writeInt(this.getPacketID()); + data.writeInt(this.slotA = slotA); + data.writeInt(this.slotB = slotB); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - if( player != null && player.openContainer instanceof AEBaseContainer ) - { - ( (AEBaseContainer) player.openContainer ).swapSlotContents( this.slotA, this.slotB ); - } - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + if (player != null && player.openContainer instanceof AEBaseContainer) { + ((AEBaseContainer) player.openContainer).swapSlotContents(this.slotA, this.slotB); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketSwitchGuis.java b/src/main/java/appeng/core/sync/packets/PacketSwitchGuis.java index 388e9a3bffb..0c744e25166 100644 --- a/src/main/java/appeng/core/sync/packets/PacketSwitchGuis.java +++ b/src/main/java/appeng/core/sync/packets/PacketSwitchGuis.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.client.gui.AEBaseGui; import appeng.container.AEBaseContainer; import appeng.container.ContainerOpenContext; @@ -32,55 +31,46 @@ import net.minecraft.inventory.Container; import net.minecraft.tileentity.TileEntity; +public class PacketSwitchGuis extends AppEngPacket { -public class PacketSwitchGuis extends AppEngPacket -{ - - private final GuiBridge newGui; + private final GuiBridge newGui; - // automatic. - public PacketSwitchGuis( final ByteBuf stream ) - { - this.newGui = GuiBridge.values()[stream.readInt()]; - } + // automatic. + public PacketSwitchGuis(final ByteBuf stream) { + this.newGui = GuiBridge.values()[stream.readInt()]; + } - // api - public PacketSwitchGuis( final GuiBridge newGui ) - { - this.newGui = newGui; + // api + public PacketSwitchGuis(final GuiBridge newGui) { + this.newGui = newGui; - if( Platform.isClient() ) - { - AEBaseGui.setSwitchingGuis( true ); - } + if (Platform.isClient()) { + AEBaseGui.setSwitchingGuis(true); + } - final ByteBuf data = Unpooled.buffer(); + final ByteBuf data = Unpooled.buffer(); - data.writeInt( this.getPacketID() ); - data.writeInt( newGui.ordinal() ); + data.writeInt(this.getPacketID()); + data.writeInt(newGui.ordinal()); - this.configureWrite( data ); - } + this.configureWrite(data); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; - if( c instanceof AEBaseContainer ) - { - final AEBaseContainer bc = (AEBaseContainer) c; - final ContainerOpenContext context = bc.getOpenContext(); - if( context != null ) - { - final TileEntity te = context.getTile(); - Platform.openGUI( player, te, context.getSide(), this.newGui ); - } - } - } + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final Container c = player.openContainer; + if (c instanceof AEBaseContainer) { + final AEBaseContainer bc = (AEBaseContainer) c; + final ContainerOpenContext context = bc.getOpenContext(); + if (context != null) { + final TileEntity te = context.getTile(); + Platform.openGUI(player, te, context.getSide(), this.newGui); + } + } + } - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - AEBaseGui.setSwitchingGuis( true ); - } + @Override + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + AEBaseGui.setSwitchingGuis(true); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java b/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java index cfd56b85cce..1864085b99a 100644 --- a/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java +++ b/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.client.ClientHelper; import appeng.client.render.effects.EnergyFx; import appeng.core.CommonHelper; @@ -38,77 +37,91 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; - -public class PacketTransitionEffect extends AppEngPacket -{ - - private final boolean mode; - private final double x; - private final double y; - private final double z; - private final ForgeDirection d; - - // automatic. - public PacketTransitionEffect( final ByteBuf stream ) - { - this.x = stream.readFloat(); - this.y = stream.readFloat(); - this.z = stream.readFloat(); - this.d = ForgeDirection.getOrientation( stream.readByte() ); - this.mode = stream.readBoolean(); - } - - // api - public PacketTransitionEffect( final double x, final double y, final double z, final ForgeDirection dir, final boolean wasBlock ) - { - this.x = x; - this.y = y; - this.z = z; - this.d = dir; - this.mode = wasBlock; - - final ByteBuf data = Unpooled.buffer(); - - data.writeInt( this.getPacketID() ); - data.writeFloat( (float) x ); - data.writeFloat( (float) y ); - data.writeFloat( (float) z ); - data.writeByte( this.d.ordinal() ); - data.writeBoolean( wasBlock ); - - this.configureWrite( data ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final World world = ClientHelper.proxy.getWorld(); - - for( int zz = 0; zz < ( this.mode ? 32 : 8 ); zz++ ) - { - if( CommonHelper.proxy.shouldAddParticles( Platform.getRandom() ) ) - { - final EnergyFx fx = new EnergyFx( world, this.x + ( this.mode ? ( Platform.getRandomInt() % 100 ) * 0.01 : ( Platform.getRandomInt() % 100 ) * 0.005 - 0.25 ), this.y + ( this.mode ? ( Platform.getRandomInt() % 100 ) * 0.01 : ( Platform.getRandomInt() % 100 ) * 0.005 - 0.25 ), this.z + ( this.mode ? ( Platform.getRandomInt() % 100 ) * 0.01 : ( Platform.getRandomInt() % 100 ) * 0.005 - 0.25 ), Items.diamond ); - - if( !this.mode ) - { - fx.fromItem( this.d ); - } - - fx.motionX = -0.1 * this.d.offsetX; - fx.motionY = -0.1 * this.d.offsetY; - fx.motionZ = -0.1 * this.d.offsetZ; - - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - - if( this.mode ) - { - final Block block = world.getBlock( (int) this.x, (int) this.y, (int) this.z ); - - Minecraft.getMinecraft().getSoundHandler().playSound( new PositionedSoundRecord( new ResourceLocation( block.stepSound.getBreakSound() ), ( block.stepSound.getVolume() + 1.0F ) / 2.0F, block.stepSound.getPitch() * 0.8F, (float) this.x + 0.5F, (float) this.y + 0.5F, (float) this.z + 0.5F ) ); - } - } +public class PacketTransitionEffect extends AppEngPacket { + + private final boolean mode; + private final double x; + private final double y; + private final double z; + private final ForgeDirection d; + + // automatic. + public PacketTransitionEffect(final ByteBuf stream) { + this.x = stream.readFloat(); + this.y = stream.readFloat(); + this.z = stream.readFloat(); + this.d = ForgeDirection.getOrientation(stream.readByte()); + this.mode = stream.readBoolean(); + } + + // api + public PacketTransitionEffect( + final double x, final double y, final double z, final ForgeDirection dir, final boolean wasBlock) { + this.x = x; + this.y = y; + this.z = z; + this.d = dir; + this.mode = wasBlock; + + final ByteBuf data = Unpooled.buffer(); + + data.writeInt(this.getPacketID()); + data.writeFloat((float) x); + data.writeFloat((float) y); + data.writeFloat((float) z); + data.writeByte(this.d.ordinal()); + data.writeBoolean(wasBlock); + + this.configureWrite(data); + } + + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final World world = ClientHelper.proxy.getWorld(); + + for (int zz = 0; zz < (this.mode ? 32 : 8); zz++) { + if (CommonHelper.proxy.shouldAddParticles(Platform.getRandom())) { + final EnergyFx fx = new EnergyFx( + world, + this.x + + (this.mode + ? (Platform.getRandomInt() % 100) * 0.01 + : (Platform.getRandomInt() % 100) * 0.005 - 0.25), + this.y + + (this.mode + ? (Platform.getRandomInt() % 100) * 0.01 + : (Platform.getRandomInt() % 100) * 0.005 - 0.25), + this.z + + (this.mode + ? (Platform.getRandomInt() % 100) * 0.01 + : (Platform.getRandomInt() % 100) * 0.005 - 0.25), + Items.diamond); + + if (!this.mode) { + fx.fromItem(this.d); + } + + fx.motionX = -0.1 * this.d.offsetX; + fx.motionY = -0.1 * this.d.offsetY; + fx.motionZ = -0.1 * this.d.offsetZ; + + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } + + if (this.mode) { + final Block block = world.getBlock((int) this.x, (int) this.y, (int) this.z); + + Minecraft.getMinecraft() + .getSoundHandler() + .playSound(new PositionedSoundRecord( + new ResourceLocation(block.stepSound.getBreakSound()), + (block.stepSound.getVolume() + 1.0F) / 2.0F, + block.stepSound.getPitch() * 0.8F, + (float) this.x + 0.5F, + (float) this.y + 0.5F, + (float) this.z + 0.5F)); + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketValueConfig.java b/src/main/java/appeng/core/sync/packets/PacketValueConfig.java index cbf410d0569..98f4eae7811 100644 --- a/src/main/java/appeng/core/sync/packets/PacketValueConfig.java +++ b/src/main/java/appeng/core/sync/packets/PacketValueConfig.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.api.config.FuzzyMode; import appeng.api.config.Settings; import appeng.api.util.IConfigManager; @@ -32,282 +31,190 @@ import appeng.helpers.IMouseWheelItem; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import java.io.*; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.item.ItemStack; -import java.io.*; - - -public class PacketValueConfig extends AppEngPacket -{ - - private final String Name; - private final String Value; - - // automatic. - public PacketValueConfig( final ByteBuf stream ) throws IOException - { - final DataInputStream dis = new DataInputStream( new ByteArrayInputStream( stream.array(), stream.readerIndex(), stream.readableBytes() ) ); - this.Name = dis.readUTF(); - this.Value = dis.readUTF(); - // dis.close(); - } - - // api - public PacketValueConfig( final String name, final String value ) throws IOException - { - this.Name = name; - this.Value = value; - - final ByteBuf data = Unpooled.buffer(); - - data.writeInt( this.getPacketID() ); - - final ByteArrayOutputStream bos = new ByteArrayOutputStream(); - final DataOutputStream dos = new DataOutputStream( bos ); - dos.writeUTF( name ); - dos.writeUTF( value ); - // dos.close(); - - data.writeBytes( bos.toByteArray() ); - - this.configureWrite( data ); - } - - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; - - if( this.Name.equals( "Item" ) && player.getHeldItem() != null && player.getHeldItem().getItem() instanceof IMouseWheelItem ) - { - final ItemStack is = player.getHeldItem(); - final IMouseWheelItem si = (IMouseWheelItem) is.getItem(); - si.onWheel( is, this.Value.equals( "WheelUp" ) ); - } - else if( this.Name.equals( "CPUTable.Cpu.Set" ) && c instanceof ICraftingCPUSelectorContainer ) - { - final ICraftingCPUSelectorContainer qk = (ICraftingCPUSelectorContainer) c; - qk.selectCPU( Integer.parseInt( this.Value ) ); - } - else if( this.Name.equals( "Terminal.Start" ) && c instanceof ContainerCraftConfirm ) - { - final ContainerCraftConfirm qk = (ContainerCraftConfirm) c; - qk.startJob(); - } - else if( this.Name.equals( "TileCrafting.Cancel" ) && c instanceof ContainerCraftingCPU ) - { - final ContainerCraftingCPU qk = (ContainerCraftingCPU) c; - qk.cancelCrafting(); - } - else if( this.Name.equals( "QuartzKnife.Name" ) && c instanceof ContainerQuartzKnife ) - { - final ContainerQuartzKnife qk = (ContainerQuartzKnife) c; - qk.setName( this.Value ); - } - else if( this.Name.equals( "QuartzKnife.ReName" ) && c instanceof ContainerRenamer ) - { - final ContainerRenamer qk = (ContainerRenamer) c; - qk.setNewName( this.Value ); - } - else if( this.Name.equals( "TileSecurity.ToggleOption" ) && c instanceof ContainerSecurity ) - { - final ContainerSecurity sc = (ContainerSecurity) c; - sc.toggleSetting( this.Value, player ); - } - else if( this.Name.equals( "PriorityHost.Priority" ) && c instanceof ContainerPriority ) - { - final ContainerPriority pc = (ContainerPriority) c; - pc.setPriority( Integer.parseInt( this.Value ), player ); - } - else if( this.Name.equals( "OreFilter" ) && c instanceof ContainerOreFilter ) - { - final ContainerOreFilter fc = (ContainerOreFilter) c; - fc.setFilter(this.Value); - } - else if( this.Name.equals( "LevelEmitter.Value" ) && c instanceof ContainerLevelEmitter ) - { - final ContainerLevelEmitter lvc = (ContainerLevelEmitter) c; - lvc.setLevel( Long.parseLong( this.Value ), player ); - } - else if( this.Name.startsWith( "PatternTerminal." ) && c instanceof ContainerPatternTerm ) - { - final ContainerPatternTerm cpt = (ContainerPatternTerm) c; - if( this.Name.equals( "PatternTerminal.CraftMode" ) ) - { - cpt.getPatternTerminal().setCraftingRecipe( this.Value.equals( "1" ) ); - } - else if( this.Name.equals( "PatternTerminal.Encode" ) ) - { - if (this.Value.equals( "2" )) - cpt.encodeAndMoveToInventory(false); - else if (this.Value.equals( "6" )) - cpt.encodeAndMoveToInventory(true); - else - cpt.encode(); - } - else if( this.Name.equals( "PatternTerminal.Clear" ) ) - { - cpt.clear(); - } - else if( this.Name.equals( "PatternTerminal.Substitute" ) ) - { - cpt.getPatternTerminal().setSubstitution( this.Value.equals( "1" ) ); - } - else if( this.Name.equals( "PatternTerminal.Double" ) ) - { - cpt.doubleStacks(Value.equals( "1" )); - } - } - else if( this.Name.startsWith( "PatternTerminalEx." ) && c instanceof ContainerPatternTermEx ) - { - final ContainerPatternTermEx cpt = (ContainerPatternTermEx) c; - if( this.Name.equals( "PatternTerminalEx.Encode" ) ) - { - if (this.Value.equals( "2" )) - cpt.encodeAndMoveToInventory(false); - else if (this.Value.equals( "6" )) - cpt.encodeAndMoveToInventory(true); - else - cpt.encode(); - } - else if( this.Name.equals( "PatternTerminalEx.Clear" ) ) - { - cpt.clear(); - } - else if( this.Name.equals( "PatternTerminalEx.Substitute" ) ) - { - cpt.getPatternTerminal().setSubstitution( this.Value.equals( "1" ) ); - } - else if( this.Name.equals( "PatternTerminalEx.Invert" ) ) - { - cpt.getPatternTerminal().setInverted( Value.equals( "1" ) ); - } - else if( this.Name.equals( "PatternTerminalEx.Double" ) ) - { - cpt.doubleStacks(Value.equals( "1" )); - } - else if( this.Name.equals( "PatternTerminalEx.ActivePage" ) ) - { - cpt.getPatternTerminal().setActivePage(Integer.parseInt( Value )); - } - } - else if( this.Name.startsWith( "StorageBus." ) && c instanceof ContainerStorageBus ) - { - final ContainerStorageBus ccw = (ContainerStorageBus) c; - if( this.Name.equals( "StorageBus.Action" ) ) - { - if( this.Value.equals( "Partition" ) ) - { - ccw.partition(); - } - else if( this.Value.equals( "Clear" ) ) - { - ccw.clear(); - } - } - } - else if( this.Name.startsWith( "CellWorkbench." ) && c instanceof ContainerCellWorkbench ) - { - final ContainerCellWorkbench ccw = (ContainerCellWorkbench) c; - if( this.Name.equals( "CellWorkbench.Action" ) ) - { - if( this.Value.equals( "CopyMode" ) ) - { - ccw.nextWorkBenchCopyMode(); - } - else if( this.Value.equals( "Partition" ) ) - { - ccw.partition(); - } - else if( this.Value.equals( "Clear" ) ) - { - ccw.clear(); - } - } - else if( this.Name.equals( "CellWorkbench.Fuzzy" ) ) - { - ccw.setFuzzy( FuzzyMode.valueOf( this.Value ) ); - } - } - else if( c instanceof ContainerNetworkTool ) - { - if( this.Name.equals( "NetworkTool" ) && this.Value.equals( "Toggle" ) ) - { - ( (ContainerNetworkTool) c ).toggleFacadeMode(); - } - } - else if( c instanceof IConfigurableObject ) - { - final IConfigManager cm = ( (IConfigurableObject) c ).getConfigManager(); - - for( final Settings e : cm.getSettings() ) - { - if( e.name().equals( this.Name ) ) - { - final Enum def = cm.getSetting( e ); - - try - { - cm.putSetting( e, Enum.valueOf( def.getClass(), this.Value ) ); - } - catch( final IllegalArgumentException err ) - { - // :P - } - - break; - } - } - } - } - - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; - - if( this.Name.equals( "CustomName" ) && c instanceof AEBaseContainer ) - { - ( (AEBaseContainer) c ).setCustomName( this.Value ); - } - else if( this.Name.startsWith( "SyncDat." ) ) - { - ( (AEBaseContainer) c ).stringSync( Integer.parseInt( this.Name.substring( 8 ) ), this.Value ); - } - else if( this.Name.equals( "CraftingStatus" ) && this.Value.equals( "Clear" ) ) - { - final GuiScreen gs = Minecraft.getMinecraft().currentScreen; - if( gs instanceof GuiCraftingCPU ) - { - ( (GuiCraftingCPU) gs ).clearItems(); - } - } - else if( c instanceof IConfigurableObject ) - { - final IConfigManager cm = ( (IConfigurableObject) c ).getConfigManager(); - - for( final Settings e : cm.getSettings() ) - { - if( e.name().equals( this.Name ) ) - { - final Enum def = cm.getSetting( e ); - - try - { - cm.putSetting( e, Enum.valueOf( def.getClass(), this.Value ) ); - } - catch( final IllegalArgumentException err ) - { - // :P - } - - break; - } - } - } - } +public class PacketValueConfig extends AppEngPacket { + + private final String Name; + private final String Value; + + // automatic. + public PacketValueConfig(final ByteBuf stream) throws IOException { + final DataInputStream dis = new DataInputStream( + new ByteArrayInputStream(stream.array(), stream.readerIndex(), stream.readableBytes())); + this.Name = dis.readUTF(); + this.Value = dis.readUTF(); + // dis.close(); + } + + // api + public PacketValueConfig(final String name, final String value) throws IOException { + this.Name = name; + this.Value = value; + + final ByteBuf data = Unpooled.buffer(); + + data.writeInt(this.getPacketID()); + + final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + final DataOutputStream dos = new DataOutputStream(bos); + dos.writeUTF(name); + dos.writeUTF(value); + // dos.close(); + + data.writeBytes(bos.toByteArray()); + + this.configureWrite(data); + } + + @Override + public void serverPacketData(final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player) { + final Container c = player.openContainer; + + if (this.Name.equals("Item") + && player.getHeldItem() != null + && player.getHeldItem().getItem() instanceof IMouseWheelItem) { + final ItemStack is = player.getHeldItem(); + final IMouseWheelItem si = (IMouseWheelItem) is.getItem(); + si.onWheel(is, this.Value.equals("WheelUp")); + } else if (this.Name.equals("CPUTable.Cpu.Set") && c instanceof ICraftingCPUSelectorContainer) { + final ICraftingCPUSelectorContainer qk = (ICraftingCPUSelectorContainer) c; + qk.selectCPU(Integer.parseInt(this.Value)); + } else if (this.Name.equals("Terminal.Start") && c instanceof ContainerCraftConfirm) { + final ContainerCraftConfirm qk = (ContainerCraftConfirm) c; + qk.startJob(); + } else if (this.Name.equals("TileCrafting.Cancel") && c instanceof ContainerCraftingCPU) { + final ContainerCraftingCPU qk = (ContainerCraftingCPU) c; + qk.cancelCrafting(); + } else if (this.Name.equals("QuartzKnife.Name") && c instanceof ContainerQuartzKnife) { + final ContainerQuartzKnife qk = (ContainerQuartzKnife) c; + qk.setName(this.Value); + } else if (this.Name.equals("QuartzKnife.ReName") && c instanceof ContainerRenamer) { + final ContainerRenamer qk = (ContainerRenamer) c; + qk.setNewName(this.Value); + } else if (this.Name.equals("TileSecurity.ToggleOption") && c instanceof ContainerSecurity) { + final ContainerSecurity sc = (ContainerSecurity) c; + sc.toggleSetting(this.Value, player); + } else if (this.Name.equals("PriorityHost.Priority") && c instanceof ContainerPriority) { + final ContainerPriority pc = (ContainerPriority) c; + pc.setPriority(Integer.parseInt(this.Value), player); + } else if (this.Name.equals("OreFilter") && c instanceof ContainerOreFilter) { + final ContainerOreFilter fc = (ContainerOreFilter) c; + fc.setFilter(this.Value); + } else if (this.Name.equals("LevelEmitter.Value") && c instanceof ContainerLevelEmitter) { + final ContainerLevelEmitter lvc = (ContainerLevelEmitter) c; + lvc.setLevel(Long.parseLong(this.Value), player); + } else if (this.Name.startsWith("PatternTerminal.") && c instanceof ContainerPatternTerm) { + final ContainerPatternTerm cpt = (ContainerPatternTerm) c; + if (this.Name.equals("PatternTerminal.CraftMode")) { + cpt.getPatternTerminal().setCraftingRecipe(this.Value.equals("1")); + } else if (this.Name.equals("PatternTerminal.Encode")) { + if (this.Value.equals("2")) cpt.encodeAndMoveToInventory(false); + else if (this.Value.equals("6")) cpt.encodeAndMoveToInventory(true); + else cpt.encode(); + } else if (this.Name.equals("PatternTerminal.Clear")) { + cpt.clear(); + } else if (this.Name.equals("PatternTerminal.Substitute")) { + cpt.getPatternTerminal().setSubstitution(this.Value.equals("1")); + } else if (this.Name.equals("PatternTerminal.Double")) { + cpt.doubleStacks(Value.equals("1")); + } + } else if (this.Name.startsWith("PatternTerminalEx.") && c instanceof ContainerPatternTermEx) { + final ContainerPatternTermEx cpt = (ContainerPatternTermEx) c; + if (this.Name.equals("PatternTerminalEx.Encode")) { + if (this.Value.equals("2")) cpt.encodeAndMoveToInventory(false); + else if (this.Value.equals("6")) cpt.encodeAndMoveToInventory(true); + else cpt.encode(); + } else if (this.Name.equals("PatternTerminalEx.Clear")) { + cpt.clear(); + } else if (this.Name.equals("PatternTerminalEx.Substitute")) { + cpt.getPatternTerminal().setSubstitution(this.Value.equals("1")); + } else if (this.Name.equals("PatternTerminalEx.Invert")) { + cpt.getPatternTerminal().setInverted(Value.equals("1")); + } else if (this.Name.equals("PatternTerminalEx.Double")) { + cpt.doubleStacks(Value.equals("1")); + } else if (this.Name.equals("PatternTerminalEx.ActivePage")) { + cpt.getPatternTerminal().setActivePage(Integer.parseInt(Value)); + } + } else if (this.Name.startsWith("StorageBus.") && c instanceof ContainerStorageBus) { + final ContainerStorageBus ccw = (ContainerStorageBus) c; + if (this.Name.equals("StorageBus.Action")) { + if (this.Value.equals("Partition")) { + ccw.partition(); + } else if (this.Value.equals("Clear")) { + ccw.clear(); + } + } + } else if (this.Name.startsWith("CellWorkbench.") && c instanceof ContainerCellWorkbench) { + final ContainerCellWorkbench ccw = (ContainerCellWorkbench) c; + if (this.Name.equals("CellWorkbench.Action")) { + if (this.Value.equals("CopyMode")) { + ccw.nextWorkBenchCopyMode(); + } else if (this.Value.equals("Partition")) { + ccw.partition(); + } else if (this.Value.equals("Clear")) { + ccw.clear(); + } + } else if (this.Name.equals("CellWorkbench.Fuzzy")) { + ccw.setFuzzy(FuzzyMode.valueOf(this.Value)); + } + } else if (c instanceof ContainerNetworkTool) { + if (this.Name.equals("NetworkTool") && this.Value.equals("Toggle")) { + ((ContainerNetworkTool) c).toggleFacadeMode(); + } + } else if (c instanceof IConfigurableObject) { + final IConfigManager cm = ((IConfigurableObject) c).getConfigManager(); + + for (final Settings e : cm.getSettings()) { + if (e.name().equals(this.Name)) { + final Enum def = cm.getSetting(e); + + try { + cm.putSetting(e, Enum.valueOf(def.getClass(), this.Value)); + } catch (final IllegalArgumentException err) { + // :P + } + + break; + } + } + } + } + + @Override + public void clientPacketData(final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player) { + final Container c = player.openContainer; + + if (this.Name.equals("CustomName") && c instanceof AEBaseContainer) { + ((AEBaseContainer) c).setCustomName(this.Value); + } else if (this.Name.startsWith("SyncDat.")) { + ((AEBaseContainer) c).stringSync(Integer.parseInt(this.Name.substring(8)), this.Value); + } else if (this.Name.equals("CraftingStatus") && this.Value.equals("Clear")) { + final GuiScreen gs = Minecraft.getMinecraft().currentScreen; + if (gs instanceof GuiCraftingCPU) { + ((GuiCraftingCPU) gs).clearItems(); + } + } else if (c instanceof IConfigurableObject) { + final IConfigManager cm = ((IConfigurableObject) c).getConfigManager(); + + for (final Settings e : cm.getSettings()) { + if (e.name().equals(this.Name)) { + final Enum def = cm.getSetting(e); + + try { + cm.putSetting(e, Enum.valueOf(def.getClass(), this.Value)); + } catch (final IllegalArgumentException err) { + // :P + } + + break; + } + } + } + } } diff --git a/src/main/java/appeng/core/worlddata/CompassData.java b/src/main/java/appeng/core/worlddata/CompassData.java index aaf7aaf10b5..7b0625a78de 100644 --- a/src/main/java/appeng/core/worlddata/CompassData.java +++ b/src/main/java/appeng/core/worlddata/CompassData.java @@ -18,41 +18,34 @@ package appeng.core.worlddata; - import appeng.services.CompassService; import com.google.common.base.Preconditions; - -import javax.annotation.Nonnull; import java.io.File; - +import javax.annotation.Nonnull; /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -final class CompassData implements IWorldCompassData, IOnWorldStoppable -{ - @Nonnull - private final CompassService service; - - public CompassData( @Nonnull final File compassDirectory, @Nonnull final CompassService service ) - { - Preconditions.checkNotNull( compassDirectory ); - Preconditions.checkNotNull( service ); - - this.service = service; - } - - @Override - public CompassService service() - { - return this.service; - } - - @Override - public void onWorldStop() - { - this.service.kill(); - } +final class CompassData implements IWorldCompassData, IOnWorldStoppable { + @Nonnull + private final CompassService service; + + public CompassData(@Nonnull final File compassDirectory, @Nonnull final CompassService service) { + Preconditions.checkNotNull(compassDirectory); + Preconditions.checkNotNull(service); + + this.service = service; + } + + @Override + public CompassService service() { + return this.service; + } + + @Override + public void onWorldStop() { + this.service.kill(); + } } diff --git a/src/main/java/appeng/core/worlddata/DimensionData.java b/src/main/java/appeng/core/worlddata/DimensionData.java index 1b839647969..d5158e9bf25 100644 --- a/src/main/java/appeng/core/worlddata/DimensionData.java +++ b/src/main/java/appeng/core/worlddata/DimensionData.java @@ -18,7 +18,6 @@ package appeng.core.worlddata; - import appeng.api.util.WorldCoord; import appeng.core.AEConfig; import appeng.core.sync.network.NetworkHandler; @@ -26,143 +25,126 @@ import appeng.hooks.TickHandler; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; +import java.util.List; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.network.NetworkManager; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.List; - - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -final class DimensionData implements IWorldDimensionData, IOnWorldStartable, IOnWorldStoppable -{ - private static final String CONFIG_CATEGORY = "DimensionManager"; - private static final String CONFIG_KEY = "StorageCells"; - private static final int[] STORAGE_CELLS_DEFAULT = new int[0]; +final class DimensionData implements IWorldDimensionData, IOnWorldStartable, IOnWorldStoppable { + private static final String CONFIG_CATEGORY = "DimensionManager"; + private static final String CONFIG_KEY = "StorageCells"; + private static final int[] STORAGE_CELLS_DEFAULT = new int[0]; + + private static final String STORAGE_CELL_CATEGORY = "StorageCell"; - private static final String STORAGE_CELL_CATEGORY = "StorageCell"; - - private static final String STORAGE_CELL_SCALE_X_KEY = "scaleX"; - private static final String STORAGE_CELL_SCALE_Y_KEY = "scaleY"; - private static final String STORAGE_CELL_SCALE_Z_KEY = "scaleZ"; - - private static final String PACKAGE_DEST_CATEGORY = "DimensionManager"; - private static final String PACKAGE_KEY_CATEGORY = "StorageCells"; - private static final int[] PACKAGE_DEF_CATEGORY = new int[0]; - - private final Configuration config; - private final List storageCellDimensionIDs; - - DimensionData( @Nonnull final Configuration parentFile ) - { - Preconditions.checkNotNull( parentFile ); - - this.config = parentFile; - - final int[] storageCellIDs = this.storageCellIDsProperty().getIntList(); - - this.storageCellDimensionIDs = Lists.newArrayList(); - for( final int storageCellID : storageCellIDs ) - { - this.storageCellDimensionIDs.add( storageCellID ); - } - } - - private Property storageCellIDsProperty() - { - return this.config.get( CONFIG_CATEGORY, CONFIG_KEY, STORAGE_CELLS_DEFAULT ); - } - - @Override - public void onWorldStart() - { - for( final Integer storageCellDimID : this.storageCellDimensionIDs ) - { - DimensionManager.registerDimension( storageCellDimID, AEConfig.instance.storageProviderID ); - } - - this.config.save(); - } - - @Override - public void onWorldStop() - { - this.config.save(); - - for( final Integer storageCellDimID : this.storageCellDimensionIDs ) - { - DimensionManager.unregisterDimension( storageCellDimID ); - } - - this.storageCellDimensionIDs.clear(); - } - - @Override - public void addStorageCell( final int newStorageCellID ) - { - this.storageCellDimensionIDs.add( newStorageCellID ); - DimensionManager.registerDimension( newStorageCellID, AEConfig.instance.storageProviderID ); - - NetworkHandler.instance.sendToAll( new PacketNewStorageDimension( newStorageCellID ) ); - - final String[] values = new String[this.storageCellDimensionIDs.size()]; - - for( int x = 0; x < values.length; x++ ) - { - values[x] = String.valueOf( this.storageCellDimensionIDs.get( x ) ); - } - - this.storageCellIDsProperty().set( values ); - this.config.save(); - } - - @Override - public WorldCoord getStoredSize( final int dim ) - { - final String category = STORAGE_CELL_CATEGORY + dim; - - final int x = this.config.get( category, STORAGE_CELL_SCALE_X_KEY, 0 ).getInt(); - final int y = this.config.get( category, STORAGE_CELL_SCALE_Y_KEY, 0 ).getInt(); - final int z = this.config.get( category, STORAGE_CELL_SCALE_Z_KEY, 0 ).getInt(); - - return new WorldCoord( x, y, z ); - } - - @Override - public void setStoredSize( final int dim, final int targetX, final int targetY, final int targetZ ) - { - final String category = STORAGE_CELL_CATEGORY + dim; - - this.config.get( category, STORAGE_CELL_SCALE_X_KEY, 0 ).set( targetX ); - this.config.get( category, STORAGE_CELL_SCALE_Y_KEY, 0 ).set( targetY ); - this.config.get( category, STORAGE_CELL_SCALE_Z_KEY, 0 ).set( targetZ ); - - this.config.save(); - } - - @Override - public void sendToPlayer( @Nullable final NetworkManager manager ) - { - if( manager != null ) - { - for( final int newDim : this.config.get( PACKAGE_DEST_CATEGORY, PACKAGE_KEY_CATEGORY, PACKAGE_DEF_CATEGORY ).getIntList() ) - { - manager.scheduleOutboundPacket( ( new PacketNewStorageDimension( newDim ) ).getProxy() ); - } - } - else - { - for( final TickHandler.PlayerColor pc : TickHandler.INSTANCE.getPlayerColors().values() ) - { - NetworkHandler.instance.sendToAll( pc.getPacket() ); - } - } - } + private static final String STORAGE_CELL_SCALE_X_KEY = "scaleX"; + private static final String STORAGE_CELL_SCALE_Y_KEY = "scaleY"; + private static final String STORAGE_CELL_SCALE_Z_KEY = "scaleZ"; + + private static final String PACKAGE_DEST_CATEGORY = "DimensionManager"; + private static final String PACKAGE_KEY_CATEGORY = "StorageCells"; + private static final int[] PACKAGE_DEF_CATEGORY = new int[0]; + + private final Configuration config; + private final List storageCellDimensionIDs; + + DimensionData(@Nonnull final Configuration parentFile) { + Preconditions.checkNotNull(parentFile); + + this.config = parentFile; + + final int[] storageCellIDs = this.storageCellIDsProperty().getIntList(); + + this.storageCellDimensionIDs = Lists.newArrayList(); + for (final int storageCellID : storageCellIDs) { + this.storageCellDimensionIDs.add(storageCellID); + } + } + + private Property storageCellIDsProperty() { + return this.config.get(CONFIG_CATEGORY, CONFIG_KEY, STORAGE_CELLS_DEFAULT); + } + + @Override + public void onWorldStart() { + for (final Integer storageCellDimID : this.storageCellDimensionIDs) { + DimensionManager.registerDimension(storageCellDimID, AEConfig.instance.storageProviderID); + } + + this.config.save(); + } + + @Override + public void onWorldStop() { + this.config.save(); + + for (final Integer storageCellDimID : this.storageCellDimensionIDs) { + DimensionManager.unregisterDimension(storageCellDimID); + } + + this.storageCellDimensionIDs.clear(); + } + + @Override + public void addStorageCell(final int newStorageCellID) { + this.storageCellDimensionIDs.add(newStorageCellID); + DimensionManager.registerDimension(newStorageCellID, AEConfig.instance.storageProviderID); + + NetworkHandler.instance.sendToAll(new PacketNewStorageDimension(newStorageCellID)); + + final String[] values = new String[this.storageCellDimensionIDs.size()]; + + for (int x = 0; x < values.length; x++) { + values[x] = String.valueOf(this.storageCellDimensionIDs.get(x)); + } + + this.storageCellIDsProperty().set(values); + this.config.save(); + } + + @Override + public WorldCoord getStoredSize(final int dim) { + final String category = STORAGE_CELL_CATEGORY + dim; + + final int x = this.config.get(category, STORAGE_CELL_SCALE_X_KEY, 0).getInt(); + final int y = this.config.get(category, STORAGE_CELL_SCALE_Y_KEY, 0).getInt(); + final int z = this.config.get(category, STORAGE_CELL_SCALE_Z_KEY, 0).getInt(); + + return new WorldCoord(x, y, z); + } + + @Override + public void setStoredSize(final int dim, final int targetX, final int targetY, final int targetZ) { + final String category = STORAGE_CELL_CATEGORY + dim; + + this.config.get(category, STORAGE_CELL_SCALE_X_KEY, 0).set(targetX); + this.config.get(category, STORAGE_CELL_SCALE_Y_KEY, 0).set(targetY); + this.config.get(category, STORAGE_CELL_SCALE_Z_KEY, 0).set(targetZ); + + this.config.save(); + } + + @Override + public void sendToPlayer(@Nullable final NetworkManager manager) { + if (manager != null) { + for (final int newDim : this.config + .get(PACKAGE_DEST_CATEGORY, PACKAGE_KEY_CATEGORY, PACKAGE_DEF_CATEGORY) + .getIntList()) { + manager.scheduleOutboundPacket((new PacketNewStorageDimension(newDim)).getProxy()); + } + } else { + for (final TickHandler.PlayerColor pc : + TickHandler.INSTANCE.getPlayerColors().values()) { + NetworkHandler.instance.sendToAll(pc.getPacket()); + } + } + } } diff --git a/src/main/java/appeng/core/worlddata/IOnWorldStartable.java b/src/main/java/appeng/core/worlddata/IOnWorldStartable.java index b6c5c325da2..209076aedd4 100644 --- a/src/main/java/appeng/core/worlddata/IOnWorldStartable.java +++ b/src/main/java/appeng/core/worlddata/IOnWorldStartable.java @@ -18,13 +18,11 @@ package appeng.core.worlddata; - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IOnWorldStartable -{ - void onWorldStart(); +public interface IOnWorldStartable { + void onWorldStart(); } diff --git a/src/main/java/appeng/core/worlddata/IOnWorldStoppable.java b/src/main/java/appeng/core/worlddata/IOnWorldStoppable.java index 7a36e771f67..c9e9d963c46 100644 --- a/src/main/java/appeng/core/worlddata/IOnWorldStoppable.java +++ b/src/main/java/appeng/core/worlddata/IOnWorldStoppable.java @@ -18,13 +18,11 @@ package appeng.core.worlddata; - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IOnWorldStoppable -{ - void onWorldStop(); +public interface IOnWorldStoppable { + void onWorldStop(); } diff --git a/src/main/java/appeng/core/worlddata/IWorldCompassData.java b/src/main/java/appeng/core/worlddata/IWorldCompassData.java index c4b74b85c7c..e9c4f14faf9 100644 --- a/src/main/java/appeng/core/worlddata/IWorldCompassData.java +++ b/src/main/java/appeng/core/worlddata/IWorldCompassData.java @@ -18,16 +18,13 @@ package appeng.core.worlddata; - import appeng.services.CompassService; - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldCompassData -{ - CompassService service(); +public interface IWorldCompassData { + CompassService service(); } diff --git a/src/main/java/appeng/core/worlddata/IWorldData.java b/src/main/java/appeng/core/worlddata/IWorldData.java index bd24d3e342c..b68020f6e23 100644 --- a/src/main/java/appeng/core/worlddata/IWorldData.java +++ b/src/main/java/appeng/core/worlddata/IWorldData.java @@ -18,33 +18,30 @@ package appeng.core.worlddata; - import javax.annotation.Nonnull; - /** * @author thatsIch * @version rv3 - 02.11.2015 * @since rv3 30.05.2015 */ -public interface IWorldData -{ - void onServerStopping(); +public interface IWorldData { + void onServerStopping(); - void onServerStoppped(); + void onServerStoppped(); - @Nonnull - IWorldGridStorageData storageData(); + @Nonnull + IWorldGridStorageData storageData(); - @Nonnull - IWorldPlayerData playerData(); + @Nonnull + IWorldPlayerData playerData(); - @Nonnull - IWorldDimensionData dimensionData(); + @Nonnull + IWorldDimensionData dimensionData(); - @Nonnull - IWorldCompassData compassData(); + @Nonnull + IWorldCompassData compassData(); - @Nonnull - IWorldSpawnData spawnData(); + @Nonnull + IWorldSpawnData spawnData(); } diff --git a/src/main/java/appeng/core/worlddata/IWorldDimensionData.java b/src/main/java/appeng/core/worlddata/IWorldDimensionData.java index ffbc1659c6f..464c77657b7 100644 --- a/src/main/java/appeng/core/worlddata/IWorldDimensionData.java +++ b/src/main/java/appeng/core/worlddata/IWorldDimensionData.java @@ -18,25 +18,21 @@ package appeng.core.worlddata; - import appeng.api.util.WorldCoord; -import net.minecraft.network.NetworkManager; - import javax.annotation.Nullable; - +import net.minecraft.network.NetworkManager; /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldDimensionData -{ - void addStorageCell( int newStorageCellID ); +public interface IWorldDimensionData { + void addStorageCell(int newStorageCellID); - WorldCoord getStoredSize( int dim ); + WorldCoord getStoredSize(int dim); - void setStoredSize( int dim, int targetX, int targetY, int targetZ ); + void setStoredSize(int dim, int targetX, int targetY, int targetZ); - void sendToPlayer( @Nullable NetworkManager manager ); + void sendToPlayer(@Nullable NetworkManager manager); } diff --git a/src/main/java/appeng/core/worlddata/IWorldGridStorageData.java b/src/main/java/appeng/core/worlddata/IWorldGridStorageData.java index 32767d1070b..6ea3f2a4709 100644 --- a/src/main/java/appeng/core/worlddata/IWorldGridStorageData.java +++ b/src/main/java/appeng/core/worlddata/IWorldGridStorageData.java @@ -18,29 +18,25 @@ package appeng.core.worlddata; - import appeng.me.GridStorage; - import javax.annotation.Nonnull; import javax.annotation.Nullable; - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldGridStorageData -{ - @Nullable - GridStorage getGridStorage( long storageID ); +public interface IWorldGridStorageData { + @Nullable + GridStorage getGridStorage(long storageID); - @Nonnull - GridStorage getNewGridStorage(); + @Nonnull + GridStorage getNewGridStorage(); - long nextGridStorage(); + long nextGridStorage(); - void destroyGridStorage( long id ); + void destroyGridStorage(long id); - int getNextOrderedValue( String name ); + int getNextOrderedValue(String name); } diff --git a/src/main/java/appeng/core/worlddata/IWorldPlayerData.java b/src/main/java/appeng/core/worlddata/IWorldPlayerData.java index 793a0d8a41b..9f5201827d3 100644 --- a/src/main/java/appeng/core/worlddata/IWorldPlayerData.java +++ b/src/main/java/appeng/core/worlddata/IWorldPlayerData.java @@ -18,22 +18,18 @@ package appeng.core.worlddata; - import com.mojang.authlib.GameProfile; -import net.minecraft.entity.player.EntityPlayer; - import javax.annotation.Nullable; - +import net.minecraft.entity.player.EntityPlayer; /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldPlayerData -{ - @Nullable - EntityPlayer getPlayerFromID( int playerID ); +public interface IWorldPlayerData { + @Nullable + EntityPlayer getPlayerFromID(int playerID); - int getPlayerID( GameProfile profile ); + int getPlayerID(GameProfile profile); } diff --git a/src/main/java/appeng/core/worlddata/IWorldPlayerMapping.java b/src/main/java/appeng/core/worlddata/IWorldPlayerMapping.java index 7ae08fe944f..fd564e4a0ed 100644 --- a/src/main/java/appeng/core/worlddata/IWorldPlayerMapping.java +++ b/src/main/java/appeng/core/worlddata/IWorldPlayerMapping.java @@ -18,36 +18,32 @@ package appeng.core.worlddata; - import com.google.common.base.Optional; - -import javax.annotation.Nonnull; import java.util.UUID; - +import javax.annotation.Nonnull; /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldPlayerMapping -{ - /** - * Tries to retrieve the UUID of a player. - * Might not be stored inside of the map. - * Should not happen though. - * - * @param id ID of the to be searched player - * @return maybe the UUID of the searched player - */ - @Nonnull - Optional get( int id ); +public interface IWorldPlayerMapping { + /** + * Tries to retrieve the UUID of a player. + * Might not be stored inside of the map. + * Should not happen though. + * + * @param id ID of the to be searched player + * @return maybe the UUID of the searched player + */ + @Nonnull + Optional get(int id); - /** - * Put in new players when they join the server - * - * @param id id of new player - * @param uuid UUID of new player - */ - void put( int id, @Nonnull UUID uuid ); + /** + * Put in new players when they join the server + * + * @param id id of new player + * @param uuid UUID of new player + */ + void put(int id, @Nonnull UUID uuid); } diff --git a/src/main/java/appeng/core/worlddata/IWorldSpawnData.java b/src/main/java/appeng/core/worlddata/IWorldSpawnData.java index cb945dde232..ffec39bbb4d 100644 --- a/src/main/java/appeng/core/worlddata/IWorldSpawnData.java +++ b/src/main/java/appeng/core/worlddata/IWorldSpawnData.java @@ -18,24 +18,20 @@ package appeng.core.worlddata; - -import net.minecraft.nbt.NBTTagCompound; - import java.util.Collection; - +import net.minecraft.nbt.NBTTagCompound; /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldSpawnData -{ - void setGenerated( int dim, int chunkX, int chunkZ ); +public interface IWorldSpawnData { + void setGenerated(int dim, int chunkX, int chunkZ); - boolean hasGenerated( int dim, int chunkX, int chunkZ ); + boolean hasGenerated(int dim, int chunkX, int chunkZ); - boolean addNearByMeteorites( int dim, int chunkX, int chunkZ, NBTTagCompound newData ); + boolean addNearByMeteorites(int dim, int chunkX, int chunkZ, NBTTagCompound newData); - Collection getNearByMeteorites( int dim, int chunkX, int chunkZ ); + Collection getNearByMeteorites(int dim, int chunkX, int chunkZ); } diff --git a/src/main/java/appeng/core/worlddata/MeteorDataNameEncoder.java b/src/main/java/appeng/core/worlddata/MeteorDataNameEncoder.java index af20f0294ed..5a432dfde9a 100644 --- a/src/main/java/appeng/core/worlddata/MeteorDataNameEncoder.java +++ b/src/main/java/appeng/core/worlddata/MeteorDataNameEncoder.java @@ -18,12 +18,9 @@ package appeng.core.worlddata; - import com.google.common.base.Preconditions; - import javax.annotation.Nonnull; - /** * encodes data into a common name * @@ -31,51 +28,61 @@ * @version rv3 - 05.06.2015 * @since rv3 05.06.2015 */ -public class MeteorDataNameEncoder -{ - private static final char DATA_SEPARATOR = '_'; - private static final char BASE_EXTENSION_SEPARATOR = '.'; - private static final String FILE_EXTENSION = "dat"; +public class MeteorDataNameEncoder { + private static final char DATA_SEPARATOR = '_'; + private static final char BASE_EXTENSION_SEPARATOR = '.'; + private static final String FILE_EXTENSION = "dat"; + + private final char dataSeparator; + + @Nonnull + private final String fileExtension; - private final char dataSeparator; - @Nonnull - private final String fileExtension; - private final char baseExtSeparator; - private final int bitScale; + private final char baseExtSeparator; + private final int bitScale; - /** - * @param bitScale how often the coordinates will be shifted right (will scale coordinates down) - */ - public MeteorDataNameEncoder( final int bitScale ) - { - this( DATA_SEPARATOR, BASE_EXTENSION_SEPARATOR, FILE_EXTENSION, bitScale ); - } + /** + * @param bitScale how often the coordinates will be shifted right (will scale coordinates down) + */ + public MeteorDataNameEncoder(final int bitScale) { + this(DATA_SEPARATOR, BASE_EXTENSION_SEPARATOR, FILE_EXTENSION, bitScale); + } - private MeteorDataNameEncoder( final char dataSeparator, final char baseExtSeparator, @Nonnull final String fileExtension, final int bitScale ) - { - Preconditions.checkNotNull( fileExtension ); - Preconditions.checkArgument( !fileExtension.isEmpty() ); - Preconditions.checkArgument( bitScale >= 0 ); + private MeteorDataNameEncoder( + final char dataSeparator, + final char baseExtSeparator, + @Nonnull final String fileExtension, + final int bitScale) { + Preconditions.checkNotNull(fileExtension); + Preconditions.checkArgument(!fileExtension.isEmpty()); + Preconditions.checkArgument(bitScale >= 0); - this.dataSeparator = dataSeparator; - this.baseExtSeparator = baseExtSeparator; - this.fileExtension = fileExtension; - this.bitScale = bitScale; - } + this.dataSeparator = dataSeparator; + this.baseExtSeparator = baseExtSeparator; + this.fileExtension = fileExtension; + this.bitScale = bitScale; + } - /** - * @param dimension ID of the processed dimension. Can be any integer - * @param chunkX X coordinate of the chunk. Can be any integer - * @param chunkZ Z coordinate of the chunk. Can be any integer - * @return encoded file name suggestion in form of dim_x_y.dat where x and y will be - * shifted to stay conform with the vanilla chunk system - * @since rv3 05.06.2015 - */ - public String encode( final int dimension, final int chunkX, final int chunkZ ) - { - final int shiftedX = chunkX >> this.bitScale; - final int shiftedZ = chunkZ >> this.bitScale; + /** + * @param dimension ID of the processed dimension. Can be any integer + * @param chunkX X coordinate of the chunk. Can be any integer + * @param chunkZ Z coordinate of the chunk. Can be any integer + * @return encoded file name suggestion in form of dim_x_y.dat where x and y will be + * shifted to stay conform with the vanilla chunk system + * @since rv3 05.06.2015 + */ + public String encode(final int dimension, final int chunkX, final int chunkZ) { + final int shiftedX = chunkX >> this.bitScale; + final int shiftedZ = chunkZ >> this.bitScale; - return String.format( "%d%c%d%c%d%c%s", dimension, this.dataSeparator, shiftedX, this.dataSeparator, shiftedZ, this.baseExtSeparator, this.fileExtension ); - } + return String.format( + "%d%c%d%c%d%c%s", + dimension, + this.dataSeparator, + shiftedX, + this.dataSeparator, + shiftedZ, + this.baseExtSeparator, + this.fileExtension); + } } diff --git a/src/main/java/appeng/core/worlddata/PlayerData.java b/src/main/java/appeng/core/worlddata/PlayerData.java index f0be8d41d76..1d73c135926 100644 --- a/src/main/java/appeng/core/worlddata/PlayerData.java +++ b/src/main/java/appeng/core/worlddata/PlayerData.java @@ -18,21 +18,18 @@ package appeng.core.worlddata; - import appeng.core.CommonHelper; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.mojang.authlib.GameProfile; +import java.util.UUID; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.UUID; - - /** * Handles the matching between UUIDs and internal IDs for security systems. * This whole system could be replaced by storing directly the UUID, @@ -42,96 +39,87 @@ * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -final class PlayerData implements IWorldPlayerData, IOnWorldStartable, IOnWorldStoppable -{ - private static final String LAST_PLAYER_CATEGORY = "Counters"; - private static final String LAST_PLAYER_KEY = "lastPlayer"; - private static final int LAST_PLAYER_DEFAULT = 0; - - private final Configuration config; - private final IWorldPlayerMapping playerMapping; - - private int lastPlayerID; - - public PlayerData( @Nonnull final Configuration configFile ) - { - Preconditions.checkNotNull( configFile ); - - this.config = configFile; - - final ConfigCategory playerList = this.config.getCategory( "players" ); - this.playerMapping = new PlayerMapping( playerList ); - } - - @Nullable - @Override - public EntityPlayer getPlayerFromID( final int playerID ) - { - final Optional maybe = this.playerMapping.get( playerID ); - - if( maybe.isPresent() ) - { - final UUID uuid = maybe.get(); - for( final EntityPlayer player : CommonHelper.proxy.getPlayers() ) - { - if( player.getUniqueID().equals( uuid ) ) - { - return player; - } - } - } - - return null; - } - - @Override - public int getPlayerID( @Nonnull final GameProfile profile ) - { - Preconditions.checkNotNull( profile ); - Preconditions.checkNotNull( this.config.getCategory( "players" ) ); - Preconditions.checkState( profile.isComplete() ); - - final ConfigCategory players = this.config.getCategory( "players" ); - final String uuid = profile.getId().toString(); - final Property maybePlayerID = players.get( uuid ); - - if( maybePlayerID != null && maybePlayerID.isIntValue() ) - { - return maybePlayerID.getInt(); - } - else - { - final int newPlayerID = this.nextPlayer(); - final Property newPlayer = new Property( uuid, String.valueOf( newPlayerID ), Property.Type.INTEGER ); - players.put( uuid, newPlayer ); - this.playerMapping.put( newPlayerID, profile.getId() ); // add to reverse map - this.config.save(); - - return newPlayerID; - } - } - - private int nextPlayer() - { - final int r = this.lastPlayerID; - this.lastPlayerID++; - this.config.get( LAST_PLAYER_CATEGORY, LAST_PLAYER_KEY, this.lastPlayerID ).set( this.lastPlayerID ); - return r; - } - - @Override - public void onWorldStart() - { - this.lastPlayerID = this.config.get( LAST_PLAYER_CATEGORY, LAST_PLAYER_KEY, LAST_PLAYER_DEFAULT ).getInt( LAST_PLAYER_DEFAULT ); - - this.config.save(); - } - - @Override - public void onWorldStop() - { - this.config.save(); - - this.lastPlayerID = 0; - } +final class PlayerData implements IWorldPlayerData, IOnWorldStartable, IOnWorldStoppable { + private static final String LAST_PLAYER_CATEGORY = "Counters"; + private static final String LAST_PLAYER_KEY = "lastPlayer"; + private static final int LAST_PLAYER_DEFAULT = 0; + + private final Configuration config; + private final IWorldPlayerMapping playerMapping; + + private int lastPlayerID; + + public PlayerData(@Nonnull final Configuration configFile) { + Preconditions.checkNotNull(configFile); + + this.config = configFile; + + final ConfigCategory playerList = this.config.getCategory("players"); + this.playerMapping = new PlayerMapping(playerList); + } + + @Nullable + @Override + public EntityPlayer getPlayerFromID(final int playerID) { + final Optional maybe = this.playerMapping.get(playerID); + + if (maybe.isPresent()) { + final UUID uuid = maybe.get(); + for (final EntityPlayer player : CommonHelper.proxy.getPlayers()) { + if (player.getUniqueID().equals(uuid)) { + return player; + } + } + } + + return null; + } + + @Override + public int getPlayerID(@Nonnull final GameProfile profile) { + Preconditions.checkNotNull(profile); + Preconditions.checkNotNull(this.config.getCategory("players")); + Preconditions.checkState(profile.isComplete()); + + final ConfigCategory players = this.config.getCategory("players"); + final String uuid = profile.getId().toString(); + final Property maybePlayerID = players.get(uuid); + + if (maybePlayerID != null && maybePlayerID.isIntValue()) { + return maybePlayerID.getInt(); + } else { + final int newPlayerID = this.nextPlayer(); + final Property newPlayer = new Property(uuid, String.valueOf(newPlayerID), Property.Type.INTEGER); + players.put(uuid, newPlayer); + this.playerMapping.put(newPlayerID, profile.getId()); // add to reverse map + this.config.save(); + + return newPlayerID; + } + } + + private int nextPlayer() { + final int r = this.lastPlayerID; + this.lastPlayerID++; + this.config + .get(LAST_PLAYER_CATEGORY, LAST_PLAYER_KEY, this.lastPlayerID) + .set(this.lastPlayerID); + return r; + } + + @Override + public void onWorldStart() { + this.lastPlayerID = this.config + .get(LAST_PLAYER_CATEGORY, LAST_PLAYER_KEY, LAST_PLAYER_DEFAULT) + .getInt(LAST_PLAYER_DEFAULT); + + this.config.save(); + } + + @Override + public void onWorldStop() { + this.config.save(); + + this.lastPlayerID = 0; + } } diff --git a/src/main/java/appeng/core/worlddata/PlayerMapping.java b/src/main/java/appeng/core/worlddata/PlayerMapping.java index 4455eb0c662..dd2c2521d7f 100644 --- a/src/main/java/appeng/core/worlddata/PlayerMapping.java +++ b/src/main/java/appeng/core/worlddata/PlayerMapping.java @@ -18,51 +18,44 @@ package appeng.core.worlddata; - import com.google.common.base.Optional; import com.google.common.base.Preconditions; -import net.minecraftforge.common.config.ConfigCategory; - -import javax.annotation.Nonnull; import java.util.Map; import java.util.UUID; - +import javax.annotation.Nonnull; +import net.minecraftforge.common.config.ConfigCategory; /** * Wrapper class for the player mappings. * Will grant access to a pre initialized player map * based on the "players" category in the settings.cfg */ -final class PlayerMapping implements IWorldPlayerMapping -{ - /** - * View of player mappings, is not immutable, - * since it needs to be edited upon runtime, - * cause new players can join - */ - private final Map mappings; - - public PlayerMapping( final ConfigCategory category ) - { - final PlayerMappingsInitializer init = new PlayerMappingsInitializer( category ); - - this.mappings = init.getPlayerMappings(); - } - - @Nonnull - @Override - public Optional get( final int id ) - { - final UUID maybe = this.mappings.get( id ); - - return Optional.fromNullable( maybe ); - } - - @Override - public void put( final int id, @Nonnull final UUID uuid ) - { - Preconditions.checkNotNull( uuid ); - - this.mappings.put( id, uuid ); - } +final class PlayerMapping implements IWorldPlayerMapping { + /** + * View of player mappings, is not immutable, + * since it needs to be edited upon runtime, + * cause new players can join + */ + private final Map mappings; + + public PlayerMapping(final ConfigCategory category) { + final PlayerMappingsInitializer init = new PlayerMappingsInitializer(category); + + this.mappings = init.getPlayerMappings(); + } + + @Nonnull + @Override + public Optional get(final int id) { + final UUID maybe = this.mappings.get(id); + + return Optional.fromNullable(maybe); + } + + @Override + public void put(final int id, @Nonnull final UUID uuid) { + Preconditions.checkNotNull(uuid); + + this.mappings.put(id, uuid); + } } diff --git a/src/main/java/appeng/core/worlddata/PlayerMappingsInitializer.java b/src/main/java/appeng/core/worlddata/PlayerMappingsInitializer.java index 00910d1d6e1..6792a5c5579 100644 --- a/src/main/java/appeng/core/worlddata/PlayerMappingsInitializer.java +++ b/src/main/java/appeng/core/worlddata/PlayerMappingsInitializer.java @@ -18,75 +18,66 @@ package appeng.core.worlddata; - import appeng.core.AELog; import appeng.util.UUIDMatcher; -import net.minecraftforge.common.config.ConfigCategory; -import net.minecraftforge.common.config.Property; - import java.util.HashMap; import java.util.Map; import java.util.UUID; - +import net.minecraftforge.common.config.ConfigCategory; +import net.minecraftforge.common.config.Property; /** * Initializes a map of ID to UUID from the player list in the settings.cfg */ -class PlayerMappingsInitializer -{ - /** - * Internal immutable mapping - */ - private final Map playerMappings; +class PlayerMappingsInitializer { + /** + * Internal immutable mapping + */ + private final Map playerMappings; - /** - * Creates the initializer for the player mappings. - * The map will be filled upon construction - * and will only be filled with valid entries. - * If an invalid entry is found, an warning is printed, - * mostly due to migration problems from 1.7.2 to 1.7.10 - * where the UUIDs were introduced. - * - * @param playerList the category for the player list, generally extracted using the "players" tag - * @param log the logger used to warn the server or user of faulty entries - */ - PlayerMappingsInitializer( final ConfigCategory playerList ) - { - // Matcher for UUIDs - final UUIDMatcher matcher = new UUIDMatcher(); + /** + * Creates the initializer for the player mappings. + * The map will be filled upon construction + * and will only be filled with valid entries. + * If an invalid entry is found, an warning is printed, + * mostly due to migration problems from 1.7.2 to 1.7.10 + * where the UUIDs were introduced. + * + * @param playerList the category for the player list, generally extracted using the "players" tag + * @param log the logger used to warn the server or user of faulty entries + */ + PlayerMappingsInitializer(final ConfigCategory playerList) { + // Matcher for UUIDs + final UUIDMatcher matcher = new UUIDMatcher(); - // Initial capacity for mappings - final int capacity = playerList.size(); + // Initial capacity for mappings + final int capacity = playerList.size(); - // Mappings for the IDs is a regular HashMap - this.playerMappings = new HashMap( capacity ); + // Mappings for the IDs is a regular HashMap + this.playerMappings = new HashMap(capacity); - // Iterates through every pair of UUID to ID - for( final Map.Entry entry : playerList.getValues().entrySet() ) - { - final String maybeUUID = entry.getKey(); - final int id = entry.getValue().getInt(); + // Iterates through every pair of UUID to ID + for (final Map.Entry entry : playerList.getValues().entrySet()) { + final String maybeUUID = entry.getKey(); + final int id = entry.getValue().getInt(); - if( matcher.isUUID( maybeUUID ) ) - { - final UUID uuidString = UUID.fromString( maybeUUID ); + if (matcher.isUUID(maybeUUID)) { + final UUID uuidString = UUID.fromString(maybeUUID); - this.playerMappings.put( id, uuidString ); - } - else - { - AELog.warn( "The configuration for players contained an outdated entry instead an expected UUID " + maybeUUID + " for the player " + id + ". Please clean this up." ); - } - } - } + this.playerMappings.put(id, uuidString); + } else { + AELog.warn("The configuration for players contained an outdated entry instead an expected UUID " + + maybeUUID + " for the player " + id + ". Please clean this up."); + } + } + } - /** - * Getter - * - * @return Immutable map of the players mappings of their ID to their UUID - */ - public Map getPlayerMappings() - { - return this.playerMappings; - } + /** + * Getter + * + * @return Immutable map of the players mappings of their ID to their UUID + */ + public Map getPlayerMappings() { + return this.playerMappings; + } } diff --git a/src/main/java/appeng/core/worlddata/SpawnData.java b/src/main/java/appeng/core/worlddata/SpawnData.java index 06d6d7b6d8c..49c9d01fda8 100644 --- a/src/main/java/appeng/core/worlddata/SpawnData.java +++ b/src/main/java/appeng/core/worlddata/SpawnData.java @@ -18,196 +18,156 @@ package appeng.core.worlddata; - import appeng.core.AELog; import com.google.common.base.Preconditions; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; - -import javax.annotation.Nonnull; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collection; import java.util.LinkedList; - +import javax.annotation.Nonnull; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -final class SpawnData implements IWorldSpawnData -{ - @Nonnull - private final File spawnDirectory; - @Nonnull - private final MeteorDataNameEncoder encoder; - - public SpawnData( @Nonnull final File spawnDirectory ) - { - Preconditions.checkNotNull( spawnDirectory ); - - this.spawnDirectory = spawnDirectory; - this.encoder = new MeteorDataNameEncoder( 4 ); - } - - @Override - public void setGenerated( final int dim, final int chunkX, final int chunkZ ) - { - synchronized( SpawnData.class ) - { - final NBTTagCompound data = this.loadSpawnData( dim, chunkX, chunkZ ); - - // edit. - data.setBoolean( chunkX + "," + chunkZ, true ); - - this.writeSpawnData( dim, chunkX, chunkZ, data ); - } - } - - @Override - public boolean hasGenerated( final int dim, final int chunkX, final int chunkZ ) - { - synchronized( SpawnData.class ) - { - final NBTTagCompound data = this.loadSpawnData( dim, chunkX, chunkZ ); - return data.getBoolean( chunkX + "," + chunkZ ); - } - } - - @Override - public boolean addNearByMeteorites( final int dim, final int chunkX, final int chunkZ, final NBTTagCompound newData ) - { - synchronized( SpawnData.class ) - { - final NBTTagCompound data = this.loadSpawnData( dim, chunkX, chunkZ ); - - // edit. - final int size = data.getInteger( "num" ); - data.setTag( String.valueOf( size ), newData ); - data.setInteger( "num", size + 1 ); - - this.writeSpawnData( dim, chunkX, chunkZ, data ); - - return true; - } - } - - @Override - public Collection getNearByMeteorites( final int dim, final int chunkX, final int chunkZ ) - { - final Collection ll = new LinkedList(); - - synchronized( SpawnData.class ) - { - for( int x = -1; x <= 1; x++ ) - { - for( int z = -1; z <= 1; z++ ) - { - final int cx = x + ( chunkX >> 4 ); - final int cz = z + ( chunkZ >> 4 ); - - final NBTTagCompound data = this.loadSpawnData( dim, cx << 4, cz << 4 ); - - if( data != null ) - { - // edit. - final int size = data.getInteger( "num" ); - for( int s = 0; s < size; s++ ) - { - ll.add( data.getCompoundTag( String.valueOf( s ) ) ); - } - } - } - } - } - - return ll; - } - - private NBTTagCompound loadSpawnData( final int dim, final int chunkX, final int chunkZ ) - { - if( !Thread.holdsLock( SpawnData.class ) ) - { - throw new IllegalStateException( "Invalid Request" ); - } - - NBTTagCompound data = null; - final String fileName = this.encoder.encode( dim, chunkX, chunkZ ); - final File file = new File( this.spawnDirectory, fileName ); - - if( file.isFile() ) - { - FileInputStream fileInputStream = null; - - try - { - fileInputStream = new FileInputStream( file ); - data = CompressedStreamTools.readCompressed( fileInputStream ); - } - catch( final Throwable e ) - { - data = new NBTTagCompound(); - AELog.debug( e ); - } - finally - { - if( fileInputStream != null ) - { - try - { - fileInputStream.close(); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - } - else - { - data = new NBTTagCompound(); - } - - return data; - } - - private void writeSpawnData( final int dim, final int chunkX, final int chunkZ, final NBTTagCompound data ) - { - if( !Thread.holdsLock( SpawnData.class ) ) - { - throw new IllegalStateException( "Invalid Request" ); - } - - final String fileName = this.encoder.encode( dim, chunkX, chunkZ ); - final File file = new File( this.spawnDirectory, fileName ); - FileOutputStream fileOutputStream = null; - - try - { - fileOutputStream = new FileOutputStream( file ); - CompressedStreamTools.writeCompressed( data, fileOutputStream ); - } - catch( final Throwable e ) - { - AELog.debug( e ); - } - finally - { - if( fileOutputStream != null ) - { - try - { - fileOutputStream.close(); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - } +final class SpawnData implements IWorldSpawnData { + @Nonnull + private final File spawnDirectory; + + @Nonnull + private final MeteorDataNameEncoder encoder; + + public SpawnData(@Nonnull final File spawnDirectory) { + Preconditions.checkNotNull(spawnDirectory); + + this.spawnDirectory = spawnDirectory; + this.encoder = new MeteorDataNameEncoder(4); + } + + @Override + public void setGenerated(final int dim, final int chunkX, final int chunkZ) { + synchronized (SpawnData.class) { + final NBTTagCompound data = this.loadSpawnData(dim, chunkX, chunkZ); + + // edit. + data.setBoolean(chunkX + "," + chunkZ, true); + + this.writeSpawnData(dim, chunkX, chunkZ, data); + } + } + + @Override + public boolean hasGenerated(final int dim, final int chunkX, final int chunkZ) { + synchronized (SpawnData.class) { + final NBTTagCompound data = this.loadSpawnData(dim, chunkX, chunkZ); + return data.getBoolean(chunkX + "," + chunkZ); + } + } + + @Override + public boolean addNearByMeteorites( + final int dim, final int chunkX, final int chunkZ, final NBTTagCompound newData) { + synchronized (SpawnData.class) { + final NBTTagCompound data = this.loadSpawnData(dim, chunkX, chunkZ); + + // edit. + final int size = data.getInteger("num"); + data.setTag(String.valueOf(size), newData); + data.setInteger("num", size + 1); + + this.writeSpawnData(dim, chunkX, chunkZ, data); + + return true; + } + } + + @Override + public Collection getNearByMeteorites(final int dim, final int chunkX, final int chunkZ) { + final Collection ll = new LinkedList(); + + synchronized (SpawnData.class) { + for (int x = -1; x <= 1; x++) { + for (int z = -1; z <= 1; z++) { + final int cx = x + (chunkX >> 4); + final int cz = z + (chunkZ >> 4); + + final NBTTagCompound data = this.loadSpawnData(dim, cx << 4, cz << 4); + + if (data != null) { + // edit. + final int size = data.getInteger("num"); + for (int s = 0; s < size; s++) { + ll.add(data.getCompoundTag(String.valueOf(s))); + } + } + } + } + } + + return ll; + } + + private NBTTagCompound loadSpawnData(final int dim, final int chunkX, final int chunkZ) { + if (!Thread.holdsLock(SpawnData.class)) { + throw new IllegalStateException("Invalid Request"); + } + + NBTTagCompound data = null; + final String fileName = this.encoder.encode(dim, chunkX, chunkZ); + final File file = new File(this.spawnDirectory, fileName); + + if (file.isFile()) { + FileInputStream fileInputStream = null; + + try { + fileInputStream = new FileInputStream(file); + data = CompressedStreamTools.readCompressed(fileInputStream); + } catch (final Throwable e) { + data = new NBTTagCompound(); + AELog.debug(e); + } finally { + if (fileInputStream != null) { + try { + fileInputStream.close(); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + } else { + data = new NBTTagCompound(); + } + + return data; + } + + private void writeSpawnData(final int dim, final int chunkX, final int chunkZ, final NBTTagCompound data) { + if (!Thread.holdsLock(SpawnData.class)) { + throw new IllegalStateException("Invalid Request"); + } + + final String fileName = this.encoder.encode(dim, chunkX, chunkZ); + final File file = new File(this.spawnDirectory, fileName); + FileOutputStream fileOutputStream = null; + + try { + fileOutputStream = new FileOutputStream(file); + CompressedStreamTools.writeCompressed(data, fileOutputStream); + } catch (final Throwable e) { + AELog.debug(e); + } finally { + if (fileOutputStream != null) { + try { + fileOutputStream.close(); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + } } diff --git a/src/main/java/appeng/core/worlddata/StorageData.java b/src/main/java/appeng/core/worlddata/StorageData.java index ce0f91b4f19..850874812e6 100644 --- a/src/main/java/appeng/core/worlddata/StorageData.java +++ b/src/main/java/appeng/core/worlddata/StorageData.java @@ -18,144 +18,133 @@ package appeng.core.worlddata; - import appeng.core.AELog; import appeng.me.GridStorage; import appeng.me.GridStorageSearch; import com.google.common.base.Preconditions; -import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.common.config.Property; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.lang.ref.WeakReference; import java.util.Map; import java.util.WeakHashMap; - +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.common.config.Property; /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -final class StorageData implements IWorldGridStorageData, IOnWorldStartable, IOnWorldStoppable -{ - private static final String LAST_GRID_STORAGE_CATEGORY = "Counters"; - private static final String LAST_GRID_STORAGE_KEY = "lastGridStorage"; - private static final int LAST_GRID_STORAGE_DEFAULT = 0; - - private static final String GRID_STORAGE_CATEGORY = "gridstorage"; - - private final Map> loadedStorage = new WeakHashMap>( 10 ); - private final Configuration config; - - private long lastGridStorage; - - public StorageData( @Nonnull final Configuration settingsFile ) - { - Preconditions.checkNotNull( settingsFile ); - - this.config = settingsFile; - } - - /** - * lazy loading, can load any id, even ones that don't exist anymore. - * - * @param storageID ID of grid storage - * @return corresponding grid storage - */ - @Nullable - @Override - public GridStorage getGridStorage( final long storageID ) - { - final GridStorageSearch gss = new GridStorageSearch( storageID ); - final WeakReference result = this.loadedStorage.get( gss ); - - if( result == null || result.get() == null ) - { - final String id = String.valueOf( storageID ); - final String data = this.config.get( "gridstorage", id, "" ).getString(); - final GridStorage thisStorage = new GridStorage( data, storageID, gss ); - gss.setGridStorage( new WeakReference( thisStorage ) ); - this.loadedStorage.put( gss, new WeakReference( gss ) ); - return thisStorage; - } - - return result.get().getGridStorage().get(); - } - - /** - * create a new storage - */ - @Nonnull - @Override - public GridStorage getNewGridStorage() - { - final long storageID = this.nextGridStorage(); - final GridStorageSearch gss = new GridStorageSearch( storageID ); - final GridStorage newStorage = new GridStorage( storageID, gss ); - gss.setGridStorage( new WeakReference( newStorage ) ); - this.loadedStorage.put( gss, new WeakReference( gss ) ); - - return newStorage; - } - - @Override - public long nextGridStorage() - { - final long r = this.lastGridStorage; - this.lastGridStorage++; - this.config.get( "Counters", "lastGridStorage", this.lastGridStorage ).set( Long.toString( this.lastGridStorage ) ); - return r; - } - - @Override - public void destroyGridStorage( final long id ) - { - final String stringID = String.valueOf( id ); - this.config.getCategory( "gridstorage" ).remove( stringID ); - } - - @Override - public int getNextOrderedValue( final String name ) - { - final Property p = this.config.get( "orderedValues", name, 0 ); - final int myValue = p.getInt(); - p.set( myValue + 1 ); - return myValue; - } - - @Override - public void onWorldStart() - { - final String lastString = this.config.get( LAST_GRID_STORAGE_CATEGORY, LAST_GRID_STORAGE_KEY, LAST_GRID_STORAGE_DEFAULT ).getString(); - - try - { - this.lastGridStorage = Long.parseLong( lastString ); - } - catch( final NumberFormatException err ) - { - AELog.warn( "The config contained a value which was not represented as a Long: %s", lastString ); - - this.lastGridStorage = 0; - } - } - - @Override - public void onWorldStop() - { - // populate new data - for( final GridStorageSearch gs : this.loadedStorage.keySet() ) - { - final GridStorage thisStorage = gs.getGridStorage().get(); - if( thisStorage != null && thisStorage.getGrid() != null && !thisStorage.getGrid().isEmpty() ) - { - final String value = thisStorage.getValue(); - this.config.get( GRID_STORAGE_CATEGORY, String.valueOf( thisStorage.getID() ), value ).set( value ); - } - } - - this.config.save(); - } +final class StorageData implements IWorldGridStorageData, IOnWorldStartable, IOnWorldStoppable { + private static final String LAST_GRID_STORAGE_CATEGORY = "Counters"; + private static final String LAST_GRID_STORAGE_KEY = "lastGridStorage"; + private static final int LAST_GRID_STORAGE_DEFAULT = 0; + + private static final String GRID_STORAGE_CATEGORY = "gridstorage"; + + private final Map> loadedStorage = + new WeakHashMap>(10); + private final Configuration config; + + private long lastGridStorage; + + public StorageData(@Nonnull final Configuration settingsFile) { + Preconditions.checkNotNull(settingsFile); + + this.config = settingsFile; + } + + /** + * lazy loading, can load any id, even ones that don't exist anymore. + * + * @param storageID ID of grid storage + * @return corresponding grid storage + */ + @Nullable + @Override + public GridStorage getGridStorage(final long storageID) { + final GridStorageSearch gss = new GridStorageSearch(storageID); + final WeakReference result = this.loadedStorage.get(gss); + + if (result == null || result.get() == null) { + final String id = String.valueOf(storageID); + final String data = this.config.get("gridstorage", id, "").getString(); + final GridStorage thisStorage = new GridStorage(data, storageID, gss); + gss.setGridStorage(new WeakReference(thisStorage)); + this.loadedStorage.put(gss, new WeakReference(gss)); + return thisStorage; + } + + return result.get().getGridStorage().get(); + } + + /** + * create a new storage + */ + @Nonnull + @Override + public GridStorage getNewGridStorage() { + final long storageID = this.nextGridStorage(); + final GridStorageSearch gss = new GridStorageSearch(storageID); + final GridStorage newStorage = new GridStorage(storageID, gss); + gss.setGridStorage(new WeakReference(newStorage)); + this.loadedStorage.put(gss, new WeakReference(gss)); + + return newStorage; + } + + @Override + public long nextGridStorage() { + final long r = this.lastGridStorage; + this.lastGridStorage++; + this.config.get("Counters", "lastGridStorage", this.lastGridStorage).set(Long.toString(this.lastGridStorage)); + return r; + } + + @Override + public void destroyGridStorage(final long id) { + final String stringID = String.valueOf(id); + this.config.getCategory("gridstorage").remove(stringID); + } + + @Override + public int getNextOrderedValue(final String name) { + final Property p = this.config.get("orderedValues", name, 0); + final int myValue = p.getInt(); + p.set(myValue + 1); + return myValue; + } + + @Override + public void onWorldStart() { + final String lastString = this.config + .get(LAST_GRID_STORAGE_CATEGORY, LAST_GRID_STORAGE_KEY, LAST_GRID_STORAGE_DEFAULT) + .getString(); + + try { + this.lastGridStorage = Long.parseLong(lastString); + } catch (final NumberFormatException err) { + AELog.warn("The config contained a value which was not represented as a Long: %s", lastString); + + this.lastGridStorage = 0; + } + } + + @Override + public void onWorldStop() { + // populate new data + for (final GridStorageSearch gs : this.loadedStorage.keySet()) { + final GridStorage thisStorage = gs.getGridStorage().get(); + if (thisStorage != null + && thisStorage.getGrid() != null + && !thisStorage.getGrid().isEmpty()) { + final String value = thisStorage.getValue(); + this.config + .get(GRID_STORAGE_CATEGORY, String.valueOf(thisStorage.getID()), value) + .set(value); + } + } + + this.config.save(); + } } diff --git a/src/main/java/appeng/core/worlddata/WorldData.java b/src/main/java/appeng/core/worlddata/WorldData.java index 3ead1880ae0..39da7944c15 100644 --- a/src/main/java/appeng/core/worlddata/WorldData.java +++ b/src/main/java/appeng/core/worlddata/WorldData.java @@ -18,21 +18,18 @@ package appeng.core.worlddata; - import appeng.core.AEConfig; import appeng.services.CompassService; import appeng.services.compass.CompassThreadFactory; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; -import net.minecraftforge.common.DimensionManager; -import net.minecraftforge.common.config.Configuration; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.io.File; import java.util.List; import java.util.concurrent.ThreadFactory; - +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import net.minecraftforge.common.DimensionManager; +import net.minecraftforge.common.config.Configuration; /** * Singleton access to anything related to world-based data. @@ -45,166 +42,149 @@ * @version rv3 - 02.11.2015 * @since rv3 30.05.2015 */ -public final class WorldData implements IWorldData -{ - private static final String AE2_DIRECTORY_NAME = "AE2"; - private static final String SETTING_FILE_NAME = "settings.cfg"; - private static final String SPAWNDATA_DIR_NAME = "spawndata"; - private static final String COMPASS_DIR_NAME = "compass"; - - @Nullable - private static IWorldData instance; - - private final IWorldPlayerData playerData; - private final IWorldDimensionData dimensionData; - private final IWorldGridStorageData storageData; - private final IWorldCompassData compassData; - private final IWorldSpawnData spawnData; - - private final List startables; - private final List stoppables; - - private final File ae2directory; - private final File spawnDirectory; - private final File compassDirectory; - - private final Configuration sharedConfig; - - private WorldData( @Nonnull final File worldDirectory ) - { - Preconditions.checkNotNull( worldDirectory ); - Preconditions.checkArgument( worldDirectory.isDirectory() ); - - this.ae2directory = new File( worldDirectory, AE2_DIRECTORY_NAME ); - this.spawnDirectory = new File( this.ae2directory, SPAWNDATA_DIR_NAME ); - this.compassDirectory = new File( this.ae2directory, COMPASS_DIR_NAME ); - - final File settingsFile = new File( this.ae2directory, SETTING_FILE_NAME ); - this.sharedConfig = new Configuration( settingsFile, AEConfig.VERSION ); - - final PlayerData playerData = new PlayerData( this.sharedConfig ); - final DimensionData dimensionData = new DimensionData( this.sharedConfig ); - final StorageData storageData = new StorageData( this.sharedConfig ); - - final ThreadFactory compassThreadFactory = new CompassThreadFactory(); - final CompassService compassService = new CompassService( this.compassDirectory, compassThreadFactory ); - final CompassData compassData = new CompassData( this.compassDirectory, compassService ); - - final IWorldSpawnData spawnData = new SpawnData( this.spawnDirectory ); - - this.playerData = playerData; - this.dimensionData = dimensionData; - this.storageData = storageData; - this.compassData = compassData; - this.spawnData = spawnData; - - this.startables = Lists.newArrayList( playerData, dimensionData, storageData ); - this.stoppables = Lists.newArrayList( playerData, dimensionData, storageData, compassData ); - } - - /** - * @return ae2 data related to a specific world - * @deprecated do not use singletons which are dependent on specific world state - */ - @Deprecated - @Nonnull - public static IWorldData instance() - { - return instance; - } - - /** - * Requires to start up from external from here - *

- * drawback of the singleton build style - */ - public static void onServerAboutToStart() - { - final File worldDirectory = DimensionManager.getCurrentSaveRootDirectory(); - final WorldData newInstance = new WorldData( worldDirectory ); - - instance = newInstance; - newInstance.onServerStarting(); - } - - private void onServerStarting() - { - // check if ae2 folder already exists, else create - if( !this.ae2directory.isDirectory() && !this.ae2directory.mkdir() ) - { - throw new IllegalStateException( "Failed to create " + this.ae2directory.getAbsolutePath() ); - } - - // check if compass folder already exists, else create - if( !this.compassDirectory.isDirectory() && !this.compassDirectory.mkdir() ) - { - throw new IllegalStateException( "Failed to create " + this.compassDirectory.getAbsolutePath() ); - } - - // check if spawn data dir already exists, else create - if( !this.spawnDirectory.isDirectory() && !this.spawnDirectory.mkdir() ) - { - throw new IllegalStateException( "Failed to create " + this.spawnDirectory.getAbsolutePath() ); - } - - for( final IOnWorldStartable startable : this.startables ) - { - startable.onWorldStart(); - } - - this.startables.clear(); - } - - @Override - public void onServerStopping() - { - for( final IOnWorldStoppable stoppable : this.stoppables ) - { - stoppable.onWorldStop(); - } - } - - @Override - public void onServerStoppped() - { - Preconditions.checkNotNull( instance ); - - this.stoppables.clear(); - instance = null; - } - - @Nonnull - @Override - public IWorldGridStorageData storageData() - { - return this.storageData; - } - - @Nonnull - @Override - public IWorldPlayerData playerData() - { - return this.playerData; - } - - @Nonnull - @Override - public IWorldDimensionData dimensionData() - { - return this.dimensionData; - } - - @Nonnull - @Override - public IWorldCompassData compassData() - { - return this.compassData; - } - - @Nonnull - @Override - public IWorldSpawnData spawnData() - { - return this.spawnData; - } +public final class WorldData implements IWorldData { + private static final String AE2_DIRECTORY_NAME = "AE2"; + private static final String SETTING_FILE_NAME = "settings.cfg"; + private static final String SPAWNDATA_DIR_NAME = "spawndata"; + private static final String COMPASS_DIR_NAME = "compass"; + + @Nullable + private static IWorldData instance; + + private final IWorldPlayerData playerData; + private final IWorldDimensionData dimensionData; + private final IWorldGridStorageData storageData; + private final IWorldCompassData compassData; + private final IWorldSpawnData spawnData; + + private final List startables; + private final List stoppables; + + private final File ae2directory; + private final File spawnDirectory; + private final File compassDirectory; + + private final Configuration sharedConfig; + + private WorldData(@Nonnull final File worldDirectory) { + Preconditions.checkNotNull(worldDirectory); + Preconditions.checkArgument(worldDirectory.isDirectory()); + + this.ae2directory = new File(worldDirectory, AE2_DIRECTORY_NAME); + this.spawnDirectory = new File(this.ae2directory, SPAWNDATA_DIR_NAME); + this.compassDirectory = new File(this.ae2directory, COMPASS_DIR_NAME); + + final File settingsFile = new File(this.ae2directory, SETTING_FILE_NAME); + this.sharedConfig = new Configuration(settingsFile, AEConfig.VERSION); + + final PlayerData playerData = new PlayerData(this.sharedConfig); + final DimensionData dimensionData = new DimensionData(this.sharedConfig); + final StorageData storageData = new StorageData(this.sharedConfig); + + final ThreadFactory compassThreadFactory = new CompassThreadFactory(); + final CompassService compassService = new CompassService(this.compassDirectory, compassThreadFactory); + final CompassData compassData = new CompassData(this.compassDirectory, compassService); + + final IWorldSpawnData spawnData = new SpawnData(this.spawnDirectory); + + this.playerData = playerData; + this.dimensionData = dimensionData; + this.storageData = storageData; + this.compassData = compassData; + this.spawnData = spawnData; + + this.startables = Lists.newArrayList(playerData, dimensionData, storageData); + this.stoppables = Lists.newArrayList(playerData, dimensionData, storageData, compassData); + } + + /** + * @return ae2 data related to a specific world + * @deprecated do not use singletons which are dependent on specific world state + */ + @Deprecated + @Nonnull + public static IWorldData instance() { + return instance; + } + + /** + * Requires to start up from external from here + *

+ * drawback of the singleton build style + */ + public static void onServerAboutToStart() { + final File worldDirectory = DimensionManager.getCurrentSaveRootDirectory(); + final WorldData newInstance = new WorldData(worldDirectory); + + instance = newInstance; + newInstance.onServerStarting(); + } + + private void onServerStarting() { + // check if ae2 folder already exists, else create + if (!this.ae2directory.isDirectory() && !this.ae2directory.mkdir()) { + throw new IllegalStateException("Failed to create " + this.ae2directory.getAbsolutePath()); + } + + // check if compass folder already exists, else create + if (!this.compassDirectory.isDirectory() && !this.compassDirectory.mkdir()) { + throw new IllegalStateException("Failed to create " + this.compassDirectory.getAbsolutePath()); + } + + // check if spawn data dir already exists, else create + if (!this.spawnDirectory.isDirectory() && !this.spawnDirectory.mkdir()) { + throw new IllegalStateException("Failed to create " + this.spawnDirectory.getAbsolutePath()); + } + + for (final IOnWorldStartable startable : this.startables) { + startable.onWorldStart(); + } + + this.startables.clear(); + } + + @Override + public void onServerStopping() { + for (final IOnWorldStoppable stoppable : this.stoppables) { + stoppable.onWorldStop(); + } + } + + @Override + public void onServerStoppped() { + Preconditions.checkNotNull(instance); + + this.stoppables.clear(); + instance = null; + } + + @Nonnull + @Override + public IWorldGridStorageData storageData() { + return this.storageData; + } + + @Nonnull + @Override + public IWorldPlayerData playerData() { + return this.playerData; + } + + @Nonnull + @Override + public IWorldDimensionData dimensionData() { + return this.dimensionData; + } + + @Nonnull + @Override + public IWorldCompassData compassData() { + return this.compassData; + } + + @Nonnull + @Override + public IWorldSpawnData spawnData() { + return this.spawnData; + } } diff --git a/src/main/java/appeng/crafting/CraftBranchFailure.java b/src/main/java/appeng/crafting/CraftBranchFailure.java index c04916783bb..98ed7e5e795 100644 --- a/src/main/java/appeng/crafting/CraftBranchFailure.java +++ b/src/main/java/appeng/crafting/CraftBranchFailure.java @@ -18,21 +18,17 @@ package appeng.crafting; - import appeng.api.storage.data.IAEItemStack; +public class CraftBranchFailure extends Exception { -public class CraftBranchFailure extends Exception -{ - - private static final long serialVersionUID = 654603652836724823L; + private static final long serialVersionUID = 654603652836724823L; - private final IAEItemStack missing; + private final IAEItemStack missing; - public CraftBranchFailure( final IAEItemStack what, final long howMany ) - { - super( "Failed: " + what.getItem().getUnlocalizedName() + " x " + howMany ); - this.missing = what.copy(); - this.missing.setStackSize( howMany ); - } + public CraftBranchFailure(final IAEItemStack what, final long howMany) { + super("Failed: " + what.getItem().getUnlocalizedName() + " x " + howMany); + this.missing = what.copy(); + this.missing.setStackSize(howMany); + } } diff --git a/src/main/java/appeng/crafting/CraftingCalculationFailure.java b/src/main/java/appeng/crafting/CraftingCalculationFailure.java index bfaa7ece25b..bf2313a3727 100644 --- a/src/main/java/appeng/crafting/CraftingCalculationFailure.java +++ b/src/main/java/appeng/crafting/CraftingCalculationFailure.java @@ -18,21 +18,17 @@ package appeng.crafting; - import appeng.api.storage.data.IAEItemStack; +public class CraftingCalculationFailure extends RuntimeException { -public class CraftingCalculationFailure extends RuntimeException -{ - - private static final long serialVersionUID = 654603652836724823L; + private static final long serialVersionUID = 654603652836724823L; - private final IAEItemStack missing; + private final IAEItemStack missing; - public CraftingCalculationFailure( final IAEItemStack what, final long howMany ) - { - super( "this should have been caught!" ); - this.missing = what.copy(); - this.missing.setStackSize( howMany ); - } + public CraftingCalculationFailure(final IAEItemStack what, final long howMany) { + super("this should have been caught!"); + this.missing = what.copy(); + this.missing.setStackSize(howMany); + } } diff --git a/src/main/java/appeng/crafting/CraftingJob.java b/src/main/java/appeng/crafting/CraftingJob.java index 9d8470999c6..dafafb67622 100644 --- a/src/main/java/appeng/crafting/CraftingJob.java +++ b/src/main/java/appeng/crafting/CraftingJob.java @@ -18,7 +18,6 @@ package appeng.crafting; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.networking.IGrid; @@ -39,367 +38,305 @@ import appeng.core.AELog; import appeng.hooks.TickHandler; import com.google.common.base.Stopwatch; +import java.util.HashMap; +import java.util.concurrent.TimeUnit; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; - - -public class CraftingJob implements Runnable, ICraftingJob -{ - private static final String LOG_CRAFTING_JOB = "CraftingJob (%s) issued by %s requesting [%s] using %s bytes took %s ms"; - private static final String LOG_MACHINE_SOURCE_DETAILS = "Machine[object=%s, %s]"; - - private final MECraftingInventory original; - private final World world; - private final IItemList crafting = AEApi.instance().storage().createItemList(); - private final IItemList missing = AEApi.instance().storage().createItemList(); - private final HashMap opsAndMultiplier = new HashMap(); - private final Object monitor = new Object(); - private final Stopwatch watch = Stopwatch.createUnstarted(); - private CraftingTreeNode tree; - private final IAEItemStack output; - private boolean simulate = false; - private MECraftingInventory availableCheck; - private long bytes = 0; - private final BaseActionSource actionSrc; - private final ICraftingCallback callback; - private boolean running = false; - private boolean done = false; - private int time = 5; - private int incTime = Integer.MAX_VALUE; - - private World wrapWorld( final World w ) - { - return w; - } - - public CraftingJob( final World w, final IGrid grid, final BaseActionSource actionSrc, final IAEItemStack what, final ICraftingCallback callback ) - { - this.world = this.wrapWorld( w ); - this.output = what.copy(); - this.actionSrc = actionSrc; - - this.callback = callback; - final ICraftingGrid cc = grid.getCache( ICraftingGrid.class ); - final IStorageGrid sg = grid.getCache( IStorageGrid.class ); - this.original = new MECraftingInventory( sg.getItemInventory(), actionSrc, false, false, false ); - - this.setTree( this.getCraftingTree( cc, what ) ); - this.availableCheck = null; - } - - private CraftingTreeNode getCraftingTree( final ICraftingGrid cc, final IAEItemStack what ) - { - return new CraftingTreeNode( cc, this, what, null, -1, 0 ); - } - - void refund( final IAEItemStack o ) - { - this.availableCheck.injectItems( o, Actionable.MODULATE, this.actionSrc ); - } - - IAEItemStack checkUse( final IAEItemStack available ) - { - return this.availableCheck.extractItems( available, Actionable.MODULATE, this.actionSrc ); - } - - public void writeToNBT( final NBTTagCompound out ) - { - - } - - void addTask( IAEItemStack what, final long crafts, final ICraftingPatternDetails details, final int depth ) - { - if( crafts > 0 ) - { - what = what.copy(); - what.setStackSize( what.getStackSize() * crafts ); - this.crafting.add( what ); - } - } - - void addMissing( IAEItemStack what ) - { - what = what.copy(); - this.missing.add( what ); - } - - @Override - public void run() - { - try - { - try - { - TickHandler.INSTANCE.registerCraftingSimulation( this.world, this ); - this.handlePausing(); - - final Stopwatch timer = Stopwatch.createStarted(); - - final MECraftingInventory craftingInventory = new MECraftingInventory( this.original, true, false, true ); - craftingInventory.ignore( this.output ); - - this.availableCheck = new MECraftingInventory( this.original, false, false, false ); - this.getTree().request( craftingInventory, this.output.getStackSize(), this.actionSrc ); - this.getTree().dive( this ); - - for( final String s : this.opsAndMultiplier.keySet() ) - { - final TwoIntegers ti = this.opsAndMultiplier.get( s ); - AELog.crafting( s + " * " + ti.times + " = " + ( ti.perOp * ti.times ) ); - } - - this.logCraftingJob( "real", timer ); - // if ( mode == Actionable.MODULATE ) - // craftingInventory.moveItemsToStorage( storage ); - } - catch( final CraftBranchFailure e ) - { - this.simulate = true; - - try - { - final Stopwatch timer = Stopwatch.createStarted(); - final MECraftingInventory craftingInventory = new MECraftingInventory( this.original, true, false, true ); - craftingInventory.ignore( this.output ); - - this.availableCheck = new MECraftingInventory( this.original, false, false, false ); - - this.getTree().setSimulate(); - this.getTree().request( craftingInventory, this.output.getStackSize(), this.actionSrc ); - this.getTree().dive( this ); - - for( final String s : this.opsAndMultiplier.keySet() ) - { - final TwoIntegers ti = this.opsAndMultiplier.get( s ); - AELog.crafting( s + " * " + ti.times + " = " + ( ti.perOp * ti.times ) ); - } - - this.logCraftingJob( "simulate", timer ); - } - catch( final CraftBranchFailure e1 ) - { - AELog.debug( e1 ); - } - catch( final CraftingCalculationFailure f ) - { - AELog.debug( f ); - } - catch( final InterruptedException e1 ) - { - AELog.crafting( "Crafting calculation canceled." ); - this.finish(); - return; - } - } - catch( final CraftingCalculationFailure f ) - { - AELog.debug( f ); - } - catch( final InterruptedException e1 ) - { - AELog.crafting( "Crafting calculation canceled." ); - this.finish(); - return; - } - - AELog.craftingDebug( "crafting job now done" ); - } - catch( final Throwable t ) - { - this.finish(); - throw new IllegalStateException( t ); - } - - this.finish(); - } - - void handlePausing() throws InterruptedException - { - if( this.incTime > 100 ) - { - this.incTime = 0; - - synchronized( this.monitor ) - { - if( this.watch.elapsed( TimeUnit.MICROSECONDS ) > this.time ) - { - this.running = false; - this.watch.stop(); - this.monitor.notify(); - } - - if( !this.running ) - { - AELog.craftingDebug( "crafting job will now sleep" ); - - while( !this.running ) - { - this.monitor.wait(); - } - - AELog.craftingDebug( "crafting job now active" ); - } - } - - if( Thread.interrupted() ) - { - throw new InterruptedException(); - } - } - this.incTime++; - } - - private void finish() - { - if( this.callback != null ) - { - this.callback.calculationComplete( this ); - } - - this.availableCheck = null; - - synchronized( this.monitor ) - { - this.running = false; - this.done = true; - this.monitor.notify(); - } - } - - @Override - public boolean isSimulation() - { - return this.simulate; - } - - @Override - public long getByteTotal() - { - return this.bytes; - } - - @Override - public void populatePlan( final IItemList plan ) - { - if( this.getTree() != null ) - { - this.getTree().getPlan( plan ); - } - } - - @Override - public IAEItemStack getOutput() - { - return this.output; - } - - public boolean isDone() - { - return this.done; - } - - World getWorld() - { - return this.world; - } - - /** - * returns true if this needs more simulation. - * - * @param milli milliseconds of simulation - * @return true if this needs more simulation - */ - public boolean simulateFor( final int milli ) - { - this.time = milli; - - synchronized( this.monitor ) - { - if( this.done ) - { - return false; - } - - this.watch.reset(); - this.watch.start(); - this.running = true; - - AELog.craftingDebug( "main thread is now going to sleep" ); - - this.monitor.notify(); - - while( this.running ) - { - try - { - this.monitor.wait(); - } - catch( final InterruptedException ignored ) - { - } - } - - AELog.craftingDebug( "main thread is now active" ); - } - - return true; - } - - void addBytes( final long crafts ) - { - this.bytes += crafts; - } - - public CraftingTreeNode getTree() - { - return this.tree; - } - - private void setTree( final CraftingTreeNode tree ) - { - this.tree = tree; - } - - private void logCraftingJob( String type, Stopwatch timer ) - { - if( AELog.isCraftingLogEnabled() ) - { - final String itemToOutput = this.output.toString(); - final long elapsedTime = timer.elapsed( TimeUnit.MILLISECONDS ); - final String actionSource; - - if( this.actionSrc instanceof MachineSource ) - { - final IActionHost machineSource = ( (MachineSource) this.actionSrc ).via; - final IGridNode actionableNode = machineSource.getActionableNode(); - final IGridHost machine = actionableNode.getMachine(); - final DimensionalCoord location = actionableNode.getGridBlock().getLocation(); - - actionSource = String.format( LOG_MACHINE_SOURCE_DETAILS, machine, location ); - } - else if( this.actionSrc instanceof PlayerSource ) - { - final PlayerSource source = (PlayerSource) this.actionSrc; - final EntityPlayer player = source.player; - - actionSource = player.toString(); - } - else - { - actionSource = "[unknown source]"; - } - - AELog.crafting( LOG_CRAFTING_JOB, type, actionSource, itemToOutput, this.bytes, elapsedTime ); - } - } - - private static class TwoIntegers - { - private final long perOp = 0; - private final long times = 0; - } +public class CraftingJob implements Runnable, ICraftingJob { + private static final String LOG_CRAFTING_JOB = + "CraftingJob (%s) issued by %s requesting [%s] using %s bytes took %s ms"; + private static final String LOG_MACHINE_SOURCE_DETAILS = "Machine[object=%s, %s]"; + + private final MECraftingInventory original; + private final World world; + private final IItemList crafting = AEApi.instance().storage().createItemList(); + private final IItemList missing = AEApi.instance().storage().createItemList(); + private final HashMap opsAndMultiplier = new HashMap(); + private final Object monitor = new Object(); + private final Stopwatch watch = Stopwatch.createUnstarted(); + private CraftingTreeNode tree; + private final IAEItemStack output; + private boolean simulate = false; + private MECraftingInventory availableCheck; + private long bytes = 0; + private final BaseActionSource actionSrc; + private final ICraftingCallback callback; + private boolean running = false; + private boolean done = false; + private int time = 5; + private int incTime = Integer.MAX_VALUE; + + private World wrapWorld(final World w) { + return w; + } + + public CraftingJob( + final World w, + final IGrid grid, + final BaseActionSource actionSrc, + final IAEItemStack what, + final ICraftingCallback callback) { + this.world = this.wrapWorld(w); + this.output = what.copy(); + this.actionSrc = actionSrc; + + this.callback = callback; + final ICraftingGrid cc = grid.getCache(ICraftingGrid.class); + final IStorageGrid sg = grid.getCache(IStorageGrid.class); + this.original = new MECraftingInventory(sg.getItemInventory(), actionSrc, false, false, false); + + this.setTree(this.getCraftingTree(cc, what)); + this.availableCheck = null; + } + + private CraftingTreeNode getCraftingTree(final ICraftingGrid cc, final IAEItemStack what) { + return new CraftingTreeNode(cc, this, what, null, -1, 0); + } + + void refund(final IAEItemStack o) { + this.availableCheck.injectItems(o, Actionable.MODULATE, this.actionSrc); + } + + IAEItemStack checkUse(final IAEItemStack available) { + return this.availableCheck.extractItems(available, Actionable.MODULATE, this.actionSrc); + } + + public void writeToNBT(final NBTTagCompound out) {} + + void addTask(IAEItemStack what, final long crafts, final ICraftingPatternDetails details, final int depth) { + if (crafts > 0) { + what = what.copy(); + what.setStackSize(what.getStackSize() * crafts); + this.crafting.add(what); + } + } + + void addMissing(IAEItemStack what) { + what = what.copy(); + this.missing.add(what); + } + + @Override + public void run() { + try { + try { + TickHandler.INSTANCE.registerCraftingSimulation(this.world, this); + this.handlePausing(); + + final Stopwatch timer = Stopwatch.createStarted(); + + final MECraftingInventory craftingInventory = new MECraftingInventory(this.original, true, false, true); + craftingInventory.ignore(this.output); + + this.availableCheck = new MECraftingInventory(this.original, false, false, false); + this.getTree().request(craftingInventory, this.output.getStackSize(), this.actionSrc); + this.getTree().dive(this); + + for (final String s : this.opsAndMultiplier.keySet()) { + final TwoIntegers ti = this.opsAndMultiplier.get(s); + AELog.crafting(s + " * " + ti.times + " = " + (ti.perOp * ti.times)); + } + + this.logCraftingJob("real", timer); + // if ( mode == Actionable.MODULATE ) + // craftingInventory.moveItemsToStorage( storage ); + } catch (final CraftBranchFailure e) { + this.simulate = true; + + try { + final Stopwatch timer = Stopwatch.createStarted(); + final MECraftingInventory craftingInventory = + new MECraftingInventory(this.original, true, false, true); + craftingInventory.ignore(this.output); + + this.availableCheck = new MECraftingInventory(this.original, false, false, false); + + this.getTree().setSimulate(); + this.getTree().request(craftingInventory, this.output.getStackSize(), this.actionSrc); + this.getTree().dive(this); + + for (final String s : this.opsAndMultiplier.keySet()) { + final TwoIntegers ti = this.opsAndMultiplier.get(s); + AELog.crafting(s + " * " + ti.times + " = " + (ti.perOp * ti.times)); + } + + this.logCraftingJob("simulate", timer); + } catch (final CraftBranchFailure e1) { + AELog.debug(e1); + } catch (final CraftingCalculationFailure f) { + AELog.debug(f); + } catch (final InterruptedException e1) { + AELog.crafting("Crafting calculation canceled."); + this.finish(); + return; + } + } catch (final CraftingCalculationFailure f) { + AELog.debug(f); + } catch (final InterruptedException e1) { + AELog.crafting("Crafting calculation canceled."); + this.finish(); + return; + } + + AELog.craftingDebug("crafting job now done"); + } catch (final Throwable t) { + this.finish(); + throw new IllegalStateException(t); + } + + this.finish(); + } + + void handlePausing() throws InterruptedException { + if (this.incTime > 100) { + this.incTime = 0; + + synchronized (this.monitor) { + if (this.watch.elapsed(TimeUnit.MICROSECONDS) > this.time) { + this.running = false; + this.watch.stop(); + this.monitor.notify(); + } + + if (!this.running) { + AELog.craftingDebug("crafting job will now sleep"); + + while (!this.running) { + this.monitor.wait(); + } + + AELog.craftingDebug("crafting job now active"); + } + } + + if (Thread.interrupted()) { + throw new InterruptedException(); + } + } + this.incTime++; + } + + private void finish() { + if (this.callback != null) { + this.callback.calculationComplete(this); + } + + this.availableCheck = null; + + synchronized (this.monitor) { + this.running = false; + this.done = true; + this.monitor.notify(); + } + } + + @Override + public boolean isSimulation() { + return this.simulate; + } + + @Override + public long getByteTotal() { + return this.bytes; + } + + @Override + public void populatePlan(final IItemList plan) { + if (this.getTree() != null) { + this.getTree().getPlan(plan); + } + } + + @Override + public IAEItemStack getOutput() { + return this.output; + } + + public boolean isDone() { + return this.done; + } + + World getWorld() { + return this.world; + } + + /** + * returns true if this needs more simulation. + * + * @param milli milliseconds of simulation + * @return true if this needs more simulation + */ + public boolean simulateFor(final int milli) { + this.time = milli; + + synchronized (this.monitor) { + if (this.done) { + return false; + } + + this.watch.reset(); + this.watch.start(); + this.running = true; + + AELog.craftingDebug("main thread is now going to sleep"); + + this.monitor.notify(); + + while (this.running) { + try { + this.monitor.wait(); + } catch (final InterruptedException ignored) { + } + } + + AELog.craftingDebug("main thread is now active"); + } + + return true; + } + + void addBytes(final long crafts) { + this.bytes += crafts; + } + + public CraftingTreeNode getTree() { + return this.tree; + } + + private void setTree(final CraftingTreeNode tree) { + this.tree = tree; + } + + private void logCraftingJob(String type, Stopwatch timer) { + if (AELog.isCraftingLogEnabled()) { + final String itemToOutput = this.output.toString(); + final long elapsedTime = timer.elapsed(TimeUnit.MILLISECONDS); + final String actionSource; + + if (this.actionSrc instanceof MachineSource) { + final IActionHost machineSource = ((MachineSource) this.actionSrc).via; + final IGridNode actionableNode = machineSource.getActionableNode(); + final IGridHost machine = actionableNode.getMachine(); + final DimensionalCoord location = actionableNode.getGridBlock().getLocation(); + + actionSource = String.format(LOG_MACHINE_SOURCE_DETAILS, machine, location); + } else if (this.actionSrc instanceof PlayerSource) { + final PlayerSource source = (PlayerSource) this.actionSrc; + final EntityPlayer player = source.player; + + actionSource = player.toString(); + } else { + actionSource = "[unknown source]"; + } + + AELog.crafting(LOG_CRAFTING_JOB, type, actionSource, itemToOutput, this.bytes, elapsedTime); + } + } + + private static class TwoIntegers { + private final long perOp = 0; + private final long times = 0; + } } diff --git a/src/main/java/appeng/crafting/CraftingLink.java b/src/main/java/appeng/crafting/CraftingLink.java index 1ea6e6ec17f..895b562f979 100644 --- a/src/main/java/appeng/crafting/CraftingLink.java +++ b/src/main/java/appeng/crafting/CraftingLink.java @@ -18,7 +18,6 @@ package appeng.crafting; - import appeng.api.config.Actionable; import appeng.api.networking.crafting.ICraftingCPU; import appeng.api.networking.crafting.ICraftingLink; @@ -26,189 +25,159 @@ import appeng.api.storage.data.IAEItemStack; import net.minecraft.nbt.NBTTagCompound; - -public class CraftingLink implements ICraftingLink -{ - - private final ICraftingRequester req; - private final ICraftingCPU cpu; - private final String CraftID; - private final boolean standalone; - private boolean canceled = false; - private boolean done = false; - private CraftingLinkNexus tie; - - public CraftingLink( final NBTTagCompound data, final ICraftingRequester req ) - { - this.CraftID = data.getString( "CraftID" ); - this.setCanceled( data.getBoolean( "canceled" ) ); - this.setDone( data.getBoolean( "done" ) ); - this.standalone = data.getBoolean( "standalone" ); - - if( !data.hasKey( "req" ) || !data.getBoolean( "req" ) ) - { - throw new IllegalStateException( "Invalid Crafting Link for Object" ); - } - - this.req = req; - this.cpu = null; - } - - public CraftingLink( final NBTTagCompound data, final ICraftingCPU cpu ) - { - this.CraftID = data.getString( "CraftID" ); - this.setCanceled( data.getBoolean( "canceled" ) ); - this.setDone( data.getBoolean( "done" ) ); - this.standalone = data.getBoolean( "standalone" ); - - if( !data.hasKey( "req" ) || data.getBoolean( "req" ) ) - { - throw new IllegalStateException( "Invalid Crafting Link for Object" ); - } - - this.cpu = cpu; - this.req = null; - } - - @Override - public boolean isCanceled() - { - if( this.canceled ) - { - return true; - } - - if( this.done ) - { - return false; - } - - if( this.tie == null ) - { - return false; - } - - return this.tie.isCanceled(); - } - - @Override - public boolean isDone() - { - if( this.done ) - { - return true; - } - - if( this.canceled ) - { - return false; - } - - if( this.tie == null ) - { - return false; - } - - return this.tie.isDone(); - } - - @Override - public void cancel() - { - if( this.done ) - { - return; - } - - this.setCanceled( true ); - - if( this.tie != null ) - { - this.tie.cancel(); - } - - this.tie = null; - } - - @Override - public boolean isStandalone() - { - return this.standalone; - } - - @Override - public void writeToNBT( final NBTTagCompound tag ) - { - tag.setString( "CraftID", this.CraftID ); - tag.setBoolean( "canceled", this.isCanceled() ); - tag.setBoolean( "done", this.isDone() ); - tag.setBoolean( "standalone", this.standalone ); - tag.setBoolean( "req", this.getRequester() != null ); - } - - @Override - public String getCraftingID() - { - return this.CraftID; - } - - public void setNexus( final CraftingLinkNexus n ) - { - if( this.tie != null ) - { - this.tie.remove( this ); - } - - if( this.isCanceled() && n != null ) - { - n.cancel(); - this.tie = null; - return; - } - - this.tie = n; - - if( n != null ) - { - n.add( this ); - } - } - - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode ) - { - if( this.tie == null || this.tie.getRequest() == null || this.tie.getRequest().getRequester() == null ) - { - return input; - } - - return this.tie.getRequest().getRequester().injectCraftedItems( this.tie.getRequest(), input, mode ); - } - - public void markDone() - { - if( this.tie != null ) - { - this.tie.markDone(); - } - } - - void setCanceled( final boolean canceled ) - { - this.canceled = canceled; - } - - ICraftingRequester getRequester() - { - return this.req; - } - - ICraftingCPU getCpu() - { - return this.cpu; - } - - void setDone( final boolean done ) - { - this.done = done; - } +public class CraftingLink implements ICraftingLink { + + private final ICraftingRequester req; + private final ICraftingCPU cpu; + private final String CraftID; + private final boolean standalone; + private boolean canceled = false; + private boolean done = false; + private CraftingLinkNexus tie; + + public CraftingLink(final NBTTagCompound data, final ICraftingRequester req) { + this.CraftID = data.getString("CraftID"); + this.setCanceled(data.getBoolean("canceled")); + this.setDone(data.getBoolean("done")); + this.standalone = data.getBoolean("standalone"); + + if (!data.hasKey("req") || !data.getBoolean("req")) { + throw new IllegalStateException("Invalid Crafting Link for Object"); + } + + this.req = req; + this.cpu = null; + } + + public CraftingLink(final NBTTagCompound data, final ICraftingCPU cpu) { + this.CraftID = data.getString("CraftID"); + this.setCanceled(data.getBoolean("canceled")); + this.setDone(data.getBoolean("done")); + this.standalone = data.getBoolean("standalone"); + + if (!data.hasKey("req") || data.getBoolean("req")) { + throw new IllegalStateException("Invalid Crafting Link for Object"); + } + + this.cpu = cpu; + this.req = null; + } + + @Override + public boolean isCanceled() { + if (this.canceled) { + return true; + } + + if (this.done) { + return false; + } + + if (this.tie == null) { + return false; + } + + return this.tie.isCanceled(); + } + + @Override + public boolean isDone() { + if (this.done) { + return true; + } + + if (this.canceled) { + return false; + } + + if (this.tie == null) { + return false; + } + + return this.tie.isDone(); + } + + @Override + public void cancel() { + if (this.done) { + return; + } + + this.setCanceled(true); + + if (this.tie != null) { + this.tie.cancel(); + } + + this.tie = null; + } + + @Override + public boolean isStandalone() { + return this.standalone; + } + + @Override + public void writeToNBT(final NBTTagCompound tag) { + tag.setString("CraftID", this.CraftID); + tag.setBoolean("canceled", this.isCanceled()); + tag.setBoolean("done", this.isDone()); + tag.setBoolean("standalone", this.standalone); + tag.setBoolean("req", this.getRequester() != null); + } + + @Override + public String getCraftingID() { + return this.CraftID; + } + + public void setNexus(final CraftingLinkNexus n) { + if (this.tie != null) { + this.tie.remove(this); + } + + if (this.isCanceled() && n != null) { + n.cancel(); + this.tie = null; + return; + } + + this.tie = n; + + if (n != null) { + n.add(this); + } + } + + public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode) { + if (this.tie == null + || this.tie.getRequest() == null + || this.tie.getRequest().getRequester() == null) { + return input; + } + + return this.tie.getRequest().getRequester().injectCraftedItems(this.tie.getRequest(), input, mode); + } + + public void markDone() { + if (this.tie != null) { + this.tie.markDone(); + } + } + + void setCanceled(final boolean canceled) { + this.canceled = canceled; + } + + ICraftingRequester getRequester() { + return this.req; + } + + ICraftingCPU getCpu() { + return this.cpu; + } + + void setDone(final boolean done) { + this.done = done; + } } diff --git a/src/main/java/appeng/crafting/CraftingLinkNexus.java b/src/main/java/appeng/crafting/CraftingLinkNexus.java index 7a30dcf6064..c72b99e6aa8 100644 --- a/src/main/java/appeng/crafting/CraftingLinkNexus.java +++ b/src/main/java/appeng/crafting/CraftingLinkNexus.java @@ -18,157 +18,122 @@ package appeng.crafting; - import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.me.cache.CraftingGridCache; - -public class CraftingLinkNexus -{ - - private final String craftID; - private boolean canceled = false; - private boolean done = false; - private int tickOfDeath = 0; - private CraftingLink req; - private CraftingLink cpu; - - public CraftingLinkNexus( final String craftID ) - { - this.craftID = craftID; - } - - public boolean isDead( final IGrid g, final CraftingGridCache craftingGridCache ) - { - if( this.canceled || this.done ) - { - return true; - } - - if( this.getRequest() == null || this.cpu == null ) - { - this.tickOfDeath++; - } - else - { - final boolean hasCpu = craftingGridCache.hasCpu( this.cpu.getCpu() ); - final boolean hasMachine = this.getRequest().getRequester().getActionableNode().getGrid() == g; - - if( hasCpu && hasMachine ) - { - this.tickOfDeath = 0; - } - else - { - this.tickOfDeath += 60; - } - } - - if( this.tickOfDeath > 60 ) - { - this.cancel(); - return true; - } - - return false; - } - - void cancel() - { - this.canceled = true; - - if( this.getRequest() != null ) - { - this.getRequest().setCanceled( true ); - if( this.getRequest().getRequester() != null ) - { - this.getRequest().getRequester().jobStateChange( this.getRequest() ); - } - } - - if( this.cpu != null ) - { - this.cpu.setCanceled( true ); - } - } - - void remove( final CraftingLink craftingLink ) - { - if( this.getRequest() == craftingLink ) - { - this.setRequest( null ); - } - else if( this.cpu == craftingLink ) - { - this.cpu = null; - } - } - - void add( final CraftingLink craftingLink ) - { - if( craftingLink.getCpu() != null ) - { - this.cpu = craftingLink; - } - else if( craftingLink.getRequester() != null ) - { - this.setRequest( craftingLink ); - } - } - - boolean isCanceled() - { - return this.canceled; - } - - boolean isDone() - { - return this.done; - } - - void markDone() - { - this.done = true; - - if( this.getRequest() != null ) - { - this.getRequest().setDone( true ); - if( this.getRequest().getRequester() != null ) - { - this.getRequest().getRequester().jobStateChange( this.getRequest() ); - } - } - - if( this.cpu != null ) - { - this.cpu.setDone( true ); - } - } - - public boolean isMachine( final IGridHost machine ) - { - return this.getRequest() == machine; - } - - public void removeNode() - { - if( this.getRequest() != null ) - { - this.getRequest().setNexus( null ); - } - - this.setRequest( null ); - this.tickOfDeath = 0; - } - - public CraftingLink getRequest() - { - return req; - } - - public void setRequest( CraftingLink req ) - { - this.req = req; - } +public class CraftingLinkNexus { + + private final String craftID; + private boolean canceled = false; + private boolean done = false; + private int tickOfDeath = 0; + private CraftingLink req; + private CraftingLink cpu; + + public CraftingLinkNexus(final String craftID) { + this.craftID = craftID; + } + + public boolean isDead(final IGrid g, final CraftingGridCache craftingGridCache) { + if (this.canceled || this.done) { + return true; + } + + if (this.getRequest() == null || this.cpu == null) { + this.tickOfDeath++; + } else { + final boolean hasCpu = craftingGridCache.hasCpu(this.cpu.getCpu()); + final boolean hasMachine = + this.getRequest().getRequester().getActionableNode().getGrid() == g; + + if (hasCpu && hasMachine) { + this.tickOfDeath = 0; + } else { + this.tickOfDeath += 60; + } + } + + if (this.tickOfDeath > 60) { + this.cancel(); + return true; + } + + return false; + } + + void cancel() { + this.canceled = true; + + if (this.getRequest() != null) { + this.getRequest().setCanceled(true); + if (this.getRequest().getRequester() != null) { + this.getRequest().getRequester().jobStateChange(this.getRequest()); + } + } + + if (this.cpu != null) { + this.cpu.setCanceled(true); + } + } + + void remove(final CraftingLink craftingLink) { + if (this.getRequest() == craftingLink) { + this.setRequest(null); + } else if (this.cpu == craftingLink) { + this.cpu = null; + } + } + + void add(final CraftingLink craftingLink) { + if (craftingLink.getCpu() != null) { + this.cpu = craftingLink; + } else if (craftingLink.getRequester() != null) { + this.setRequest(craftingLink); + } + } + + boolean isCanceled() { + return this.canceled; + } + + boolean isDone() { + return this.done; + } + + void markDone() { + this.done = true; + + if (this.getRequest() != null) { + this.getRequest().setDone(true); + if (this.getRequest().getRequester() != null) { + this.getRequest().getRequester().jobStateChange(this.getRequest()); + } + } + + if (this.cpu != null) { + this.cpu.setDone(true); + } + } + + public boolean isMachine(final IGridHost machine) { + return this.getRequest() == machine; + } + + public void removeNode() { + if (this.getRequest() != null) { + this.getRequest().setNexus(null); + } + + this.setRequest(null); + this.tickOfDeath = 0; + } + + public CraftingLink getRequest() { + return req; + } + + public void setRequest(CraftingLink req) { + this.req = req; + } } diff --git a/src/main/java/appeng/crafting/CraftingTreeNode.java b/src/main/java/appeng/crafting/CraftingTreeNode.java index 583218a1918..92c9147da40 100644 --- a/src/main/java/appeng/crafting/CraftingTreeNode.java +++ b/src/main/java/appeng/crafting/CraftingTreeNode.java @@ -18,7 +18,6 @@ package appeng.crafting; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.FuzzyMode; @@ -29,377 +28,319 @@ import appeng.api.storage.data.IItemList; import appeng.me.cluster.implementations.CraftingCPUCluster; import com.google.common.collect.Lists; -import net.minecraft.world.World; - import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; +import net.minecraft.world.World; - -public class CraftingTreeNode -{ - - // what slot! - private final int slot; - private final CraftingJob job; - private final IItemList used = AEApi.instance().storage().createItemList(); - // parent node. - private final CraftingTreeProcess parent; - private final World world; - // what item is this? - private final IAEItemStack what; - // what are the crafting patterns for this? - private final ArrayList nodes = new ArrayList(); - private int bytes = 0; - private boolean canEmit = false; - private long missing = 0; - private long howManyEmitted = 0; - private boolean exhausted = false; - - private boolean sim; - - public CraftingTreeNode( final ICraftingGrid cc, final CraftingJob job, final IAEItemStack wat, final CraftingTreeProcess par, final int slot, final int depth ) - { - this.what = wat; - this.parent = par; - this.slot = slot; - this.world = job.getWorld(); - this.job = job; - this.sim = false; - - this.canEmit = cc.canEmitFor( this.what ); - - if( this.canEmit ) - { - return; // if you can emit for something, you can't make it with patterns. - } - - for( final ICraftingPatternDetails details : cc.getCraftingFor( this.what, this.parent == null ? null : this.parent.details, slot, this.world ) )// in - // order. - { - if( this.parent == null || this.parent.notRecursive( details ) ) - { - this.nodes.add( new CraftingTreeProcess( cc, job, details, this, depth + 1 ) ); - } - } - } - - boolean notRecursive( final ICraftingPatternDetails details ) - { - IAEItemStack[] o = details.getCondensedOutputs(); - - for( final IAEItemStack i : o ) - { - if( i.equals( this.what ) ) - { - return false; - } - } - - o = details.getCondensedInputs(); - - for( final IAEItemStack i : o ) - { - if( i.equals( this.what ) ) - { - return false; - } - } - - if( this.parent == null ) - { - return true; - } - - return this.parent.notRecursive( details ); - } - - IAEItemStack request( final MECraftingInventory inv, long l, final BaseActionSource src ) throws CraftBranchFailure, InterruptedException - { - this.job.handlePausing(); - - final List thingsUsed = new LinkedList(); - - this.what.setStackSize( l ); - if( this.getSlot() >= 0 && this.parent != null && this.parent.details.isCraftable() ) - { - final Collection itemList; - final IItemList inventoryList = inv.getItemList(); - - if( this.parent.details.canSubstitute() ) - { - itemList = inventoryList.findFuzzy( this.what, FuzzyMode.IGNORE_ALL ); - } - else - { - itemList = Lists.newArrayList(); - - final IAEItemStack item = inventoryList.findPrecise( this.what ); - - if( item != null ) - { - itemList.add( item ); - } - } - - for( IAEItemStack fuzz : itemList ) - { - if( this.parent.details.isValidItemForSlot( this.getSlot(), fuzz.getItemStack(), this.world ) ) - { - fuzz = fuzz.copy(); - fuzz.setStackSize( l ); - - final IAEItemStack available = inv.extractItems( fuzz, Actionable.MODULATE, src ); - - if( available != null ) - { - if( !this.exhausted ) - { - final IAEItemStack is = this.job.checkUse( available ); - - if( is != null ) - { - thingsUsed.add( is.copy() ); - this.used.add( is ); - } - } - - this.bytes += available.getStackSize(); - l -= available.getStackSize(); - - if( l == 0 ) - { - return available; - } - } - } - } - } - else - { - final IAEItemStack available = inv.extractItems( this.what, Actionable.MODULATE, src ); - - if( available != null ) - { - if( !this.exhausted ) - { - final IAEItemStack is = this.job.checkUse( available ); - - if( is != null ) - { - thingsUsed.add( is.copy() ); - this.used.add( is ); - } - } - - this.bytes += available.getStackSize(); - l -= available.getStackSize(); - - if( l == 0 ) - { - return available; - } - } - } - - if( this.canEmit ) - { - final IAEItemStack wat = this.what.copy(); - wat.setStackSize( l ); - - this.howManyEmitted = wat.getStackSize(); - this.bytes += wat.getStackSize(); - - return wat; - } - - this.exhausted = true; - - if( this.nodes.size() == 1 ) - { - final CraftingTreeProcess pro = this.nodes.get( 0 ); - - while( pro.possible && l > 0 ) - { - final IAEItemStack madeWhat = pro.getAmountCrafted( this.what ); - - pro.request( inv, pro.getTimes( l, madeWhat.getStackSize() ), src ); - - madeWhat.setStackSize( l ); - - final IAEItemStack available = inv.extractItems( madeWhat, Actionable.MODULATE, src ); - - if( available != null ) - { - this.bytes += available.getStackSize(); - l -= available.getStackSize(); - - if( l <= 0 ) - { - return available; - } - } - else - { - pro.possible = false; // ;P - } - } - } - else if( this.nodes.size() > 1 ) - { - for( final CraftingTreeProcess pro : this.nodes ) - { - try - { - while( pro.possible && l > 0 ) - { - final MECraftingInventory subInv = new MECraftingInventory( inv, true, true, true ); - pro.request( subInv, 1, src ); - - this.what.setStackSize( l ); - final IAEItemStack available = subInv.extractItems( this.what, Actionable.MODULATE, src ); - - if( available != null ) - { - if( !subInv.commit( src ) ) - { - throw new CraftBranchFailure( this.what, l ); - } - - this.bytes += available.getStackSize(); - l -= available.getStackSize(); - - if( l <= 0 ) - { - return available; - } - } - else - { - pro.possible = false; // ;P - } - } - } - catch( final CraftBranchFailure fail ) - { - pro.possible = true; - } - } - } - - if( this.sim ) - { - this.missing += l; - this.bytes += l; - final IAEItemStack rv = this.what.copy(); - rv.setStackSize( l ); - return rv; - } - - for( final IAEItemStack o : thingsUsed ) - { - this.job.refund( o.copy() ); - o.setStackSize( -o.getStackSize() ); - this.used.add( o ); - } - - throw new CraftBranchFailure( this.what, l ); - } - - void dive( final CraftingJob job ) - { - if( this.missing > 0 ) - { - job.addMissing( this.getStack( this.missing ) ); - } - // missing = 0; - - job.addBytes( 8 + this.bytes ); - - for( final CraftingTreeProcess pro : this.nodes ) - { - pro.dive( job ); - } - } - - IAEItemStack getStack( final long size ) - { - final IAEItemStack is = this.what.copy(); - is.setStackSize( size ); - return is; - } - - void setSimulate() - { - this.sim = true; - this.missing = 0; - this.bytes = 0; - this.used.resetStatus(); - this.exhausted = false; - - for( final CraftingTreeProcess pro : this.nodes ) - { - pro.setSimulate(); - } - } - - public void setJob( final MECraftingInventory storage, final CraftingCPUCluster craftingCPUCluster, final BaseActionSource src ) throws CraftBranchFailure - { - for( final IAEItemStack i : this.used ) - { - final IAEItemStack ex = storage.extractItems( i, Actionable.MODULATE, src ); - - if( ex == null || ex.getStackSize() != i.getStackSize() ) - { - throw new CraftBranchFailure( i, i.getStackSize() ); - } - - craftingCPUCluster.addStorage( ex ); - } - - if( this.howManyEmitted > 0 ) - { - final IAEItemStack i = this.what.copy(); - i.setStackSize( this.howManyEmitted ); - craftingCPUCluster.addEmitable( i ); - } - - for( final CraftingTreeProcess pro : this.nodes ) - { - pro.setJob( storage, craftingCPUCluster, src ); - } - } - - void getPlan( final IItemList plan ) - { - if( this.missing > 0 ) - { - final IAEItemStack o = this.what.copy(); - o.setStackSize( this.missing ); - plan.add( o ); - } - - if( this.howManyEmitted > 0 ) - { - final IAEItemStack i = this.what.copy(); - i.setCountRequestable( this.howManyEmitted ); - plan.addRequestable( i ); - } - - for( final IAEItemStack i : this.used ) - { - plan.add( i.copy() ); - } - - for( final CraftingTreeProcess pro : this.nodes ) - { - pro.getPlan( plan ); - } - } - - int getSlot() - { - return this.slot; - } +public class CraftingTreeNode { + + // what slot! + private final int slot; + private final CraftingJob job; + private final IItemList used = AEApi.instance().storage().createItemList(); + // parent node. + private final CraftingTreeProcess parent; + private final World world; + // what item is this? + private final IAEItemStack what; + // what are the crafting patterns for this? + private final ArrayList nodes = new ArrayList(); + private int bytes = 0; + private boolean canEmit = false; + private long missing = 0; + private long howManyEmitted = 0; + private boolean exhausted = false; + + private boolean sim; + + public CraftingTreeNode( + final ICraftingGrid cc, + final CraftingJob job, + final IAEItemStack wat, + final CraftingTreeProcess par, + final int slot, + final int depth) { + this.what = wat; + this.parent = par; + this.slot = slot; + this.world = job.getWorld(); + this.job = job; + this.sim = false; + + this.canEmit = cc.canEmitFor(this.what); + + if (this.canEmit) { + return; // if you can emit for something, you can't make it with patterns. + } + + for (final ICraftingPatternDetails details : + cc.getCraftingFor(this.what, this.parent == null ? null : this.parent.details, slot, this.world)) // in + // order. + { + if (this.parent == null || this.parent.notRecursive(details)) { + this.nodes.add(new CraftingTreeProcess(cc, job, details, this, depth + 1)); + } + } + } + + boolean notRecursive(final ICraftingPatternDetails details) { + IAEItemStack[] o = details.getCondensedOutputs(); + + for (final IAEItemStack i : o) { + if (i.equals(this.what)) { + return false; + } + } + + o = details.getCondensedInputs(); + + for (final IAEItemStack i : o) { + if (i.equals(this.what)) { + return false; + } + } + + if (this.parent == null) { + return true; + } + + return this.parent.notRecursive(details); + } + + IAEItemStack request(final MECraftingInventory inv, long l, final BaseActionSource src) + throws CraftBranchFailure, InterruptedException { + this.job.handlePausing(); + + final List thingsUsed = new LinkedList(); + + this.what.setStackSize(l); + if (this.getSlot() >= 0 && this.parent != null && this.parent.details.isCraftable()) { + final Collection itemList; + final IItemList inventoryList = inv.getItemList(); + + if (this.parent.details.canSubstitute()) { + itemList = inventoryList.findFuzzy(this.what, FuzzyMode.IGNORE_ALL); + } else { + itemList = Lists.newArrayList(); + + final IAEItemStack item = inventoryList.findPrecise(this.what); + + if (item != null) { + itemList.add(item); + } + } + + for (IAEItemStack fuzz : itemList) { + if (this.parent.details.isValidItemForSlot(this.getSlot(), fuzz.getItemStack(), this.world)) { + fuzz = fuzz.copy(); + fuzz.setStackSize(l); + + final IAEItemStack available = inv.extractItems(fuzz, Actionable.MODULATE, src); + + if (available != null) { + if (!this.exhausted) { + final IAEItemStack is = this.job.checkUse(available); + + if (is != null) { + thingsUsed.add(is.copy()); + this.used.add(is); + } + } + + this.bytes += available.getStackSize(); + l -= available.getStackSize(); + + if (l == 0) { + return available; + } + } + } + } + } else { + final IAEItemStack available = inv.extractItems(this.what, Actionable.MODULATE, src); + + if (available != null) { + if (!this.exhausted) { + final IAEItemStack is = this.job.checkUse(available); + + if (is != null) { + thingsUsed.add(is.copy()); + this.used.add(is); + } + } + + this.bytes += available.getStackSize(); + l -= available.getStackSize(); + + if (l == 0) { + return available; + } + } + } + + if (this.canEmit) { + final IAEItemStack wat = this.what.copy(); + wat.setStackSize(l); + + this.howManyEmitted = wat.getStackSize(); + this.bytes += wat.getStackSize(); + + return wat; + } + + this.exhausted = true; + + if (this.nodes.size() == 1) { + final CraftingTreeProcess pro = this.nodes.get(0); + + while (pro.possible && l > 0) { + final IAEItemStack madeWhat = pro.getAmountCrafted(this.what); + + pro.request(inv, pro.getTimes(l, madeWhat.getStackSize()), src); + + madeWhat.setStackSize(l); + + final IAEItemStack available = inv.extractItems(madeWhat, Actionable.MODULATE, src); + + if (available != null) { + this.bytes += available.getStackSize(); + l -= available.getStackSize(); + + if (l <= 0) { + return available; + } + } else { + pro.possible = false; // ;P + } + } + } else if (this.nodes.size() > 1) { + for (final CraftingTreeProcess pro : this.nodes) { + try { + while (pro.possible && l > 0) { + final MECraftingInventory subInv = new MECraftingInventory(inv, true, true, true); + pro.request(subInv, 1, src); + + this.what.setStackSize(l); + final IAEItemStack available = subInv.extractItems(this.what, Actionable.MODULATE, src); + + if (available != null) { + if (!subInv.commit(src)) { + throw new CraftBranchFailure(this.what, l); + } + + this.bytes += available.getStackSize(); + l -= available.getStackSize(); + + if (l <= 0) { + return available; + } + } else { + pro.possible = false; // ;P + } + } + } catch (final CraftBranchFailure fail) { + pro.possible = true; + } + } + } + + if (this.sim) { + this.missing += l; + this.bytes += l; + final IAEItemStack rv = this.what.copy(); + rv.setStackSize(l); + return rv; + } + + for (final IAEItemStack o : thingsUsed) { + this.job.refund(o.copy()); + o.setStackSize(-o.getStackSize()); + this.used.add(o); + } + + throw new CraftBranchFailure(this.what, l); + } + + void dive(final CraftingJob job) { + if (this.missing > 0) { + job.addMissing(this.getStack(this.missing)); + } + // missing = 0; + + job.addBytes(8 + this.bytes); + + for (final CraftingTreeProcess pro : this.nodes) { + pro.dive(job); + } + } + + IAEItemStack getStack(final long size) { + final IAEItemStack is = this.what.copy(); + is.setStackSize(size); + return is; + } + + void setSimulate() { + this.sim = true; + this.missing = 0; + this.bytes = 0; + this.used.resetStatus(); + this.exhausted = false; + + for (final CraftingTreeProcess pro : this.nodes) { + pro.setSimulate(); + } + } + + public void setJob( + final MECraftingInventory storage, final CraftingCPUCluster craftingCPUCluster, final BaseActionSource src) + throws CraftBranchFailure { + for (final IAEItemStack i : this.used) { + final IAEItemStack ex = storage.extractItems(i, Actionable.MODULATE, src); + + if (ex == null || ex.getStackSize() != i.getStackSize()) { + throw new CraftBranchFailure(i, i.getStackSize()); + } + + craftingCPUCluster.addStorage(ex); + } + + if (this.howManyEmitted > 0) { + final IAEItemStack i = this.what.copy(); + i.setStackSize(this.howManyEmitted); + craftingCPUCluster.addEmitable(i); + } + + for (final CraftingTreeProcess pro : this.nodes) { + pro.setJob(storage, craftingCPUCluster, src); + } + } + + void getPlan(final IItemList plan) { + if (this.missing > 0) { + final IAEItemStack o = this.what.copy(); + o.setStackSize(this.missing); + plan.add(o); + } + + if (this.howManyEmitted > 0) { + final IAEItemStack i = this.what.copy(); + i.setCountRequestable(this.howManyEmitted); + plan.addRequestable(i); + } + + for (final IAEItemStack i : this.used) { + plan.add(i.copy()); + } + + for (final CraftingTreeProcess pro : this.nodes) { + pro.getPlan(plan); + } + } + + int getSlot() { + return this.slot; + } } diff --git a/src/main/java/appeng/crafting/CraftingTreeProcess.java b/src/main/java/appeng/crafting/CraftingTreeProcess.java index c5d86e8e766..3fde4a96dcf 100644 --- a/src/main/java/appeng/crafting/CraftingTreeProcess.java +++ b/src/main/java/appeng/crafting/CraftingTreeProcess.java @@ -18,7 +18,6 @@ package appeng.crafting; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.networking.crafting.ICraftingGrid; @@ -30,294 +29,253 @@ import appeng.me.cluster.implementations.CraftingCPUCluster; import appeng.util.Platform; import cpw.mods.fml.common.FMLCommonHandler; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraft.world.WorldServer; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - - -public class CraftingTreeProcess -{ - - private final CraftingTreeNode parent; - final ICraftingPatternDetails details; - private final CraftingJob job; - private final Map nodes = new HashMap(); - private final int depth; - boolean possible = true; - private World world; - private long crafts = 0; - private boolean containerItems; - private boolean limitQty; - private boolean fullSimulation; - private long bytes = 0; - - public CraftingTreeProcess( final ICraftingGrid cc, final CraftingJob job, final ICraftingPatternDetails details, final CraftingTreeNode craftingTreeNode, final int depth ) - { - this.parent = craftingTreeNode; - this.details = details; - this.job = job; - this.depth = depth; - final World world = job.getWorld(); - - if( details.isCraftable() ) - { - final IAEItemStack[] list = details.getInputs(); - - final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); - final IAEItemStack[] is = details.getInputs(); - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - ic.setInventorySlotContents( x, is[x] == null ? null : is[x].getItemStack() ); - } - - FMLCommonHandler.instance().firePlayerCraftingEvent( Platform.getPlayer( (WorldServer) world ), details.getOutput( ic, world ), ic ); - - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - final ItemStack g = ic.getStackInSlot( x ); - if( g != null && g.stackSize > 1 ) - { - this.fullSimulation = true; - } - } - - for( final IAEItemStack part : details.getCondensedInputs() ) - { - final ItemStack g = part.getItemStack(); - - boolean isAnInput = false; - for( final IAEItemStack a : details.getCondensedOutputs() ) - { - if( g != null && a != null && a.equals( g ) ) - { - isAnInput = true; - } - } - - if( isAnInput ) - { - this.limitQty = true; - } - - if( g.getItem().hasContainerItem( g ) ) - { - this.limitQty = this.containerItems = true; - } - } - - final boolean complicated = false; - - if( this.containerItems || complicated ) - { - for( int x = 0; x < list.length; x++ ) - { - final IAEItemStack part = list[x]; - if( part != null ) - { - this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), this, x, depth + 1 ), part.getStackSize() ); - } - } - } - else - { - // this is minor different then below, this slot uses the pattern, but kinda fudges it. - for( final IAEItemStack part : details.getCondensedInputs() ) - { - for( int x = 0; x < list.length; x++ ) - { - final IAEItemStack comparePart = list[x]; - if( part != null && part.equals( comparePart ) ) - { - // use the first slot... - this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), this, x, depth + 1 ), part.getStackSize() ); - break; - } - } - } - } - } - else - { - for( final IAEItemStack part : details.getCondensedInputs() ) - { - final ItemStack g = part.getItemStack(); - - boolean isAnInput = false; - for( final IAEItemStack a : details.getCondensedOutputs() ) - { - if( g != null && a != null && a.equals( g ) ) - { - isAnInput = true; - } - } - - if( isAnInput ) - { - this.limitQty = true; - } - } - - for( final IAEItemStack part : details.getCondensedInputs() ) - { - this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), this, -1, depth + 1 ), part.getStackSize() ); - } - } - } - - boolean notRecursive( final ICraftingPatternDetails details ) - { - return this.parent == null || this.parent.notRecursive( details ); - } - - long getTimes( final long remaining, final long stackSize ) - { - if( this.limitQty || this.fullSimulation ) - { - return 1; - } - return ( remaining / stackSize ) + ( remaining % stackSize != 0 ? 1 : 0 ); - } - - void request( final MECraftingInventory inv, final long i, final BaseActionSource src ) throws CraftBranchFailure, InterruptedException - { - this.job.handlePausing(); - - if( this.fullSimulation ) - { - final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); - - for( final Entry entry : this.nodes.entrySet() ) - { - final IAEItemStack item = entry.getKey().getStack( entry.getValue() ); - final IAEItemStack stack = entry.getKey().request( inv, item.getStackSize(), src ); - - ic.setInventorySlotContents( entry.getKey().getSlot(), stack.getItemStack() ); - } - - FMLCommonHandler.instance().firePlayerCraftingEvent( Platform.getPlayer( (WorldServer) this.world ), this.details.getOutput( ic, this.world ), ic ); - - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - ItemStack is = ic.getStackInSlot( x ); - is = Platform.getContainerItem( is ); - - final IAEItemStack o = AEApi.instance().storage().createItemStack( is ); - if( o != null ) - { - this.bytes++; - inv.injectItems( o, Actionable.MODULATE, src ); - } - } - } - else - { - // request and remove inputs... - for( final Entry entry : this.nodes.entrySet() ) - { - final IAEItemStack item = entry.getKey().getStack( entry.getValue() ); - final IAEItemStack stack = entry.getKey().request( inv, item.getStackSize() * i, src ); - - if( this.containerItems ) - { - final ItemStack is = Platform.getContainerItem( stack.getItemStack() ); - final IAEItemStack o = AEApi.instance().storage().createItemStack( is ); - if( o != null ) - { - this.bytes++; - inv.injectItems( o, Actionable.MODULATE, src ); - } - } - } - } - - // assume its possible. - - // add crafting results.. - for( final IAEItemStack out : this.details.getCondensedOutputs() ) - { - final IAEItemStack o = out.copy(); - o.setStackSize( o.getStackSize() * i ); - inv.injectItems( o, Actionable.MODULATE, src ); - } - - this.crafts += i; - } - - void dive( final CraftingJob job ) - { - job.addTask( this.getAmountCrafted( this.parent.getStack( 1 ) ), this.crafts, this.details, this.depth ); - for( final CraftingTreeNode pro : this.nodes.keySet() ) - { - pro.dive( job ); - } - - job.addBytes( 8 + this.crafts + this.bytes ); - } - - IAEItemStack getAmountCrafted( IAEItemStack what2 ) - { - for( final IAEItemStack is : this.details.getCondensedOutputs() ) - { - if( is.equals( what2 ) ) - { - what2 = what2.copy(); - what2.setStackSize( is.getStackSize() ); - return what2; - } - } - - // more fuzzy! - for( final IAEItemStack is : this.details.getCondensedOutputs() ) - { - if( is.getItem() == what2.getItem() && ( is.getItem().isDamageable() || is.getItemDamage() == what2.getItemDamage() ) ) - { - what2 = is.copy(); - what2.setStackSize( is.getStackSize() ); - return what2; - } - } - - throw new IllegalStateException( "Crafting Tree construction failed." ); - } - - void setSimulate() - { - this.crafts = 0; - this.bytes = 0; - - for( final CraftingTreeNode pro : this.nodes.keySet() ) - { - pro.setSimulate(); - } - } - - void setJob( final MECraftingInventory storage, final CraftingCPUCluster craftingCPUCluster, final BaseActionSource src ) throws CraftBranchFailure - { - craftingCPUCluster.addCrafting( this.details, this.crafts ); - - for( final CraftingTreeNode pro : this.nodes.keySet() ) - { - pro.setJob( storage, craftingCPUCluster, src ); - } - } - - void getPlan( final IItemList plan ) - { - for( IAEItemStack i : this.details.getOutputs() ) - { - i = i.copy(); - i.setCountRequestable( i.getStackSize() * this.crafts ); - plan.addRequestable( i ); - } - - for( final CraftingTreeNode pro : this.nodes.keySet() ) - { - pro.getPlan( plan ); - } - } +public class CraftingTreeProcess { + + private final CraftingTreeNode parent; + final ICraftingPatternDetails details; + private final CraftingJob job; + private final Map nodes = new HashMap(); + private final int depth; + boolean possible = true; + private World world; + private long crafts = 0; + private boolean containerItems; + private boolean limitQty; + private boolean fullSimulation; + private long bytes = 0; + + public CraftingTreeProcess( + final ICraftingGrid cc, + final CraftingJob job, + final ICraftingPatternDetails details, + final CraftingTreeNode craftingTreeNode, + final int depth) { + this.parent = craftingTreeNode; + this.details = details; + this.job = job; + this.depth = depth; + final World world = job.getWorld(); + + if (details.isCraftable()) { + final IAEItemStack[] list = details.getInputs(); + + final InventoryCrafting ic = new InventoryCrafting(new ContainerNull(), 3, 3); + final IAEItemStack[] is = details.getInputs(); + for (int x = 0; x < ic.getSizeInventory(); x++) { + ic.setInventorySlotContents(x, is[x] == null ? null : is[x].getItemStack()); + } + + FMLCommonHandler.instance() + .firePlayerCraftingEvent(Platform.getPlayer((WorldServer) world), details.getOutput(ic, world), ic); + + for (int x = 0; x < ic.getSizeInventory(); x++) { + final ItemStack g = ic.getStackInSlot(x); + if (g != null && g.stackSize > 1) { + this.fullSimulation = true; + } + } + + for (final IAEItemStack part : details.getCondensedInputs()) { + final ItemStack g = part.getItemStack(); + + boolean isAnInput = false; + for (final IAEItemStack a : details.getCondensedOutputs()) { + if (g != null && a != null && a.equals(g)) { + isAnInput = true; + } + } + + if (isAnInput) { + this.limitQty = true; + } + + if (g.getItem().hasContainerItem(g)) { + this.limitQty = this.containerItems = true; + } + } + + final boolean complicated = false; + + if (this.containerItems || complicated) { + for (int x = 0; x < list.length; x++) { + final IAEItemStack part = list[x]; + if (part != null) { + this.nodes.put( + new CraftingTreeNode(cc, job, part.copy(), this, x, depth + 1), part.getStackSize()); + } + } + } else { + // this is minor different then below, this slot uses the pattern, but kinda fudges it. + for (final IAEItemStack part : details.getCondensedInputs()) { + for (int x = 0; x < list.length; x++) { + final IAEItemStack comparePart = list[x]; + if (part != null && part.equals(comparePart)) { + // use the first slot... + this.nodes.put( + new CraftingTreeNode(cc, job, part.copy(), this, x, depth + 1), + part.getStackSize()); + break; + } + } + } + } + } else { + for (final IAEItemStack part : details.getCondensedInputs()) { + final ItemStack g = part.getItemStack(); + + boolean isAnInput = false; + for (final IAEItemStack a : details.getCondensedOutputs()) { + if (g != null && a != null && a.equals(g)) { + isAnInput = true; + } + } + + if (isAnInput) { + this.limitQty = true; + } + } + + for (final IAEItemStack part : details.getCondensedInputs()) { + this.nodes.put(new CraftingTreeNode(cc, job, part.copy(), this, -1, depth + 1), part.getStackSize()); + } + } + } + + boolean notRecursive(final ICraftingPatternDetails details) { + return this.parent == null || this.parent.notRecursive(details); + } + + long getTimes(final long remaining, final long stackSize) { + if (this.limitQty || this.fullSimulation) { + return 1; + } + return (remaining / stackSize) + (remaining % stackSize != 0 ? 1 : 0); + } + + void request(final MECraftingInventory inv, final long i, final BaseActionSource src) + throws CraftBranchFailure, InterruptedException { + this.job.handlePausing(); + + if (this.fullSimulation) { + final InventoryCrafting ic = new InventoryCrafting(new ContainerNull(), 3, 3); + + for (final Entry entry : this.nodes.entrySet()) { + final IAEItemStack item = entry.getKey().getStack(entry.getValue()); + final IAEItemStack stack = entry.getKey().request(inv, item.getStackSize(), src); + + ic.setInventorySlotContents(entry.getKey().getSlot(), stack.getItemStack()); + } + + FMLCommonHandler.instance() + .firePlayerCraftingEvent( + Platform.getPlayer((WorldServer) this.world), this.details.getOutput(ic, this.world), ic); + + for (int x = 0; x < ic.getSizeInventory(); x++) { + ItemStack is = ic.getStackInSlot(x); + is = Platform.getContainerItem(is); + + final IAEItemStack o = AEApi.instance().storage().createItemStack(is); + if (o != null) { + this.bytes++; + inv.injectItems(o, Actionable.MODULATE, src); + } + } + } else { + // request and remove inputs... + for (final Entry entry : this.nodes.entrySet()) { + final IAEItemStack item = entry.getKey().getStack(entry.getValue()); + final IAEItemStack stack = entry.getKey().request(inv, item.getStackSize() * i, src); + + if (this.containerItems) { + final ItemStack is = Platform.getContainerItem(stack.getItemStack()); + final IAEItemStack o = AEApi.instance().storage().createItemStack(is); + if (o != null) { + this.bytes++; + inv.injectItems(o, Actionable.MODULATE, src); + } + } + } + } + + // assume its possible. + + // add crafting results.. + for (final IAEItemStack out : this.details.getCondensedOutputs()) { + final IAEItemStack o = out.copy(); + o.setStackSize(o.getStackSize() * i); + inv.injectItems(o, Actionable.MODULATE, src); + } + + this.crafts += i; + } + + void dive(final CraftingJob job) { + job.addTask(this.getAmountCrafted(this.parent.getStack(1)), this.crafts, this.details, this.depth); + for (final CraftingTreeNode pro : this.nodes.keySet()) { + pro.dive(job); + } + + job.addBytes(8 + this.crafts + this.bytes); + } + + IAEItemStack getAmountCrafted(IAEItemStack what2) { + for (final IAEItemStack is : this.details.getCondensedOutputs()) { + if (is.equals(what2)) { + what2 = what2.copy(); + what2.setStackSize(is.getStackSize()); + return what2; + } + } + + // more fuzzy! + for (final IAEItemStack is : this.details.getCondensedOutputs()) { + if (is.getItem() == what2.getItem() + && (is.getItem().isDamageable() || is.getItemDamage() == what2.getItemDamage())) { + what2 = is.copy(); + what2.setStackSize(is.getStackSize()); + return what2; + } + } + + throw new IllegalStateException("Crafting Tree construction failed."); + } + + void setSimulate() { + this.crafts = 0; + this.bytes = 0; + + for (final CraftingTreeNode pro : this.nodes.keySet()) { + pro.setSimulate(); + } + } + + void setJob( + final MECraftingInventory storage, final CraftingCPUCluster craftingCPUCluster, final BaseActionSource src) + throws CraftBranchFailure { + craftingCPUCluster.addCrafting(this.details, this.crafts); + + for (final CraftingTreeNode pro : this.nodes.keySet()) { + pro.setJob(storage, craftingCPUCluster, src); + } + } + + void getPlan(final IItemList plan) { + for (IAEItemStack i : this.details.getOutputs()) { + i = i.copy(); + i.setCountRequestable(i.getStackSize() * this.crafts); + plan.addRequestable(i); + } + + for (final CraftingTreeNode pro : this.nodes.keySet()) { + pro.getPlan(plan); + } + } } diff --git a/src/main/java/appeng/crafting/CraftingWatcher.java b/src/main/java/appeng/crafting/CraftingWatcher.java index 8dfe57c3a37..1630bfccbe8 100644 --- a/src/main/java/appeng/crafting/CraftingWatcher.java +++ b/src/main/java/appeng/crafting/CraftingWatcher.java @@ -18,184 +18,154 @@ package appeng.crafting; - import appeng.api.networking.crafting.ICraftingWatcher; import appeng.api.networking.crafting.ICraftingWatcherHost; import appeng.api.storage.data.IAEStack; import appeng.me.cache.CraftingGridCache; - -import javax.annotation.Nonnull; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; - +import javax.annotation.Nonnull; /** * Maintain my interests, and a global watch list, they should always be fully synchronized. */ -public class CraftingWatcher implements ICraftingWatcher -{ - - private final CraftingGridCache gsc; - private final ICraftingWatcherHost host; - private final HashSet myInterests = new HashSet(); - - public CraftingWatcher( final CraftingGridCache cache, final ICraftingWatcherHost host ) - { - this.gsc = cache; - this.host = host; - } - - public ICraftingWatcherHost getHost() - { - return this.host; - } - - @Override - public int size() - { - return this.myInterests.size(); - } - - @Override - public boolean isEmpty() - { - return this.myInterests.isEmpty(); - } - - @Override - public boolean contains( final Object o ) - { - return this.myInterests.contains( o ); - } - - @Nonnull - @Override - public Iterator iterator() - { - return new ItemWatcherIterator( this, this.myInterests.iterator() ); - } - - @Nonnull - @Override - public Object[] toArray() - { - return this.myInterests.toArray(); - } - - @Nonnull - @Override - public T[] toArray( @Nonnull final T[] a ) - { - return this.myInterests.toArray( a ); - } - - @Override - public boolean add( final IAEStack e ) - { - if( this.myInterests.contains( e ) ) - { - return false; - } - - return this.myInterests.add( e.copy() ) && this.gsc.getInterestManager().put( e, this ); - } - - @Override - public boolean remove( final Object o ) - { - return this.myInterests.remove( o ) && this.gsc.getInterestManager().remove( (IAEStack) o, this ); - } - - @Override - public boolean containsAll( @Nonnull final Collection c ) - { - return this.myInterests.containsAll( c ); - } - - @Override - public boolean addAll( @Nonnull final Collection c ) - { - boolean didChange = false; - - for( final IAEStack o : c ) - { - didChange = this.add( o ) || didChange; - } - - return didChange; - } - - @Override - public boolean removeAll( @Nonnull final Collection c ) - { - boolean didSomething = false; - for( final Object o : c ) - { - didSomething = this.remove( o ) || didSomething; - } - return didSomething; - } - - @Override - public boolean retainAll( @Nonnull final Collection c ) - { - boolean changed = false; - final Iterator i = this.iterator(); - - while( i.hasNext() ) - { - if( !c.contains( i.next() ) ) - { - i.remove(); - changed = true; - } - } - - return changed; - } - - @Override - public void clear() - { - final Iterator i = this.myInterests.iterator(); - while( i.hasNext() ) - { - this.gsc.getInterestManager().remove( i.next(), this ); - i.remove(); - } - } - - private class ItemWatcherIterator implements Iterator - { - - private final CraftingWatcher watcher; - private final Iterator interestIterator; - private IAEStack myLast; - - public ItemWatcherIterator( final CraftingWatcher parent, final Iterator i ) - { - this.watcher = parent; - this.interestIterator = i; - } - - @Override - public boolean hasNext() - { - return this.interestIterator.hasNext(); - } - - @Override - public IAEStack next() - { - return this.myLast = this.interestIterator.next(); - } - - @Override - public void remove() - { - CraftingWatcher.this.gsc.getInterestManager().remove( this.myLast, this.watcher ); - this.interestIterator.remove(); - } - } +public class CraftingWatcher implements ICraftingWatcher { + + private final CraftingGridCache gsc; + private final ICraftingWatcherHost host; + private final HashSet myInterests = new HashSet(); + + public CraftingWatcher(final CraftingGridCache cache, final ICraftingWatcherHost host) { + this.gsc = cache; + this.host = host; + } + + public ICraftingWatcherHost getHost() { + return this.host; + } + + @Override + public int size() { + return this.myInterests.size(); + } + + @Override + public boolean isEmpty() { + return this.myInterests.isEmpty(); + } + + @Override + public boolean contains(final Object o) { + return this.myInterests.contains(o); + } + + @Nonnull + @Override + public Iterator iterator() { + return new ItemWatcherIterator(this, this.myInterests.iterator()); + } + + @Nonnull + @Override + public Object[] toArray() { + return this.myInterests.toArray(); + } + + @Nonnull + @Override + public T[] toArray(@Nonnull final T[] a) { + return this.myInterests.toArray(a); + } + + @Override + public boolean add(final IAEStack e) { + if (this.myInterests.contains(e)) { + return false; + } + + return this.myInterests.add(e.copy()) && this.gsc.getInterestManager().put(e, this); + } + + @Override + public boolean remove(final Object o) { + return this.myInterests.remove(o) && this.gsc.getInterestManager().remove((IAEStack) o, this); + } + + @Override + public boolean containsAll(@Nonnull final Collection c) { + return this.myInterests.containsAll(c); + } + + @Override + public boolean addAll(@Nonnull final Collection c) { + boolean didChange = false; + + for (final IAEStack o : c) { + didChange = this.add(o) || didChange; + } + + return didChange; + } + + @Override + public boolean removeAll(@Nonnull final Collection c) { + boolean didSomething = false; + for (final Object o : c) { + didSomething = this.remove(o) || didSomething; + } + return didSomething; + } + + @Override + public boolean retainAll(@Nonnull final Collection c) { + boolean changed = false; + final Iterator i = this.iterator(); + + while (i.hasNext()) { + if (!c.contains(i.next())) { + i.remove(); + changed = true; + } + } + + return changed; + } + + @Override + public void clear() { + final Iterator i = this.myInterests.iterator(); + while (i.hasNext()) { + this.gsc.getInterestManager().remove(i.next(), this); + i.remove(); + } + } + + private class ItemWatcherIterator implements Iterator { + + private final CraftingWatcher watcher; + private final Iterator interestIterator; + private IAEStack myLast; + + public ItemWatcherIterator(final CraftingWatcher parent, final Iterator i) { + this.watcher = parent; + this.interestIterator = i; + } + + @Override + public boolean hasNext() { + return this.interestIterator.hasNext(); + } + + @Override + public IAEStack next() { + return this.myLast = this.interestIterator.next(); + } + + @Override + public void remove() { + CraftingWatcher.this.gsc.getInterestManager().remove(this.myLast, this.watcher); + this.interestIterator.remove(); + } + } } diff --git a/src/main/java/appeng/crafting/MECraftingInventory.java b/src/main/java/appeng/crafting/MECraftingInventory.java index 433e5dc7dfb..47127af7469 100644 --- a/src/main/java/appeng/crafting/MECraftingInventory.java +++ b/src/main/java/appeng/crafting/MECraftingInventory.java @@ -18,7 +18,6 @@ package appeng.crafting; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -28,325 +27,268 @@ import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; - -public class MECraftingInventory implements IMEInventory -{ - - private final MECraftingInventory par; - - private final IMEInventory target; - private final IItemList localCache; - - private final boolean logExtracted; - private final IItemList extractedCache; - - private final boolean logInjections; - private final IItemList injectedCache; - - private final boolean logMissing; - private final IItemList missingCache; - - public MECraftingInventory() - { - this.localCache = AEApi.instance().storage().createItemList(); - this.extractedCache = null; - this.injectedCache = null; - this.missingCache = null; - this.logExtracted = false; - this.logInjections = false; - this.logMissing = false; - this.target = null; - this.par = null; - } - - public MECraftingInventory( final MECraftingInventory parent ) - { - this.target = parent; - this.logExtracted = parent.logExtracted; - this.logInjections = parent.logInjections; - this.logMissing = parent.logMissing; - - if( this.logMissing ) - { - this.missingCache = AEApi.instance().storage().createItemList(); - } - else - { - this.missingCache = null; - } - - if( this.logExtracted ) - { - this.extractedCache = AEApi.instance().storage().createItemList(); - } - else - { - this.extractedCache = null; - } - - if( this.logInjections ) - { - this.injectedCache = AEApi.instance().storage().createItemList(); - } - else - { - this.injectedCache = null; - } - - this.localCache = this.target.getAvailableItems( AEApi.instance().storage().createItemList() ); - - this.par = parent; - } - - public MECraftingInventory( final IMEMonitor target, final BaseActionSource src, final boolean logExtracted, final boolean logInjections, final boolean logMissing ) - { - this.target = target; - this.logExtracted = logExtracted; - this.logInjections = logInjections; - this.logMissing = logMissing; - - if( logMissing ) - { - this.missingCache = AEApi.instance().storage().createItemList(); - } - else - { - this.missingCache = null; - } - - if( logExtracted ) - { - this.extractedCache = AEApi.instance().storage().createItemList(); - } - else - { - this.extractedCache = null; - } - - if( logInjections ) - { - this.injectedCache = AEApi.instance().storage().createItemList(); - } - else - { - this.injectedCache = null; - } - - this.localCache = AEApi.instance().storage().createItemList(); - for( final IAEItemStack is : target.getStorageList() ) - { - this.localCache.add( target.extractItems( is, Actionable.SIMULATE, src ) ); - } - - this.par = null; - } - - public MECraftingInventory( final IMEInventory target, final boolean logExtracted, final boolean logInjections, final boolean logMissing ) - { - this.target = target; - this.logExtracted = logExtracted; - this.logInjections = logInjections; - this.logMissing = logMissing; - - if( logMissing ) - { - this.missingCache = AEApi.instance().storage().createItemList(); - } - else - { - this.missingCache = null; - } - - if( logExtracted ) - { - this.extractedCache = AEApi.instance().storage().createItemList(); - } - else - { - this.extractedCache = null; - } - - if( logInjections ) - { - this.injectedCache = AEApi.instance().storage().createItemList(); - } - else - { - this.injectedCache = null; - } - - this.localCache = target.getAvailableItems( AEApi.instance().storage().createItemList() ); - this.par = null; - } - - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - if( input == null ) - { - return null; - } - - if( mode == Actionable.MODULATE ) - { - if( this.logInjections ) - { - this.injectedCache.add( input ); - } - this.localCache.add( input ); - } - - return null; - } - - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - if( request == null ) - { - return null; - } - - final IAEItemStack list = this.localCache.findPrecise( request ); - if( list == null || list.getStackSize() == 0 ) - { - return null; - } - - if( list.getStackSize() >= request.getStackSize() ) - { - if( mode == Actionable.MODULATE ) - { - list.decStackSize( request.getStackSize() ); - if( this.logExtracted ) - { - this.extractedCache.add( request ); - } - } - - return request; - } - - final IAEItemStack ret = request.copy(); - ret.setStackSize( list.getStackSize() ); - - if( mode == Actionable.MODULATE ) - { - list.reset(); - if( this.logExtracted ) - { - this.extractedCache.add( ret ); - } - } - - return ret; - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final IAEItemStack is : this.localCache ) - { - out.add( is ); - } - - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - public IItemList getItemList() - { - return this.localCache; - } - - public boolean commit( final BaseActionSource src ) - { - final IItemList added = AEApi.instance().storage().createItemList(); - final IItemList pulled = AEApi.instance().storage().createItemList(); - boolean failed = false; - - if( this.logInjections ) - { - for( final IAEItemStack inject : this.injectedCache ) - { - IAEItemStack result = null; - added.add( result = this.target.injectItems( inject, Actionable.MODULATE, src ) ); - - if( result != null ) - { - failed = true; - break; - } - } - } - - if( failed ) - { - for( final IAEItemStack is : added ) - { - this.target.extractItems( is, Actionable.MODULATE, src ); - } - - return false; - } - - if( this.logExtracted ) - { - for( final IAEItemStack extra : this.extractedCache ) - { - IAEItemStack result = null; - pulled.add( result = this.target.extractItems( extra, Actionable.MODULATE, src ) ); - - if( result == null || result.getStackSize() != extra.getStackSize() ) - { - failed = true; - break; - } - } - } - - if( failed ) - { - for( final IAEItemStack is : added ) - { - this.target.extractItems( is, Actionable.MODULATE, src ); - } - - for( final IAEItemStack is : pulled ) - { - this.target.injectItems( is, Actionable.MODULATE, src ); - } - - return false; - } - - if( this.logMissing && this.par != null ) - { - for( final IAEItemStack extra : this.missingCache ) - { - this.par.addMissing( extra ); - } - } - - return true; - } - - private void addMissing( final IAEItemStack extra ) - { - this.missingCache.add( extra ); - } - - void ignore( final IAEItemStack what ) - { - final IAEItemStack list = this.localCache.findPrecise( what ); - if( list != null ) - { - list.setStackSize( 0 ); - } - } +public class MECraftingInventory implements IMEInventory { + + private final MECraftingInventory par; + + private final IMEInventory target; + private final IItemList localCache; + + private final boolean logExtracted; + private final IItemList extractedCache; + + private final boolean logInjections; + private final IItemList injectedCache; + + private final boolean logMissing; + private final IItemList missingCache; + + public MECraftingInventory() { + this.localCache = AEApi.instance().storage().createItemList(); + this.extractedCache = null; + this.injectedCache = null; + this.missingCache = null; + this.logExtracted = false; + this.logInjections = false; + this.logMissing = false; + this.target = null; + this.par = null; + } + + public MECraftingInventory(final MECraftingInventory parent) { + this.target = parent; + this.logExtracted = parent.logExtracted; + this.logInjections = parent.logInjections; + this.logMissing = parent.logMissing; + + if (this.logMissing) { + this.missingCache = AEApi.instance().storage().createItemList(); + } else { + this.missingCache = null; + } + + if (this.logExtracted) { + this.extractedCache = AEApi.instance().storage().createItemList(); + } else { + this.extractedCache = null; + } + + if (this.logInjections) { + this.injectedCache = AEApi.instance().storage().createItemList(); + } else { + this.injectedCache = null; + } + + this.localCache = + this.target.getAvailableItems(AEApi.instance().storage().createItemList()); + + this.par = parent; + } + + public MECraftingInventory( + final IMEMonitor target, + final BaseActionSource src, + final boolean logExtracted, + final boolean logInjections, + final boolean logMissing) { + this.target = target; + this.logExtracted = logExtracted; + this.logInjections = logInjections; + this.logMissing = logMissing; + + if (logMissing) { + this.missingCache = AEApi.instance().storage().createItemList(); + } else { + this.missingCache = null; + } + + if (logExtracted) { + this.extractedCache = AEApi.instance().storage().createItemList(); + } else { + this.extractedCache = null; + } + + if (logInjections) { + this.injectedCache = AEApi.instance().storage().createItemList(); + } else { + this.injectedCache = null; + } + + this.localCache = AEApi.instance().storage().createItemList(); + for (final IAEItemStack is : target.getStorageList()) { + this.localCache.add(target.extractItems(is, Actionable.SIMULATE, src)); + } + + this.par = null; + } + + public MECraftingInventory( + final IMEInventory target, + final boolean logExtracted, + final boolean logInjections, + final boolean logMissing) { + this.target = target; + this.logExtracted = logExtracted; + this.logInjections = logInjections; + this.logMissing = logMissing; + + if (logMissing) { + this.missingCache = AEApi.instance().storage().createItemList(); + } else { + this.missingCache = null; + } + + if (logExtracted) { + this.extractedCache = AEApi.instance().storage().createItemList(); + } else { + this.extractedCache = null; + } + + if (logInjections) { + this.injectedCache = AEApi.instance().storage().createItemList(); + } else { + this.injectedCache = null; + } + + this.localCache = target.getAvailableItems(AEApi.instance().storage().createItemList()); + this.par = null; + } + + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode, final BaseActionSource src) { + if (input == null) { + return null; + } + + if (mode == Actionable.MODULATE) { + if (this.logInjections) { + this.injectedCache.add(input); + } + this.localCache.add(input); + } + + return null; + } + + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final BaseActionSource src) { + if (request == null) { + return null; + } + + final IAEItemStack list = this.localCache.findPrecise(request); + if (list == null || list.getStackSize() == 0) { + return null; + } + + if (list.getStackSize() >= request.getStackSize()) { + if (mode == Actionable.MODULATE) { + list.decStackSize(request.getStackSize()); + if (this.logExtracted) { + this.extractedCache.add(request); + } + } + + return request; + } + + final IAEItemStack ret = request.copy(); + ret.setStackSize(list.getStackSize()); + + if (mode == Actionable.MODULATE) { + list.reset(); + if (this.logExtracted) { + this.extractedCache.add(ret); + } + } + + return ret; + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final IAEItemStack is : this.localCache) { + out.add(is); + } + + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } + + public IItemList getItemList() { + return this.localCache; + } + + public boolean commit(final BaseActionSource src) { + final IItemList added = AEApi.instance().storage().createItemList(); + final IItemList pulled = AEApi.instance().storage().createItemList(); + boolean failed = false; + + if (this.logInjections) { + for (final IAEItemStack inject : this.injectedCache) { + IAEItemStack result = null; + added.add(result = this.target.injectItems(inject, Actionable.MODULATE, src)); + + if (result != null) { + failed = true; + break; + } + } + } + + if (failed) { + for (final IAEItemStack is : added) { + this.target.extractItems(is, Actionable.MODULATE, src); + } + + return false; + } + + if (this.logExtracted) { + for (final IAEItemStack extra : this.extractedCache) { + IAEItemStack result = null; + pulled.add(result = this.target.extractItems(extra, Actionable.MODULATE, src)); + + if (result == null || result.getStackSize() != extra.getStackSize()) { + failed = true; + break; + } + } + } + + if (failed) { + for (final IAEItemStack is : added) { + this.target.extractItems(is, Actionable.MODULATE, src); + } + + for (final IAEItemStack is : pulled) { + this.target.injectItems(is, Actionable.MODULATE, src); + } + + return false; + } + + if (this.logMissing && this.par != null) { + for (final IAEItemStack extra : this.missingCache) { + this.par.addMissing(extra); + } + } + + return true; + } + + private void addMissing(final IAEItemStack extra) { + this.missingCache.add(extra); + } + + void ignore(final IAEItemStack what) { + final IAEItemStack list = this.localCache.findPrecise(what); + if (list != null) { + list.setStackSize(0); + } + } } diff --git a/src/main/java/appeng/debug/BlockChunkloader.java b/src/main/java/appeng/debug/BlockChunkloader.java index 2023704945a..8ed835ac2df 100644 --- a/src/main/java/appeng/debug/BlockChunkloader.java +++ b/src/main/java/appeng/debug/BlockChunkloader.java @@ -18,10 +18,11 @@ package appeng.debug; - import appeng.block.AEBaseTileBlock; import appeng.core.AppEng; import appeng.core.features.AEFeature; +import java.util.EnumSet; +import java.util.List; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.world.World; @@ -29,30 +30,20 @@ import net.minecraftforge.common.ForgeChunkManager.LoadingCallback; import net.minecraftforge.common.ForgeChunkManager.Ticket; -import java.util.EnumSet; -import java.util.List; - - -public class BlockChunkloader extends AEBaseTileBlock implements LoadingCallback -{ - - public BlockChunkloader() - { - super( Material.iron ); - this.setTileEntity( TileChunkLoader.class ); - ForgeChunkManager.setForcedChunkLoadingCallback( AppEng.instance(), this ); - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } +public class BlockChunkloader extends AEBaseTileBlock implements LoadingCallback { - @Override - public void ticketsLoaded( final List tickets, final World world ) - { + public BlockChunkloader() { + super(Material.iron); + this.setTileEntity(TileChunkLoader.class); + ForgeChunkManager.setForcedChunkLoadingCallback(AppEng.instance(), this); + this.setFeature(EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative)); + } - } + @Override + public void ticketsLoaded(final List tickets, final World world) {} - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - this.registerNoIcons(); - } + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) { + this.registerNoIcons(); + } } diff --git a/src/main/java/appeng/debug/BlockCubeGenerator.java b/src/main/java/appeng/debug/BlockCubeGenerator.java index e7a185b14f2..1f2b7c993b3 100644 --- a/src/main/java/appeng/debug/BlockCubeGenerator.java +++ b/src/main/java/appeng/debug/BlockCubeGenerator.java @@ -18,42 +18,43 @@ package appeng.debug; - import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; +import java.util.EnumSet; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; -import java.util.EnumSet; - - -public class BlockCubeGenerator extends AEBaseTileBlock -{ - - public BlockCubeGenerator() - { - super( Material.iron ); - this.setTileEntity( TileCubeGenerator.class ); - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - final TileCubeGenerator tcg = this.getTileEntity( w, x, y, z ); - if( tcg != null ) - { - tcg.click( player ); - } - - return true; - } - - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - this.registerNoIcons(); - } +public class BlockCubeGenerator extends AEBaseTileBlock { + + public BlockCubeGenerator() { + super(Material.iron); + this.setTileEntity(TileCubeGenerator.class); + this.setFeature(EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative)); + } + + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + final TileCubeGenerator tcg = this.getTileEntity(w, x, y, z); + if (tcg != null) { + tcg.click(player); + } + + return true; + } + + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) { + this.registerNoIcons(); + } } diff --git a/src/main/java/appeng/debug/BlockItemGen.java b/src/main/java/appeng/debug/BlockItemGen.java index 05edc75558a..9e929620872 100644 --- a/src/main/java/appeng/debug/BlockItemGen.java +++ b/src/main/java/appeng/debug/BlockItemGen.java @@ -18,28 +18,22 @@ package appeng.debug; - import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; +import java.util.EnumSet; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; -import java.util.EnumSet; - - -public class BlockItemGen extends AEBaseTileBlock -{ +public class BlockItemGen extends AEBaseTileBlock { - public BlockItemGen() - { - super( Material.iron ); - this.setTileEntity( TileItemGen.class ); - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } + public BlockItemGen() { + super(Material.iron); + this.setTileEntity(TileItemGen.class); + this.setFeature(EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative)); + } - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - this.registerNoIcons(); - } + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) { + this.registerNoIcons(); + } } diff --git a/src/main/java/appeng/debug/BlockPhantomNode.java b/src/main/java/appeng/debug/BlockPhantomNode.java index 26b4b1d3a97..b12ce6df1ae 100644 --- a/src/main/java/appeng/debug/BlockPhantomNode.java +++ b/src/main/java/appeng/debug/BlockPhantomNode.java @@ -18,38 +18,40 @@ package appeng.debug; - import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; +import java.util.EnumSet; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; -import java.util.EnumSet; - - -public class BlockPhantomNode extends AEBaseTileBlock -{ - - public BlockPhantomNode() - { - super( Material.iron ); - this.setTileEntity( TilePhantomNode.class ); - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - final TilePhantomNode tpn = this.getTileEntity( w, x, y, z ); - tpn.triggerCrashMode(); - return true; - } - - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - this.registerNoIcons(); - } +public class BlockPhantomNode extends AEBaseTileBlock { + + public BlockPhantomNode() { + super(Material.iron); + this.setTileEntity(TilePhantomNode.class); + this.setFeature(EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative)); + } + + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + final TilePhantomNode tpn = this.getTileEntity(w, x, y, z); + tpn.triggerCrashMode(); + return true; + } + + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) { + this.registerNoIcons(); + } } diff --git a/src/main/java/appeng/debug/TileChunkLoader.java b/src/main/java/appeng/debug/TileChunkLoader.java index 0b7254b4b80..4dfd38b15b9 100644 --- a/src/main/java/appeng/debug/TileChunkLoader.java +++ b/src/main/java/appeng/debug/TileChunkLoader.java @@ -18,7 +18,6 @@ package appeng.debug; - import appeng.core.AELog; import appeng.core.AppEng; import appeng.tile.AEBaseTile; @@ -26,6 +25,7 @@ import appeng.tile.events.TileEventType; import appeng.util.Platform; import cpw.mods.fml.common.FMLCommonHandler; +import java.util.List; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentText; @@ -34,61 +34,48 @@ import net.minecraftforge.common.ForgeChunkManager.Ticket; import net.minecraftforge.common.ForgeChunkManager.Type; -import java.util.List; - - -public class TileChunkLoader extends AEBaseTile -{ +public class TileChunkLoader extends AEBaseTile { - private boolean requestTicket = true; - private Ticket ct = null; + private boolean requestTicket = true; + private Ticket ct = null; - @TileEvent( TileEventType.TICK ) - public void onTickEvent() - { - if( this.requestTicket ) - { - this.requestTicket = false; - this.initTicket(); - } - } + @TileEvent(TileEventType.TICK) + public void onTickEvent() { + if (this.requestTicket) { + this.requestTicket = false; + this.initTicket(); + } + } - private void initTicket() - { - if( Platform.isClient() ) - { - return; - } + private void initTicket() { + if (Platform.isClient()) { + return; + } - this.ct = ForgeChunkManager.requestTicket( AppEng.instance(), this.worldObj, Type.NORMAL ); + this.ct = ForgeChunkManager.requestTicket(AppEng.instance(), this.worldObj, Type.NORMAL); - if( this.ct == null ) - { - final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - if( server != null ) - { - final List pl = server.getConfigurationManager().playerEntityList; - for( final EntityPlayerMP p : pl ) - { - p.addChatMessage( new ChatComponentText( "Can't chunk load.." ) ); - } - } - return; - } + if (this.ct == null) { + final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + if (server != null) { + final List pl = server.getConfigurationManager().playerEntityList; + for (final EntityPlayerMP p : pl) { + p.addChatMessage(new ChatComponentText("Can't chunk load..")); + } + } + return; + } - AELog.info( "New Ticket " + this.ct.toString() ); - ForgeChunkManager.forceChunk( this.ct, new ChunkCoordIntPair( this.xCoord >> 4, this.zCoord >> 4 ) ); - } + AELog.info("New Ticket " + this.ct.toString()); + ForgeChunkManager.forceChunk(this.ct, new ChunkCoordIntPair(this.xCoord >> 4, this.zCoord >> 4)); + } - @Override - public void invalidate() - { - if( Platform.isClient() ) - { - return; - } + @Override + public void invalidate() { + if (Platform.isClient()) { + return; + } - AELog.info( "Released Ticket " + this.ct.toString() ); - ForgeChunkManager.releaseTicket( this.ct ); - } + AELog.info("Released Ticket " + this.ct.toString()); + ForgeChunkManager.releaseTicket(this.ct); + } } diff --git a/src/main/java/appeng/debug/TileCubeGenerator.java b/src/main/java/appeng/debug/TileCubeGenerator.java index 6dcb29aecc6..bc866807f32 100644 --- a/src/main/java/appeng/debug/TileCubeGenerator.java +++ b/src/main/java/appeng/debug/TileCubeGenerator.java @@ -18,7 +18,6 @@ package appeng.debug; - import appeng.core.CommonHelper; import appeng.tile.AEBaseTile; import appeng.tile.TileEvent; @@ -30,94 +29,83 @@ import net.minecraft.util.ChatComponentText; import net.minecraftforge.common.util.ForgeDirection; - -public class TileCubeGenerator extends AEBaseTile -{ - - private int size = 3; - private ItemStack is = null; - private int countdown = 20 * 10; - private EntityPlayer who = null; - - @TileEvent( TileEventType.TICK ) - public void onTickEvent() - { - if( this.is != null && Platform.isServer() ) - { - this.countdown--; - - if( this.countdown % 20 == 0 ) - { - for( final EntityPlayer e : CommonHelper.proxy.getPlayers() ) - { - e.addChatMessage( new ChatComponentText( "Spawning in... " + ( this.countdown / 20 ) ) ); - } - } - - if( this.countdown <= 0 ) - { - this.spawn(); - } - } - } - - private void spawn() - { - this.worldObj.setBlock( this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK, 0, 3 ); - - final Item i = this.is.getItem(); - final int side = ForgeDirection.UP.ordinal(); - - final int half = (int) Math.floor( this.size / 2 ); - - for( int y = 0; y < this.size; y++ ) - { - for( int x = -half; x < half; x++ ) - { - for( int z = -half; z < half; z++ ) - { - i.onItemUse( this.is.copy(), this.who, this.worldObj, x + this.xCoord, y + this.yCoord - 1, z + this.zCoord, side, 0.5f, 0.0f, 0.5f ); - } - } - } - } - - void click( final EntityPlayer player ) - { - if( Platform.isServer() ) - { - final ItemStack hand = player.inventory.getCurrentItem(); - this.who = player; - - if( hand == null ) - { - this.is = null; - - if( player.isSneaking() ) - { - this.size--; - } - else - { - this.size++; - } - - if( this.size < 3 ) - { - this.size = 3; - } - if( this.size > 64 ) - { - this.size = 64; - } - - player.addChatMessage( new ChatComponentText( "Size: " + this.size ) ); - } - else - { - this.countdown = 20 * 10; - this.is = hand; - } - } - } +public class TileCubeGenerator extends AEBaseTile { + + private int size = 3; + private ItemStack is = null; + private int countdown = 20 * 10; + private EntityPlayer who = null; + + @TileEvent(TileEventType.TICK) + public void onTickEvent() { + if (this.is != null && Platform.isServer()) { + this.countdown--; + + if (this.countdown % 20 == 0) { + for (final EntityPlayer e : CommonHelper.proxy.getPlayers()) { + e.addChatMessage(new ChatComponentText("Spawning in... " + (this.countdown / 20))); + } + } + + if (this.countdown <= 0) { + this.spawn(); + } + } + } + + private void spawn() { + this.worldObj.setBlock(this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK, 0, 3); + + final Item i = this.is.getItem(); + final int side = ForgeDirection.UP.ordinal(); + + final int half = (int) Math.floor(this.size / 2); + + for (int y = 0; y < this.size; y++) { + for (int x = -half; x < half; x++) { + for (int z = -half; z < half; z++) { + i.onItemUse( + this.is.copy(), + this.who, + this.worldObj, + x + this.xCoord, + y + this.yCoord - 1, + z + this.zCoord, + side, + 0.5f, + 0.0f, + 0.5f); + } + } + } + } + + void click(final EntityPlayer player) { + if (Platform.isServer()) { + final ItemStack hand = player.inventory.getCurrentItem(); + this.who = player; + + if (hand == null) { + this.is = null; + + if (player.isSneaking()) { + this.size--; + } else { + this.size++; + } + + if (this.size < 3) { + this.size = 3; + } + if (this.size > 64) { + this.size = 64; + } + + player.addChatMessage(new ChatComponentText("Size: " + this.size)); + } else { + this.countdown = 20 * 10; + this.is = hand; + } + } + } } diff --git a/src/main/java/appeng/debug/TileItemGen.java b/src/main/java/appeng/debug/TileItemGen.java index 5eff7e25b0e..eff4ebf48be 100644 --- a/src/main/java/appeng/debug/TileItemGen.java +++ b/src/main/java/appeng/debug/TileItemGen.java @@ -18,129 +18,100 @@ package appeng.debug; - import appeng.tile.AEBaseTile; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; - -public class TileItemGen extends AEBaseTile implements IInventory -{ - - private static final Queue POSSIBLE_ITEMS = new LinkedList(); - - public TileItemGen() - { - if( POSSIBLE_ITEMS.isEmpty() ) - { - for( final Object obj : Item.itemRegistry ) - { - final Item mi = (Item) obj; - if( mi != null ) - { - if( mi.isDamageable() ) - { - for( int dmg = 0; dmg < mi.getMaxDamage(); dmg++ ) - { - POSSIBLE_ITEMS.add( new ItemStack( mi, 1, dmg ) ); - } - } - else - { - final List list = new ArrayList(); - mi.getSubItems( mi, mi.getCreativeTab(), list ); - POSSIBLE_ITEMS.addAll( list ); - } - } - } - } - } - - @Override - public int getSizeInventory() - { - return 1; - } - - @Override - public ItemStack getStackInSlot( final int i ) - { - return this.getRandomItem(); - } - - private ItemStack getRandomItem() - { - return POSSIBLE_ITEMS.peek(); - } - - @Override - public ItemStack decrStackSize( final int i, final int j ) - { - final ItemStack a = POSSIBLE_ITEMS.poll(); - final ItemStack out = a.copy(); - POSSIBLE_ITEMS.add( a ); - return out; - } - - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - return null; - } - - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - final ItemStack a = POSSIBLE_ITEMS.poll(); - POSSIBLE_ITEMS.add( a ); - } - - @Override - public String getInventoryName() - { - return null; - } - - @Override - public boolean hasCustomInventoryName() - { - return false; - } - - @Override - public int getInventoryStackLimit() - { - return 1; - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return false; - } - - @Override - public void openInventory() - { - - } - - @Override - public void closeInventory() - { - - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return false; - } +public class TileItemGen extends AEBaseTile implements IInventory { + + private static final Queue POSSIBLE_ITEMS = new LinkedList(); + + public TileItemGen() { + if (POSSIBLE_ITEMS.isEmpty()) { + for (final Object obj : Item.itemRegistry) { + final Item mi = (Item) obj; + if (mi != null) { + if (mi.isDamageable()) { + for (int dmg = 0; dmg < mi.getMaxDamage(); dmg++) { + POSSIBLE_ITEMS.add(new ItemStack(mi, 1, dmg)); + } + } else { + final List list = new ArrayList(); + mi.getSubItems(mi, mi.getCreativeTab(), list); + POSSIBLE_ITEMS.addAll(list); + } + } + } + } + } + + @Override + public int getSizeInventory() { + return 1; + } + + @Override + public ItemStack getStackInSlot(final int i) { + return this.getRandomItem(); + } + + private ItemStack getRandomItem() { + return POSSIBLE_ITEMS.peek(); + } + + @Override + public ItemStack decrStackSize(final int i, final int j) { + final ItemStack a = POSSIBLE_ITEMS.poll(); + final ItemStack out = a.copy(); + POSSIBLE_ITEMS.add(a); + return out; + } + + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + return null; + } + + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + final ItemStack a = POSSIBLE_ITEMS.poll(); + POSSIBLE_ITEMS.add(a); + } + + @Override + public String getInventoryName() { + return null; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return false; + } + + @Override + public void openInventory() {} + + @Override + public void closeInventory() {} + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return false; + } } diff --git a/src/main/java/appeng/debug/TilePhantomNode.java b/src/main/java/appeng/debug/TilePhantomNode.java index 746b623077f..aabf4c4925c 100644 --- a/src/main/java/appeng/debug/TilePhantomNode.java +++ b/src/main/java/appeng/debug/TilePhantomNode.java @@ -18,47 +18,38 @@ package appeng.debug; - import appeng.api.networking.IGridNode; import appeng.me.helpers.AENetworkProxy; import appeng.tile.grid.AENetworkTile; -import net.minecraftforge.common.util.ForgeDirection; - import java.util.EnumSet; +import net.minecraftforge.common.util.ForgeDirection; - -public class TilePhantomNode extends AENetworkTile -{ - - private AENetworkProxy proxy = null; - private boolean crashMode = false; - - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - if( !this.crashMode ) - { - return super.getGridNode( dir ); - } - - return this.proxy.getNode(); - } - - @Override - public void onReady() - { - super.onReady(); - this.proxy = this.createProxy(); - this.proxy.onReady(); - this.crashMode = true; - } - - void triggerCrashMode() - { - if( this.proxy != null ) - { - this.crashMode = true; - this.proxy.setValidSides( EnumSet.allOf( ForgeDirection.class ) ); - } - } +public class TilePhantomNode extends AENetworkTile { + + private AENetworkProxy proxy = null; + private boolean crashMode = false; + + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + if (!this.crashMode) { + return super.getGridNode(dir); + } + + return this.proxy.getNode(); + } + + @Override + public void onReady() { + super.onReady(); + this.proxy = this.createProxy(); + this.proxy.onReady(); + this.crashMode = true; + } + + void triggerCrashMode() { + if (this.proxy != null) { + this.crashMode = true; + this.proxy.setValidSides(EnumSet.allOf(ForgeDirection.class)); + } + } } diff --git a/src/main/java/appeng/debug/ToolDebugCard.java b/src/main/java/appeng/debug/ToolDebugCard.java index 27a7c6fef4b..36ca64eefbf 100644 --- a/src/main/java/appeng/debug/ToolDebugCard.java +++ b/src/main/java/appeng/debug/ToolDebugCard.java @@ -18,7 +18,6 @@ package appeng.debug; - import appeng.api.networking.IGridConnection; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; @@ -38,6 +37,9 @@ import appeng.parts.p2p.PartP2PTunnel; import appeng.tile.networking.TileController; import appeng.util.Platform; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.Set; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -47,183 +49,153 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.ForgeEventFactory; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Set; - - -public class ToolDebugCard extends AEBaseItem -{ - public ToolDebugCard() - { - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } - - @Override - public boolean onItemUseFirst( final ItemStack stack, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, stack, 1 ) <= 0 ) - return true; - - if( Platform.isClient() ) - { - return false; - } - - if( player.isSneaking() ) - { - int grids = 0; - int totalNodes = 0; - - for( final Grid g : TickHandler.INSTANCE.getGridList() ) - { - grids++; - totalNodes += g.getNodes().size(); - } - - this.outputMsg( player, "Grids: " + grids ); - this.outputMsg( player, "Total Nodes: " + totalNodes ); - } - else - { - final TileEntity te = world.getTileEntity( x, y, z ); - - if( te instanceof IGridHost ) - { - final GridNode node = (GridNode) ( (IGridHost) te ).getGridNode( ForgeDirection.getOrientation( side ) ); - if( node != null ) - { - final Grid g = node.getInternalGrid(); - final IGridNode center = g.getPivot(); - this.outputMsg( player, "This Node: " + node.toString() ); - this.outputMsg( player, "Center Node: " + center.toString() ); - - final IPathingGrid pg = g.getCache( IPathingGrid.class ); - if( pg.getControllerState() == ControllerState.CONTROLLER_ONLINE ) - { - - Set next = new HashSet(); - next.add( node ); - - final int maxLength = 10000; - - int length = 0; - outer: - while( !next.isEmpty() ) - { - final Iterable current = next; - next = new HashSet(); - - for( final IGridNode n : current ) - { - if( n.getMachine() instanceof TileController ) - { - break outer; - } - - for( final IGridConnection c : n.getConnections() ) - { - next.add( c.getOtherSide( n ) ); - } - } - - length++; - - if( length > maxLength ) - { - break; - } - } - - this.outputMsg( player, "Cable Distance: " + length ); - } - - if( center.getMachine() instanceof PartP2PTunnel ) - { - this.outputMsg( player, "Freq: " + ( (PartP2PTunnel) center.getMachine() ).getFrequency() ); - } - - final TickManagerCache tmc = g.getCache( ITickManager.class ); - for( final Class c : g.getMachineClasses() ) - { - int o = 0; - long nanos = 0; - for( final IGridNode oj : g.getMachines( c ) ) - { - o++; - nanos += tmc.getAvgNanoTime( oj ); - } - - if( nanos < 0 ) - { - this.outputMsg( player, c.getSimpleName() + " - " + o ); - } - else - { - this.outputMsg( player, c.getSimpleName() + " - " + o + "; " + this.timeMeasurement( nanos ) ); - } - } - } - else - { - this.outputMsg( player, "No Node Available." ); - } - } - else - { - this.outputMsg( player, "Not Networked Block" ); - } - - if( te instanceof IPartHost ) - { - final IPart center = ( (IPartHost) te ).getPart( ForgeDirection.UNKNOWN ); - ( (IPartHost) te ).markForUpdate(); - if( center != null ) - { - final GridNode n = (GridNode) center.getGridNode(); - this.outputMsg( player, "Node Channels: " + n.usedChannels() ); - for( final IGridConnection gc : n.getConnections() ) - { - final ForgeDirection fd = gc.getDirection( n ); - if( fd != ForgeDirection.UNKNOWN ) - { - this.outputMsg( player, fd.toString() + ": " + gc.getUsedChannels() ); - } - } - } - } - - if( te instanceof IAEPowerStorage ) - { - final IAEPowerStorage ps = (IAEPowerStorage) te; - this.outputMsg( player, "Energy: " + ps.getAECurrentPower() + " / " + ps.getAEMaxPower() ); - - if( te instanceof IGridHost ) - { - final IGridNode node = ( (IGridHost) te ).getGridNode( ForgeDirection.getOrientation( side ) ); - if( node != null && node.getGrid() != null ) - { - final IEnergyGrid eg = node.getGrid().getCache( IEnergyGrid.class ); - this.outputMsg( player, "GridEnergy: " + eg.getStoredPower() + " : " + eg.getEnergyDemand( Double.MAX_VALUE ) ); - } - } - } - } - return true; - } - - private void outputMsg( final ICommandSender player, final String string ) - { - player.addChatMessage( new ChatComponentText( string ) ); - } - - private String timeMeasurement( final long nanos ) - { - final long ms = nanos / 100000; - if( nanos <= 100000 ) - { - return nanos + "ns"; - } - return ( ms / 10.0f ) + "ms"; - } +public class ToolDebugCard extends AEBaseItem { + public ToolDebugCard() { + this.setFeature(EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative)); + } + + @Override + public boolean onItemUseFirst( + final ItemStack stack, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (ForgeEventFactory.onItemUseStart(player, stack, 1) <= 0) return true; + + if (Platform.isClient()) { + return false; + } + + if (player.isSneaking()) { + int grids = 0; + int totalNodes = 0; + + for (final Grid g : TickHandler.INSTANCE.getGridList()) { + grids++; + totalNodes += g.getNodes().size(); + } + + this.outputMsg(player, "Grids: " + grids); + this.outputMsg(player, "Total Nodes: " + totalNodes); + } else { + final TileEntity te = world.getTileEntity(x, y, z); + + if (te instanceof IGridHost) { + final GridNode node = (GridNode) ((IGridHost) te).getGridNode(ForgeDirection.getOrientation(side)); + if (node != null) { + final Grid g = node.getInternalGrid(); + final IGridNode center = g.getPivot(); + this.outputMsg(player, "This Node: " + node.toString()); + this.outputMsg(player, "Center Node: " + center.toString()); + + final IPathingGrid pg = g.getCache(IPathingGrid.class); + if (pg.getControllerState() == ControllerState.CONTROLLER_ONLINE) { + + Set next = new HashSet(); + next.add(node); + + final int maxLength = 10000; + + int length = 0; + outer: + while (!next.isEmpty()) { + final Iterable current = next; + next = new HashSet(); + + for (final IGridNode n : current) { + if (n.getMachine() instanceof TileController) { + break outer; + } + + for (final IGridConnection c : n.getConnections()) { + next.add(c.getOtherSide(n)); + } + } + + length++; + + if (length > maxLength) { + break; + } + } + + this.outputMsg(player, "Cable Distance: " + length); + } + + if (center.getMachine() instanceof PartP2PTunnel) { + this.outputMsg(player, "Freq: " + ((PartP2PTunnel) center.getMachine()).getFrequency()); + } + + final TickManagerCache tmc = g.getCache(ITickManager.class); + for (final Class c : g.getMachineClasses()) { + int o = 0; + long nanos = 0; + for (final IGridNode oj : g.getMachines(c)) { + o++; + nanos += tmc.getAvgNanoTime(oj); + } + + if (nanos < 0) { + this.outputMsg(player, c.getSimpleName() + " - " + o); + } else { + this.outputMsg(player, c.getSimpleName() + " - " + o + "; " + this.timeMeasurement(nanos)); + } + } + } else { + this.outputMsg(player, "No Node Available."); + } + } else { + this.outputMsg(player, "Not Networked Block"); + } + + if (te instanceof IPartHost) { + final IPart center = ((IPartHost) te).getPart(ForgeDirection.UNKNOWN); + ((IPartHost) te).markForUpdate(); + if (center != null) { + final GridNode n = (GridNode) center.getGridNode(); + this.outputMsg(player, "Node Channels: " + n.usedChannels()); + for (final IGridConnection gc : n.getConnections()) { + final ForgeDirection fd = gc.getDirection(n); + if (fd != ForgeDirection.UNKNOWN) { + this.outputMsg(player, fd.toString() + ": " + gc.getUsedChannels()); + } + } + } + } + + if (te instanceof IAEPowerStorage) { + final IAEPowerStorage ps = (IAEPowerStorage) te; + this.outputMsg(player, "Energy: " + ps.getAECurrentPower() + " / " + ps.getAEMaxPower()); + + if (te instanceof IGridHost) { + final IGridNode node = ((IGridHost) te).getGridNode(ForgeDirection.getOrientation(side)); + if (node != null && node.getGrid() != null) { + final IEnergyGrid eg = node.getGrid().getCache(IEnergyGrid.class); + this.outputMsg( + player, + "GridEnergy: " + eg.getStoredPower() + " : " + eg.getEnergyDemand(Double.MAX_VALUE)); + } + } + } + } + return true; + } + + private void outputMsg(final ICommandSender player, final String string) { + player.addChatMessage(new ChatComponentText(string)); + } + + private String timeMeasurement(final long nanos) { + final long ms = nanos / 100000; + if (nanos <= 100000) { + return nanos + "ns"; + } + return (ms / 10.0f) + "ms"; + } } diff --git a/src/main/java/appeng/debug/ToolEraser.java b/src/main/java/appeng/debug/ToolEraser.java index c105674e345..72774ec5be0 100644 --- a/src/main/java/appeng/debug/ToolEraser.java +++ b/src/main/java/appeng/debug/ToolEraser.java @@ -18,13 +18,16 @@ package appeng.debug; - import appeng.api.util.WorldCoord; import appeng.client.texture.MissingIcon; import appeng.core.AELog; import appeng.core.features.AEFeature; import appeng.items.AEBaseItem; import appeng.util.Platform; +import java.util.Collection; +import java.util.EnumSet; +import java.util.LinkedList; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; @@ -33,81 +36,78 @@ import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import java.util.Collection; -import java.util.EnumSet; -import java.util.LinkedList; -import java.util.List; - - -public class ToolEraser extends AEBaseItem -{ - - private static final int BLOCK_ERASE_LIMIT = 90000; - - public ToolEraser() - { - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } - - @Override - public void registerIcons( final IIconRegister par1IconRegister ) - { - this.itemIcon = new MissingIcon( this ); - } - - @Override - public boolean onItemUseFirst( final ItemStack stack, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, stack, 1 ) <= 0 ) - return true; - - if( Platform.isClient() ) - { - return false; - } - - final Block blk = world.getBlock( x, y, z ); - final int meta = world.getBlockMetadata( x, y, z ); - - if( blk != null && ForgeEventFactory.onPlayerInteract( player, PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, x, y, z, side, world ).isCanceled() ) - return true; - - List next = new LinkedList(); - next.add( new WorldCoord( x, y, z ) ); - - int blocks = 0; - while( blocks < BLOCK_ERASE_LIMIT && !next.isEmpty() ) - { - final List c = next; - next = new LinkedList(); - - for( final WorldCoord wc : c ) - { - final Block c_blk = world.getBlock( wc.x, wc.y, wc.z ); - final int c_meta = world.getBlockMetadata( wc.x, wc.y, wc.z ); - - if( c_blk == blk && c_meta == meta ) - { - blocks++; - world.setBlock( wc.x, wc.y, wc.z, Platform.AIR_BLOCK ); - - this.wrappedAdd( world, wc.x + 1, wc.y, wc.z, next ); - this.wrappedAdd( world, wc.x - 1, wc.y, wc.z, next ); - this.wrappedAdd( world, wc.x, wc.y + 1, wc.z, next ); - this.wrappedAdd( world, wc.x, wc.y - 1, wc.z, next ); - this.wrappedAdd( world, wc.x, wc.y, wc.z + 1, next ); - this.wrappedAdd( world, wc.x, wc.y, wc.z - 1, next ); - } - } - } - - AELog.info( "Delete " + blocks + " blocks" ); - - return true; - } - - private void wrappedAdd( final World world, final int i, final int y, final int z, final Collection next ) - { - next.add( new WorldCoord( i, y, z ) ); - } +public class ToolEraser extends AEBaseItem { + + private static final int BLOCK_ERASE_LIMIT = 90000; + + public ToolEraser() { + this.setFeature(EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative)); + } + + @Override + public void registerIcons(final IIconRegister par1IconRegister) { + this.itemIcon = new MissingIcon(this); + } + + @Override + public boolean onItemUseFirst( + final ItemStack stack, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (ForgeEventFactory.onItemUseStart(player, stack, 1) <= 0) return true; + + if (Platform.isClient()) { + return false; + } + + final Block blk = world.getBlock(x, y, z); + final int meta = world.getBlockMetadata(x, y, z); + + if (blk != null + && ForgeEventFactory.onPlayerInteract( + player, PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, x, y, z, side, world) + .isCanceled()) return true; + + List next = new LinkedList(); + next.add(new WorldCoord(x, y, z)); + + int blocks = 0; + while (blocks < BLOCK_ERASE_LIMIT && !next.isEmpty()) { + final List c = next; + next = new LinkedList(); + + for (final WorldCoord wc : c) { + final Block c_blk = world.getBlock(wc.x, wc.y, wc.z); + final int c_meta = world.getBlockMetadata(wc.x, wc.y, wc.z); + + if (c_blk == blk && c_meta == meta) { + blocks++; + world.setBlock(wc.x, wc.y, wc.z, Platform.AIR_BLOCK); + + this.wrappedAdd(world, wc.x + 1, wc.y, wc.z, next); + this.wrappedAdd(world, wc.x - 1, wc.y, wc.z, next); + this.wrappedAdd(world, wc.x, wc.y + 1, wc.z, next); + this.wrappedAdd(world, wc.x, wc.y - 1, wc.z, next); + this.wrappedAdd(world, wc.x, wc.y, wc.z + 1, next); + this.wrappedAdd(world, wc.x, wc.y, wc.z - 1, next); + } + } + } + + AELog.info("Delete " + blocks + " blocks"); + + return true; + } + + private void wrappedAdd( + final World world, final int i, final int y, final int z, final Collection next) { + next.add(new WorldCoord(i, y, z)); + } } diff --git a/src/main/java/appeng/debug/ToolMeteoritePlacer.java b/src/main/java/appeng/debug/ToolMeteoritePlacer.java index 1a210befdec..6faa605375a 100644 --- a/src/main/java/appeng/debug/ToolMeteoritePlacer.java +++ b/src/main/java/appeng/debug/ToolMeteoritePlacer.java @@ -18,13 +18,13 @@ package appeng.debug; - import appeng.client.texture.MissingIcon; import appeng.core.features.AEFeature; import appeng.items.AEBaseItem; import appeng.util.Platform; import appeng.worldgen.MeteoritePlacer; import appeng.worldgen.meteorite.StandardWorld; +import java.util.EnumSet; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -32,41 +32,41 @@ import net.minecraft.world.World; import net.minecraftforge.event.ForgeEventFactory; -import java.util.EnumSet; - - -public class ToolMeteoritePlacer extends AEBaseItem -{ - public ToolMeteoritePlacer() - { - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } +public class ToolMeteoritePlacer extends AEBaseItem { + public ToolMeteoritePlacer() { + this.setFeature(EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative)); + } - @Override - public void registerIcons( final IIconRegister par1IconRegister ) - { - this.itemIcon = new MissingIcon( this ); - } + @Override + public void registerIcons(final IIconRegister par1IconRegister) { + this.itemIcon = new MissingIcon(this); + } - @Override - public boolean onItemUseFirst( final ItemStack stack, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, stack, 1 ) <= 0 ) - return true; + @Override + public boolean onItemUseFirst( + final ItemStack stack, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (ForgeEventFactory.onItemUseStart(player, stack, 1) <= 0) return true; - if( Platform.isClient() ) - { - return false; - } + if (Platform.isClient()) { + return false; + } - final MeteoritePlacer mp = new MeteoritePlacer(); - final boolean worked = mp.spawnMeteorite( new StandardWorld( world ), x, y, z ); + final MeteoritePlacer mp = new MeteoritePlacer(); + final boolean worked = mp.spawnMeteorite(new StandardWorld(world), x, y, z); - if( !worked ) - { - player.addChatMessage( new ChatComponentText( "Un-suitable Location." ) ); - } + if (!worked) { + player.addChatMessage(new ChatComponentText("Un-suitable Location.")); + } - return true; - } + return true; + } } diff --git a/src/main/java/appeng/debug/ToolReplicatorCard.java b/src/main/java/appeng/debug/ToolReplicatorCard.java index 1565752259d..36119da720a 100644 --- a/src/main/java/appeng/debug/ToolReplicatorCard.java +++ b/src/main/java/appeng/debug/ToolReplicatorCard.java @@ -18,7 +18,6 @@ package appeng.debug; - import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; @@ -27,6 +26,7 @@ import appeng.core.features.AEFeature; import appeng.items.AEBaseItem; import appeng.util.Platform; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; @@ -39,144 +39,121 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.ForgeEventFactory; -import java.util.EnumSet; - - -public class ToolReplicatorCard extends AEBaseItem -{ - public ToolReplicatorCard() - { - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } - - @Override - public boolean onItemUseFirst( final ItemStack stack, final EntityPlayer player, final World world, int x, int y, int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, stack, 1 ) <= 0 ) - return true; - - if( Platform.isClient() ) - { - return false; - } - - if( player.isSneaking() ) - { - if( world.getTileEntity( x, y, z ) instanceof IGridHost ) - { - final NBTTagCompound tag = new NBTTagCompound(); - tag.setInteger( "x", x ); - tag.setInteger( "y", y ); - tag.setInteger( "z", z ); - tag.setInteger( "side", side ); - tag.setInteger( "dimid", world.provider.dimensionId ); - stack.setTagCompound( tag ); - } - else - { - this.outputMsg( player, "This is not a Grid Tile." ); - } - } - else - { - final NBTTagCompound ish = stack.getTagCompound(); - if( ish != null ) - { - final int src_x = ish.getInteger( "x" ); - final int src_y = ish.getInteger( "y" ); - final int src_z = ish.getInteger( "z" ); - final int src_side = ish.getInteger( "side" ); - final int dimid = ish.getInteger( "dimid" ); - final World src_w = DimensionManager.getWorld( dimid ); - - final TileEntity te = src_w.getTileEntity( src_x, src_y, src_z ); - if( te instanceof IGridHost ) - { - final IGridHost gh = (IGridHost) te; - final ForgeDirection sideOff = ForgeDirection.getOrientation( src_side ); - final ForgeDirection currentSideOff = ForgeDirection.getOrientation( side ); - final IGridNode n = gh.getGridNode( sideOff ); - if( n != null ) - { - final IGrid g = n.getGrid(); - if( g != null ) - { - final ISpatialCache sc = g.getCache( ISpatialCache.class ); - if( sc.isValidRegion() ) - { - final DimensionalCoord min = sc.getMin(); - final DimensionalCoord max = sc.getMax(); - - x += currentSideOff.offsetX; - y += currentSideOff.offsetY; - z += currentSideOff.offsetZ; - - final int min_x = min.x; - final int min_y = min.y; - final int min_z = min.z; - - final int rel_x = min.x - src_x + x; - final int rel_y = min.y - src_y + y; - final int rel_z = min.z - src_z + z; - - final int scale_x = max.x - min.x; - final int scale_y = max.y - min.y; - final int scale_z = max.z - min.z; - - for( int i = 1; i < scale_x; i++ ) - { - for( int j = 1; j < scale_y; j++ ) - { - for( int k = 1; k < scale_z; k++ ) - { - final Block blk = src_w.getBlock( min_x + i, min_y + j, min_z + k ); - final int meta = src_w.getBlockMetadata( min_x + i, min_y + j, min_z + k ); - world.setBlock( i + rel_x, j + rel_y, k + rel_z, blk, meta, 4 ); - - if( blk != null && blk.hasTileEntity( meta ) ) - { - final TileEntity ote = src_w.getTileEntity( min_x + i, min_y + j, min_z + k ); - final TileEntity nte = blk.createTileEntity( world, meta ); - final NBTTagCompound data = new NBTTagCompound(); - ote.writeToNBT( data ); - nte.readFromNBT( (NBTTagCompound) data.copy() ); - world.setTileEntity( i + rel_x, j + rel_y, k + rel_z, nte ); - } - world.markBlockForUpdate( i + rel_x, j + rel_y, k + rel_z ); - } - } - } - } - else - { - this.outputMsg( player, "requires valid spatial pylon setup." ); - } - } - else - { - this.outputMsg( player, "no grid?" ); - } - } - else - { - this.outputMsg( player, "No grid node?" ); - } - } - else - { - this.outputMsg( player, "Src is no longer a grid block?" ); - } - } - else - { - this.outputMsg( player, "No Source Defined" ); - } - } - return true; - } - - private void outputMsg( final ICommandSender player, final String string ) - { - player.addChatMessage( new ChatComponentText( string ) ); - } +public class ToolReplicatorCard extends AEBaseItem { + public ToolReplicatorCard() { + this.setFeature(EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative)); + } + + @Override + public boolean onItemUseFirst( + final ItemStack stack, + final EntityPlayer player, + final World world, + int x, + int y, + int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (ForgeEventFactory.onItemUseStart(player, stack, 1) <= 0) return true; + + if (Platform.isClient()) { + return false; + } + + if (player.isSneaking()) { + if (world.getTileEntity(x, y, z) instanceof IGridHost) { + final NBTTagCompound tag = new NBTTagCompound(); + tag.setInteger("x", x); + tag.setInteger("y", y); + tag.setInteger("z", z); + tag.setInteger("side", side); + tag.setInteger("dimid", world.provider.dimensionId); + stack.setTagCompound(tag); + } else { + this.outputMsg(player, "This is not a Grid Tile."); + } + } else { + final NBTTagCompound ish = stack.getTagCompound(); + if (ish != null) { + final int src_x = ish.getInteger("x"); + final int src_y = ish.getInteger("y"); + final int src_z = ish.getInteger("z"); + final int src_side = ish.getInteger("side"); + final int dimid = ish.getInteger("dimid"); + final World src_w = DimensionManager.getWorld(dimid); + + final TileEntity te = src_w.getTileEntity(src_x, src_y, src_z); + if (te instanceof IGridHost) { + final IGridHost gh = (IGridHost) te; + final ForgeDirection sideOff = ForgeDirection.getOrientation(src_side); + final ForgeDirection currentSideOff = ForgeDirection.getOrientation(side); + final IGridNode n = gh.getGridNode(sideOff); + if (n != null) { + final IGrid g = n.getGrid(); + if (g != null) { + final ISpatialCache sc = g.getCache(ISpatialCache.class); + if (sc.isValidRegion()) { + final DimensionalCoord min = sc.getMin(); + final DimensionalCoord max = sc.getMax(); + + x += currentSideOff.offsetX; + y += currentSideOff.offsetY; + z += currentSideOff.offsetZ; + + final int min_x = min.x; + final int min_y = min.y; + final int min_z = min.z; + + final int rel_x = min.x - src_x + x; + final int rel_y = min.y - src_y + y; + final int rel_z = min.z - src_z + z; + + final int scale_x = max.x - min.x; + final int scale_y = max.y - min.y; + final int scale_z = max.z - min.z; + + for (int i = 1; i < scale_x; i++) { + for (int j = 1; j < scale_y; j++) { + for (int k = 1; k < scale_z; k++) { + final Block blk = src_w.getBlock(min_x + i, min_y + j, min_z + k); + final int meta = src_w.getBlockMetadata(min_x + i, min_y + j, min_z + k); + world.setBlock(i + rel_x, j + rel_y, k + rel_z, blk, meta, 4); + + if (blk != null && blk.hasTileEntity(meta)) { + final TileEntity ote = + src_w.getTileEntity(min_x + i, min_y + j, min_z + k); + final TileEntity nte = blk.createTileEntity(world, meta); + final NBTTagCompound data = new NBTTagCompound(); + ote.writeToNBT(data); + nte.readFromNBT((NBTTagCompound) data.copy()); + world.setTileEntity(i + rel_x, j + rel_y, k + rel_z, nte); + } + world.markBlockForUpdate(i + rel_x, j + rel_y, k + rel_z); + } + } + } + } else { + this.outputMsg(player, "requires valid spatial pylon setup."); + } + } else { + this.outputMsg(player, "no grid?"); + } + } else { + this.outputMsg(player, "No grid node?"); + } + } else { + this.outputMsg(player, "Src is no longer a grid block?"); + } + } else { + this.outputMsg(player, "No Source Defined"); + } + } + return true; + } + + private void outputMsg(final ICommandSender player, final String string) { + player.addChatMessage(new ChatComponentText(string)); + } } diff --git a/src/main/java/appeng/entity/AEBaseEntityItem.java b/src/main/java/appeng/entity/AEBaseEntityItem.java index 375916b7973..227d558887f 100644 --- a/src/main/java/appeng/entity/AEBaseEntityItem.java +++ b/src/main/java/appeng/entity/AEBaseEntityItem.java @@ -18,31 +18,24 @@ package appeng.entity; - +import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; -import java.util.List; - - -public abstract class AEBaseEntityItem extends EntityItem -{ - public AEBaseEntityItem( final World world ) - { - super( world ); - } +public abstract class AEBaseEntityItem extends EntityItem { + public AEBaseEntityItem(final World world) { + super(world); + } - public AEBaseEntityItem( final World world, final double x, final double y, final double z, final ItemStack stack ) - { - super( world, x, y, z, stack ); - } + public AEBaseEntityItem(final World world, final double x, final double y, final double z, final ItemStack stack) { + super(world, x, y, z, stack); + } - @SuppressWarnings( "unchecked" ) - protected List getCheckedEntitiesWithinAABBExcludingEntity( final AxisAlignedBB region ) - { - return this.worldObj.getEntitiesWithinAABBExcludingEntity( this, region ); - } + @SuppressWarnings("unchecked") + protected List getCheckedEntitiesWithinAABBExcludingEntity(final AxisAlignedBB region) { + return this.worldObj.getEntitiesWithinAABBExcludingEntity(this, region); + } } diff --git a/src/main/java/appeng/entity/EntityChargedQuartz.java b/src/main/java/appeng/entity/EntityChargedQuartz.java index 58afcc4495d..c543fbc6375 100644 --- a/src/main/java/appeng/entity/EntityChargedQuartz.java +++ b/src/main/java/appeng/entity/EntityChargedQuartz.java @@ -18,7 +18,6 @@ package appeng.entity; - import appeng.api.AEApi; import appeng.api.definitions.IMaterials; import appeng.client.EffectType; @@ -27,6 +26,7 @@ import appeng.core.features.AEFeature; import appeng.helpers.Reflected; import appeng.util.Platform; +import java.util.List; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; @@ -36,130 +36,107 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.World; -import java.util.List; - - -public final class EntityChargedQuartz extends AEBaseEntityItem -{ - - private int delay = 0; - private int transformTime = 0; - - @Reflected - public EntityChargedQuartz( final World w ) - { - super( w ); - } - - public EntityChargedQuartz( final World w, final double x, final double y, final double z, final ItemStack is ) - { - super( w, x, y, z, is ); - } - - @Override - public void onUpdate() - { - super.onUpdate(); - - if( !AEConfig.instance.isFeatureEnabled( AEFeature.InWorldFluix ) ) - { - return; - } - - if( Platform.isClient() && this.delay > 30 && AEConfig.instance.enableEffects ) - { - CommonHelper.proxy.spawnEffect( EffectType.Lightning, this.worldObj, this.posX, this.posY, this.posZ, null ); - this.delay = 0; - } - this.delay++; - - final int j = MathHelper.floor_double( this.posX ); - final int i = MathHelper.floor_double( this.posY ); - final int k = MathHelper.floor_double( this.posZ ); - - final Material mat = this.worldObj.getBlock( j, i, k ).getMaterial(); - if( Platform.isServer() && mat.isLiquid() ) - { - this.transformTime++; - if( this.transformTime > 60 ) - { - if( !this.transform() ) - { - this.transformTime = 0; - } - } - } - else - { - this.transformTime = 0; - } - } - - private boolean transform() - { - final ItemStack item = this.getEntityItem(); - final IMaterials materials = AEApi.instance().definitions().materials(); - - if( materials.certusQuartzCrystalCharged().isSameAs( item ) ) - { - final AxisAlignedBB region = AxisAlignedBB.getBoundingBox( this.posX - 1, this.posY - 1, this.posZ - 1, this.posX + 1, this.posY + 1, this.posZ + 1 ); - final List l = this.getCheckedEntitiesWithinAABBExcludingEntity( region ); - - EntityItem redstone = null; - EntityItem netherQuartz = null; - - for( final Entity e : l ) - { - if( e instanceof EntityItem && !e.isDead ) - { - final ItemStack other = ( (EntityItem) e ).getEntityItem(); - if( other != null && other.stackSize > 0 ) - { - if( Platform.isSameItem( other, new ItemStack( Items.redstone ) ) ) - { - redstone = (EntityItem) e; - } - - if( Platform.isSameItem( other, new ItemStack( Items.quartz ) ) ) - { - netherQuartz = (EntityItem) e; - } - } - } - } - - if( redstone != null && netherQuartz != null ) - { - this.getEntityItem().stackSize--; - redstone.getEntityItem().stackSize--; - netherQuartz.getEntityItem().stackSize--; - - if( this.getEntityItem().stackSize <= 0 ) - { - this.setDead(); - } - - if( redstone.getEntityItem().stackSize <= 0 ) - { - redstone.setDead(); - } - - if( netherQuartz.getEntityItem().stackSize <= 0 ) - { - netherQuartz.setDead(); - } - - for( final ItemStack fluixCrystalStack : materials.fluixCrystal().maybeStack( 2 ).asSet() ) - { - final EntityItem entity = new EntityItem( this.worldObj, this.posX, this.posY, this.posZ, fluixCrystalStack ); - - this.worldObj.spawnEntityInWorld( entity ); - } - - return true; - } - } - - return false; - } +public final class EntityChargedQuartz extends AEBaseEntityItem { + + private int delay = 0; + private int transformTime = 0; + + @Reflected + public EntityChargedQuartz(final World w) { + super(w); + } + + public EntityChargedQuartz(final World w, final double x, final double y, final double z, final ItemStack is) { + super(w, x, y, z, is); + } + + @Override + public void onUpdate() { + super.onUpdate(); + + if (!AEConfig.instance.isFeatureEnabled(AEFeature.InWorldFluix)) { + return; + } + + if (Platform.isClient() && this.delay > 30 && AEConfig.instance.enableEffects) { + CommonHelper.proxy.spawnEffect(EffectType.Lightning, this.worldObj, this.posX, this.posY, this.posZ, null); + this.delay = 0; + } + this.delay++; + + final int j = MathHelper.floor_double(this.posX); + final int i = MathHelper.floor_double(this.posY); + final int k = MathHelper.floor_double(this.posZ); + + final Material mat = this.worldObj.getBlock(j, i, k).getMaterial(); + if (Platform.isServer() && mat.isLiquid()) { + this.transformTime++; + if (this.transformTime > 60) { + if (!this.transform()) { + this.transformTime = 0; + } + } + } else { + this.transformTime = 0; + } + } + + private boolean transform() { + final ItemStack item = this.getEntityItem(); + final IMaterials materials = AEApi.instance().definitions().materials(); + + if (materials.certusQuartzCrystalCharged().isSameAs(item)) { + final AxisAlignedBB region = AxisAlignedBB.getBoundingBox( + this.posX - 1, this.posY - 1, this.posZ - 1, this.posX + 1, this.posY + 1, this.posZ + 1); + final List l = this.getCheckedEntitiesWithinAABBExcludingEntity(region); + + EntityItem redstone = null; + EntityItem netherQuartz = null; + + for (final Entity e : l) { + if (e instanceof EntityItem && !e.isDead) { + final ItemStack other = ((EntityItem) e).getEntityItem(); + if (other != null && other.stackSize > 0) { + if (Platform.isSameItem(other, new ItemStack(Items.redstone))) { + redstone = (EntityItem) e; + } + + if (Platform.isSameItem(other, new ItemStack(Items.quartz))) { + netherQuartz = (EntityItem) e; + } + } + } + } + + if (redstone != null && netherQuartz != null) { + this.getEntityItem().stackSize--; + redstone.getEntityItem().stackSize--; + netherQuartz.getEntityItem().stackSize--; + + if (this.getEntityItem().stackSize <= 0) { + this.setDead(); + } + + if (redstone.getEntityItem().stackSize <= 0) { + redstone.setDead(); + } + + if (netherQuartz.getEntityItem().stackSize <= 0) { + netherQuartz.setDead(); + } + + for (final ItemStack fluixCrystalStack : + materials.fluixCrystal().maybeStack(2).asSet()) { + final EntityItem entity = + new EntityItem(this.worldObj, this.posX, this.posY, this.posZ, fluixCrystalStack); + + this.worldObj.spawnEntityInWorld(entity); + } + + return true; + } + } + + return false; + } } diff --git a/src/main/java/appeng/entity/EntityFloatingItem.java b/src/main/java/appeng/entity/EntityFloatingItem.java index 57e930addbb..adc13243087 100644 --- a/src/main/java/appeng/entity/EntityFloatingItem.java +++ b/src/main/java/appeng/entity/EntityFloatingItem.java @@ -18,60 +18,56 @@ package appeng.entity; - import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import net.minecraft.world.World; +public final class EntityFloatingItem extends EntityItem { -public final class EntityFloatingItem extends EntityItem -{ - - public static int ageStatic = 0; - private final Entity parent; - private int superDeath = 0; - private float progress = 0; + public static int ageStatic = 0; + private final Entity parent; + private int superDeath = 0; + private float progress = 0; - public EntityFloatingItem( final Entity parent, final World world, final double x, final double y, final double z, final ItemStack stack ) - { - super( world, x, y, z, stack ); - this.motionX = this.motionY = this.motionZ = 0.0d; - this.hoverStart = 0.5f; - this.rotationYaw = 0; - this.parent = parent; - } + public EntityFloatingItem( + final Entity parent, + final World world, + final double x, + final double y, + final double z, + final ItemStack stack) { + super(world, x, y, z, stack); + this.motionX = this.motionY = this.motionZ = 0.0d; + this.hoverStart = 0.5f; + this.rotationYaw = 0; + this.parent = parent; + } - // public boolean isEntityAlive() + // public boolean isEntityAlive() - @Override - public void onUpdate() - { - if( !this.isDead && this.parent.isDead ) - { - this.setDead(); - } + @Override + public void onUpdate() { + if (!this.isDead && this.parent.isDead) { + this.setDead(); + } - if( this.superDeath > 100 ) - { - this.setDead(); - } - this.superDeath++; + if (this.superDeath > 100) { + this.setDead(); + } + this.superDeath++; - this.age = ageStatic; - } + this.age = ageStatic; + } - public void setProgress( final float progress ) - { - this.progress = progress; - if( this.progress > 0.99 ) - { - this.setDead(); - } - } + public void setProgress(final float progress) { + this.progress = progress; + if (this.progress > 0.99) { + this.setDead(); + } + } - float getProgress() - { - return this.progress; - } + float getProgress() { + return this.progress; + } } diff --git a/src/main/java/appeng/entity/EntityGrowingCrystal.java b/src/main/java/appeng/entity/EntityGrowingCrystal.java index 6fe79e91507..39b387febbe 100644 --- a/src/main/java/appeng/entity/EntityGrowingCrystal.java +++ b/src/main/java/appeng/entity/EntityGrowingCrystal.java @@ -18,7 +18,6 @@ package appeng.entity; - import appeng.api.implementations.items.IGrowableCrystal; import appeng.api.implementations.tiles.ICrystalGrowthAccelerator; import appeng.client.EffectType; @@ -35,166 +34,135 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.World; - -public final class EntityGrowingCrystal extends EntityItem -{ - - private int progress_1000 = 0; - - public EntityGrowingCrystal( final World w ) - { - super( w ); - } - - public EntityGrowingCrystal( final World w, final double x, final double y, final double z, final ItemStack is ) - { - super( w, x, y, z, is ); - } - - @Override - public void onUpdate() - { - super.onUpdate(); - - if( !AEConfig.instance.isFeatureEnabled( AEFeature.InWorldPurification ) ) - { - return; - } - - if( this.age > 600 ) - { - this.age = 100; - } - - final ItemStack is = this.getEntityItem(); - final Item gc = is.getItem(); - - if( gc instanceof IGrowableCrystal ) // if it changes this just stops being an issue... - { - final int j = MathHelper.floor_double( this.posX ); - final int i = MathHelper.floor_double( this.posY ); - final int k = MathHelper.floor_double( this.posZ ); - - final Block blk = this.worldObj.getBlock( j, i, k ); - final Material mat = blk.getMaterial(); - final IGrowableCrystal cry = (IGrowableCrystal) is.getItem(); - - final float multiplier = cry.getMultiplier( blk, mat ); - final int speed = (int) Math.max( 1, this.getSpeed( j, i, k ) * multiplier ); - - final boolean isClient = Platform.isClient(); - - if( mat.isLiquid() ) - { - if( isClient ) - { - this.progress_1000++; - } - else - { - this.progress_1000 += speed; - } - } - else - { - this.progress_1000 = 0; - } - - if( isClient ) - { - int len = 40; - - if( speed > 2 ) - { - len = 20; - } - - if( speed > 90 ) - { - len = 15; - } - - if( speed > 150 ) - { - len = 10; - } - - if( speed > 240 ) - { - len = 7; - } - - if( speed > 360 ) - { - len = 3; - } - - if( speed > 500 ) - { - len = 1; - } - - if( this.progress_1000 >= len ) - { - this.progress_1000 = 0; - CommonHelper.proxy.spawnEffect( EffectType.Vibrant, this.worldObj, this.posX, this.posY + 0.2, this.posZ, null ); - } - } - else - { - if( this.progress_1000 > 1000 ) - { - this.progress_1000 -= 1000; - this.setEntityItemStack( cry.triggerGrowth( is ) ); - } - } - } - } - - private int getSpeed( final int x, final int y, final int z ) - { - final int per = 80; - final float mul = 0.3f; - - int qty = 0; - - if( this.isAccelerated( x + 1, y, z ) ) - { - qty += per + qty * mul; - } - - if( this.isAccelerated( x, y + 1, z ) ) - { - qty += per + qty * mul; - } - - if( this.isAccelerated( x, y, z + 1 ) ) - { - qty += per + qty * mul; - } - - if( this.isAccelerated( x - 1, y, z ) ) - { - qty += per + qty * mul; - } - - if( this.isAccelerated( x, y - 1, z ) ) - { - qty += per + qty * mul; - } - - if( this.isAccelerated( x, y, z - 1 ) ) - { - qty += per + qty * mul; - } - - return qty; - } - - private boolean isAccelerated( final int x, final int y, final int z ) - { - final TileEntity te = this.worldObj.getTileEntity( x, y, z ); - - return te instanceof ICrystalGrowthAccelerator && ( (ICrystalGrowthAccelerator) te ).isPowered(); - } +public final class EntityGrowingCrystal extends EntityItem { + + private int progress_1000 = 0; + + public EntityGrowingCrystal(final World w) { + super(w); + } + + public EntityGrowingCrystal(final World w, final double x, final double y, final double z, final ItemStack is) { + super(w, x, y, z, is); + } + + @Override + public void onUpdate() { + super.onUpdate(); + + if (!AEConfig.instance.isFeatureEnabled(AEFeature.InWorldPurification)) { + return; + } + + if (this.age > 600) { + this.age = 100; + } + + final ItemStack is = this.getEntityItem(); + final Item gc = is.getItem(); + + if (gc instanceof IGrowableCrystal) // if it changes this just stops being an issue... + { + final int j = MathHelper.floor_double(this.posX); + final int i = MathHelper.floor_double(this.posY); + final int k = MathHelper.floor_double(this.posZ); + + final Block blk = this.worldObj.getBlock(j, i, k); + final Material mat = blk.getMaterial(); + final IGrowableCrystal cry = (IGrowableCrystal) is.getItem(); + + final float multiplier = cry.getMultiplier(blk, mat); + final int speed = (int) Math.max(1, this.getSpeed(j, i, k) * multiplier); + + final boolean isClient = Platform.isClient(); + + if (mat.isLiquid()) { + if (isClient) { + this.progress_1000++; + } else { + this.progress_1000 += speed; + } + } else { + this.progress_1000 = 0; + } + + if (isClient) { + int len = 40; + + if (speed > 2) { + len = 20; + } + + if (speed > 90) { + len = 15; + } + + if (speed > 150) { + len = 10; + } + + if (speed > 240) { + len = 7; + } + + if (speed > 360) { + len = 3; + } + + if (speed > 500) { + len = 1; + } + + if (this.progress_1000 >= len) { + this.progress_1000 = 0; + CommonHelper.proxy.spawnEffect( + EffectType.Vibrant, this.worldObj, this.posX, this.posY + 0.2, this.posZ, null); + } + } else { + if (this.progress_1000 > 1000) { + this.progress_1000 -= 1000; + this.setEntityItemStack(cry.triggerGrowth(is)); + } + } + } + } + + private int getSpeed(final int x, final int y, final int z) { + final int per = 80; + final float mul = 0.3f; + + int qty = 0; + + if (this.isAccelerated(x + 1, y, z)) { + qty += per + qty * mul; + } + + if (this.isAccelerated(x, y + 1, z)) { + qty += per + qty * mul; + } + + if (this.isAccelerated(x, y, z + 1)) { + qty += per + qty * mul; + } + + if (this.isAccelerated(x - 1, y, z)) { + qty += per + qty * mul; + } + + if (this.isAccelerated(x, y - 1, z)) { + qty += per + qty * mul; + } + + if (this.isAccelerated(x, y, z - 1)) { + qty += per + qty * mul; + } + + return qty; + } + + private boolean isAccelerated(final int x, final int y, final int z) { + final TileEntity te = this.worldObj.getTileEntity(x, y, z); + + return te instanceof ICrystalGrowthAccelerator && ((ICrystalGrowthAccelerator) te).isPowered(); + } } diff --git a/src/main/java/appeng/entity/EntityIds.java b/src/main/java/appeng/entity/EntityIds.java index a79ac012e1a..d232a6066ca 100644 --- a/src/main/java/appeng/entity/EntityIds.java +++ b/src/main/java/appeng/entity/EntityIds.java @@ -18,40 +18,30 @@ package appeng.entity; - import net.minecraft.entity.Entity; - -public final class EntityIds -{ - private static final int TINY_TNT = 10; - private static final int SINGULARITY = 11; - private static final int CHARGED_QUARTZ = 12; - private static final int GROWING_CRYSTAL = 13; - - private EntityIds() - { - } - - public static int get( final Class droppedEntity ) - { - if( droppedEntity == EntityTinyTNTPrimed.class ) - { - return TINY_TNT; - } - if( droppedEntity == EntitySingularity.class ) - { - return SINGULARITY; - } - if( droppedEntity == EntityChargedQuartz.class ) - { - return CHARGED_QUARTZ; - } - if( droppedEntity == EntityGrowingCrystal.class ) - { - return GROWING_CRYSTAL; - } - - throw new IllegalStateException( "Missing entity id: " + droppedEntity.getName() ); - } +public final class EntityIds { + private static final int TINY_TNT = 10; + private static final int SINGULARITY = 11; + private static final int CHARGED_QUARTZ = 12; + private static final int GROWING_CRYSTAL = 13; + + private EntityIds() {} + + public static int get(final Class droppedEntity) { + if (droppedEntity == EntityTinyTNTPrimed.class) { + return TINY_TNT; + } + if (droppedEntity == EntitySingularity.class) { + return SINGULARITY; + } + if (droppedEntity == EntityChargedQuartz.class) { + return CHARGED_QUARTZ; + } + if (droppedEntity == EntityGrowingCrystal.class) { + return GROWING_CRYSTAL; + } + + throw new IllegalStateException("Missing entity id: " + droppedEntity.getName()); + } } diff --git a/src/main/java/appeng/entity/EntitySingularity.java b/src/main/java/appeng/entity/EntitySingularity.java index a91de0b893d..82f03f18230 100644 --- a/src/main/java/appeng/entity/EntitySingularity.java +++ b/src/main/java/appeng/entity/EntitySingularity.java @@ -18,13 +18,14 @@ package appeng.entity; - import appeng.api.AEApi; import appeng.api.definitions.IMaterials; import appeng.core.AEConfig; import appeng.core.features.AEFeature; import appeng.helpers.Reflected; import appeng.util.Platform; +import java.util.Date; +import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; @@ -34,119 +35,96 @@ import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; -import java.util.Date; -import java.util.List; - - -public final class EntitySingularity extends AEBaseEntityItem -{ - - private static int randTickSeed = 0; - - @Reflected - public EntitySingularity( final World w ) - { - super( w ); - } - - public EntitySingularity( final World w, final double x, final double y, final double z, final ItemStack is ) - { - super( w, x, y, z, is ); - } - - @Override - public boolean attackEntityFrom( final DamageSource src, final float dmg ) - { - if( src.isExplosion() ) - { - this.doExplosion(); - return false; - } - - return super.attackEntityFrom( src, dmg ); - } - - private void doExplosion() - { - if( Platform.isClient() ) - { - return; - } - - if( !AEConfig.instance.isFeatureEnabled( AEFeature.InWorldSingularity ) ) - { - return; - } - - final ItemStack item = this.getEntityItem(); - - final IMaterials materials = AEApi.instance().definitions().materials(); - - if( materials.singularity().isSameAs( item ) ) - { - final AxisAlignedBB region = AxisAlignedBB.getBoundingBox( this.posX - 4, this.posY - 4, this.posZ - 4, this.posX + 4, this.posY + 4, this.posZ + 4 ); - final List l = this.getCheckedEntitiesWithinAABBExcludingEntity( region ); - - for( final Entity e : l ) - { - if( e instanceof EntityItem ) - { - final ItemStack other = ( (EntityItem) e ).getEntityItem(); - if( other != null ) - { - boolean matches = false; - for( final ItemStack is : OreDictionary.getOres( "dustEnder" ) ) - { - if( OreDictionary.itemMatches( other, is, false ) ) - { - matches = true; - break; - } - } - - // check... other name. - if( !matches ) - { - for( final ItemStack is : OreDictionary.getOres( "dustEnderPearl" ) ) - { - if( OreDictionary.itemMatches( other, is, false ) ) - { - matches = true; - break; - } - } - } - - if( matches ) - { - while( item.stackSize > 0 && other.stackSize > 0 ) - { - other.stackSize--; - if( other.stackSize == 0 ) - { - e.setDead(); - } - - for( final ItemStack singularityStack : materials.qESingularity().maybeStack( 2 ).asSet() ) - { - final NBTTagCompound cmp = Platform.openNbtData( singularityStack ); - cmp.setLong( "freq", ( new Date() ).getTime() * 100 + ( randTickSeed ) % 100 ); - randTickSeed++; - item.stackSize--; - - final EntitySingularity entity = new EntitySingularity( this.worldObj, this.posX, this.posY, this.posZ, singularityStack ); - this.worldObj.spawnEntityInWorld( entity ); - } - } - - if( item.stackSize <= 0 ) - { - this.setDead(); - } - } - } - } - } - } - } +public final class EntitySingularity extends AEBaseEntityItem { + + private static int randTickSeed = 0; + + @Reflected + public EntitySingularity(final World w) { + super(w); + } + + public EntitySingularity(final World w, final double x, final double y, final double z, final ItemStack is) { + super(w, x, y, z, is); + } + + @Override + public boolean attackEntityFrom(final DamageSource src, final float dmg) { + if (src.isExplosion()) { + this.doExplosion(); + return false; + } + + return super.attackEntityFrom(src, dmg); + } + + private void doExplosion() { + if (Platform.isClient()) { + return; + } + + if (!AEConfig.instance.isFeatureEnabled(AEFeature.InWorldSingularity)) { + return; + } + + final ItemStack item = this.getEntityItem(); + + final IMaterials materials = AEApi.instance().definitions().materials(); + + if (materials.singularity().isSameAs(item)) { + final AxisAlignedBB region = AxisAlignedBB.getBoundingBox( + this.posX - 4, this.posY - 4, this.posZ - 4, this.posX + 4, this.posY + 4, this.posZ + 4); + final List l = this.getCheckedEntitiesWithinAABBExcludingEntity(region); + + for (final Entity e : l) { + if (e instanceof EntityItem) { + final ItemStack other = ((EntityItem) e).getEntityItem(); + if (other != null) { + boolean matches = false; + for (final ItemStack is : OreDictionary.getOres("dustEnder")) { + if (OreDictionary.itemMatches(other, is, false)) { + matches = true; + break; + } + } + + // check... other name. + if (!matches) { + for (final ItemStack is : OreDictionary.getOres("dustEnderPearl")) { + if (OreDictionary.itemMatches(other, is, false)) { + matches = true; + break; + } + } + } + + if (matches) { + while (item.stackSize > 0 && other.stackSize > 0) { + other.stackSize--; + if (other.stackSize == 0) { + e.setDead(); + } + + for (final ItemStack singularityStack : + materials.qESingularity().maybeStack(2).asSet()) { + final NBTTagCompound cmp = Platform.openNbtData(singularityStack); + cmp.setLong("freq", (new Date()).getTime() * 100 + (randTickSeed) % 100); + randTickSeed++; + item.stackSize--; + + final EntitySingularity entity = new EntitySingularity( + this.worldObj, this.posX, this.posY, this.posZ, singularityStack); + this.worldObj.spawnEntityInWorld(entity); + } + } + + if (item.stackSize <= 0) { + this.setDead(); + } + } + } + } + } + } + } } diff --git a/src/main/java/appeng/entity/EntityTinyTNTPrimed.java b/src/main/java/appeng/entity/EntityTinyTNTPrimed.java index 2c6fc5eefa1..a6e2f1c0e1c 100644 --- a/src/main/java/appeng/entity/EntityTinyTNTPrimed.java +++ b/src/main/java/appeng/entity/EntityTinyTNTPrimed.java @@ -18,7 +18,6 @@ package appeng.entity; - import appeng.api.AEApi; import appeng.core.AEConfig; import appeng.core.CommonHelper; @@ -40,148 +39,161 @@ import net.minecraft.world.Explosion; import net.minecraft.world.World; - -public final class EntityTinyTNTPrimed extends EntityTNTPrimed implements IEntityAdditionalSpawnData -{ - @Reflected - public EntityTinyTNTPrimed( final World w ) - { - super( w ); - this.setSize( 0.35F, 0.35F ); - } - - public EntityTinyTNTPrimed( final World w, final double x, final double y, final double z, final EntityLivingBase igniter ) - { - super( w, x, y, z, igniter ); - this.setSize( 0.55F, 0.55F ); - this.yOffset = this.height / 2.0F; - } - - /** - * Called to update the entity's position/logic. - */ - @Override - public void onUpdate() - { - this.handleWaterMovement(); - - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - this.motionY -= 0.03999999910593033D; - this.moveEntity( this.motionX, this.motionY, this.motionZ ); - this.motionX *= 0.9800000190734863D; - this.motionY *= 0.9800000190734863D; - this.motionZ *= 0.9800000190734863D; - - if( this.onGround ) - { - this.motionX *= 0.699999988079071D; - this.motionZ *= 0.699999988079071D; - this.motionY *= -0.5D; - } - - if( this.isInWater() && Platform.isServer() ) // put out the fuse. - { - for( final ItemStack tntStack : AEApi.instance().definitions().blocks().tinyTNT().maybeStack( 1 ).asSet() ) - { - final EntityItem item = new EntityItem( this.worldObj, this.posX, this.posY, this.posZ, tntStack ); - - item.motionX = this.motionX; - item.motionY = this.motionY; - item.motionZ = this.motionZ; - item.prevPosX = this.prevPosX; - item.prevPosY = this.prevPosY; - item.prevPosZ = this.prevPosZ; - - this.worldObj.spawnEntityInWorld( item ); - this.setDead(); - } - } - - if( this.fuse <= 0 ) - { - this.setDead(); - - if( !this.worldObj.isRemote ) - { - this.explode(); - } - } - else - { - this.worldObj.spawnParticle( "smoke", this.posX, this.posY, this.posZ, 0.0D, 0.0D, 0.0D ); - } - this.fuse--; - } - - // override :P - void explode() - { - this.worldObj.playSoundEffect( this.posX, this.posY, this.posZ, "random.explode", 4.0F, ( 1.0F + ( this.worldObj.rand.nextFloat() - this.worldObj.rand.nextFloat() ) * 0.2F ) * 32.9F ); - - if( this.isInWater() ) - { - return; - } - - for( final Object e : this.worldObj.getEntitiesWithinAABBExcludingEntity( this, AxisAlignedBB.getBoundingBox( this.posX - 1.5, this.posY - 1.5f, this.posZ - 1.5, this.posX + 1.5, this.posY + 1.5, this.posZ + 1.5 ) ) ) - { - if( e instanceof Entity ) - { - ( (Entity) e ).attackEntityFrom( DamageSource.setExplosionSource( null ), 6 ); - } - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.TinyTNTBlockDamage ) ) - { - this.posY -= 0.25; - final Explosion ex = new Explosion( this.worldObj, this, this.posX, this.posY, this.posZ, 0.2f ); - - for( int x = (int) ( this.posX - 2 ); x <= this.posX + 2; x++ ) - { - for( int y = (int) ( this.posY - 2 ); y <= this.posY + 2; y++ ) - { - for( int z = (int) ( this.posZ - 2 ); z <= this.posZ + 2; z++ ) - { - final Block block = this.worldObj.getBlock( x, y, z ); - if( block != null && !block.isAir( this.worldObj, x, y, z ) ) - { - float strength = (float) ( 2.3f - ( ( ( x + 0.5f ) - this.posX ) * ( ( x + 0.5f ) - this.posX ) + ( ( y + 0.5f ) - this.posY ) * ( ( y + 0.5f ) - this.posY ) + ( ( z + 0.5f ) - this.posZ ) * ( ( z + 0.5f ) - this.posZ ) ) ); - - final float resistance = block.getExplosionResistance( this, this.worldObj, x, y, z, this.posX, this.posY, this.posZ ); - strength -= ( resistance + 0.3F ) * 0.11f; - - if( strength > 0.01 ) - { - if( block.getMaterial() != Material.air ) - { - if( block.canDropFromExplosion( ex ) ) - { - block.dropBlockAsItemWithChance( this.worldObj, x, y, z, this.worldObj.getBlockMetadata( x, y, z ), 1.0F / 1.0f, 0 ); - } - - block.onBlockExploded( this.worldObj, x, y, z, ex ); - } - } - } - } - } - } - } - - CommonHelper.proxy.sendToAllNearExcept( null, this.posX, this.posY, this.posZ, 64, this.worldObj, new PacketMockExplosion( this.posX, this.posY, this.posZ ) ); - } - - @Override - public void writeSpawnData( final ByteBuf data ) - { - data.writeByte( this.fuse ); - } - - @Override - public void readSpawnData( final ByteBuf data ) - { - this.fuse = data.readByte(); - } +public final class EntityTinyTNTPrimed extends EntityTNTPrimed implements IEntityAdditionalSpawnData { + @Reflected + public EntityTinyTNTPrimed(final World w) { + super(w); + this.setSize(0.35F, 0.35F); + } + + public EntityTinyTNTPrimed( + final World w, final double x, final double y, final double z, final EntityLivingBase igniter) { + super(w, x, y, z, igniter); + this.setSize(0.55F, 0.55F); + this.yOffset = this.height / 2.0F; + } + + /** + * Called to update the entity's position/logic. + */ + @Override + public void onUpdate() { + this.handleWaterMovement(); + + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + this.motionY -= 0.03999999910593033D; + this.moveEntity(this.motionX, this.motionY, this.motionZ); + this.motionX *= 0.9800000190734863D; + this.motionY *= 0.9800000190734863D; + this.motionZ *= 0.9800000190734863D; + + if (this.onGround) { + this.motionX *= 0.699999988079071D; + this.motionZ *= 0.699999988079071D; + this.motionY *= -0.5D; + } + + if (this.isInWater() && Platform.isServer()) // put out the fuse. + { + for (final ItemStack tntStack : AEApi.instance() + .definitions() + .blocks() + .tinyTNT() + .maybeStack(1) + .asSet()) { + final EntityItem item = new EntityItem(this.worldObj, this.posX, this.posY, this.posZ, tntStack); + + item.motionX = this.motionX; + item.motionY = this.motionY; + item.motionZ = this.motionZ; + item.prevPosX = this.prevPosX; + item.prevPosY = this.prevPosY; + item.prevPosZ = this.prevPosZ; + + this.worldObj.spawnEntityInWorld(item); + this.setDead(); + } + } + + if (this.fuse <= 0) { + this.setDead(); + + if (!this.worldObj.isRemote) { + this.explode(); + } + } else { + this.worldObj.spawnParticle("smoke", this.posX, this.posY, this.posZ, 0.0D, 0.0D, 0.0D); + } + this.fuse--; + } + + // override :P + void explode() { + this.worldObj.playSoundEffect( + this.posX, + this.posY, + this.posZ, + "random.explode", + 4.0F, + (1.0F + (this.worldObj.rand.nextFloat() - this.worldObj.rand.nextFloat()) * 0.2F) * 32.9F); + + if (this.isInWater()) { + return; + } + + for (final Object e : this.worldObj.getEntitiesWithinAABBExcludingEntity( + this, + AxisAlignedBB.getBoundingBox( + this.posX - 1.5, + this.posY - 1.5f, + this.posZ - 1.5, + this.posX + 1.5, + this.posY + 1.5, + this.posZ + 1.5))) { + if (e instanceof Entity) { + ((Entity) e).attackEntityFrom(DamageSource.setExplosionSource(null), 6); + } + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.TinyTNTBlockDamage)) { + this.posY -= 0.25; + final Explosion ex = new Explosion(this.worldObj, this, this.posX, this.posY, this.posZ, 0.2f); + + for (int x = (int) (this.posX - 2); x <= this.posX + 2; x++) { + for (int y = (int) (this.posY - 2); y <= this.posY + 2; y++) { + for (int z = (int) (this.posZ - 2); z <= this.posZ + 2; z++) { + final Block block = this.worldObj.getBlock(x, y, z); + if (block != null && !block.isAir(this.worldObj, x, y, z)) { + float strength = (float) (2.3f + - (((x + 0.5f) - this.posX) * ((x + 0.5f) - this.posX) + + ((y + 0.5f) - this.posY) * ((y + 0.5f) - this.posY) + + ((z + 0.5f) - this.posZ) * ((z + 0.5f) - this.posZ))); + + final float resistance = block.getExplosionResistance( + this, this.worldObj, x, y, z, this.posX, this.posY, this.posZ); + strength -= (resistance + 0.3F) * 0.11f; + + if (strength > 0.01) { + if (block.getMaterial() != Material.air) { + if (block.canDropFromExplosion(ex)) { + block.dropBlockAsItemWithChance( + this.worldObj, + x, + y, + z, + this.worldObj.getBlockMetadata(x, y, z), + 1.0F / 1.0f, + 0); + } + + block.onBlockExploded(this.worldObj, x, y, z, ex); + } + } + } + } + } + } + } + + CommonHelper.proxy.sendToAllNearExcept( + null, + this.posX, + this.posY, + this.posZ, + 64, + this.worldObj, + new PacketMockExplosion(this.posX, this.posY, this.posZ)); + } + + @Override + public void writeSpawnData(final ByteBuf data) { + data.writeByte(this.fuse); + } + + @Override + public void readSpawnData(final ByteBuf data) { + this.fuse = data.readByte(); + } } diff --git a/src/main/java/appeng/entity/RenderFloatingItem.java b/src/main/java/appeng/entity/RenderFloatingItem.java index 93e7c960fba..9bcf5760093 100644 --- a/src/main/java/appeng/entity/RenderFloatingItem.java +++ b/src/main/java/appeng/entity/RenderFloatingItem.java @@ -18,7 +18,6 @@ package appeng.entity; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.entity.RenderItem; @@ -27,41 +26,39 @@ import net.minecraft.item.ItemBlock; import org.lwjgl.opengl.GL11; +@SideOnly(Side.CLIENT) +public class RenderFloatingItem extends RenderItem { -@SideOnly( Side.CLIENT ) -public class RenderFloatingItem extends RenderItem -{ - - public RenderFloatingItem() - { - this.shadowOpaque = 0.0F; - this.renderManager = RenderManager.instance; - } + public RenderFloatingItem() { + this.shadowOpaque = 0.0F; + this.renderManager = RenderManager.instance; + } - @Override - public void doRender( final EntityItem entityItem, final double x, final double y, final double z, final float yaw, final float partialTick ) - { - if( entityItem instanceof EntityFloatingItem ) - { - final EntityFloatingItem efi = (EntityFloatingItem) entityItem; - if( efi.getProgress() > 0.0 ) - { - GL11.glPushMatrix(); + @Override + public void doRender( + final EntityItem entityItem, + final double x, + final double y, + final double z, + final float yaw, + final float partialTick) { + if (entityItem instanceof EntityFloatingItem) { + final EntityFloatingItem efi = (EntityFloatingItem) entityItem; + if (efi.getProgress() > 0.0) { + GL11.glPushMatrix(); - if( !( efi.getEntityItem().getItem() instanceof ItemBlock ) ) - { - GL11.glTranslatef( 0, -0.15f, 0 ); - } + if (!(efi.getEntityItem().getItem() instanceof ItemBlock)) { + GL11.glTranslatef(0, -0.15f, 0); + } - super.doRender( efi, x, y, z, yaw, partialTick ); - GL11.glPopMatrix(); - } - } - } + super.doRender(efi, x, y, z, yaw, partialTick); + GL11.glPopMatrix(); + } + } + } - @Override - public boolean shouldBob() - { - return false; - } + @Override + public boolean shouldBob() { + return false; + } } diff --git a/src/main/java/appeng/entity/RenderTinyTNTPrimed.java b/src/main/java/appeng/entity/RenderTinyTNTPrimed.java index 665a43fb151..5a4becc854c 100644 --- a/src/main/java/appeng/entity/RenderTinyTNTPrimed.java +++ b/src/main/java/appeng/entity/RenderTinyTNTPrimed.java @@ -18,7 +18,6 @@ package appeng.entity; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.RenderBlocks; @@ -30,76 +29,68 @@ import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; - -@SideOnly( Side.CLIENT ) -public class RenderTinyTNTPrimed extends Render -{ - - private final RenderBlocks blockRenderer = new RenderBlocks(); - - public RenderTinyTNTPrimed() - { - this.shadowSize = 0.5F; - this.renderManager = RenderManager.instance; - } - - @Override - public void doRender( final Entity tnt, final double x, final double y, final double z, final float unused, final float life ) - { - this.renderPrimedTNT( (EntityTinyTNTPrimed) tnt, x, y, z, life ); - } - - private void renderPrimedTNT( final EntityTinyTNTPrimed tnt, final double x, final double y, final double z, final float life ) - { - GL11.glPushMatrix(); - GL11.glTranslatef( (float) x, (float) y - 0.25f, (float) z ); - float f2; - - if( tnt.fuse - life + 1.0F < 10.0F ) - { - f2 = 1.0F - ( tnt.fuse - life + 1.0F ) / 10.0F; - - if( f2 < 0.0F ) - { - f2 = 0.0F; - } - - if( f2 > 1.0F ) - { - f2 = 1.0F; - } - - f2 *= f2; - f2 *= f2; - final float f3 = 1.0F + f2 * 0.3F; - GL11.glScalef( f3, f3, f3 ); - } - - GL11.glScalef( 0.5f, 0.5f, 0.5f ); - f2 = ( 1.0F - ( tnt.fuse - life + 1.0F ) / 100.0F ) * 0.8F; - this.bindEntityTexture( tnt ); - this.blockRenderer.renderBlockAsItem( Blocks.tnt, 0, tnt.getBrightness( life ) ); - - if( tnt.fuse / 5 % 2 == 0 ) - { - GL11.glDisable( GL11.GL_TEXTURE_2D ); - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glEnable( GL11.GL_BLEND ); - GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_DST_ALPHA ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, f2 ); - this.blockRenderer.renderBlockAsItem( Blocks.tnt, 0, 1.0F ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - GL11.glDisable( GL11.GL_BLEND ); - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL11.GL_TEXTURE_2D ); - } - - GL11.glPopMatrix(); - } - - @Override - protected ResourceLocation getEntityTexture( final Entity entity ) - { - return TextureMap.locationBlocksTexture; - } +@SideOnly(Side.CLIENT) +public class RenderTinyTNTPrimed extends Render { + + private final RenderBlocks blockRenderer = new RenderBlocks(); + + public RenderTinyTNTPrimed() { + this.shadowSize = 0.5F; + this.renderManager = RenderManager.instance; + } + + @Override + public void doRender( + final Entity tnt, final double x, final double y, final double z, final float unused, final float life) { + this.renderPrimedTNT((EntityTinyTNTPrimed) tnt, x, y, z, life); + } + + private void renderPrimedTNT( + final EntityTinyTNTPrimed tnt, final double x, final double y, final double z, final float life) { + GL11.glPushMatrix(); + GL11.glTranslatef((float) x, (float) y - 0.25f, (float) z); + float f2; + + if (tnt.fuse - life + 1.0F < 10.0F) { + f2 = 1.0F - (tnt.fuse - life + 1.0F) / 10.0F; + + if (f2 < 0.0F) { + f2 = 0.0F; + } + + if (f2 > 1.0F) { + f2 = 1.0F; + } + + f2 *= f2; + f2 *= f2; + final float f3 = 1.0F + f2 * 0.3F; + GL11.glScalef(f3, f3, f3); + } + + GL11.glScalef(0.5f, 0.5f, 0.5f); + f2 = (1.0F - (tnt.fuse - life + 1.0F) / 100.0F) * 0.8F; + this.bindEntityTexture(tnt); + this.blockRenderer.renderBlockAsItem(Blocks.tnt, 0, tnt.getBrightness(life)); + + if (tnt.fuse / 5 % 2 == 0) { + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_DST_ALPHA); + GL11.glColor4f(1.0F, 1.0F, 1.0F, f2); + this.blockRenderer.renderBlockAsItem(Blocks.tnt, 0, 1.0F); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_TEXTURE_2D); + } + + GL11.glPopMatrix(); + } + + @Override + protected ResourceLocation getEntityTexture(final Entity entity) { + return TextureMap.locationBlocksTexture; + } } diff --git a/src/main/java/appeng/facade/FacadeContainer.java b/src/main/java/appeng/facade/FacadeContainer.java index 4c6bc5901ff..513f142f8d7 100644 --- a/src/main/java/appeng/facade/FacadeContainer.java +++ b/src/main/java/appeng/facade/FacadeContainer.java @@ -18,7 +18,6 @@ package appeng.facade; - import appeng.api.AEApi; import appeng.api.parts.IFacadeContainer; import appeng.api.parts.IFacadePart; @@ -29,214 +28,180 @@ import appeng.items.parts.ItemFacade; import appeng.parts.CableBusStorage; import io.netty.buffer.ByteBuf; +import java.io.IOException; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; - - -public class FacadeContainer implements IFacadeContainer -{ - - private final int facades = 6; - private final CableBusStorage storage; - - public FacadeContainer( final CableBusStorage cbs ) - { - this.storage = cbs; - } - - @Override - public boolean addFacade( final IFacadePart a ) - { - if( this.getFacade( a.getSide() ) == null ) - { - this.storage.setFacade( a.getSide().ordinal(), a ); - return true; - } - return false; - } - - @Override - public void removeFacade( final IPartHost host, final ForgeDirection side ) - { - if( side != null && side != ForgeDirection.UNKNOWN ) - { - if( this.storage.getFacade( side.ordinal() ) != null ) - { - this.storage.setFacade( side.ordinal(), null ); - if( host != null ) - { - host.markForUpdate(); - } - } - } - } - - @Override - public IFacadePart getFacade( final ForgeDirection s ) - { - return this.storage.getFacade( s.ordinal() ); - } - - @Override - public void rotateLeft() - { - final IFacadePart[] newFacades = new FacadePart[6]; - - newFacades[ForgeDirection.UP.ordinal()] = this.storage.getFacade( ForgeDirection.UP.ordinal() ); - newFacades[ForgeDirection.DOWN.ordinal()] = this.storage.getFacade( ForgeDirection.DOWN.ordinal() ); - - newFacades[ForgeDirection.EAST.ordinal()] = this.storage.getFacade( ForgeDirection.NORTH.ordinal() ); - newFacades[ForgeDirection.SOUTH.ordinal()] = this.storage.getFacade( ForgeDirection.EAST.ordinal() ); - - newFacades[ForgeDirection.WEST.ordinal()] = this.storage.getFacade( ForgeDirection.SOUTH.ordinal() ); - newFacades[ForgeDirection.NORTH.ordinal()] = this.storage.getFacade( ForgeDirection.WEST.ordinal() ); - - for( int x = 0; x < this.facades; x++ ) - { - this.storage.setFacade( x, newFacades[x] ); - } - } - - @Override - public void writeToNBT( final NBTTagCompound c ) - { - for( int x = 0; x < this.facades; x++ ) - { - if( this.storage.getFacade( x ) != null ) - { - final NBTTagCompound data = new NBTTagCompound(); - this.storage.getFacade( x ).getItemStack().writeToNBT( data ); - c.setTag( "facade:" + x, data ); - } - } - } - - @Override - public boolean readFromStream( final ByteBuf out ) throws IOException - { - final int facadeSides = out.readByte(); - - boolean changed = false; - - final int[] ids = new int[2]; - for( int x = 0; x < this.facades; x++ ) - { - final ForgeDirection side = ForgeDirection.getOrientation( x ); - final int ix = ( 1 << x ); - if( ( facadeSides & ix ) == ix ) - { - ids[0] = out.readInt(); - ids[1] = out.readInt(); - final boolean isBC = ids[0] < 0; - ids[0] = Math.abs( ids[0] ); - - if( isBC && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport bc = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - final IFacadePart created = bc.createFacadePart( (Block) Block.blockRegistry.getObjectById( ids[0] ), ids[1], side ); - changed = changed || this.storage.getFacade( x ) == null; - - this.storage.setFacade( x, created ); - } - else if( !isBC ) - { - for( final Item facadeItem : AEApi.instance().definitions().items().facade().maybeItem().asSet() ) - { - final ItemFacade ifa = (ItemFacade) facadeItem; - final ItemStack facade = ifa.createFromIDs( ids ); - if( facade != null ) - { - changed = changed || this.storage.getFacade( x ) == null; - this.storage.setFacade( x, ifa.createPartFromItemStack( facade, side ) ); - } - } - } - } - else - { - changed = changed || this.storage.getFacade( x ) != null; - this.storage.setFacade( x, null ); - } - } - - return changed; - } - - @Override - public void readFromNBT( final NBTTagCompound c ) - { - for( int x = 0; x < this.facades; x++ ) - { - this.storage.setFacade( x, null ); - - final NBTTagCompound t = c.getCompoundTag( "facade:" + x ); - if( t != null ) - { - final ItemStack is = ItemStack.loadItemStackFromNBT( t ); - if( is != null ) - { - final Item i = is.getItem(); - if( i instanceof IFacadeItem ) - { - this.storage.setFacade( x, ( (IFacadeItem) i ).createPartFromItemStack( is, ForgeDirection.getOrientation( x ) ) ); - } - else - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport bc = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - if( bc.isFacade( is ) ) - { - this.storage.setFacade( x, bc.createFacadePart( is, ForgeDirection.getOrientation( x ) ) ); - } - } - } - } - } - } - } - - @Override - public void writeToStream( final ByteBuf out ) throws IOException - { - int facadeSides = 0; - for( int x = 0; x < this.facades; x++ ) - { - if( this.getFacade( ForgeDirection.getOrientation( x ) ) != null ) - { - facadeSides |= ( 1 << x ); - } - } - out.writeByte( (byte) facadeSides ); - - for( int x = 0; x < this.facades; x++ ) - { - final IFacadePart part = this.getFacade( ForgeDirection.getOrientation( x ) ); - if( part != null ) - { - final int itemID = Item.getIdFromItem( part.getItem() ); - final int dmgValue = part.getItemDamage(); - out.writeInt( itemID * ( part.notAEFacade() ? -1 : 1 ) ); - out.writeInt( dmgValue ); - } - } - } - - @Override - public boolean isEmpty() - { - for( int x = 0; x < this.facades; x++ ) - { - if( this.storage.getFacade( x ) != null ) - { - return false; - } - } - return true; - } +public class FacadeContainer implements IFacadeContainer { + + private final int facades = 6; + private final CableBusStorage storage; + + public FacadeContainer(final CableBusStorage cbs) { + this.storage = cbs; + } + + @Override + public boolean addFacade(final IFacadePart a) { + if (this.getFacade(a.getSide()) == null) { + this.storage.setFacade(a.getSide().ordinal(), a); + return true; + } + return false; + } + + @Override + public void removeFacade(final IPartHost host, final ForgeDirection side) { + if (side != null && side != ForgeDirection.UNKNOWN) { + if (this.storage.getFacade(side.ordinal()) != null) { + this.storage.setFacade(side.ordinal(), null); + if (host != null) { + host.markForUpdate(); + } + } + } + } + + @Override + public IFacadePart getFacade(final ForgeDirection s) { + return this.storage.getFacade(s.ordinal()); + } + + @Override + public void rotateLeft() { + final IFacadePart[] newFacades = new FacadePart[6]; + + newFacades[ForgeDirection.UP.ordinal()] = this.storage.getFacade(ForgeDirection.UP.ordinal()); + newFacades[ForgeDirection.DOWN.ordinal()] = this.storage.getFacade(ForgeDirection.DOWN.ordinal()); + + newFacades[ForgeDirection.EAST.ordinal()] = this.storage.getFacade(ForgeDirection.NORTH.ordinal()); + newFacades[ForgeDirection.SOUTH.ordinal()] = this.storage.getFacade(ForgeDirection.EAST.ordinal()); + + newFacades[ForgeDirection.WEST.ordinal()] = this.storage.getFacade(ForgeDirection.SOUTH.ordinal()); + newFacades[ForgeDirection.NORTH.ordinal()] = this.storage.getFacade(ForgeDirection.WEST.ordinal()); + + for (int x = 0; x < this.facades; x++) { + this.storage.setFacade(x, newFacades[x]); + } + } + + @Override + public void writeToNBT(final NBTTagCompound c) { + for (int x = 0; x < this.facades; x++) { + if (this.storage.getFacade(x) != null) { + final NBTTagCompound data = new NBTTagCompound(); + this.storage.getFacade(x).getItemStack().writeToNBT(data); + c.setTag("facade:" + x, data); + } + } + } + + @Override + public boolean readFromStream(final ByteBuf out) throws IOException { + final int facadeSides = out.readByte(); + + boolean changed = false; + + final int[] ids = new int[2]; + for (int x = 0; x < this.facades; x++) { + final ForgeDirection side = ForgeDirection.getOrientation(x); + final int ix = (1 << x); + if ((facadeSides & ix) == ix) { + ids[0] = out.readInt(); + ids[1] = out.readInt(); + final boolean isBC = ids[0] < 0; + ids[0] = Math.abs(ids[0]); + + if (isBC && IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport)) { + final IBuildCraftTransport bc = (IBuildCraftTransport) + IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport); + final IFacadePart created = + bc.createFacadePart((Block) Block.blockRegistry.getObjectById(ids[0]), ids[1], side); + changed = changed || this.storage.getFacade(x) == null; + + this.storage.setFacade(x, created); + } else if (!isBC) { + for (final Item facadeItem : AEApi.instance() + .definitions() + .items() + .facade() + .maybeItem() + .asSet()) { + final ItemFacade ifa = (ItemFacade) facadeItem; + final ItemStack facade = ifa.createFromIDs(ids); + if (facade != null) { + changed = changed || this.storage.getFacade(x) == null; + this.storage.setFacade(x, ifa.createPartFromItemStack(facade, side)); + } + } + } + } else { + changed = changed || this.storage.getFacade(x) != null; + this.storage.setFacade(x, null); + } + } + + return changed; + } + + @Override + public void readFromNBT(final NBTTagCompound c) { + for (int x = 0; x < this.facades; x++) { + this.storage.setFacade(x, null); + + final NBTTagCompound t = c.getCompoundTag("facade:" + x); + if (t != null) { + final ItemStack is = ItemStack.loadItemStackFromNBT(t); + if (is != null) { + final Item i = is.getItem(); + if (i instanceof IFacadeItem) { + this.storage.setFacade( + x, ((IFacadeItem) i).createPartFromItemStack(is, ForgeDirection.getOrientation(x))); + } else { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport)) { + final IBuildCraftTransport bc = (IBuildCraftTransport) + IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport); + if (bc.isFacade(is)) { + this.storage.setFacade(x, bc.createFacadePart(is, ForgeDirection.getOrientation(x))); + } + } + } + } + } + } + } + + @Override + public void writeToStream(final ByteBuf out) throws IOException { + int facadeSides = 0; + for (int x = 0; x < this.facades; x++) { + if (this.getFacade(ForgeDirection.getOrientation(x)) != null) { + facadeSides |= (1 << x); + } + } + out.writeByte((byte) facadeSides); + + for (int x = 0; x < this.facades; x++) { + final IFacadePart part = this.getFacade(ForgeDirection.getOrientation(x)); + if (part != null) { + final int itemID = Item.getIdFromItem(part.getItem()); + final int dmgValue = part.getItemDamage(); + out.writeInt(itemID * (part.notAEFacade() ? -1 : 1)); + out.writeInt(dmgValue); + } + } + } + + @Override + public boolean isEmpty() { + for (int x = 0; x < this.facades; x++) { + if (this.storage.getFacade(x) != null) { + return false; + } + } + return true; + } } diff --git a/src/main/java/appeng/facade/FacadePart.java b/src/main/java/appeng/facade/FacadePart.java index b98ded0dfb0..969ab284e0f 100644 --- a/src/main/java/appeng/facade/FacadePart.java +++ b/src/main/java/appeng/facade/FacadePart.java @@ -18,7 +18,6 @@ package appeng.facade; - import appeng.api.AEApi; import appeng.api.parts.*; import appeng.client.render.BusRenderHelper; @@ -30,6 +29,8 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; @@ -45,553 +46,582 @@ import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import javax.annotation.Nullable; -import java.util.EnumSet; - - -public class FacadePart implements IFacadePart, IBoxProvider -{ - - private final ItemStack facade; - private final ForgeDirection side; - private int thickness = 2; - - @SideOnly( Side.CLIENT ) - private ISimplifiedBundle prevLight; - - public FacadePart( final ItemStack facade, final ForgeDirection side ) - { - if( facade == null ) - { - throw new IllegalArgumentException( "Facade Part constructed on null item." ); - } - this.facade = facade.copy(); - this.facade.stackSize = 1; - this.side = side; - } - - public static boolean isFacade( final ItemStack is ) - { - return is.getItem() instanceof IFacadeItem; - } - - @Override - public ItemStack getItemStack() - { - return this.facade; - } - - @Override - public void getBoxes( final IPartCollisionHelper ch, final Entity e ) - { - if( e instanceof EntityLivingBase ) - { - // prevent weird snag behavior - ch.addBox( 0.0, 0.0, 14, 16.0, 16.0, 16.0 ); - } - else - { - // the box is 15.9 for transition planes to pick up collision events. - ch.addBox( 0.0, 0.0, 14, 16.0, 16.0, 15.9 ); - } - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper instance2, final RenderBlocks renderer, final IFacadeContainer fc, final AxisAlignedBB busBounds, final boolean renderStilt ) - { - if( this.facade != null ) - { - final BusRenderHelper instance = (BusRenderHelper) instance2; - - try - { - final ItemStack randomItem = this.getTexture(); - - RenderBlocksWorkaround rbw = null; - if( renderer instanceof RenderBlocksWorkaround ) - { - rbw = (RenderBlocksWorkaround) renderer; - } - - if( renderStilt && busBounds == null ) - { - if( rbw != null ) - { - rbw.setFacade( false ); - rbw.setCalculations( true ); - } - - IIcon myIcon = null; - if( this.notAEFacade() && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport bc = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - myIcon = bc.getCobbleStructurePipeTexture(); - } - - if( myIcon == null ) - { - myIcon = this.facade.getIconIndex(); - } - - instance.setTexture( myIcon ); - - if( this.notAEFacade() ) - { - instance.setBounds( 6, 6, 10, 10, 10, 15 ); - } - else - { - instance.setBounds( 7, 7, 10, 9, 9, 15 ); - } - - instance.renderBlock( x, y, z, renderer ); - instance.setTexture( null ); - } - - if( randomItem != null ) - { - if( randomItem.getItem() instanceof ItemBlock ) - { - final ItemBlock ib = (ItemBlock) randomItem.getItem(); - final Block blk = Block.getBlockFromItem( ib ); - - if( AEApi.instance().partHelper().getCableRenderMode().transparentFacades ) - { - if( rbw != null ) - { - rbw.setOpacity( 0.3f ); - } - instance.renderForPass( 1 ); - } - else - { - if( blk.canRenderInPass( 1 ) ) - { - instance.renderForPass( 1 ); - } - } - - int color = 0xffffff; - - try - { - color = ib.getColorFromItemStack( randomItem, 0 ); - } - catch( final Throwable ignored ) - { - } - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - instance.setBounds( 0, 0, 16 - this.thickness, 16, 16, 16 ); - instance.prepareBounds( renderer ); - - if( rbw != null ) - { - rbw.setFacade( true ); - - rbw.setCalculations( true ); - rbw.setFaces( EnumSet.noneOf( ForgeDirection.class ) ); - - if( this.prevLight != null && rbw.similarLighting( blk, rbw.blockAccess, x, y, z, this.prevLight ) ) - { - rbw.populate( this.prevLight ); - } - else - { - instance.setRenderColor( color ); - rbw.renderStandardBlock( instance.getBlock(), x, y, z ); - instance.setRenderColor( 0xffffff ); - this.prevLight = rbw.getLightingCache(); - } - - rbw.setCalculations( false ); - rbw.setFaces( this.calculateFaceOpenFaces( rbw.blockAccess, fc, x, y, z, this.side ) ); - - ( (RenderBlocksWorkaround) renderer ).setTexture( blk.getIcon( ForgeDirection.DOWN.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.UP.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.NORTH.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.SOUTH.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.WEST.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.EAST.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ) ); - } - else - { - instance.setTexture( blk.getIcon( ForgeDirection.DOWN.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.UP.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.NORTH.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.SOUTH.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.WEST.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ), blk.getIcon( ForgeDirection.EAST.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ) ); - } - - if( busBounds == null ) - { - if( this.side == ForgeDirection.UP || this.side == ForgeDirection.DOWN ) - { - instance.renderBlockCurrentBounds( x, y, z, renderer ); - } - else if( this.side == ForgeDirection.NORTH || this.side == ForgeDirection.SOUTH ) - { - if( fc.getFacade( ForgeDirection.UP ) != null ) - { - renderer.renderMaxY -= this.thickness / 16.0; - } - - if( fc.getFacade( ForgeDirection.DOWN ) != null ) - { - renderer.renderMinY += this.thickness / 16.0; - } - - instance.renderBlockCurrentBounds( x, y, z, renderer ); - } - else - { - if( fc.getFacade( ForgeDirection.UP ) != null ) - { - renderer.renderMaxY -= this.thickness / 16.0; - } - - if( fc.getFacade( ForgeDirection.DOWN ) != null ) - { - renderer.renderMinY += this.thickness / 16.0; - } - - if( fc.getFacade( ForgeDirection.SOUTH ) != null ) - { - renderer.renderMaxZ -= this.thickness / 16.0; - } - - if( fc.getFacade( ForgeDirection.NORTH ) != null ) - { - renderer.renderMinZ += this.thickness / 16.0; - } - - instance.renderBlockCurrentBounds( x, y, z, renderer ); - } - } - else - { - if( this.side == ForgeDirection.UP || this.side == ForgeDirection.DOWN ) - { - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, 0.0, 0.0, busBounds.maxZ, 1.0, 1.0, 1.0 ); - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, 0.0, 0.0, 0.0, 1.0, 1.0, busBounds.minZ ); - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, 0.0, 0.0, busBounds.minZ, busBounds.minX, 1.0, busBounds.maxZ ); - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, busBounds.maxX, 0.0, busBounds.minZ, 1.0, 1.0, busBounds.maxZ ); - } - else if( this.side == ForgeDirection.NORTH || this.side == ForgeDirection.SOUTH ) - { - if( fc.getFacade( ForgeDirection.UP ) != null ) - { - renderer.renderMaxY -= this.thickness / 16.0; - } - - if( fc.getFacade( ForgeDirection.DOWN ) != null ) - { - renderer.renderMinY += this.thickness / 16.0; - } - - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, busBounds.maxX, 0.0, 0.0, 1.0, 1.0, 1.0 ); - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, 0.0, 0.0, 0.0, busBounds.minX, 1.0, 1.0 ); - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, busBounds.minX, 0.0, 0.0, busBounds.maxX, busBounds.minY, 1.0 ); - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, busBounds.minX, busBounds.maxY, 0.0, busBounds.maxX, 1.0, 1.0 ); - } - else - { - if( fc.getFacade( ForgeDirection.UP ) != null ) - { - renderer.renderMaxY -= this.thickness / 16.0; - } - - if( fc.getFacade( ForgeDirection.DOWN ) != null ) - { - renderer.renderMinY += this.thickness / 16.0; - } - - if( fc.getFacade( ForgeDirection.SOUTH ) != null ) - { - renderer.renderMaxZ -= this.thickness / 16.0; - } - - if( fc.getFacade( ForgeDirection.NORTH ) != null ) - { - renderer.renderMinZ += this.thickness / 16.0; - } - - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, 0.0, 0.0, busBounds.maxZ, 1.0, 1.0, 1.0 ); - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, 0.0, 0.0, 0.0, 1.0, 1.0, busBounds.minZ ); - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, 0.0, 0.0, busBounds.minZ, 1.0, busBounds.minY, busBounds.maxZ ); - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, 0.0, busBounds.maxY, busBounds.minZ, 1.0, 1.0, busBounds.maxZ ); - } - } - - if( rbw != null ) - { - rbw.setOpacity( 1.0f ); - rbw.setFaces( EnumSet.allOf( ForgeDirection.class ) ); - } - - instance.renderForPass( 0 ); - instance.setTexture( null ); - Tessellator.instance.setColorOpaque_F( 1, 1, 1 ); - } - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - } - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper instance, final RenderBlocks renderer ) - { - if( this.facade != null ) - { - final IFacadeItem fi = (IFacadeItem) this.facade.getItem(); - - try - { - if( fi != null ) - { - final ItemStack randomItem = fi.getTextureItem( this.facade ); - - instance.setTexture( this.facade.getIconIndex() ); - instance.setBounds( 7, 7, 4, 9, 9, 14 ); - instance.renderInventoryBox( renderer ); - instance.setTexture( null ); - - if( randomItem != null ) - { - if( randomItem.getItem() instanceof ItemBlock ) - { - final ItemBlock ib = (ItemBlock) randomItem.getItem(); - final Block blk = Block.getBlockFromItem( ib ); - - try - { - final int color = ib.getColorFromItemStack( randomItem, 0 ); - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0F ); - instance.setInvColor( color ); - } - catch( final Throwable error ) - { - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0F ); - instance.setInvColor( 0xffffff ); - } - - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); - Tessellator.instance.setColorOpaque_F( 1, 1, 1 ); - instance.setTexture( blk.getIcon( this.side.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ) ); - - instance.setBounds( 0, 0, 14, 16, 16, 16 ); - instance.renderInventoryBox( renderer ); - - instance.setTexture( null ); - } - } - } - } - catch( final Exception ignored ) - { - - } - } - } - - @Override - public ForgeDirection getSide() - { - return this.side; - } - - @Override - public AxisAlignedBB getPrimaryBox() - { - return Platform.getPrimaryBox( this.side, this.thickness ); - } - - @Override - public Item getItem() - { - final ItemStack is = this.getTexture(); - if( is == null ) - { - return null; - } - return is.getItem(); - } - - @Override - public int getItemDamage() - { - final ItemStack is = this.getTexture(); - if( is == null ) - { - return 0; - } - return is.getItemDamage(); - } - - @Override - public boolean notAEFacade() - { - return !( this.facade.getItem() instanceof IFacadeItem ); - } - - @Override - public void setThinFacades( final boolean useThinFacades ) - { - this.thickness = useThinFacades ? 1 : 2; - } - - @Override - public boolean isTransparent() - { - if( AEApi.instance().partHelper().getCableRenderMode().transparentFacades ) - { - return true; - } - - final ItemStack is = this.getTexture(); - final Block blk = Block.getBlockFromItem( is.getItem() ); - - return !blk.isOpaqueCube(); - } - - @Nullable - private ItemStack getTexture() - { - final Item maybeFacade = this.facade.getItem(); - - // AE Facade - if( maybeFacade instanceof IFacadeItem ) - { - final IFacadeItem facade = (IFacadeItem) maybeFacade; - - return facade.getTextureItem( this.facade ); - } - else if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport bc = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - - return bc.getTextureForFacade( this.facade ); - } - - return null; - } - - private EnumSet calculateFaceOpenFaces( final IBlockAccess blockAccess, final IFacadeContainer fc, final int x, final int y, final int z, final ForgeDirection side ) - { - final EnumSet out = EnumSet.of( side, side.getOpposite() ); - final IFacadePart facade = fc.getFacade( side ); - - for( final ForgeDirection it : ForgeDirection.VALID_DIRECTIONS ) - { - if( !out.contains( it ) && this.hasAlphaDiff( blockAccess.getTileEntity( x + it.offsetX, y + it.offsetY, z + it.offsetZ ), side, facade ) ) - { - out.add( it ); - } - } - - if( out.contains( ForgeDirection.UP ) && ( side.offsetX != 0 || side.offsetZ != 0 ) ) - { - final IFacadePart fp = fc.getFacade( ForgeDirection.UP ); - if( fp != null && ( fp.isTransparent() == facade.isTransparent() ) ) - { - out.remove( ForgeDirection.UP ); - } - } - - if( out.contains( ForgeDirection.DOWN ) && ( side.offsetX != 0 || side.offsetZ != 0 ) ) - { - final IFacadePart fp = fc.getFacade( ForgeDirection.DOWN ); - if( fp != null && ( fp.isTransparent() == facade.isTransparent() ) ) - { - out.remove( ForgeDirection.DOWN ); - } - } - - if( out.contains( ForgeDirection.SOUTH ) && ( side.offsetX != 0 ) ) - { - final IFacadePart fp = fc.getFacade( ForgeDirection.SOUTH ); - if( fp != null && ( fp.isTransparent() == facade.isTransparent() ) ) - { - out.remove( ForgeDirection.SOUTH ); - } - } - - if( out.contains( ForgeDirection.NORTH ) && ( side.offsetX != 0 ) ) - { - final IFacadePart fp = fc.getFacade( ForgeDirection.NORTH ); - if( fp != null && ( fp.isTransparent() == facade.isTransparent() ) ) - { - out.remove( ForgeDirection.NORTH ); - } - } - - /* - * if ( out.contains( ForgeDirection.EAST ) && (side.offsetZ != 0) ) { IFacadePart fp = fc.getFacade( - * ForgeDirection.EAST ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( - * ForgeDirection.EAST ); } - * if ( out.contains( ForgeDirection.WEST ) && (side.offsetZ != 0) ) { IFacadePart fp = fc.getFacade( - * ForgeDirection.WEST ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( - * ForgeDirection.WEST ); } - * if ( out.contains( ForgeDirection.NORTH ) && (side.offsetY != 0) ) { IFacadePart fp = fc.getFacade( - * ForgeDirection.NORTH ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( - * ForgeDirection.NORTH ); } - * if ( out.contains( ForgeDirection.SOUTH ) && (side.offsetY != 0) ) { IFacadePart fp = fc.getFacade( - * ForgeDirection.SOUTH ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( - * ForgeDirection.SOUTH ); } - * if ( out.contains( ForgeDirection.EAST ) && (side.offsetY != 0) ) { IFacadePart fp = fc.getFacade( - * ForgeDirection.EAST ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( - * ForgeDirection.EAST ); } - * if ( out.contains( ForgeDirection.WEST ) && (side.offsetY != 0) ) { IFacadePart fp = fc.getFacade( - * ForgeDirection.WEST ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( - * ForgeDirection.WEST ); } - */ - return out; - } - - @SideOnly( Side.CLIENT ) - private void renderSegmentBlockCurrentBounds( final IPartRenderHelper instance, final int x, final int y, final int z, final RenderBlocks renderer, final double minX, final double minY, final double minZ, final double maxX, final double maxY, final double maxZ ) - { - final double oldMinX = renderer.renderMinX; - final double oldMinY = renderer.renderMinY; - final double oldMinZ = renderer.renderMinZ; - final double oldMaxX = renderer.renderMaxX; - final double oldMaxY = renderer.renderMaxY; - final double oldMaxZ = renderer.renderMaxZ; - - renderer.renderMinX = Math.max( renderer.renderMinX, minX ); - renderer.renderMinY = Math.max( renderer.renderMinY, minY ); - renderer.renderMinZ = Math.max( renderer.renderMinZ, minZ ); - renderer.renderMaxX = Math.min( renderer.renderMaxX, maxX ); - renderer.renderMaxY = Math.min( renderer.renderMaxY, maxY ); - renderer.renderMaxZ = Math.min( renderer.renderMaxZ, maxZ ); - - // don't draw it if its not at least a pixel wide... - if( renderer.renderMaxX - renderer.renderMinX >= 1.0 / 16.0 && renderer.renderMaxY - renderer.renderMinY >= 1.0 / 16.0 && renderer.renderMaxZ - renderer.renderMinZ >= 1.0 / 16.0 ) - { - instance.renderBlockCurrentBounds( x, y, z, renderer ); - } - - renderer.renderMinX = oldMinX; - renderer.renderMinY = oldMinY; - renderer.renderMinZ = oldMinZ; - renderer.renderMaxX = oldMaxX; - renderer.renderMaxY = oldMaxY; - renderer.renderMaxZ = oldMaxZ; - } - - private boolean hasAlphaDiff( final TileEntity tileEntity, final ForgeDirection side, final IFacadePart facade ) - { - if( tileEntity instanceof IPartHost ) - { - final IPartHost ph = (IPartHost) tileEntity; - final IFacadePart fp = ph.getFacadeContainer().getFacade( side ); - - return fp == null || ( fp.isTransparent() != facade.isTransparent() ); - } - - return true; - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - this.getBoxes( bch, null ); - } +public class FacadePart implements IFacadePart, IBoxProvider { + + private final ItemStack facade; + private final ForgeDirection side; + private int thickness = 2; + + @SideOnly(Side.CLIENT) + private ISimplifiedBundle prevLight; + + public FacadePart(final ItemStack facade, final ForgeDirection side) { + if (facade == null) { + throw new IllegalArgumentException("Facade Part constructed on null item."); + } + this.facade = facade.copy(); + this.facade.stackSize = 1; + this.side = side; + } + + public static boolean isFacade(final ItemStack is) { + return is.getItem() instanceof IFacadeItem; + } + + @Override + public ItemStack getItemStack() { + return this.facade; + } + + @Override + public void getBoxes(final IPartCollisionHelper ch, final Entity e) { + if (e instanceof EntityLivingBase) { + // prevent weird snag behavior + ch.addBox(0.0, 0.0, 14, 16.0, 16.0, 16.0); + } else { + // the box is 15.9 for transition planes to pick up collision events. + ch.addBox(0.0, 0.0, 14, 16.0, 16.0, 15.9); + } + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper instance2, + final RenderBlocks renderer, + final IFacadeContainer fc, + final AxisAlignedBB busBounds, + final boolean renderStilt) { + if (this.facade != null) { + final BusRenderHelper instance = (BusRenderHelper) instance2; + + try { + final ItemStack randomItem = this.getTexture(); + + RenderBlocksWorkaround rbw = null; + if (renderer instanceof RenderBlocksWorkaround) { + rbw = (RenderBlocksWorkaround) renderer; + } + + if (renderStilt && busBounds == null) { + if (rbw != null) { + rbw.setFacade(false); + rbw.setCalculations(true); + } + + IIcon myIcon = null; + if (this.notAEFacade() + && IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport)) { + final IBuildCraftTransport bc = (IBuildCraftTransport) + IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport); + myIcon = bc.getCobbleStructurePipeTexture(); + } + + if (myIcon == null) { + myIcon = this.facade.getIconIndex(); + } + + instance.setTexture(myIcon); + + if (this.notAEFacade()) { + instance.setBounds(6, 6, 10, 10, 10, 15); + } else { + instance.setBounds(7, 7, 10, 9, 9, 15); + } + + instance.renderBlock(x, y, z, renderer); + instance.setTexture(null); + } + + if (randomItem != null) { + if (randomItem.getItem() instanceof ItemBlock) { + final ItemBlock ib = (ItemBlock) randomItem.getItem(); + final Block blk = Block.getBlockFromItem(ib); + + if (AEApi.instance().partHelper().getCableRenderMode().transparentFacades) { + if (rbw != null) { + rbw.setOpacity(0.3f); + } + instance.renderForPass(1); + } else { + if (blk.canRenderInPass(1)) { + instance.renderForPass(1); + } + } + + int color = 0xffffff; + + try { + color = ib.getColorFromItemStack(randomItem, 0); + } catch (final Throwable ignored) { + } + + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = + renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + instance.setBounds(0, 0, 16 - this.thickness, 16, 16, 16); + instance.prepareBounds(renderer); + + if (rbw != null) { + rbw.setFacade(true); + + rbw.setCalculations(true); + rbw.setFaces(EnumSet.noneOf(ForgeDirection.class)); + + if (this.prevLight != null + && rbw.similarLighting(blk, rbw.blockAccess, x, y, z, this.prevLight)) { + rbw.populate(this.prevLight); + } else { + instance.setRenderColor(color); + rbw.renderStandardBlock(instance.getBlock(), x, y, z); + instance.setRenderColor(0xffffff); + this.prevLight = rbw.getLightingCache(); + } + + rbw.setCalculations(false); + rbw.setFaces(this.calculateFaceOpenFaces(rbw.blockAccess, fc, x, y, z, this.side)); + + ((RenderBlocksWorkaround) renderer) + .setTexture( + blk.getIcon( + ForgeDirection.DOWN.ordinal(), + ib.getMetadata(randomItem.getItemDamage())), + blk.getIcon( + ForgeDirection.UP.ordinal(), + ib.getMetadata(randomItem.getItemDamage())), + blk.getIcon( + ForgeDirection.NORTH.ordinal(), + ib.getMetadata(randomItem.getItemDamage())), + blk.getIcon( + ForgeDirection.SOUTH.ordinal(), + ib.getMetadata(randomItem.getItemDamage())), + blk.getIcon( + ForgeDirection.WEST.ordinal(), + ib.getMetadata(randomItem.getItemDamage())), + blk.getIcon( + ForgeDirection.EAST.ordinal(), + ib.getMetadata(randomItem.getItemDamage()))); + } else { + instance.setTexture( + blk.getIcon( + ForgeDirection.DOWN.ordinal(), ib.getMetadata(randomItem.getItemDamage())), + blk.getIcon( + ForgeDirection.UP.ordinal(), ib.getMetadata(randomItem.getItemDamage())), + blk.getIcon( + ForgeDirection.NORTH.ordinal(), ib.getMetadata(randomItem.getItemDamage())), + blk.getIcon( + ForgeDirection.SOUTH.ordinal(), ib.getMetadata(randomItem.getItemDamage())), + blk.getIcon( + ForgeDirection.WEST.ordinal(), ib.getMetadata(randomItem.getItemDamage())), + blk.getIcon( + ForgeDirection.EAST.ordinal(), ib.getMetadata(randomItem.getItemDamage()))); + } + + if (busBounds == null) { + if (this.side == ForgeDirection.UP || this.side == ForgeDirection.DOWN) { + instance.renderBlockCurrentBounds(x, y, z, renderer); + } else if (this.side == ForgeDirection.NORTH || this.side == ForgeDirection.SOUTH) { + if (fc.getFacade(ForgeDirection.UP) != null) { + renderer.renderMaxY -= this.thickness / 16.0; + } + + if (fc.getFacade(ForgeDirection.DOWN) != null) { + renderer.renderMinY += this.thickness / 16.0; + } + + instance.renderBlockCurrentBounds(x, y, z, renderer); + } else { + if (fc.getFacade(ForgeDirection.UP) != null) { + renderer.renderMaxY -= this.thickness / 16.0; + } + + if (fc.getFacade(ForgeDirection.DOWN) != null) { + renderer.renderMinY += this.thickness / 16.0; + } + + if (fc.getFacade(ForgeDirection.SOUTH) != null) { + renderer.renderMaxZ -= this.thickness / 16.0; + } + + if (fc.getFacade(ForgeDirection.NORTH) != null) { + renderer.renderMinZ += this.thickness / 16.0; + } + + instance.renderBlockCurrentBounds(x, y, z, renderer); + } + } else { + if (this.side == ForgeDirection.UP || this.side == ForgeDirection.DOWN) { + this.renderSegmentBlockCurrentBounds( + instance, x, y, z, renderer, 0.0, 0.0, busBounds.maxZ, 1.0, 1.0, 1.0); + this.renderSegmentBlockCurrentBounds( + instance, x, y, z, renderer, 0.0, 0.0, 0.0, 1.0, 1.0, busBounds.minZ); + this.renderSegmentBlockCurrentBounds( + instance, + x, + y, + z, + renderer, + 0.0, + 0.0, + busBounds.minZ, + busBounds.minX, + 1.0, + busBounds.maxZ); + this.renderSegmentBlockCurrentBounds( + instance, + x, + y, + z, + renderer, + busBounds.maxX, + 0.0, + busBounds.minZ, + 1.0, + 1.0, + busBounds.maxZ); + } else if (this.side == ForgeDirection.NORTH || this.side == ForgeDirection.SOUTH) { + if (fc.getFacade(ForgeDirection.UP) != null) { + renderer.renderMaxY -= this.thickness / 16.0; + } + + if (fc.getFacade(ForgeDirection.DOWN) != null) { + renderer.renderMinY += this.thickness / 16.0; + } + + this.renderSegmentBlockCurrentBounds( + instance, x, y, z, renderer, busBounds.maxX, 0.0, 0.0, 1.0, 1.0, 1.0); + this.renderSegmentBlockCurrentBounds( + instance, x, y, z, renderer, 0.0, 0.0, 0.0, busBounds.minX, 1.0, 1.0); + this.renderSegmentBlockCurrentBounds( + instance, + x, + y, + z, + renderer, + busBounds.minX, + 0.0, + 0.0, + busBounds.maxX, + busBounds.minY, + 1.0); + this.renderSegmentBlockCurrentBounds( + instance, + x, + y, + z, + renderer, + busBounds.minX, + busBounds.maxY, + 0.0, + busBounds.maxX, + 1.0, + 1.0); + } else { + if (fc.getFacade(ForgeDirection.UP) != null) { + renderer.renderMaxY -= this.thickness / 16.0; + } + + if (fc.getFacade(ForgeDirection.DOWN) != null) { + renderer.renderMinY += this.thickness / 16.0; + } + + if (fc.getFacade(ForgeDirection.SOUTH) != null) { + renderer.renderMaxZ -= this.thickness / 16.0; + } + + if (fc.getFacade(ForgeDirection.NORTH) != null) { + renderer.renderMinZ += this.thickness / 16.0; + } + + this.renderSegmentBlockCurrentBounds( + instance, x, y, z, renderer, 0.0, 0.0, busBounds.maxZ, 1.0, 1.0, 1.0); + this.renderSegmentBlockCurrentBounds( + instance, x, y, z, renderer, 0.0, 0.0, 0.0, 1.0, 1.0, busBounds.minZ); + this.renderSegmentBlockCurrentBounds( + instance, + x, + y, + z, + renderer, + 0.0, + 0.0, + busBounds.minZ, + 1.0, + busBounds.minY, + busBounds.maxZ); + this.renderSegmentBlockCurrentBounds( + instance, + x, + y, + z, + renderer, + 0.0, + busBounds.maxY, + busBounds.minZ, + 1.0, + 1.0, + busBounds.maxZ); + } + } + + if (rbw != null) { + rbw.setOpacity(1.0f); + rbw.setFaces(EnumSet.allOf(ForgeDirection.class)); + } + + instance.renderForPass(0); + instance.setTexture(null); + Tessellator.instance.setColorOpaque_F(1, 1, 1); + } + } + } catch (final Throwable t) { + AELog.debug(t); + } + } + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper instance, final RenderBlocks renderer) { + if (this.facade != null) { + final IFacadeItem fi = (IFacadeItem) this.facade.getItem(); + + try { + if (fi != null) { + final ItemStack randomItem = fi.getTextureItem(this.facade); + + instance.setTexture(this.facade.getIconIndex()); + instance.setBounds(7, 7, 4, 9, 9, 14); + instance.renderInventoryBox(renderer); + instance.setTexture(null); + + if (randomItem != null) { + if (randomItem.getItem() instanceof ItemBlock) { + final ItemBlock ib = (ItemBlock) randomItem.getItem(); + final Block blk = Block.getBlockFromItem(ib); + + try { + final int color = ib.getColorFromItemStack(randomItem, 0); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); + instance.setInvColor(color); + } catch (final Throwable error) { + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); + instance.setInvColor(0xffffff); + } + + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); + Tessellator.instance.setColorOpaque_F(1, 1, 1); + instance.setTexture( + blk.getIcon(this.side.ordinal(), ib.getMetadata(randomItem.getItemDamage()))); + + instance.setBounds(0, 0, 14, 16, 16, 16); + instance.renderInventoryBox(renderer); + + instance.setTexture(null); + } + } + } + } catch (final Exception ignored) { + + } + } + } + + @Override + public ForgeDirection getSide() { + return this.side; + } + + @Override + public AxisAlignedBB getPrimaryBox() { + return Platform.getPrimaryBox(this.side, this.thickness); + } + + @Override + public Item getItem() { + final ItemStack is = this.getTexture(); + if (is == null) { + return null; + } + return is.getItem(); + } + + @Override + public int getItemDamage() { + final ItemStack is = this.getTexture(); + if (is == null) { + return 0; + } + return is.getItemDamage(); + } + + @Override + public boolean notAEFacade() { + return !(this.facade.getItem() instanceof IFacadeItem); + } + + @Override + public void setThinFacades(final boolean useThinFacades) { + this.thickness = useThinFacades ? 1 : 2; + } + + @Override + public boolean isTransparent() { + if (AEApi.instance().partHelper().getCableRenderMode().transparentFacades) { + return true; + } + + final ItemStack is = this.getTexture(); + final Block blk = Block.getBlockFromItem(is.getItem()); + + return !blk.isOpaqueCube(); + } + + @Nullable + private ItemStack getTexture() { + final Item maybeFacade = this.facade.getItem(); + + // AE Facade + if (maybeFacade instanceof IFacadeItem) { + final IFacadeItem facade = (IFacadeItem) maybeFacade; + + return facade.getTextureItem(this.facade); + } else if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport)) { + final IBuildCraftTransport bc = (IBuildCraftTransport) + IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport); + + return bc.getTextureForFacade(this.facade); + } + + return null; + } + + private EnumSet calculateFaceOpenFaces( + final IBlockAccess blockAccess, + final IFacadeContainer fc, + final int x, + final int y, + final int z, + final ForgeDirection side) { + final EnumSet out = EnumSet.of(side, side.getOpposite()); + final IFacadePart facade = fc.getFacade(side); + + for (final ForgeDirection it : ForgeDirection.VALID_DIRECTIONS) { + if (!out.contains(it) + && this.hasAlphaDiff( + blockAccess.getTileEntity(x + it.offsetX, y + it.offsetY, z + it.offsetZ), side, facade)) { + out.add(it); + } + } + + if (out.contains(ForgeDirection.UP) && (side.offsetX != 0 || side.offsetZ != 0)) { + final IFacadePart fp = fc.getFacade(ForgeDirection.UP); + if (fp != null && (fp.isTransparent() == facade.isTransparent())) { + out.remove(ForgeDirection.UP); + } + } + + if (out.contains(ForgeDirection.DOWN) && (side.offsetX != 0 || side.offsetZ != 0)) { + final IFacadePart fp = fc.getFacade(ForgeDirection.DOWN); + if (fp != null && (fp.isTransparent() == facade.isTransparent())) { + out.remove(ForgeDirection.DOWN); + } + } + + if (out.contains(ForgeDirection.SOUTH) && (side.offsetX != 0)) { + final IFacadePart fp = fc.getFacade(ForgeDirection.SOUTH); + if (fp != null && (fp.isTransparent() == facade.isTransparent())) { + out.remove(ForgeDirection.SOUTH); + } + } + + if (out.contains(ForgeDirection.NORTH) && (side.offsetX != 0)) { + final IFacadePart fp = fc.getFacade(ForgeDirection.NORTH); + if (fp != null && (fp.isTransparent() == facade.isTransparent())) { + out.remove(ForgeDirection.NORTH); + } + } + + /* + * if ( out.contains( ForgeDirection.EAST ) && (side.offsetZ != 0) ) { IFacadePart fp = fc.getFacade( + * ForgeDirection.EAST ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( + * ForgeDirection.EAST ); } + * if ( out.contains( ForgeDirection.WEST ) && (side.offsetZ != 0) ) { IFacadePart fp = fc.getFacade( + * ForgeDirection.WEST ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( + * ForgeDirection.WEST ); } + * if ( out.contains( ForgeDirection.NORTH ) && (side.offsetY != 0) ) { IFacadePart fp = fc.getFacade( + * ForgeDirection.NORTH ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( + * ForgeDirection.NORTH ); } + * if ( out.contains( ForgeDirection.SOUTH ) && (side.offsetY != 0) ) { IFacadePart fp = fc.getFacade( + * ForgeDirection.SOUTH ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( + * ForgeDirection.SOUTH ); } + * if ( out.contains( ForgeDirection.EAST ) && (side.offsetY != 0) ) { IFacadePart fp = fc.getFacade( + * ForgeDirection.EAST ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( + * ForgeDirection.EAST ); } + * if ( out.contains( ForgeDirection.WEST ) && (side.offsetY != 0) ) { IFacadePart fp = fc.getFacade( + * ForgeDirection.WEST ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( + * ForgeDirection.WEST ); } + */ + return out; + } + + @SideOnly(Side.CLIENT) + private void renderSegmentBlockCurrentBounds( + final IPartRenderHelper instance, + final int x, + final int y, + final int z, + final RenderBlocks renderer, + final double minX, + final double minY, + final double minZ, + final double maxX, + final double maxY, + final double maxZ) { + final double oldMinX = renderer.renderMinX; + final double oldMinY = renderer.renderMinY; + final double oldMinZ = renderer.renderMinZ; + final double oldMaxX = renderer.renderMaxX; + final double oldMaxY = renderer.renderMaxY; + final double oldMaxZ = renderer.renderMaxZ; + + renderer.renderMinX = Math.max(renderer.renderMinX, minX); + renderer.renderMinY = Math.max(renderer.renderMinY, minY); + renderer.renderMinZ = Math.max(renderer.renderMinZ, minZ); + renderer.renderMaxX = Math.min(renderer.renderMaxX, maxX); + renderer.renderMaxY = Math.min(renderer.renderMaxY, maxY); + renderer.renderMaxZ = Math.min(renderer.renderMaxZ, maxZ); + + // don't draw it if its not at least a pixel wide... + if (renderer.renderMaxX - renderer.renderMinX >= 1.0 / 16.0 + && renderer.renderMaxY - renderer.renderMinY >= 1.0 / 16.0 + && renderer.renderMaxZ - renderer.renderMinZ >= 1.0 / 16.0) { + instance.renderBlockCurrentBounds(x, y, z, renderer); + } + + renderer.renderMinX = oldMinX; + renderer.renderMinY = oldMinY; + renderer.renderMinZ = oldMinZ; + renderer.renderMaxX = oldMaxX; + renderer.renderMaxY = oldMaxY; + renderer.renderMaxZ = oldMaxZ; + } + + private boolean hasAlphaDiff(final TileEntity tileEntity, final ForgeDirection side, final IFacadePart facade) { + if (tileEntity instanceof IPartHost) { + final IPartHost ph = (IPartHost) tileEntity; + final IFacadePart fp = ph.getFacadeContainer().getFacade(side); + + return fp == null || (fp.isTransparent() != facade.isTransparent()); + } + + return true; + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + this.getBoxes(bch, null); + } } diff --git a/src/main/java/appeng/facade/IFacadeItem.java b/src/main/java/appeng/facade/IFacadeItem.java index 39c4baede46..4fd42d3df72 100644 --- a/src/main/java/appeng/facade/IFacadeItem.java +++ b/src/main/java/appeng/facade/IFacadeItem.java @@ -18,20 +18,17 @@ package appeng.facade; - import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; +public interface IFacadeItem { -public interface IFacadeItem -{ - - FacadePart createPartFromItemStack( ItemStack is, ForgeDirection side ); + FacadePart createPartFromItemStack(ItemStack is, ForgeDirection side); - ItemStack getTextureItem( ItemStack is ); + ItemStack getTextureItem(ItemStack is); - int getMeta( ItemStack is ); + int getMeta(ItemStack is); - Block getBlock( ItemStack is ); + Block getBlock(ItemStack is); } diff --git a/src/main/java/appeng/fmp/CableBusPart.java b/src/main/java/appeng/fmp/CableBusPart.java index 9d670555a8b..804dde1ca15 100644 --- a/src/main/java/appeng/fmp/CableBusPart.java +++ b/src/main/java/appeng/fmp/CableBusPart.java @@ -18,7 +18,6 @@ package appeng.fmp; - import appeng.api.implementations.parts.IPartCable; import appeng.api.networking.IGridNode; import appeng.api.parts.*; @@ -45,6 +44,8 @@ import codechicken.multipart.scalatraits.TIInventoryTile; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import java.io.IOException; +import java.util.*; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -55,636 +56,532 @@ import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; -import java.util.*; - - /** * Implementing these might help improve visuals for hollow covers *

* TSlottedPart,ISidedHollowConnect */ -public class CableBusPart extends JCuboidPart implements JNormalOcclusion, IMaskedRedstonePart, AEMultiTile -{ - private static final ThreadLocal DISABLE_FACADE_OCCLUSION = new ThreadLocal(); - private static final double SHORTER = 6.0 / 16.0; - private static final double LONGER = 10.0 / 16.0; - private static final double MIN_DIRECTION = 0; - private static final double MAX_DIRECTION = 1.0; - private static final Cuboid6[] SIDE_TESTS = { - - // DOWN(0, -1, 0), - new Cuboid6( SHORTER, MIN_DIRECTION, SHORTER, LONGER, SHORTER, LONGER ), - - // UP(0, 1, 0), - new Cuboid6( SHORTER, LONGER, SHORTER, LONGER, MAX_DIRECTION, LONGER ), - - // NORTH(0, 0, -1), - new Cuboid6( SHORTER, SHORTER, MIN_DIRECTION, LONGER, LONGER, SHORTER ), - - // SOUTH(0, 0, 1), - new Cuboid6( SHORTER, SHORTER, LONGER, LONGER, LONGER, MAX_DIRECTION ), - - // WEST(-1, 0, 0), - new Cuboid6( MIN_DIRECTION, SHORTER, SHORTER, SHORTER, LONGER, LONGER ), - - // EAST(1, 0, 0), - new Cuboid6( LONGER, SHORTER, SHORTER, MAX_DIRECTION, LONGER, LONGER ), - }; - - /** - * Mask for {@link IMaskedRedstonePart#getConnectionMask(int)} - *

- * the bits are derived from the rotation, where 4 is the center - */ - private static final int CONNECTION_MASK = 0x000010; - private CableBusContainer cb = new CableBusContainer( this ); - private boolean canUpdate = false; - - @Override - public boolean recolourBlock( final ForgeDirection side, final AEColor colour, final EntityPlayer who ) - { - return this.getCableBus().recolourBlock( side, colour, who ); - } - - @Override - public Cuboid6 getBounds() - { - AxisAlignedBB b = null; - - for( final AxisAlignedBB bx : this.getCableBus().getSelectedBoundingBoxesFromPool( false, true, null, true ) ) - { - if( b == null ) - { - b = bx; - } - else - { - final double minX = Math.min( b.minX, bx.minX ); - final double minY = Math.min( b.minY, bx.minY ); - final double minZ = Math.min( b.minZ, bx.minZ ); - final double maxX = Math.max( b.maxX, bx.maxX ); - final double maxY = Math.max( b.maxY, bx.maxY ); - final double maxZ = Math.max( b.maxZ, bx.maxZ ); - b.setBounds( minX, minY, minZ, maxX, maxY, maxZ ); - } - } - - if( b == null ) - { - return new Cuboid6( 0.0, 0.0, 0.0, 1.0, 1.0, 1.0 ); - } - - return new Cuboid6( b.minX, b.minY, b.minZ, b.maxX, b.maxY, b.maxZ ); - } - - @Override - public String getType() - { - return PartRegistry.CableBusPart.getName(); - } - - @Override - public int getLightValue() - { - return this.getCableBus().getLightValue(); - } - - @Override - public void onWorldJoin() - { - this.canUpdate = true; - this.getCableBus().updateConnections(); - this.getCableBus().addToWorld(); - } - - @Override - public boolean occlusionTest( final TMultiPart part ) - { - return NormalOcclusionTest.apply( this, part ); - } - - @Override - public boolean renderStatic( final Vector3 pos, final int pass ) - { - if( pass == 0 || ( pass == 1 && AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) ) ) - { - BusRenderHelper.INSTANCE.setPass( pass ); - BusRenderer.INSTANCE.getRenderer().renderAllFaces = true; - BusRenderer.INSTANCE.getRenderer().blockAccess = this.world(); - BusRenderer.INSTANCE.getRenderer().overrideBlockTexture = null; - this.getCableBus().renderStatic( pos.x, pos.y, pos.z ); - return BusRenderHelper.INSTANCE.getItemsRendered() > 0; - } - return false; - } - - @Override - public void renderDynamic( final Vector3 pos, final float frame, final int pass ) - { - if( pass == 0 || ( pass == 1 && AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) ) ) - { - BusRenderHelper.INSTANCE.setPass( pass ); - this.getCableBus().renderDynamic( pos.x, pos.y, pos.z ); - } - } - - @Override - public void onPartChanged( final TMultiPart part ) - { - this.getCableBus().updateConnections(); - } - - @Override - public void onEntityCollision( final Entity entity ) - { - this.getCableBus().onEntityCollision( entity ); - } - - @Override - public boolean activate( final EntityPlayer player, final MovingObjectPosition hit, final ItemStack item ) - { - return this.getCableBus().activate( player, hit.hitVec.addVector( -hit.blockX, -hit.blockY, -hit.blockZ ) ); - } - - @Override - public void load( final NBTTagCompound tag ) - { - this.getCableBus().readFromNBT( tag ); - } - - @Override - public void onWorldSeparate() - { - this.canUpdate = false; - this.getCableBus().removeFromWorld(); - } - - @Override - public void save( final NBTTagCompound tag ) - { - this.getCableBus().writeToNBT( tag ); - } - - @Override - public void writeDesc( final MCDataOutput packet ) - { - final ByteBuf stream = Unpooled.buffer(); - - try - { - this.getCableBus().writeToStream( stream ); - packet.writeInt( stream.readableBytes() ); - stream.capacity( stream.readableBytes() ); - packet.writeByteArray( stream.array() ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - - @Override - public ItemStack pickItem( final MovingObjectPosition hit ) - { - final Vec3 v3 = hit.hitVec.addVector( -hit.blockX, -hit.blockY, -hit.blockZ ); - final SelectedPart sp = this.getCableBus().selectPart( v3 ); - if( sp != null ) - { - if( sp.part != null ) - { - return sp.part.getItemStack( PartItemStack.Break ); - } - if( sp.facade != null ) - { - return sp.facade.getItemStack(); - } - } - return null; - } - - @Override - public Iterable getDrops() - { - return this.getCableBus().getDrops( new ArrayList() ); - } - - @Override - public void onNeighborChanged() - { - this.getCableBus().onNeighborChanged(); - } - - @Override - public boolean doesTick() - { - return false; - } - - @Override - public void invalidateConvertedTile() - { - this.getCableBus().setHost( this ); - } - - @Override - public void readDesc( final MCDataInput packet ) - { - final int len = packet.readInt(); - final byte[] data = packet.readByteArray( len ); - - try - { - if( len > 0 ) - { - final ByteBuf byteBuffer = Unpooled.wrappedBuffer( data ); - this.getCableBus().readFromStream( byteBuffer ); - } - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - - @Override - public boolean canConnectRedstone( final int side ) - { - return this.getCableBus().canConnectRedstone( EnumSet.of( ForgeDirection.getOrientation( side ) ) ); - } - - @Override - public int weakPowerLevel( final int side ) - { - return this.getCableBus().isProvidingWeakPower( ForgeDirection.getOrientation( side ) ); - } - - @Override - public int strongPowerLevel( final int side ) - { - return this.getCableBus().isProvidingStrongPower( ForgeDirection.getOrientation( side ) ); - } - - public void convertFromTile( final TileEntity blockTileEntity ) - { - final TileCableBus tcb = (TileCableBus) blockTileEntity; - this.setCableBus( tcb.getCableBus() ); - } - - @Override - public Iterable getOcclusionBoxes() - { - final LinkedList l = new LinkedList(); - for( final AxisAlignedBB b : this.getCableBus().getSelectedBoundingBoxesFromPool( true, DISABLE_FACADE_OCCLUSION.get() == null, null, true ) ) - { - l.add( new Cuboid6( b.minX, b.minY, b.minZ, b.maxX, b.maxY, b.maxZ ) ); - } - return l; - } - - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - return this.getCableBus().getGridNode( dir ); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return this.getCableBus().getCableConnectionType( dir ); - } - - @Override - public void securityBreak() - { - this.getCableBus().securityBreak(); - } - - // @Override - public int getHollowSize( final int side ) - { - final IPartCable cable = (IPartCable) this.getPart( ForgeDirection.UNKNOWN ); - - final ForgeDirection dir = ForgeDirection.getOrientation( side ); - if( cable != null && cable.isConnected( dir ) ) - { - final List boxes = new ArrayList(); - - final BusCollisionHelper bch = new BusCollisionHelper( boxes, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH, null, true ); - - for( final ForgeDirection whichSide : ForgeDirection.values() ) - { - final IPart fPart = this.getPart( whichSide ); - - if( fPart != null ) - { - fPart.getBoxes( bch ); - } - } - - AxisAlignedBB b = null; - final AxisAlignedBB pb = Platform.getPrimaryBox( dir, 2 ); - - for( final AxisAlignedBB bb : boxes ) - { - if( bb.intersectsWith( pb ) ) - { - if( b == null ) - { - b = bb; - } - else - { - b.maxX = Math.max( b.maxX, bb.maxX ); - b.maxY = Math.max( b.maxY, bb.maxY ); - b.maxZ = Math.max( b.maxZ, bb.maxZ ); - b.minX = Math.min( b.minX, bb.minX ); - b.minY = Math.min( b.minY, bb.minY ); - b.minZ = Math.min( b.minZ, bb.minZ ); - } - } - } - - if( b == null ) - { - return 0; - } - - switch( dir ) - { - case WEST: - case EAST: - return this.getSize( b.minZ, b.maxZ, b.minY, b.maxY ); - case DOWN: - case NORTH: - return this.getSize( b.minX, b.maxX, b.minZ, b.maxZ ); - case SOUTH: - case UP: - return this.getSize( b.minX, b.maxX, b.minY, b.maxY ); - default: - } - } - - return 12; - } - - private int getSize( final double a, final double b, final double c, final double d ) - { - double r = Math.abs( a - 0.5 ); - r = Math.max( Math.abs( b - 0.5 ), r ); - r = Math.max( Math.abs( c - 0.5 ), r ); - return ( 8 * (int) Math.max( Math.abs( d - 0.5 ), r ) ); - } - - // @Override - public int getSlotMask() - { - int mask = 0; - - for( final ForgeDirection side : ForgeDirection.values() ) - { - if( this.getPart( side ) != null ) - { - mask |= 1 << side.ordinal(); - } - else if( side != ForgeDirection.UNKNOWN && this.getFacadeContainer().getFacade( side ) != null ) - { - mask |= 1 << side.ordinal(); - } - } - - return mask; - } - - @Override - public IFacadeContainer getFacadeContainer() - { - return this.getCableBus().getFacadeContainer(); - } - - @Override - public boolean canAddPart( ItemStack is, final ForgeDirection side ) - { - final IFacadePart fp = PartPlacement.isFacade( is, side ); - if( fp != null ) - { - if( !( side == null || side == ForgeDirection.UNKNOWN || this.tile() == null ) ) - { - final List boxes = new ArrayList(); - final IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); - fp.getBoxes( bch, null ); - for( final AxisAlignedBB bb : boxes ) - { - DISABLE_FACADE_OCCLUSION.set( true ); - final boolean canAdd = this.tile().canAddPart( new NormallyOccludedPart( new Cuboid6( bb ) ) ); - DISABLE_FACADE_OCCLUSION.remove(); - if( !canAdd ) - { - return false; - } - } - } - return true; - } - - if( is.getItem() instanceof IPartItem ) - { - final IPartItem bi = (IPartItem) is.getItem(); - - is = is.copy(); - is.stackSize = 1; - - final IPart bp = bi.createPartFromItemStack( is ); - if( !( side == null || side == ForgeDirection.UNKNOWN || this.tile() == null ) ) - { - final List boxes = new ArrayList(); - final IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); - if( bp != null ) - { - bp.getBoxes( bch ); - } - for( final AxisAlignedBB bb : boxes ) - { - if( !this.tile().canAddPart( new NormallyOccludedPart( new Cuboid6( bb ) ) ) ) - { - return false; - } - } - } - } - - return this.getCableBus().canAddPart( is, side ); - } - - @Override - public ForgeDirection addPart( final ItemStack is, final ForgeDirection side, final EntityPlayer owner ) - { - return this.getCableBus().addPart( is, side, owner ); - } - - @Override - public IPart getPart( final ForgeDirection side ) - { - return this.getCableBus().getPart( side ); - } - - @Override - public void removePart( final ForgeDirection side, final boolean suppressUpdate ) - { - this.getCableBus().removePart( side, suppressUpdate ); - } - - @Override - public void markForUpdate() - { - if( Platform.isServer() && this.canUpdate ) - { - this.sendDescUpdate(); - } - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this.tile() ); - } - - @Override - public AEColor getColor() - { - return this.getCableBus().getColor(); - } - - @Override - public void clearContainer() - { - this.setCableBus( new CableBusContainer( this ) ); - } - - @Override - public boolean isBlocked( final ForgeDirection side ) - { - if( side == null || side == ForgeDirection.UNKNOWN || this.tile() == null ) - { - return false; - } - - DISABLE_FACADE_OCCLUSION.set( true ); - - final int ordinal = side.ordinal(); - final Cuboid6 sideTest = SIDE_TESTS[ordinal]; - final NormallyOccludedPart occludedPart = new NormallyOccludedPart( sideTest ); - final boolean blocked = !this.tile().canAddPart( occludedPart ); - DISABLE_FACADE_OCCLUSION.remove(); - - return blocked; - } - - @Override - public SelectedPart selectPart( final Vec3 pos ) - { - return this.getCableBus().selectPart( pos ); - } - - @Override - public void markForSave() - { - // mark the chunk for save... - final TileEntity te = this.tile(); - if( te != null && te.getWorldObj() != null ) - { - te.getWorldObj().getChunkFromBlockCoords( this.x(), this.z() ).isModified = true; - } - } - - @Override - public void partChanged() - { - if( this.isInWorld() ) - { - this.notifyNeighbors(); - } - } - - @Override - public boolean hasRedstone( final ForgeDirection side ) - { - return this.getCableBus().hasRedstone( side ); - } - - @Override - public boolean isEmpty() - { - return this.getCableBus().isEmpty(); - } - - @Override - public Set getLayerFlags() - { - return this.getCableBus().getLayerFlags(); - } - - @Override - public void cleanup() - { - this.tile().remPart( this ); - } - - @Override - public void notifyNeighbors() - { - if( this.tile() instanceof TIInventoryTile ) - { - ( (TIInventoryTile) this.tile() ).rebuildSlotMap(); - } - - if( this.world() != null && this.world().blockExists( this.x(), this.y(), this.z() ) && !CableBusContainer.isLoading() ) - { - Platform.notifyBlocksOfNeighbors( this.world(), this.x(), this.y(), this.z() ); - } - } - - @Override - public boolean isInWorld() - { - return this.getCableBus().isInWorld(); - } - - @Override - public Iterable getCollisionBoxes() - { - final LinkedList l = new LinkedList(); - for( final AxisAlignedBB b : this.getCableBus().getSelectedBoundingBoxesFromPool( false, true, null, true ) ) - { - l.add( new Cuboid6( b.minX, b.minY, b.minZ, b.maxX, b.maxY, b.maxZ ) ); - } - return l; - } - - @Override - public Iterable getSubParts() - { - final LinkedList l = new LinkedList(); - for( final Cuboid6 c : this.getCollisionBoxes() ) - { - l.add( new IndexedCuboid6( 0, c ) ); - } - return l; - } - - @Override - public int getConnectionMask( final int side ) - { - return CONNECTION_MASK; - } - - public CableBusContainer getCableBus() - { - return this.cb; - } - - private void setCableBus( final CableBusContainer cb ) - { - this.cb = cb; - } +public class CableBusPart extends JCuboidPart implements JNormalOcclusion, IMaskedRedstonePart, AEMultiTile { + private static final ThreadLocal DISABLE_FACADE_OCCLUSION = new ThreadLocal(); + private static final double SHORTER = 6.0 / 16.0; + private static final double LONGER = 10.0 / 16.0; + private static final double MIN_DIRECTION = 0; + private static final double MAX_DIRECTION = 1.0; + private static final Cuboid6[] SIDE_TESTS = { + + // DOWN(0, -1, 0), + new Cuboid6(SHORTER, MIN_DIRECTION, SHORTER, LONGER, SHORTER, LONGER), + + // UP(0, 1, 0), + new Cuboid6(SHORTER, LONGER, SHORTER, LONGER, MAX_DIRECTION, LONGER), + + // NORTH(0, 0, -1), + new Cuboid6(SHORTER, SHORTER, MIN_DIRECTION, LONGER, LONGER, SHORTER), + + // SOUTH(0, 0, 1), + new Cuboid6(SHORTER, SHORTER, LONGER, LONGER, LONGER, MAX_DIRECTION), + + // WEST(-1, 0, 0), + new Cuboid6(MIN_DIRECTION, SHORTER, SHORTER, SHORTER, LONGER, LONGER), + + // EAST(1, 0, 0), + new Cuboid6(LONGER, SHORTER, SHORTER, MAX_DIRECTION, LONGER, LONGER), + }; + + /** + * Mask for {@link IMaskedRedstonePart#getConnectionMask(int)} + *

+ * the bits are derived from the rotation, where 4 is the center + */ + private static final int CONNECTION_MASK = 0x000010; + + private CableBusContainer cb = new CableBusContainer(this); + private boolean canUpdate = false; + + @Override + public boolean recolourBlock(final ForgeDirection side, final AEColor colour, final EntityPlayer who) { + return this.getCableBus().recolourBlock(side, colour, who); + } + + @Override + public Cuboid6 getBounds() { + AxisAlignedBB b = null; + + for (final AxisAlignedBB bx : this.getCableBus().getSelectedBoundingBoxesFromPool(false, true, null, true)) { + if (b == null) { + b = bx; + } else { + final double minX = Math.min(b.minX, bx.minX); + final double minY = Math.min(b.minY, bx.minY); + final double minZ = Math.min(b.minZ, bx.minZ); + final double maxX = Math.max(b.maxX, bx.maxX); + final double maxY = Math.max(b.maxY, bx.maxY); + final double maxZ = Math.max(b.maxZ, bx.maxZ); + b.setBounds(minX, minY, minZ, maxX, maxY, maxZ); + } + } + + if (b == null) { + return new Cuboid6(0.0, 0.0, 0.0, 1.0, 1.0, 1.0); + } + + return new Cuboid6(b.minX, b.minY, b.minZ, b.maxX, b.maxY, b.maxZ); + } + + @Override + public String getType() { + return PartRegistry.CableBusPart.getName(); + } + + @Override + public int getLightValue() { + return this.getCableBus().getLightValue(); + } + + @Override + public void onWorldJoin() { + this.canUpdate = true; + this.getCableBus().updateConnections(); + this.getCableBus().addToWorld(); + } + + @Override + public boolean occlusionTest(final TMultiPart part) { + return NormalOcclusionTest.apply(this, part); + } + + @Override + public boolean renderStatic(final Vector3 pos, final int pass) { + if (pass == 0 || (pass == 1 && AEConfig.instance.isFeatureEnabled(AEFeature.AlphaPass))) { + BusRenderHelper.INSTANCE.setPass(pass); + BusRenderer.INSTANCE.getRenderer().renderAllFaces = true; + BusRenderer.INSTANCE.getRenderer().blockAccess = this.world(); + BusRenderer.INSTANCE.getRenderer().overrideBlockTexture = null; + this.getCableBus().renderStatic(pos.x, pos.y, pos.z); + return BusRenderHelper.INSTANCE.getItemsRendered() > 0; + } + return false; + } + + @Override + public void renderDynamic(final Vector3 pos, final float frame, final int pass) { + if (pass == 0 || (pass == 1 && AEConfig.instance.isFeatureEnabled(AEFeature.AlphaPass))) { + BusRenderHelper.INSTANCE.setPass(pass); + this.getCableBus().renderDynamic(pos.x, pos.y, pos.z); + } + } + + @Override + public void onPartChanged(final TMultiPart part) { + this.getCableBus().updateConnections(); + } + + @Override + public void onEntityCollision(final Entity entity) { + this.getCableBus().onEntityCollision(entity); + } + + @Override + public boolean activate(final EntityPlayer player, final MovingObjectPosition hit, final ItemStack item) { + return this.getCableBus().activate(player, hit.hitVec.addVector(-hit.blockX, -hit.blockY, -hit.blockZ)); + } + + @Override + public void load(final NBTTagCompound tag) { + this.getCableBus().readFromNBT(tag); + } + + @Override + public void onWorldSeparate() { + this.canUpdate = false; + this.getCableBus().removeFromWorld(); + } + + @Override + public void save(final NBTTagCompound tag) { + this.getCableBus().writeToNBT(tag); + } + + @Override + public void writeDesc(final MCDataOutput packet) { + final ByteBuf stream = Unpooled.buffer(); + + try { + this.getCableBus().writeToStream(stream); + packet.writeInt(stream.readableBytes()); + stream.capacity(stream.readableBytes()); + packet.writeByteArray(stream.array()); + } catch (final IOException e) { + AELog.debug(e); + } + } + + @Override + public ItemStack pickItem(final MovingObjectPosition hit) { + final Vec3 v3 = hit.hitVec.addVector(-hit.blockX, -hit.blockY, -hit.blockZ); + final SelectedPart sp = this.getCableBus().selectPart(v3); + if (sp != null) { + if (sp.part != null) { + return sp.part.getItemStack(PartItemStack.Break); + } + if (sp.facade != null) { + return sp.facade.getItemStack(); + } + } + return null; + } + + @Override + public Iterable getDrops() { + return this.getCableBus().getDrops(new ArrayList()); + } + + @Override + public void onNeighborChanged() { + this.getCableBus().onNeighborChanged(); + } + + @Override + public boolean doesTick() { + return false; + } + + @Override + public void invalidateConvertedTile() { + this.getCableBus().setHost(this); + } + + @Override + public void readDesc(final MCDataInput packet) { + final int len = packet.readInt(); + final byte[] data = packet.readByteArray(len); + + try { + if (len > 0) { + final ByteBuf byteBuffer = Unpooled.wrappedBuffer(data); + this.getCableBus().readFromStream(byteBuffer); + } + } catch (final IOException e) { + AELog.debug(e); + } + } + + @Override + public boolean canConnectRedstone(final int side) { + return this.getCableBus().canConnectRedstone(EnumSet.of(ForgeDirection.getOrientation(side))); + } + + @Override + public int weakPowerLevel(final int side) { + return this.getCableBus().isProvidingWeakPower(ForgeDirection.getOrientation(side)); + } + + @Override + public int strongPowerLevel(final int side) { + return this.getCableBus().isProvidingStrongPower(ForgeDirection.getOrientation(side)); + } + + public void convertFromTile(final TileEntity blockTileEntity) { + final TileCableBus tcb = (TileCableBus) blockTileEntity; + this.setCableBus(tcb.getCableBus()); + } + + @Override + public Iterable getOcclusionBoxes() { + final LinkedList l = new LinkedList(); + for (final AxisAlignedBB b : this.getCableBus() + .getSelectedBoundingBoxesFromPool(true, DISABLE_FACADE_OCCLUSION.get() == null, null, true)) { + l.add(new Cuboid6(b.minX, b.minY, b.minZ, b.maxX, b.maxY, b.maxZ)); + } + return l; + } + + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + return this.getCableBus().getGridNode(dir); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return this.getCableBus().getCableConnectionType(dir); + } + + @Override + public void securityBreak() { + this.getCableBus().securityBreak(); + } + + // @Override + public int getHollowSize(final int side) { + final IPartCable cable = (IPartCable) this.getPart(ForgeDirection.UNKNOWN); + + final ForgeDirection dir = ForgeDirection.getOrientation(side); + if (cable != null && cable.isConnected(dir)) { + final List boxes = new ArrayList(); + + final BusCollisionHelper bch = new BusCollisionHelper( + boxes, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH, null, true); + + for (final ForgeDirection whichSide : ForgeDirection.values()) { + final IPart fPart = this.getPart(whichSide); + + if (fPart != null) { + fPart.getBoxes(bch); + } + } + + AxisAlignedBB b = null; + final AxisAlignedBB pb = Platform.getPrimaryBox(dir, 2); + + for (final AxisAlignedBB bb : boxes) { + if (bb.intersectsWith(pb)) { + if (b == null) { + b = bb; + } else { + b.maxX = Math.max(b.maxX, bb.maxX); + b.maxY = Math.max(b.maxY, bb.maxY); + b.maxZ = Math.max(b.maxZ, bb.maxZ); + b.minX = Math.min(b.minX, bb.minX); + b.minY = Math.min(b.minY, bb.minY); + b.minZ = Math.min(b.minZ, bb.minZ); + } + } + } + + if (b == null) { + return 0; + } + + switch (dir) { + case WEST: + case EAST: + return this.getSize(b.minZ, b.maxZ, b.minY, b.maxY); + case DOWN: + case NORTH: + return this.getSize(b.minX, b.maxX, b.minZ, b.maxZ); + case SOUTH: + case UP: + return this.getSize(b.minX, b.maxX, b.minY, b.maxY); + default: + } + } + + return 12; + } + + private int getSize(final double a, final double b, final double c, final double d) { + double r = Math.abs(a - 0.5); + r = Math.max(Math.abs(b - 0.5), r); + r = Math.max(Math.abs(c - 0.5), r); + return (8 * (int) Math.max(Math.abs(d - 0.5), r)); + } + + // @Override + public int getSlotMask() { + int mask = 0; + + for (final ForgeDirection side : ForgeDirection.values()) { + if (this.getPart(side) != null) { + mask |= 1 << side.ordinal(); + } else if (side != ForgeDirection.UNKNOWN + && this.getFacadeContainer().getFacade(side) != null) { + mask |= 1 << side.ordinal(); + } + } + + return mask; + } + + @Override + public IFacadeContainer getFacadeContainer() { + return this.getCableBus().getFacadeContainer(); + } + + @Override + public boolean canAddPart(ItemStack is, final ForgeDirection side) { + final IFacadePart fp = PartPlacement.isFacade(is, side); + if (fp != null) { + if (!(side == null || side == ForgeDirection.UNKNOWN || this.tile() == null)) { + final List boxes = new ArrayList(); + final IPartCollisionHelper bch = new BusCollisionHelper(boxes, side, null, true); + fp.getBoxes(bch, null); + for (final AxisAlignedBB bb : boxes) { + DISABLE_FACADE_OCCLUSION.set(true); + final boolean canAdd = this.tile().canAddPart(new NormallyOccludedPart(new Cuboid6(bb))); + DISABLE_FACADE_OCCLUSION.remove(); + if (!canAdd) { + return false; + } + } + } + return true; + } + + if (is.getItem() instanceof IPartItem) { + final IPartItem bi = (IPartItem) is.getItem(); + + is = is.copy(); + is.stackSize = 1; + + final IPart bp = bi.createPartFromItemStack(is); + if (!(side == null || side == ForgeDirection.UNKNOWN || this.tile() == null)) { + final List boxes = new ArrayList(); + final IPartCollisionHelper bch = new BusCollisionHelper(boxes, side, null, true); + if (bp != null) { + bp.getBoxes(bch); + } + for (final AxisAlignedBB bb : boxes) { + if (!this.tile().canAddPart(new NormallyOccludedPart(new Cuboid6(bb)))) { + return false; + } + } + } + } + + return this.getCableBus().canAddPart(is, side); + } + + @Override + public ForgeDirection addPart(final ItemStack is, final ForgeDirection side, final EntityPlayer owner) { + return this.getCableBus().addPart(is, side, owner); + } + + @Override + public IPart getPart(final ForgeDirection side) { + return this.getCableBus().getPart(side); + } + + @Override + public void removePart(final ForgeDirection side, final boolean suppressUpdate) { + this.getCableBus().removePart(side, suppressUpdate); + } + + @Override + public void markForUpdate() { + if (Platform.isServer() && this.canUpdate) { + this.sendDescUpdate(); + } + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this.tile()); + } + + @Override + public AEColor getColor() { + return this.getCableBus().getColor(); + } + + @Override + public void clearContainer() { + this.setCableBus(new CableBusContainer(this)); + } + + @Override + public boolean isBlocked(final ForgeDirection side) { + if (side == null || side == ForgeDirection.UNKNOWN || this.tile() == null) { + return false; + } + + DISABLE_FACADE_OCCLUSION.set(true); + + final int ordinal = side.ordinal(); + final Cuboid6 sideTest = SIDE_TESTS[ordinal]; + final NormallyOccludedPart occludedPart = new NormallyOccludedPart(sideTest); + final boolean blocked = !this.tile().canAddPart(occludedPart); + DISABLE_FACADE_OCCLUSION.remove(); + + return blocked; + } + + @Override + public SelectedPart selectPart(final Vec3 pos) { + return this.getCableBus().selectPart(pos); + } + + @Override + public void markForSave() { + // mark the chunk for save... + final TileEntity te = this.tile(); + if (te != null && te.getWorldObj() != null) { + te.getWorldObj().getChunkFromBlockCoords(this.x(), this.z()).isModified = true; + } + } + + @Override + public void partChanged() { + if (this.isInWorld()) { + this.notifyNeighbors(); + } + } + + @Override + public boolean hasRedstone(final ForgeDirection side) { + return this.getCableBus().hasRedstone(side); + } + + @Override + public boolean isEmpty() { + return this.getCableBus().isEmpty(); + } + + @Override + public Set getLayerFlags() { + return this.getCableBus().getLayerFlags(); + } + + @Override + public void cleanup() { + this.tile().remPart(this); + } + + @Override + public void notifyNeighbors() { + if (this.tile() instanceof TIInventoryTile) { + ((TIInventoryTile) this.tile()).rebuildSlotMap(); + } + + if (this.world() != null + && this.world().blockExists(this.x(), this.y(), this.z()) + && !CableBusContainer.isLoading()) { + Platform.notifyBlocksOfNeighbors(this.world(), this.x(), this.y(), this.z()); + } + } + + @Override + public boolean isInWorld() { + return this.getCableBus().isInWorld(); + } + + @Override + public Iterable getCollisionBoxes() { + final LinkedList l = new LinkedList(); + for (final AxisAlignedBB b : this.getCableBus().getSelectedBoundingBoxesFromPool(false, true, null, true)) { + l.add(new Cuboid6(b.minX, b.minY, b.minZ, b.maxX, b.maxY, b.maxZ)); + } + return l; + } + + @Override + public Iterable getSubParts() { + final LinkedList l = new LinkedList(); + for (final Cuboid6 c : this.getCollisionBoxes()) { + l.add(new IndexedCuboid6(0, c)); + } + return l; + } + + @Override + public int getConnectionMask(final int side) { + return CONNECTION_MASK; + } + + public CableBusContainer getCableBus() { + return this.cb; + } + + private void setCableBus(final CableBusContainer cb) { + this.cb = cb; + } } diff --git a/src/main/java/appeng/fmp/FMPEvent.java b/src/main/java/appeng/fmp/FMPEvent.java index 002c3c1e6ab..102b48ac97c 100644 --- a/src/main/java/appeng/fmp/FMPEvent.java +++ b/src/main/java/appeng/fmp/FMPEvent.java @@ -18,7 +18,6 @@ package appeng.fmp; - import appeng.block.AEBaseItemBlock; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketMultiPart; @@ -42,115 +41,120 @@ import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; - /** * Basically a total rip of of the FMP version for vanilla, seemed to work well enough... */ -public class FMPEvent -{ - - private final ThreadLocal placing = new ThreadLocal(); - - @SubscribeEvent - public void ServerFMPEvent( final FMPPacketEvent event ) - { - FMPEvent.place( event.getSender(), event.getSender().worldObj ); - } - - private static boolean place( final EntityPlayer player, final World world ) - { - final MovingObjectPosition hit = RayTracer.reTrace( world, player ); - if( hit == null ) - { - return false; - } - - final BlockCoord pos = new BlockCoord( hit.blockX, hit.blockY, hit.blockZ ).offset( hit.sideHit ); - final ItemStack held = player.getHeldItem(); - - if( held == null ) - { - return false; - } - - Block blk = null; - TMultiPart part = null; - if( held.getItem() instanceof AEBaseItemBlock ) - { - final AEBaseItemBlock ib = (AEBaseItemBlock) held.getItem(); - blk = Block.getBlockFromItem( ib ); - part = PartRegistry.getPartByBlock( blk, hit.sideHit ); - } - - if( part == null ) - { - return false; - } - - if( world.isRemote && !player.isSneaking() )// attempt to use block activated like normal and tell the server - // the right stuff - { - final Vector3 f = new Vector3( hit.hitVec ).add( -hit.blockX, -hit.blockY, -hit.blockZ ); - final Block block = world.getBlock( hit.blockX, hit.blockY, hit.blockZ ); - if( block != null && !ignoreActivate( block ) && block.onBlockActivated( world, hit.blockX, hit.blockY, hit.blockZ, player, hit.sideHit, (float) f.x, (float) f.y, (float) f.z ) ) - { - player.swingItem(); - PacketCustom.sendToServer( new C08PacketPlayerBlockPlacement( hit.blockX, hit.blockY, hit.blockZ, hit.sideHit, player.inventory.getCurrentItem(), (float) f.x, (float) f.y, (float) f.z ) ); - return true; - } - } - - final TileMultipart tile = TileMultipart.getOrConvertTile( world, pos ); - if( tile == null || !tile.canAddPart( part ) ) - { - return false; - } - - if( !world.isRemote ) - { - TileMultipart.addPart( world, pos, part ); - world.playSoundEffect( pos.x + 0.5, pos.y + 0.5, pos.z + 0.5, blk.stepSound.func_150496_b(), ( blk.stepSound.getVolume() + 1.0F ) / 2.0F, blk.stepSound.getPitch() * 0.8F ); - if( !player.capabilities.isCreativeMode ) - { - held.stackSize--; - if( held.stackSize == 0 ) - { - player.inventory.mainInventory[player.inventory.currentItem] = null; - MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( player, held ) ); - } - } - } - else - { - player.swingItem(); - NetworkHandler.instance.sendToServer( new PacketMultiPart() ); - } - return true; - } - - /** - * Because vanilla is weird. - */ - private static boolean ignoreActivate( final Block block ) - { - return block instanceof BlockFence; - } - - @SubscribeEvent - public void playerInteract( final PlayerInteractEvent event ) - { - if( event.action == Action.RIGHT_CLICK_BLOCK && event.entityPlayer.worldObj.isRemote ) - { - if( this.placing.get() != null ) - { - return; - } - this.placing.set( event ); - if( place( event.entityPlayer, event.entityPlayer.worldObj ) ) - { - event.setCanceled( true ); - } - this.placing.set( null ); - } - } +public class FMPEvent { + + private final ThreadLocal placing = new ThreadLocal(); + + @SubscribeEvent + public void ServerFMPEvent(final FMPPacketEvent event) { + FMPEvent.place(event.getSender(), event.getSender().worldObj); + } + + private static boolean place(final EntityPlayer player, final World world) { + final MovingObjectPosition hit = RayTracer.reTrace(world, player); + if (hit == null) { + return false; + } + + final BlockCoord pos = new BlockCoord(hit.blockX, hit.blockY, hit.blockZ).offset(hit.sideHit); + final ItemStack held = player.getHeldItem(); + + if (held == null) { + return false; + } + + Block blk = null; + TMultiPart part = null; + if (held.getItem() instanceof AEBaseItemBlock) { + final AEBaseItemBlock ib = (AEBaseItemBlock) held.getItem(); + blk = Block.getBlockFromItem(ib); + part = PartRegistry.getPartByBlock(blk, hit.sideHit); + } + + if (part == null) { + return false; + } + + if (world.isRemote && !player.isSneaking()) // attempt to use block activated like normal and tell the server + // the right stuff + { + final Vector3 f = new Vector3(hit.hitVec).add(-hit.blockX, -hit.blockY, -hit.blockZ); + final Block block = world.getBlock(hit.blockX, hit.blockY, hit.blockZ); + if (block != null + && !ignoreActivate(block) + && block.onBlockActivated( + world, + hit.blockX, + hit.blockY, + hit.blockZ, + player, + hit.sideHit, + (float) f.x, + (float) f.y, + (float) f.z)) { + player.swingItem(); + PacketCustom.sendToServer(new C08PacketPlayerBlockPlacement( + hit.blockX, + hit.blockY, + hit.blockZ, + hit.sideHit, + player.inventory.getCurrentItem(), + (float) f.x, + (float) f.y, + (float) f.z)); + return true; + } + } + + final TileMultipart tile = TileMultipart.getOrConvertTile(world, pos); + if (tile == null || !tile.canAddPart(part)) { + return false; + } + + if (!world.isRemote) { + TileMultipart.addPart(world, pos, part); + world.playSoundEffect( + pos.x + 0.5, + pos.y + 0.5, + pos.z + 0.5, + blk.stepSound.func_150496_b(), + (blk.stepSound.getVolume() + 1.0F) / 2.0F, + blk.stepSound.getPitch() * 0.8F); + if (!player.capabilities.isCreativeMode) { + held.stackSize--; + if (held.stackSize == 0) { + player.inventory.mainInventory[player.inventory.currentItem] = null; + MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(player, held)); + } + } + } else { + player.swingItem(); + NetworkHandler.instance.sendToServer(new PacketMultiPart()); + } + return true; + } + + /** + * Because vanilla is weird. + */ + private static boolean ignoreActivate(final Block block) { + return block instanceof BlockFence; + } + + @SubscribeEvent + public void playerInteract(final PlayerInteractEvent event) { + if (event.action == Action.RIGHT_CLICK_BLOCK && event.entityPlayer.worldObj.isRemote) { + if (this.placing.get() != null) { + return; + } + this.placing.set(event); + if (place(event.entityPlayer, event.entityPlayer.worldObj)) { + event.setCanceled(true); + } + this.placing.set(null); + } + } } diff --git a/src/main/java/appeng/fmp/FMPPlacementHelper.java b/src/main/java/appeng/fmp/FMPPlacementHelper.java index 89639d3d08f..9b20970f34f 100644 --- a/src/main/java/appeng/fmp/FMPPlacementHelper.java +++ b/src/main/java/appeng/fmp/FMPPlacementHelper.java @@ -18,7 +18,6 @@ package appeng.fmp; - import appeng.api.parts.*; import appeng.api.util.AEColor; import appeng.api.util.DimensionalCoord; @@ -28,291 +27,237 @@ import codechicken.lib.vec.BlockCoord; import codechicken.multipart.TMultiPart; import codechicken.multipart.TileMultipart; +import java.util.EnumSet; +import java.util.Set; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.Set; - - -public class FMPPlacementHelper implements IPartHost -{ - - private static final CableBusStorage NULL_STORAGE = new NullStorage(); - private boolean hasPart = false; - private TileMultipart myMP; - private CableBusPart myPart; - - public FMPPlacementHelper( final TileMultipart mp ) - { - this.myMP = mp; - } - - @Override - public IFacadeContainer getFacadeContainer() - { - if( this.myPart == null ) - { - return new FacadeContainer( NULL_STORAGE ); - } - return this.myPart.getFacadeContainer(); - } - - @Override - public boolean canAddPart( final ItemStack part, final ForgeDirection side ) - { - final CableBusPart myPart = this.getPart(); - - final boolean returnValue = this.hasPart && myPart.canAddPart( part, side ); - - this.removePart(); - - return returnValue; - } - - private CableBusPart getPart() - { - final scala.collection.Iterator i = this.myMP.partList().iterator(); - while( i.hasNext() ) - { - final TMultiPart p = i.next(); - if( p instanceof CableBusPart ) - { - this.myPart = (CableBusPart) p; - } - } - - if( this.myPart == null ) - { - this.myPart = (CableBusPart) PartRegistry.CableBusPart.construct( 0 ); - } - - final BlockCoord loc = new BlockCoord( this.myMP.xCoord, this.myMP.yCoord, this.myMP.zCoord ); - - if( this.myMP.canAddPart( this.myPart ) && Platform.isServer() ) - { - this.myMP = TileMultipart.addPart( this.myMP.getWorldObj(), loc, this.myPart ); - this.hasPart = true; - } - - return this.myPart; - } - - private void removePart() - { - if( this.myPart.isEmpty() ) - { - final scala.collection.Iterator i = this.myMP.partList().iterator(); - while( i.hasNext() ) - { - final TMultiPart p = i.next(); - if( p == this.myPart ) - { - this.myMP = this.myMP.remPart( this.myPart ); - break; - } - } - this.hasPart = false; - this.myPart = null; - } - } - - @Override - public ForgeDirection addPart( final ItemStack is, final ForgeDirection side, final EntityPlayer owner ) - { - final CableBusPart myPart = this.getPart(); - - final ForgeDirection returnValue = this.hasPart ? myPart.addPart( is, side, owner ) : null; - - this.removePart(); - - return returnValue; - } - - @Override - public IPart getPart( final ForgeDirection side ) - { - if( this.myPart == null ) - { - return null; - } - return this.myPart.getPart( side ); - } - - @Override - public void removePart( final ForgeDirection side, final boolean suppressUpdate ) - { - if( this.myPart == null ) - { - return; - } - this.myPart.removePart( side, suppressUpdate ); - } - - @Override - public void markForUpdate() - { - if( this.myPart == null ) - { - return; - } - this.myPart.markForUpdate(); - } - - @Override - public DimensionalCoord getLocation() - { - if( this.myPart == null ) - { - return new DimensionalCoord( this.myMP ); - } - return this.myPart.getLocation(); - } - - @Override - public TileEntity getTile() - { - return this.myMP; - } - - @Override - public AEColor getColor() - { - if( this.myPart == null ) - { - return AEColor.Transparent; - } - return this.myPart.getColor(); - } - - @Override - public void clearContainer() - { - if( this.myPart == null ) - { - return; - } - this.myPart.clearContainer(); - } - - @Override - public boolean isBlocked( final ForgeDirection side ) - { - this.getPart(); - - final boolean returnValue = this.myPart.isBlocked( side ); - - this.removePart(); - - return returnValue; - } - - @Override - public SelectedPart selectPart( final Vec3 pos ) - { - if( this.myPart == null ) - { - return new SelectedPart(); - } - return this.myPart.selectPart( pos ); - } - - @Override - public void markForSave() - { - if( this.myPart == null ) - { - return; - } - this.myPart.markForSave(); - } - - @Override - public void partChanged() - { - if( this.myPart == null ) - { - return; - } - this.myPart.partChanged(); - } - - @Override - public boolean hasRedstone( final ForgeDirection side ) - { - if( this.myPart == null ) - { - return false; - } - return this.myPart.hasRedstone( side ); - } - - @Override - public boolean isEmpty() - { - if( this.myPart == null ) - { - return true; - } - return this.myPart.isEmpty(); - } - - @Override - public Set getLayerFlags() - { - if( this.myPart == null ) - { - return EnumSet.noneOf( LayerFlags.class ); - } - return this.myPart.getLayerFlags(); - } - - @Override - public void cleanup() - { - if( this.myPart == null ) - { - return; - } - this.myPart.cleanup(); - } - - @Override - public void notifyNeighbors() - { - if( this.myPart == null ) - { - return; - } - this.myPart.notifyNeighbors(); - } - - @Override - public boolean isInWorld() - { - if( this.myPart == null ) - { - return this.myMP.getWorldObj() != null; - } - return this.myPart.isInWorld(); - } - - private static class NullStorage extends CableBusStorage - { - - @Override - public IFacadePart getFacade( final int x ) - { - return null; - } - - @Override - public void setFacade( final int x, final IFacadePart facade ) - { - - } - } +public class FMPPlacementHelper implements IPartHost { + + private static final CableBusStorage NULL_STORAGE = new NullStorage(); + private boolean hasPart = false; + private TileMultipart myMP; + private CableBusPart myPart; + + public FMPPlacementHelper(final TileMultipart mp) { + this.myMP = mp; + } + + @Override + public IFacadeContainer getFacadeContainer() { + if (this.myPart == null) { + return new FacadeContainer(NULL_STORAGE); + } + return this.myPart.getFacadeContainer(); + } + + @Override + public boolean canAddPart(final ItemStack part, final ForgeDirection side) { + final CableBusPart myPart = this.getPart(); + + final boolean returnValue = this.hasPart && myPart.canAddPart(part, side); + + this.removePart(); + + return returnValue; + } + + private CableBusPart getPart() { + final scala.collection.Iterator i = this.myMP.partList().iterator(); + while (i.hasNext()) { + final TMultiPart p = i.next(); + if (p instanceof CableBusPart) { + this.myPart = (CableBusPart) p; + } + } + + if (this.myPart == null) { + this.myPart = (CableBusPart) PartRegistry.CableBusPart.construct(0); + } + + final BlockCoord loc = new BlockCoord(this.myMP.xCoord, this.myMP.yCoord, this.myMP.zCoord); + + if (this.myMP.canAddPart(this.myPart) && Platform.isServer()) { + this.myMP = TileMultipart.addPart(this.myMP.getWorldObj(), loc, this.myPart); + this.hasPart = true; + } + + return this.myPart; + } + + private void removePart() { + if (this.myPart.isEmpty()) { + final scala.collection.Iterator i = this.myMP.partList().iterator(); + while (i.hasNext()) { + final TMultiPart p = i.next(); + if (p == this.myPart) { + this.myMP = this.myMP.remPart(this.myPart); + break; + } + } + this.hasPart = false; + this.myPart = null; + } + } + + @Override + public ForgeDirection addPart(final ItemStack is, final ForgeDirection side, final EntityPlayer owner) { + final CableBusPart myPart = this.getPart(); + + final ForgeDirection returnValue = this.hasPart ? myPart.addPart(is, side, owner) : null; + + this.removePart(); + + return returnValue; + } + + @Override + public IPart getPart(final ForgeDirection side) { + if (this.myPart == null) { + return null; + } + return this.myPart.getPart(side); + } + + @Override + public void removePart(final ForgeDirection side, final boolean suppressUpdate) { + if (this.myPart == null) { + return; + } + this.myPart.removePart(side, suppressUpdate); + } + + @Override + public void markForUpdate() { + if (this.myPart == null) { + return; + } + this.myPart.markForUpdate(); + } + + @Override + public DimensionalCoord getLocation() { + if (this.myPart == null) { + return new DimensionalCoord(this.myMP); + } + return this.myPart.getLocation(); + } + + @Override + public TileEntity getTile() { + return this.myMP; + } + + @Override + public AEColor getColor() { + if (this.myPart == null) { + return AEColor.Transparent; + } + return this.myPart.getColor(); + } + + @Override + public void clearContainer() { + if (this.myPart == null) { + return; + } + this.myPart.clearContainer(); + } + + @Override + public boolean isBlocked(final ForgeDirection side) { + this.getPart(); + + final boolean returnValue = this.myPart.isBlocked(side); + + this.removePart(); + + return returnValue; + } + + @Override + public SelectedPart selectPart(final Vec3 pos) { + if (this.myPart == null) { + return new SelectedPart(); + } + return this.myPart.selectPart(pos); + } + + @Override + public void markForSave() { + if (this.myPart == null) { + return; + } + this.myPart.markForSave(); + } + + @Override + public void partChanged() { + if (this.myPart == null) { + return; + } + this.myPart.partChanged(); + } + + @Override + public boolean hasRedstone(final ForgeDirection side) { + if (this.myPart == null) { + return false; + } + return this.myPart.hasRedstone(side); + } + + @Override + public boolean isEmpty() { + if (this.myPart == null) { + return true; + } + return this.myPart.isEmpty(); + } + + @Override + public Set getLayerFlags() { + if (this.myPart == null) { + return EnumSet.noneOf(LayerFlags.class); + } + return this.myPart.getLayerFlags(); + } + + @Override + public void cleanup() { + if (this.myPart == null) { + return; + } + this.myPart.cleanup(); + } + + @Override + public void notifyNeighbors() { + if (this.myPart == null) { + return; + } + this.myPart.notifyNeighbors(); + } + + @Override + public boolean isInWorld() { + if (this.myPart == null) { + return this.myMP.getWorldObj() != null; + } + return this.myPart.isInWorld(); + } + + private static class NullStorage extends CableBusStorage { + + @Override + public IFacadePart getFacade(final int x) { + return null; + } + + @Override + public void setFacade(final int x, final IFacadePart facade) {} + } } diff --git a/src/main/java/appeng/fmp/PartRegistry.java b/src/main/java/appeng/fmp/PartRegistry.java index 5ecdd1c8d5a..5874e105972 100644 --- a/src/main/java/appeng/fmp/PartRegistry.java +++ b/src/main/java/appeng/fmp/PartRegistry.java @@ -18,67 +18,54 @@ package appeng.fmp; - import appeng.block.AEBaseBlock; import appeng.block.misc.BlockQuartzTorch; import appeng.block.networking.BlockCableBus; import appeng.core.Api; import codechicken.multipart.TMultiPart; -import net.minecraft.block.Block; - import javax.annotation.Nullable; +import net.minecraft.block.Block; +public enum PartRegistry { + QuartzTorchPart("ae2_torch", BlockQuartzTorch.class, QuartzTorchPart.class), + CableBusPart("ae2_cablebus", BlockCableBus.class, CableBusPart.class); -public enum PartRegistry -{ - QuartzTorchPart( "ae2_torch", BlockQuartzTorch.class, QuartzTorchPart.class ), - CableBusPart( "ae2_cablebus", BlockCableBus.class, CableBusPart.class ); - - private final String name; - private final Class blk; - private final Class part; + private final String name; + private final Class blk; + private final Class part; - PartRegistry( final String name, final Class blk, final Class part ) - { - this.name = name; - this.blk = blk; - this.part = part; - } + PartRegistry(final String name, final Class blk, final Class part) { + this.name = name; + this.blk = blk; + this.part = part; + } - @Nullable - public static TMultiPart getPartByBlock( final Block block, final int meta ) - { - for( final PartRegistry pr : values() ) - { - if( pr.blk.isInstance( block ) ) - { - return pr.construct( meta ); - } - } - return null; - } + @Nullable + public static TMultiPart getPartByBlock(final Block block, final int meta) { + for (final PartRegistry pr : values()) { + if (pr.blk.isInstance(block)) { + return pr.construct(meta); + } + } + return null; + } - public TMultiPart construct( final int meta ) - { - try - { - if( this == CableBusPart ) - { - return (TMultiPart) Api.INSTANCE.partHelper().getCombinedInstance( this.part.getName() ).newInstance(); - } - else - { - return this.part.getConstructor( int.class ).newInstance( meta ); - } - } - catch( final Throwable t ) - { - throw new IllegalStateException( t ); - } - } + public TMultiPart construct(final int meta) { + try { + if (this == CableBusPart) { + return (TMultiPart) Api.INSTANCE + .partHelper() + .getCombinedInstance(this.part.getName()) + .newInstance(); + } else { + return this.part.getConstructor(int.class).newInstance(meta); + } + } catch (final Throwable t) { + throw new IllegalStateException(t); + } + } - public String getName() - { - return this.name; - } + public String getName() { + return this.name; + } } diff --git a/src/main/java/appeng/fmp/QuartzTorchPart.java b/src/main/java/appeng/fmp/QuartzTorchPart.java index 2d02198068f..f1d00173c36 100644 --- a/src/main/java/appeng/fmp/QuartzTorchPart.java +++ b/src/main/java/appeng/fmp/QuartzTorchPart.java @@ -18,7 +18,6 @@ package appeng.fmp; - import appeng.api.AEApi; import appeng.api.exceptions.MissingDefinition; import codechicken.lib.vec.BlockCoord; @@ -26,84 +25,74 @@ import codechicken.multipart.IRandomDisplayTick; import codechicken.multipart.minecraft.McBlockPart; import codechicken.multipart.minecraft.McSidedMetaPart; +import java.util.Random; import net.minecraft.block.Block; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Random; - - -public class QuartzTorchPart extends McSidedMetaPart implements IRandomDisplayTick -{ - - public QuartzTorchPart() - { - this( ForgeDirection.DOWN.ordinal() ); - } - - public QuartzTorchPart( final int meta ) - { - super( meta ); - } - - public static McBlockPart placement( final World world, BlockCoord pos, final int side ) - { - pos = pos.copy().offset( side ); - if( !world.isSideSolid( pos.x, pos.y, pos.z, ForgeDirection.getOrientation( side ) ) ) - { - return null; - } - - return new QuartzTorchPart( side ); - } - - @Override - public boolean doesTick() - { - return false; - } - - @Override - public String getType() - { - return PartRegistry.QuartzTorchPart.getName(); - } - - @Override - public Cuboid6 getBounds() - { - return this.getBounds( this.meta ); - } - - private Cuboid6 getBounds( final int meta ) - { - final ForgeDirection up = ForgeDirection.getOrientation( meta ); - final double xOff = -0.3 * up.offsetX; - final double yOff = -0.3 * up.offsetY; - final double zOff = -0.3 * up.offsetZ; - return new Cuboid6( xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7 ); - } - - @Override - public int sideForMeta( final int meta ) - { - return ForgeDirection.getOrientation( meta ).getOpposite().ordinal(); - } - - @Override - public void randomDisplayTick( final Random r ) - { - this.getBlock().randomDisplayTick( this.world(), this.x(), this.y(), this.z(), r ); - } - - @Override - public Block getBlock() - { - for( final Block torchBlock : AEApi.instance().definitions().blocks().quartzTorch().maybeBlock().asSet() ) - { - return torchBlock; - } - - throw new MissingDefinition( "Tried to retrieve a quartz torch, even though it is disabled." ); - } -} \ No newline at end of file +public class QuartzTorchPart extends McSidedMetaPart implements IRandomDisplayTick { + + public QuartzTorchPart() { + this(ForgeDirection.DOWN.ordinal()); + } + + public QuartzTorchPart(final int meta) { + super(meta); + } + + public static McBlockPart placement(final World world, BlockCoord pos, final int side) { + pos = pos.copy().offset(side); + if (!world.isSideSolid(pos.x, pos.y, pos.z, ForgeDirection.getOrientation(side))) { + return null; + } + + return new QuartzTorchPart(side); + } + + @Override + public boolean doesTick() { + return false; + } + + @Override + public String getType() { + return PartRegistry.QuartzTorchPart.getName(); + } + + @Override + public Cuboid6 getBounds() { + return this.getBounds(this.meta); + } + + private Cuboid6 getBounds(final int meta) { + final ForgeDirection up = ForgeDirection.getOrientation(meta); + final double xOff = -0.3 * up.offsetX; + final double yOff = -0.3 * up.offsetY; + final double zOff = -0.3 * up.offsetZ; + return new Cuboid6(xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7); + } + + @Override + public int sideForMeta(final int meta) { + return ForgeDirection.getOrientation(meta).getOpposite().ordinal(); + } + + @Override + public void randomDisplayTick(final Random r) { + this.getBlock().randomDisplayTick(this.world(), this.x(), this.y(), this.z(), r); + } + + @Override + public Block getBlock() { + for (final Block torchBlock : AEApi.instance() + .definitions() + .blocks() + .quartzTorch() + .maybeBlock() + .asSet()) { + return torchBlock; + } + + throw new MissingDefinition("Tried to retrieve a quartz torch, even though it is disabled."); + } +} diff --git a/src/main/java/appeng/helpers/AEGlassMaterial.java b/src/main/java/appeng/helpers/AEGlassMaterial.java index 478883b420e..43f8c5c9877 100644 --- a/src/main/java/appeng/helpers/AEGlassMaterial.java +++ b/src/main/java/appeng/helpers/AEGlassMaterial.java @@ -18,24 +18,19 @@ package appeng.helpers; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; +public class AEGlassMaterial extends Material { -public class AEGlassMaterial extends Material -{ - - public static final AEGlassMaterial INSTANCE = ( new AEGlassMaterial( MapColor.airColor ) ); + public static final AEGlassMaterial INSTANCE = (new AEGlassMaterial(MapColor.airColor)); - public AEGlassMaterial( final MapColor color ) - { - super( color ); - } + public AEGlassMaterial(final MapColor color) { + super(color); + } - @Override - public boolean isOpaque() - { - return false; - } + @Override + public boolean isOpaque() { + return false; + } } diff --git a/src/main/java/appeng/helpers/AEMultiTile.java b/src/main/java/appeng/helpers/AEMultiTile.java index de8165324eb..b27bbc42dbd 100644 --- a/src/main/java/appeng/helpers/AEMultiTile.java +++ b/src/main/java/appeng/helpers/AEMultiTile.java @@ -18,13 +18,8 @@ package appeng.helpers; - import appeng.api.implementations.tiles.IColorableTile; import appeng.api.networking.IGridHost; import appeng.api.parts.IPartHost; - -public interface AEMultiTile extends IGridHost, IPartHost, IColorableTile -{ - -} +public interface AEMultiTile extends IGridHost, IPartHost, IColorableTile {} diff --git a/src/main/java/appeng/helpers/DualityInterface.java b/src/main/java/appeng/helpers/DualityInterface.java index 26ec4bf475c..f789d7d0774 100644 --- a/src/main/java/appeng/helpers/DualityInterface.java +++ b/src/main/java/appeng/helpers/DualityInterface.java @@ -18,7 +18,6 @@ package appeng.helpers; - import appeng.api.AEApi; import appeng.api.config.*; import appeng.api.implementations.ICraftingPatternItem; @@ -72,7 +71,9 @@ import appeng.util.inv.ItemSlot; import appeng.util.inv.WrapperInvSlot; import appeng.util.item.AEItemStack; +import cofh.api.transport.IItemDuct; import com.google.common.collect.ImmutableSet; +import java.util.*; import net.minecraft.block.Block; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; @@ -86,1268 +87,1050 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import cofh.api.transport.IItemDuct; - -import java.util.*; - public class DualityInterface - implements IGridTickable, IStorageMonitorable, IInventoryDestination, IAEAppEngInventory, IConfigManagerHost, ICraftingProvider, IUpgradeableHost, IPriorityHost -{ - - public static final int NUMBER_OF_STORAGE_SLOTS = 9; - public static final int NUMBER_OF_CONFIG_SLOTS = 9; - public static final int NUMBER_OF_PATTERN_SLOTS = 9; - - private static final Collection BAD_BLOCKS = new HashSet( 100 ); - private final int[] sides = { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; - private final IAEItemStack[] requireWork = { null, null, null, null, null, null, null, null, null }; - private final MultiCraftingTracker craftingTracker; - private final AENetworkProxy gridProxy; - private final IInterfaceHost iHost; - private final BaseActionSource mySource; - private final BaseActionSource interfaceRequestSource; - private final ConfigManager cm = new ConfigManager( this ); - private final AppEngInternalAEInventory config = new AppEngInternalAEInventory( this, NUMBER_OF_CONFIG_SLOTS ); - private final AppEngInternalInventory storage = new AppEngInternalInventory( this, NUMBER_OF_STORAGE_SLOTS ); - private final AppEngInternalInventory patterns = new AppEngInternalInventory( this, NUMBER_OF_PATTERN_SLOTS*4 ); - private final WrapperInvSlot slotInv = new WrapperInvSlot( this.storage ); - private final MEMonitorPassThrough items = new MEMonitorPassThrough( new NullInventory(), StorageChannel.ITEMS ); - private final MEMonitorPassThrough fluids = new MEMonitorPassThrough( new NullInventory(), StorageChannel.FLUIDS ); - private final UpgradeInventory upgrades; - private boolean hasConfig = false; - private int priority; - private List craftingList = null; - private List waitingToSend = null; - private IMEInventory destination; - private boolean isWorking = false; - - public DualityInterface( final AENetworkProxy networkProxy, final IInterfaceHost ih ) - { - this.gridProxy = networkProxy; - this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL ); - - this.upgrades = new StackUpgradeInventory( this.gridProxy.getMachineRepresentation(), this, 4 ); - this.cm.registerSetting( Settings.BLOCK, YesNo.NO ); - this.cm.registerSetting( Settings.INTERFACE_TERMINAL, YesNo.YES ); - this.cm.registerSetting( Settings.INSERTION_MODE, InsertionMode.DEFAULT ); - - this.iHost = ih; - this.craftingTracker = new MultiCraftingTracker( this.iHost, 9 ); - - final MachineSource actionSource = new MachineSource( this.iHost ); - this.mySource = actionSource; - this.fluids.setChangeSource( actionSource ); - this.items.setChangeSource( actionSource ); - - this.interfaceRequestSource = new InterfaceRequestSource(this.iHost); - } - - @Override - public void saveChanges() - { - this.iHost.saveChanges(); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if (mc == InvOperation.markDirty) - { - TileEntity te = getHost().getTile(); - if (te != null && te.getWorldObj() != null) - te.getWorldObj().markTileEntityChunkModified( te.xCoord, te.yCoord, te.zCoord, te ); - } - - if( this.isWorking ) - { - return; - } - - if( inv == this.config ) - { - this.readConfig(); - } - else if( inv == this.patterns && ( removed != null || added != null ) ) - { - this.updateCraftingList(); - } - else if( inv == this.storage && slot >= 0 ) - { - final boolean had = this.hasWorkToDo(); - - this.updatePlan( slot ); - - final boolean now = this.hasWorkToDo(); - - if( had != now ) - { - try - { - if( now ) - { - this.gridProxy.getTick().alertDevice( this.gridProxy.getNode() ); - } - else - { - this.gridProxy.getTick().sleepDevice( this.gridProxy.getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - } - } - - public void writeToNBT( final NBTTagCompound data ) - { - this.config.writeToNBT( data, "config" ); - this.patterns.writeToNBT( data, "patterns" ); - this.storage.writeToNBT( data, "storage" ); - this.upgrades.writeToNBT( data, "upgrades" ); - this.cm.writeToNBT( data ); - this.craftingTracker.writeToNBT( data ); - data.setInteger( "priority", this.priority ); - - final NBTTagList waitingToSend = new NBTTagList(); - if( this.waitingToSend != null ) - { - for( final ItemStack is : this.waitingToSend ) - { - final NBTTagCompound item = new NBTTagCompound(); - is.writeToNBT( item ); - waitingToSend.appendTag( item ); - } - } - data.setTag( "waitingToSend", waitingToSend ); - } - - public void readFromNBT( final NBTTagCompound data ) - { - this.waitingToSend = null; - final NBTTagList waitingList = data.getTagList( "waitingToSend", 10 ); - if( waitingList != null ) - { - for( int x = 0; x < waitingList.tagCount(); x++ ) - { - final NBTTagCompound c = waitingList.getCompoundTagAt( x ); - if( c != null ) - { - final ItemStack is = ItemStack.loadItemStackFromNBT( c ); - this.addToSendList( is ); - } - } - } - - this.craftingTracker.readFromNBT( data ); - this.upgrades.readFromNBT( data, "upgrades" ); - this.config.readFromNBT( data, "config" ); - this.patterns.readFromNBT( data, "patterns" ); - this.storage.readFromNBT( data, "storage" ); - this.priority = data.getInteger( "priority" ); - this.cm.readFromNBT( data ); - this.readConfig(); - this.updateCraftingList(); - } - - private void addToSendList( final ItemStack is ) - { - if( is == null ) - { - return; - } - - if( this.waitingToSend == null ) - { - this.waitingToSend = new LinkedList(); - } - - this.waitingToSend.add( is ); - - try - { - this.gridProxy.getTick().wakeDevice( this.gridProxy.getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - private void readConfig() - { - this.hasConfig = false; - - for( final ItemStack p : this.config ) - { - if( p != null ) - { - this.hasConfig = true; - break; - } - } - - final boolean had = this.hasWorkToDo(); - - for( int x = 0; x < NUMBER_OF_CONFIG_SLOTS; x++ ) - { - this.updatePlan( x ); - } - - final boolean has = this.hasWorkToDo(); - - if( had != has ) - { - try - { - if( has ) - { - this.gridProxy.getTick().alertDevice( this.gridProxy.getNode() ); - } - else - { - this.gridProxy.getTick().sleepDevice( this.gridProxy.getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - - this.notifyNeighbors(); - } - - private void updateCraftingList() - { - - final boolean[] accountedFor = new boolean[patterns.getSizeInventory()]; - - if( !this.gridProxy.isReady() ) - { - return; - } - - if( this.craftingList != null ) - { - final Iterator i = this.craftingList.iterator(); - while( i.hasNext() ) - { - final ICraftingPatternDetails details = i.next(); - boolean found = false; - - for( int x = 0; x < accountedFor.length; x++ ) - { - final ItemStack is = this.patterns.getStackInSlot( x ); - if( details.getPattern() == is ) - { - accountedFor[x] = found = true; - } - } - - if( !found ) - { - i.remove(); - } - } - } - - for( int x = 0; x < accountedFor.length; x++ ) - { - if( !accountedFor[x] ) - { - this.addToCraftingList( this.patterns.getStackInSlot( x ) ); - } - } - - try - { - this.gridProxy.getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.gridProxy.getNode() ) ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - private boolean hasWorkToDo() - { - if( this.hasItemsToSend() ) - { - return true; - } - else - { - for( final IAEItemStack requiredWork : this.requireWork ) - { - if( requiredWork != null ) - { - return true; - } - } - - return false; - } - } - - private void updatePlan( final int slot ) - { - IAEItemStack req = this.config.getAEStackInSlot( slot ); - if( req != null && req.getStackSize() <= 0 ) - { - this.config.setInventorySlotContents( slot, null ); - req = null; - } - - final ItemStack Stored = this.storage.getStackInSlot( slot ); - - if( req == null && Stored != null ) - { - final IAEItemStack work = AEApi.instance().storage().createItemStack( Stored ); - this.requireWork[slot] = work.setStackSize( -work.getStackSize() ); - return; - } - else if( req != null ) - { - if( Stored == null ) // need to add stuff! - { - this.requireWork[slot] = req.copy(); - return; - } - else if( req.isSameType( Stored ) ) // same type ( qty different? )! - { - if( req.getStackSize() != Stored.stackSize ) - { - this.requireWork[slot] = req.copy(); - this.requireWork[slot].setStackSize( req.getStackSize() - Stored.stackSize ); - return; - } - } - else - // Stored != null; dispose! - { - final IAEItemStack work = AEApi.instance().storage().createItemStack( Stored ); - this.requireWork[slot] = work.setStackSize( -work.getStackSize() ); - return; - } - } - - // else - - this.requireWork[slot] = null; - } - - public void notifyNeighbors() - { - if( this.gridProxy.isActive() ) - { - try - { - this.gridProxy.getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.gridProxy.getNode() ) ); - this.gridProxy.getTick().wakeDevice( this.gridProxy.getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - final TileEntity te = this.iHost.getTileEntity(); - if( te != null && te.getWorldObj() != null ) - { - Platform.notifyBlocksOfNeighbors( te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord ); - } - } - - private void addToCraftingList( final ItemStack is ) - { - if( is == null ) - { - return; - } - - if( is.getItem() instanceof ICraftingPatternItem ) - { - final ICraftingPatternItem cpi = (ICraftingPatternItem) is.getItem(); - final ICraftingPatternDetails details = cpi.getPatternForItem( is, this.iHost.getTileEntity().getWorldObj() ); - - if( details != null ) - { - if( this.craftingList == null ) - { - this.craftingList = new LinkedList(); - } - - this.craftingList.add( details ); - } - } - } - - private boolean hasItemsToSend() - { - return this.waitingToSend != null && !this.waitingToSend.isEmpty(); - } - - @Override - public boolean canInsert( final ItemStack stack ) - { - final IAEItemStack out = this.destination.injectItems( AEApi.instance().storage().createItemStack( stack ), Actionable.SIMULATE, null ); - if( out == null ) - { - return true; - } - return out.getStackSize() != stack.stackSize; - // ItemStack after = adaptor.simulateAdd( stack ); - // if ( after == null ) - // return true; - // return after.stackSize != stack.stackSize; - } - - public IInventory getConfig() - { - return this.config; - } - - public IInventory getPatterns() - { - return this.patterns; - } - - public void gridChanged() - { - try - { - this.items.setInternal( this.gridProxy.getStorage().getItemInventory() ); - this.fluids.setInternal( this.gridProxy.getStorage().getFluidInventory() ); - } - catch( final GridAccessException gae ) - { - this.items.setInternal( new NullInventory() ); - this.fluids.setInternal( new NullInventory() ); - } - - this.notifyNeighbors(); - } - - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } - - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this.iHost.getTileEntity() ); - } - - public IInventory getInternalInventory() - { - return this.storage; - } - - public void markDirty() - { - for( int slot = 0; slot < this.storage.getSizeInventory(); slot++ ) - { - this.onChangeInventory( this.storage, slot, InvOperation.markDirty, null, null ); - } - } - - public int[] getAccessibleSlotsFromSide( final int side ) - { - return this.sides; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.Interface.getMin(), TickRates.Interface.getMax(), !this.hasWorkToDo(), true ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( !this.gridProxy.isActive() ) - { - if (AEConfig.instance.debugLogTiming) - { - TileEntity te = iHost.getTileEntity(); - AELog.debug("Timing: interface at (%d %d %d) is ticking while the grid is booting", te.xCoord, te.yCoord, te.zCoord); - } - return this.hasWorkToDo() ? TickRateModulation.SLOWER : TickRateModulation.SLEEP; - } - - if( this.hasItemsToSend() ) - { - this.pushItemsOut( this.iHost.getTargets() ); - } - - final boolean couldDoWork = this.updateStorage(); - return this.hasWorkToDo() ? ( couldDoWork ? TickRateModulation.URGENT : TickRateModulation.SLOWER ) : TickRateModulation.SLEEP; - } - - private void pushItemsOut( final EnumSet possibleDirections ) - { - if( !this.hasItemsToSend() ) - { - return; - } - - final TileEntity tile = this.iHost.getTileEntity(); - final World w = tile.getWorldObj(); - - final Iterator i = this.waitingToSend.iterator(); - while( i.hasNext() ) - { - ItemStack whatToSend = i.next(); - - for( final ForgeDirection s : possibleDirections ) - { - final TileEntity te = w.getTileEntity( tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ ); - if( te == null ) - { - continue; - } - - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() ); - ItemStack Result = whatToSend; - if( ad != null ) - { - Result = ad.addItems( whatToSend, getInsertionMode() ); - } - else if (te instanceof IItemDuct) - { - Result = ((IItemDuct)te).insertItem(s.getOpposite(), whatToSend); - } - if( Result == null ) - { - whatToSend = null; - } - else - { - whatToSend.stackSize -= whatToSend.stackSize - Result.stackSize; - } - - if( whatToSend == null ) - { - break; - } - } - - if( whatToSend == null ) - { - i.remove(); - } - } - - if( this.waitingToSend.isEmpty() ) - { - this.waitingToSend = null; - } - } - - private boolean updateStorage() - { - boolean didSomething = false; - - for( int x = 0; x < NUMBER_OF_STORAGE_SLOTS; x++ ) - { - if( this.requireWork[x] != null ) - { - didSomething = this.usePlan( x, this.requireWork[x] ) || didSomething; - } - } - - return didSomething; - } - - private boolean usePlan( final int x, final IAEItemStack itemStack ) - { - final InventoryAdaptor adaptor = this.getAdaptor( x ); - this.isWorking = true; - - boolean changed = false; - try - { - this.destination = this.gridProxy.getStorage().getItemInventory(); - final IEnergySource src = this.gridProxy.getEnergy(); - - if( itemStack.getStackSize() < 0 ) - { - IAEItemStack toStore = itemStack.copy(); - toStore.setStackSize( -toStore.getStackSize() ); - - long diff = toStore.getStackSize(); - - // make sure strange things didn't happen... - final ItemStack canExtract = adaptor.simulateRemove( (int) diff, toStore.getItemStack(), null ); - if( canExtract == null || canExtract.stackSize != diff ) - { - changed = true; - throw new GridAccessException(); - } - - toStore = Platform.poweredInsert( src, this.destination, toStore, this.interfaceRequestSource ); - - if( toStore != null ) - { - diff -= toStore.getStackSize(); - } - - if( diff != 0 ) - { - // extract items! - changed = true; - final ItemStack removed = adaptor.removeItems( (int) diff, null, null ); - if( removed == null ) - { - throw new IllegalStateException( "bad attempt at managing inventory. ( removeItems )" ); - } - else if( removed.stackSize != diff ) - { - throw new IllegalStateException( "bad attempt at managing inventory. ( removeItems )" ); - } - } - } - else if( this.craftingTracker.isBusy( x ) ) - { - changed = this.handleCrafting( x, adaptor, itemStack ); - } - else if( itemStack.getStackSize() > 0 ) - { - // make sure strange things didn't happen... - if( adaptor.simulateAdd( itemStack.getItemStack() ) != null ) - { - changed = true; - throw new GridAccessException(); - } - - final IAEItemStack acquired = Platform.poweredExtraction( src, this.destination, itemStack, this.interfaceRequestSource ); - if( acquired != null ) - { - changed = true; - final ItemStack issue = adaptor.addItems( acquired.getItemStack() ); - if( issue != null ) - { - throw new IllegalStateException( "bad attempt at managing inventory. ( addItems )" ); - } - } - else - { - changed = this.handleCrafting( x, adaptor, itemStack ); - } - } - // else wtf? - } - catch( final GridAccessException e ) - { - // :P - } - - if( changed ) - { - this.updatePlan( x ); - } - - this.isWorking = false; - return changed; - } - - private InventoryAdaptor getAdaptor( final int slot ) - { - return new AdaptorIInventory( this.slotInv.getWrapper( slot ) ); - } - - private boolean handleCrafting( final int x, final InventoryAdaptor d, final IAEItemStack itemStack ) - { - try - { - if( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 && itemStack != null ) - { - return this.craftingTracker.handleCrafting( x, itemStack.getStackSize(), itemStack, d, this.iHost.getTileEntity().getWorldObj(), this.gridProxy.getGrid(), this.gridProxy.getCrafting(), this.mySource ); - } - } - catch( final GridAccessException e ) - { - // :P - } - - return false; - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - if( this.upgrades == null ) - { - return 0; - } - return this.upgrades.getInstalledUpgrades( u ); - } - - @Override - public TileEntity getTile() - { - return (TileEntity) ( this.iHost instanceof TileEntity ? this.iHost : null ); - } - - @Override - public IMEMonitor getItemInventory() - { - if( this.hasConfig() ) - { - return new InterfaceInventory( this ); - } - - return this.items; - } - - private boolean hasConfig() - { - return this.hasConfig; - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "storage" ) ) - { - return this.storage; - } - - if( name.equals( "patterns" ) ) - { - return this.patterns; - } - - if( name.equals( "config" ) ) - { - return this.config; - } - - if( name.equals( "upgrades" ) ) - { - return this.upgrades; - } - - return null; - } - - public IInventory getStorage() - { - return this.storage; - } - - @Override - public appeng.api.util.IConfigManager getConfigManager() - { - return this.cm; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - if( this.getInstalledUpgrades( Upgrades.CRAFTING ) == 0 ) - { - this.cancelCrafting(); - } - - this.markDirty(); - } - - @Override - public IMEMonitor getFluidInventory() - { - if( this.hasConfig() ) - { - return null; - } - - return this.fluids; - } - - private void cancelCrafting() - { - this.craftingTracker.cancel(); - } - - public IStorageMonitorable getMonitorable( final ForgeDirection side, final BaseActionSource src, final IStorageMonitorable myInterface ) - { - if( Platform.canAccess( this.gridProxy, src ) ) - { - return myInterface; - } - - final DualityInterface di = this; - - return new IStorageMonitorable() - { - - @Override - public IMEMonitor getItemInventory() - { - return new InterfaceInventory( di ); - } - - @Override - public IMEMonitor getFluidInventory() - { - return null; - } - }; - } - private boolean gtMachineHasOnlyCircuit(InventoryAdaptor ad) { - for (ItemSlot i : ad) { - ItemStack is = i.getItemStack(); - if (is == null || is.getItem().getUnlocalizedName().equals("gt.integrated_circuit")) - continue; - return false; - } - return true; - } - private boolean inventoryCountsAsEmpty(TileEntity te, InventoryAdaptor ad) - { - String name = te.getBlockType().getUnlocalizedName(); - return (name.equals("gt.blockmachines") || name.equals("tile.interface")) && gtMachineHasOnlyCircuit(ad); - } - - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table ) - { - if( this.hasItemsToSend() || !this.gridProxy.isActive() || !this.craftingList.contains( patternDetails ) ) - { - return false; - } - - final TileEntity tile = this.iHost.getTileEntity(); - final World w = tile.getWorldObj(); - - final EnumSet possibleDirections = this.iHost.getTargets(); - for( final ForgeDirection s : possibleDirections ) - { - final TileEntity te = w.getTileEntity( tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ ); - if( te instanceof IInterfaceHost ) - { - try - { - if( ( (IInterfaceHost) te ).getInterfaceDuality().sameGrid( this.gridProxy.getGrid() ) ) - { - continue; - } - } - catch( final GridAccessException e ) - { - continue; - } - } - - if( te instanceof ICraftingMachine ) - { - final ICraftingMachine cm = (ICraftingMachine) te; - if( cm.acceptsPlans() ) - { - if( cm.pushPattern( patternDetails, table, s.getOpposite() ) ) - { - return true; - } - continue; - } - } - if (te != null && te.getClass().getName().equals( "li.cil.oc.common.tileentity.Adapter" )) + implements IGridTickable, + IStorageMonitorable, + IInventoryDestination, + IAEAppEngInventory, + IConfigManagerHost, + ICraftingProvider, + IUpgradeableHost, + IPriorityHost { + + public static final int NUMBER_OF_STORAGE_SLOTS = 9; + public static final int NUMBER_OF_CONFIG_SLOTS = 9; + public static final int NUMBER_OF_PATTERN_SLOTS = 9; + + private static final Collection BAD_BLOCKS = new HashSet(100); + private final int[] sides = {0, 1, 2, 3, 4, 5, 6, 7, 8}; + private final IAEItemStack[] requireWork = {null, null, null, null, null, null, null, null, null}; + private final MultiCraftingTracker craftingTracker; + private final AENetworkProxy gridProxy; + private final IInterfaceHost iHost; + private final BaseActionSource mySource; + private final BaseActionSource interfaceRequestSource; + private final ConfigManager cm = new ConfigManager(this); + private final AppEngInternalAEInventory config = new AppEngInternalAEInventory(this, NUMBER_OF_CONFIG_SLOTS); + private final AppEngInternalInventory storage = new AppEngInternalInventory(this, NUMBER_OF_STORAGE_SLOTS); + private final AppEngInternalInventory patterns = new AppEngInternalInventory(this, NUMBER_OF_PATTERN_SLOTS * 4); + private final WrapperInvSlot slotInv = new WrapperInvSlot(this.storage); + private final MEMonitorPassThrough items = + new MEMonitorPassThrough(new NullInventory(), StorageChannel.ITEMS); + private final MEMonitorPassThrough fluids = + new MEMonitorPassThrough(new NullInventory(), StorageChannel.FLUIDS); + private final UpgradeInventory upgrades; + private boolean hasConfig = false; + private int priority; + private List craftingList = null; + private List waitingToSend = null; + private IMEInventory destination; + private boolean isWorking = false; + + public DualityInterface(final AENetworkProxy networkProxy, final IInterfaceHost ih) { + this.gridProxy = networkProxy; + this.gridProxy.setFlags(GridFlags.REQUIRE_CHANNEL); + + this.upgrades = new StackUpgradeInventory(this.gridProxy.getMachineRepresentation(), this, 4); + this.cm.registerSetting(Settings.BLOCK, YesNo.NO); + this.cm.registerSetting(Settings.INTERFACE_TERMINAL, YesNo.YES); + this.cm.registerSetting(Settings.INSERTION_MODE, InsertionMode.DEFAULT); + + this.iHost = ih; + this.craftingTracker = new MultiCraftingTracker(this.iHost, 9); + + final MachineSource actionSource = new MachineSource(this.iHost); + this.mySource = actionSource; + this.fluids.setChangeSource(actionSource); + this.items.setChangeSource(actionSource); + + this.interfaceRequestSource = new InterfaceRequestSource(this.iHost); + } + + @Override + public void saveChanges() { + this.iHost.saveChanges(); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) { + if (mc == InvOperation.markDirty) { + TileEntity te = getHost().getTile(); + if (te != null && te.getWorldObj() != null) + te.getWorldObj().markTileEntityChunkModified(te.xCoord, te.yCoord, te.zCoord, te); + } + + if (this.isWorking) { + return; + } + + if (inv == this.config) { + this.readConfig(); + } else if (inv == this.patterns && (removed != null || added != null)) { + this.updateCraftingList(); + } else if (inv == this.storage && slot >= 0) { + final boolean had = this.hasWorkToDo(); + + this.updatePlan(slot); + + final boolean now = this.hasWorkToDo(); + + if (had != now) { + try { + if (now) { + this.gridProxy.getTick().alertDevice(this.gridProxy.getNode()); + } else { + this.gridProxy.getTick().sleepDevice(this.gridProxy.getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } + } + } + + public void writeToNBT(final NBTTagCompound data) { + this.config.writeToNBT(data, "config"); + this.patterns.writeToNBT(data, "patterns"); + this.storage.writeToNBT(data, "storage"); + this.upgrades.writeToNBT(data, "upgrades"); + this.cm.writeToNBT(data); + this.craftingTracker.writeToNBT(data); + data.setInteger("priority", this.priority); + + final NBTTagList waitingToSend = new NBTTagList(); + if (this.waitingToSend != null) { + for (final ItemStack is : this.waitingToSend) { + final NBTTagCompound item = new NBTTagCompound(); + is.writeToNBT(item); + waitingToSend.appendTag(item); + } + } + data.setTag("waitingToSend", waitingToSend); + } + + public void readFromNBT(final NBTTagCompound data) { + this.waitingToSend = null; + final NBTTagList waitingList = data.getTagList("waitingToSend", 10); + if (waitingList != null) { + for (int x = 0; x < waitingList.tagCount(); x++) { + final NBTTagCompound c = waitingList.getCompoundTagAt(x); + if (c != null) { + final ItemStack is = ItemStack.loadItemStackFromNBT(c); + this.addToSendList(is); + } + } + } + + this.craftingTracker.readFromNBT(data); + this.upgrades.readFromNBT(data, "upgrades"); + this.config.readFromNBT(data, "config"); + this.patterns.readFromNBT(data, "patterns"); + this.storage.readFromNBT(data, "storage"); + this.priority = data.getInteger("priority"); + this.cm.readFromNBT(data); + this.readConfig(); + this.updateCraftingList(); + } + + private void addToSendList(final ItemStack is) { + if (is == null) { + return; + } + + if (this.waitingToSend == null) { + this.waitingToSend = new LinkedList(); + } + + this.waitingToSend.add(is); + + try { + this.gridProxy.getTick().wakeDevice(this.gridProxy.getNode()); + } catch (final GridAccessException e) { + // :P + } + } + + private void readConfig() { + this.hasConfig = false; + + for (final ItemStack p : this.config) { + if (p != null) { + this.hasConfig = true; + break; + } + } + + final boolean had = this.hasWorkToDo(); + + for (int x = 0; x < NUMBER_OF_CONFIG_SLOTS; x++) { + this.updatePlan(x); + } + + final boolean has = this.hasWorkToDo(); + + if (had != has) { + try { + if (has) { + this.gridProxy.getTick().alertDevice(this.gridProxy.getNode()); + } else { + this.gridProxy.getTick().sleepDevice(this.gridProxy.getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } + + this.notifyNeighbors(); + } + + private void updateCraftingList() { + + final boolean[] accountedFor = new boolean[patterns.getSizeInventory()]; + + if (!this.gridProxy.isReady()) { + return; + } + + if (this.craftingList != null) { + final Iterator i = this.craftingList.iterator(); + while (i.hasNext()) { + final ICraftingPatternDetails details = i.next(); + boolean found = false; + + for (int x = 0; x < accountedFor.length; x++) { + final ItemStack is = this.patterns.getStackInSlot(x); + if (details.getPattern() == is) { + accountedFor[x] = found = true; + } + } + + if (!found) { + i.remove(); + } + } + } + + for (int x = 0; x < accountedFor.length; x++) { + if (!accountedFor[x]) { + this.addToCraftingList(this.patterns.getStackInSlot(x)); + } + } + + try { + this.gridProxy.getGrid().postEvent(new MENetworkCraftingPatternChange(this, this.gridProxy.getNode())); + } catch (final GridAccessException e) { + // :P + } + } + + private boolean hasWorkToDo() { + if (this.hasItemsToSend()) { + return true; + } else { + for (final IAEItemStack requiredWork : this.requireWork) { + if (requiredWork != null) { + return true; + } + } + + return false; + } + } + + private void updatePlan(final int slot) { + IAEItemStack req = this.config.getAEStackInSlot(slot); + if (req != null && req.getStackSize() <= 0) { + this.config.setInventorySlotContents(slot, null); + req = null; + } + + final ItemStack Stored = this.storage.getStackInSlot(slot); + + if (req == null && Stored != null) { + final IAEItemStack work = AEApi.instance().storage().createItemStack(Stored); + this.requireWork[slot] = work.setStackSize(-work.getStackSize()); + return; + } else if (req != null) { + if (Stored == null) // need to add stuff! + { + this.requireWork[slot] = req.copy(); + return; + } else if (req.isSameType(Stored)) // same type ( qty different? )! + { + if (req.getStackSize() != Stored.stackSize) { + this.requireWork[slot] = req.copy(); + this.requireWork[slot].setStackSize(req.getStackSize() - Stored.stackSize); + return; + } + } else + // Stored != null; dispose! + { + final IAEItemStack work = AEApi.instance().storage().createItemStack(Stored); + this.requireWork[slot] = work.setStackSize(-work.getStackSize()); + return; + } + } + + // else + + this.requireWork[slot] = null; + } + + public void notifyNeighbors() { + if (this.gridProxy.isActive()) { + try { + this.gridProxy.getGrid().postEvent(new MENetworkCraftingPatternChange(this, this.gridProxy.getNode())); + this.gridProxy.getTick().wakeDevice(this.gridProxy.getNode()); + } catch (final GridAccessException e) { + // :P + } + } + + final TileEntity te = this.iHost.getTileEntity(); + if (te != null && te.getWorldObj() != null) { + Platform.notifyBlocksOfNeighbors(te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord); + } + } + + private void addToCraftingList(final ItemStack is) { + if (is == null) { + return; + } + + if (is.getItem() instanceof ICraftingPatternItem) { + final ICraftingPatternItem cpi = (ICraftingPatternItem) is.getItem(); + final ICraftingPatternDetails details = + cpi.getPatternForItem(is, this.iHost.getTileEntity().getWorldObj()); + + if (details != null) { + if (this.craftingList == null) { + this.craftingList = new LinkedList(); + } + + this.craftingList.add(details); + } + } + } + + private boolean hasItemsToSend() { + return this.waitingToSend != null && !this.waitingToSend.isEmpty(); + } + + @Override + public boolean canInsert(final ItemStack stack) { + final IAEItemStack out = this.destination.injectItems( + AEApi.instance().storage().createItemStack(stack), Actionable.SIMULATE, null); + if (out == null) { + return true; + } + return out.getStackSize() != stack.stackSize; + // ItemStack after = adaptor.simulateAdd( stack ); + // if ( after == null ) + // return true; + // return after.stackSize != stack.stackSize; + } + + public IInventory getConfig() { + return this.config; + } + + public IInventory getPatterns() { + return this.patterns; + } + + public void gridChanged() { + try { + this.items.setInternal(this.gridProxy.getStorage().getItemInventory()); + this.fluids.setInternal(this.gridProxy.getStorage().getFluidInventory()); + } catch (final GridAccessException gae) { + this.items.setInternal(new NullInventory()); + this.fluids.setInternal(new NullInventory()); + } + + this.notifyNeighbors(); + } + + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } + + public DimensionalCoord getLocation() { + return new DimensionalCoord(this.iHost.getTileEntity()); + } + + public IInventory getInternalInventory() { + return this.storage; + } + + public void markDirty() { + for (int slot = 0; slot < this.storage.getSizeInventory(); slot++) { + this.onChangeInventory(this.storage, slot, InvOperation.markDirty, null, null); + } + } + + public int[] getAccessibleSlotsFromSide(final int side) { + return this.sides; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest( + TickRates.Interface.getMin(), TickRates.Interface.getMax(), !this.hasWorkToDo(), true); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (!this.gridProxy.isActive()) { + if (AEConfig.instance.debugLogTiming) { + TileEntity te = iHost.getTileEntity(); + AELog.debug( + "Timing: interface at (%d %d %d) is ticking while the grid is booting", + te.xCoord, te.yCoord, te.zCoord); + } + return this.hasWorkToDo() ? TickRateModulation.SLOWER : TickRateModulation.SLEEP; + } + + if (this.hasItemsToSend()) { + this.pushItemsOut(this.iHost.getTargets()); + } + + final boolean couldDoWork = this.updateStorage(); + return this.hasWorkToDo() + ? (couldDoWork ? TickRateModulation.URGENT : TickRateModulation.SLOWER) + : TickRateModulation.SLEEP; + } + + private void pushItemsOut(final EnumSet possibleDirections) { + if (!this.hasItemsToSend()) { + return; + } + + final TileEntity tile = this.iHost.getTileEntity(); + final World w = tile.getWorldObj(); + + final Iterator i = this.waitingToSend.iterator(); + while (i.hasNext()) { + ItemStack whatToSend = i.next(); + + for (final ForgeDirection s : possibleDirections) { + final TileEntity te = + w.getTileEntity(tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ); + if (te == null) { + continue; + } + + final InventoryAdaptor ad = InventoryAdaptor.getAdaptor(te, s.getOpposite()); + ItemStack Result = whatToSend; + if (ad != null) { + Result = ad.addItems(whatToSend, getInsertionMode()); + } else if (te instanceof IItemDuct) { + Result = ((IItemDuct) te).insertItem(s.getOpposite(), whatToSend); + } + if (Result == null) { + whatToSend = null; + } else { + whatToSend.stackSize -= whatToSend.stackSize - Result.stackSize; + } + + if (whatToSend == null) { + break; + } + } + + if (whatToSend == null) { + i.remove(); + } + } + + if (this.waitingToSend.isEmpty()) { + this.waitingToSend = null; + } + } + + private boolean updateStorage() { + boolean didSomething = false; + + for (int x = 0; x < NUMBER_OF_STORAGE_SLOTS; x++) { + if (this.requireWork[x] != null) { + didSomething = this.usePlan(x, this.requireWork[x]) || didSomething; + } + } + + return didSomething; + } + + private boolean usePlan(final int x, final IAEItemStack itemStack) { + final InventoryAdaptor adaptor = this.getAdaptor(x); + this.isWorking = true; + + boolean changed = false; + try { + this.destination = this.gridProxy.getStorage().getItemInventory(); + final IEnergySource src = this.gridProxy.getEnergy(); + + if (itemStack.getStackSize() < 0) { + IAEItemStack toStore = itemStack.copy(); + toStore.setStackSize(-toStore.getStackSize()); + + long diff = toStore.getStackSize(); + + // make sure strange things didn't happen... + final ItemStack canExtract = adaptor.simulateRemove((int) diff, toStore.getItemStack(), null); + if (canExtract == null || canExtract.stackSize != diff) { + changed = true; + throw new GridAccessException(); + } + + toStore = Platform.poweredInsert(src, this.destination, toStore, this.interfaceRequestSource); + + if (toStore != null) { + diff -= toStore.getStackSize(); + } + + if (diff != 0) { + // extract items! + changed = true; + final ItemStack removed = adaptor.removeItems((int) diff, null, null); + if (removed == null) { + throw new IllegalStateException("bad attempt at managing inventory. ( removeItems )"); + } else if (removed.stackSize != diff) { + throw new IllegalStateException("bad attempt at managing inventory. ( removeItems )"); + } + } + } else if (this.craftingTracker.isBusy(x)) { + changed = this.handleCrafting(x, adaptor, itemStack); + } else if (itemStack.getStackSize() > 0) { + // make sure strange things didn't happen... + if (adaptor.simulateAdd(itemStack.getItemStack()) != null) { + changed = true; + throw new GridAccessException(); + } + + final IAEItemStack acquired = + Platform.poweredExtraction(src, this.destination, itemStack, this.interfaceRequestSource); + if (acquired != null) { + changed = true; + final ItemStack issue = adaptor.addItems(acquired.getItemStack()); + if (issue != null) { + throw new IllegalStateException("bad attempt at managing inventory. ( addItems )"); + } + } else { + changed = this.handleCrafting(x, adaptor, itemStack); + } + } + // else wtf? + } catch (final GridAccessException e) { + // :P + } + + if (changed) { + this.updatePlan(x); + } + + this.isWorking = false; + return changed; + } + + private InventoryAdaptor getAdaptor(final int slot) { + return new AdaptorIInventory(this.slotInv.getWrapper(slot)); + } + + private boolean handleCrafting(final int x, final InventoryAdaptor d, final IAEItemStack itemStack) { + try { + if (this.getInstalledUpgrades(Upgrades.CRAFTING) > 0 && itemStack != null) { + return this.craftingTracker.handleCrafting( + x, + itemStack.getStackSize(), + itemStack, + d, + this.iHost.getTileEntity().getWorldObj(), + this.gridProxy.getGrid(), + this.gridProxy.getCrafting(), + this.mySource); + } + } catch (final GridAccessException e) { + // :P + } + + return false; + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + if (this.upgrades == null) { + return 0; + } + return this.upgrades.getInstalledUpgrades(u); + } + + @Override + public TileEntity getTile() { + return (TileEntity) (this.iHost instanceof TileEntity ? this.iHost : null); + } + + @Override + public IMEMonitor getItemInventory() { + if (this.hasConfig()) { + return new InterfaceInventory(this); + } + + return this.items; + } + + private boolean hasConfig() { + return this.hasConfig; + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("storage")) { + return this.storage; + } + + if (name.equals("patterns")) { + return this.patterns; + } + + if (name.equals("config")) { + return this.config; + } + + if (name.equals("upgrades")) { + return this.upgrades; + } + + return null; + } + + public IInventory getStorage() { + return this.storage; + } + + @Override + public appeng.api.util.IConfigManager getConfigManager() { + return this.cm; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + if (this.getInstalledUpgrades(Upgrades.CRAFTING) == 0) { + this.cancelCrafting(); + } + + this.markDirty(); + } + + @Override + public IMEMonitor getFluidInventory() { + if (this.hasConfig()) { + return null; + } + + return this.fluids; + } + + private void cancelCrafting() { + this.craftingTracker.cancel(); + } + + public IStorageMonitorable getMonitorable( + final ForgeDirection side, final BaseActionSource src, final IStorageMonitorable myInterface) { + if (Platform.canAccess(this.gridProxy, src)) { + return myInterface; + } + + final DualityInterface di = this; + + return new IStorageMonitorable() { + + @Override + public IMEMonitor getItemInventory() { + return new InterfaceInventory(di); + } + + @Override + public IMEMonitor getFluidInventory() { + return null; + } + }; + } + + private boolean gtMachineHasOnlyCircuit(InventoryAdaptor ad) { + for (ItemSlot i : ad) { + ItemStack is = i.getItemStack(); + if (is == null || is.getItem().getUnlocalizedName().equals("gt.integrated_circuit")) continue; + return false; + } + return true; + } + + private boolean inventoryCountsAsEmpty(TileEntity te, InventoryAdaptor ad) { + String name = te.getBlockType().getUnlocalizedName(); + return (name.equals("gt.blockmachines") || name.equals("tile.interface")) && gtMachineHasOnlyCircuit(ad); + } + + @Override + public boolean pushPattern(final ICraftingPatternDetails patternDetails, final InventoryCrafting table) { + if (this.hasItemsToSend() || !this.gridProxy.isActive() || !this.craftingList.contains(patternDetails)) { + return false; + } + + final TileEntity tile = this.iHost.getTileEntity(); + final World w = tile.getWorldObj(); + + final EnumSet possibleDirections = this.iHost.getTargets(); + for (final ForgeDirection s : possibleDirections) { + final TileEntity te = + w.getTileEntity(tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ); + if (te instanceof IInterfaceHost) { + try { + if (((IInterfaceHost) te).getInterfaceDuality().sameGrid(this.gridProxy.getGrid())) { + continue; + } + } catch (final GridAccessException e) { + continue; + } + } + + if (te instanceof ICraftingMachine) { + final ICraftingMachine cm = (ICraftingMachine) te; + if (cm.acceptsPlans()) { + if (cm.pushPattern(patternDetails, table, s.getOpposite())) { + return true; + } + continue; + } + } + if (te != null && te.getClass().getName().equals("li.cil.oc.common.tileentity.Adapter")) continue; + + final InventoryAdaptor ad = InventoryAdaptor.getAdaptor(te, s.getOpposite()); + if (ad != null) { + if (this.isBlocking() && ad.containsItems() && !inventoryCountsAsEmpty(te, ad)) continue; + + if (acceptsItems(ad, table, getInsertionMode())) { + for (int x = 0; x < table.getSizeInventory(); x++) { + final ItemStack is = table.getStackInSlot(x); + if (is != null) { + this.addToSendList(ad.addItems(is, getInsertionMode())); + } + } + this.pushItemsOut(possibleDirections); + return true; + } + } else if (te instanceof IItemDuct) { + boolean hadAcceptedSome = false; + for (int x = 0; x < table.getSizeInventory(); x++) { + final ItemStack is = table.getStackInSlot(x); + if (is != null) { + final ItemStack rest = ((IItemDuct) te).insertItem(s.getOpposite(), is); + if (!hadAcceptedSome && rest != null && rest.stackSize == is.stackSize) + break; // conduit should accept all the pattern or nothing. + hadAcceptedSome = true; + this.addToSendList(rest); + } + } + if (hadAcceptedSome) { + this.pushItemsOut(possibleDirections); + return true; + } + } + } + + return false; + } + + @Override + public boolean isBusy() { + if (this.hasItemsToSend()) { + return true; + } + + boolean busy = false; + + if (this.isBlocking()) { + final EnumSet possibleDirections = this.iHost.getTargets(); + final TileEntity tile = this.iHost.getTileEntity(); + final World w = tile.getWorldObj(); + + boolean allAreBusy = true; + + for (final ForgeDirection s : possibleDirections) { + final TileEntity te = + w.getTileEntity(tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ); + if (te != null && te.getClass().getName().equals("li.cil.oc.common.tileentity.Adapter")) continue; + final InventoryAdaptor ad = InventoryAdaptor.getAdaptor(te, s.getOpposite()); + if (ad != null) { + if (ad.simulateRemove(1, null, null) == null || inventoryCountsAsEmpty(te, ad)) { + allAreBusy = false; + break; + } + } + } + + busy = allAreBusy; + } + + return busy; + } + + private boolean sameGrid(final IGrid grid) throws GridAccessException { + return grid == this.gridProxy.getGrid(); + } + + private boolean isBlocking() { + return this.cm.getSetting(Settings.BLOCK) == YesNo.YES; + } + + private InsertionMode getInsertionMode() { + return (InsertionMode) cm.getSetting(Settings.INSERTION_MODE); + } + + private static boolean acceptsItems( + final InventoryAdaptor ad, final InventoryCrafting table, final InsertionMode insertionMode) { + for (int x = 0; x < table.getSizeInventory(); x++) { + final ItemStack is = table.getStackInSlot(x); + if (is == null) { continue; - - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() ); - if( ad != null ) - { - if (this.isBlocking() && ad.containsItems() && !inventoryCountsAsEmpty(te, ad)) - continue; - - if( acceptsItems( ad, table, getInsertionMode() ) ) - { - for( int x = 0; x < table.getSizeInventory(); x++ ) - { - final ItemStack is = table.getStackInSlot( x ); - if( is != null ) - { - this.addToSendList( ad.addItems( is, getInsertionMode() ) ); - } - } - this.pushItemsOut( possibleDirections ); - return true; - } - } - else if (te instanceof IItemDuct) - { - boolean hadAcceptedSome = false; - for( int x = 0; x < table.getSizeInventory(); x++ ) - { - final ItemStack is = table.getStackInSlot( x ); - if (is != null) - { - final ItemStack rest = ((IItemDuct)te).insertItem(s.getOpposite(), is); - if (!hadAcceptedSome && rest != null && rest.stackSize == is.stackSize) - break; // conduit should accept all the pattern or nothing. - hadAcceptedSome = true; - this.addToSendList(rest); - } - } - if (hadAcceptedSome) - { - this.pushItemsOut(possibleDirections); - return true; - } - } - } - - return false; - } - - @Override - public boolean isBusy() - { - if( this.hasItemsToSend() ) - { - return true; - } - - boolean busy = false; - - if( this.isBlocking() ) - { - final EnumSet possibleDirections = this.iHost.getTargets(); - final TileEntity tile = this.iHost.getTileEntity(); - final World w = tile.getWorldObj(); - - boolean allAreBusy = true; - - for( final ForgeDirection s : possibleDirections ) - { - final TileEntity te = w.getTileEntity( tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ ); - if (te != null && te.getClass().getName().equals( "li.cil.oc.common.tileentity.Adapter" )) - continue; - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() ); - if( ad != null ) - { - if( ad.simulateRemove( 1, null, null ) == null || inventoryCountsAsEmpty(te, ad)) - { - allAreBusy = false; - break; - } - } - } - - busy = allAreBusy; - } - - return busy; - } - - private boolean sameGrid( final IGrid grid ) throws GridAccessException - { - return grid == this.gridProxy.getGrid(); - } - - private boolean isBlocking() - { - return this.cm.getSetting( Settings.BLOCK ) == YesNo.YES; - } - - private InsertionMode getInsertionMode() - { - return (InsertionMode) cm.getSetting( Settings.INSERTION_MODE ); - } - - private static boolean acceptsItems( final InventoryAdaptor ad, final InventoryCrafting table, final InsertionMode insertionMode ) - { - for( int x = 0; x < table.getSizeInventory(); x++ ) - { - final ItemStack is = table.getStackInSlot( x ); - if( is == null ) - { - continue; - } - - if( ad.simulateAdd( is.copy(), insertionMode ) != null ) - { - return false; - } - } - - return true; - } - - @Override - public void provideCrafting( final ICraftingProviderHelper craftingTracker ) - { - if( this.gridProxy.isActive() && this.craftingList != null ) - { - for( final ICraftingPatternDetails details : this.craftingList ) - { - details.setPriority( this.priority ); - craftingTracker.addCraftingOption( this, details ); - } - } - } - - public void addDrops( final List drops ) - { - if( this.waitingToSend != null ) - { - for( final ItemStack is : this.waitingToSend ) - { - if( is != null ) - { - drops.add( is ); - } - } - } - - for( final ItemStack is : this.upgrades ) - { - if( is != null ) - { - drops.add( is ); - } - } - - for( final ItemStack is : this.storage ) - { - if( is != null ) - { - drops.add( is ); - } - } - - for( final ItemStack is : this.patterns ) - { - if( is != null ) - { - drops.add( is ); - } - } - } - - public IUpgradeableHost getHost() - { - if(this.getPart() != null) - { - return (IUpgradeableHost) this.getPart(); - } - if( this.getTile() instanceof IUpgradeableHost ) - { - return (IUpgradeableHost) this.getTile(); - } - return null; - } - - private IPart getPart() - { - return (IPart) ( this.iHost instanceof IPart ? this.iHost : null ); - } - - public ImmutableSet getRequestedJobs() - { - return this.craftingTracker.getRequestedJobs(); - } - - public IAEItemStack injectCraftedItems( final ICraftingLink link, final IAEItemStack acquired, final Actionable mode ) - { - final int slot = this.craftingTracker.getSlot( link ); - - if( acquired != null && slot >= 0 && slot <= this.requireWork.length ) - { - final InventoryAdaptor adaptor = this.getAdaptor( slot ); - - if( mode == Actionable.SIMULATE ) - { - return AEItemStack.create( adaptor.simulateAdd( acquired.getItemStack() ) ); - } - else - { - final IAEItemStack is = AEItemStack.create( adaptor.addItems( acquired.getItemStack() ) ); - this.updatePlan( slot ); - return is; - } - } - - return acquired; - } - - public void jobStateChange( final ICraftingLink link ) - { - this.craftingTracker.jobStateChange( link ); - } - - public String getTermName() - { - final TileEntity hostTile = this.iHost.getTileEntity(); - final World hostWorld = hostTile.getWorldObj(); - - if( ( (ICustomNameObject) this.iHost ).hasCustomName() ) - { - return ( (ICustomNameObject) this.iHost ).getCustomName(); - } - - final EnumSet possibleDirections = this.iHost.getTargets(); - for( final ForgeDirection direction : possibleDirections ) - { - final int xPos = hostTile.xCoord + direction.offsetX; - final int yPos = hostTile.yCoord + direction.offsetY; - final int zPos = hostTile.zCoord + direction.offsetZ; - final TileEntity directedTile = hostWorld.getTileEntity( xPos, yPos, zPos ); - - if( directedTile == null ) - { - continue; - } - - if( directedTile instanceof IInterfaceHost ) - { - try - { - if( ( (IInterfaceHost) directedTile ).getInterfaceDuality().sameGrid( this.gridProxy.getGrid() ) ) - { - continue; - } - } - catch( final GridAccessException e ) - { - continue; - } - } - - final InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor( directedTile, direction.getOpposite() ); - if( directedTile instanceof ICraftingMachine || adaptor != null ) - { - if( directedTile instanceof IInventory && ( (IInventory) directedTile ).getSizeInventory() == 0 ) - { - continue; - } - - if( directedTile instanceof ISidedInventory ) - { - final int[] sides = ( (ISidedInventory) directedTile ).getAccessibleSlotsFromSide( direction.getOpposite().ordinal() ); - - if( sides == null || sides.length == 0 ) - { - continue; - } - } - - final Block directedBlock = hostWorld.getBlock( xPos, yPos, zPos ); - ItemStack what = new ItemStack( directedBlock, 1, directedBlock.getDamageValue( hostWorld, xPos, yPos, zPos ) ); - try - { - Vec3 from = Vec3.createVectorHelper( hostTile.xCoord + 0.5, hostTile.yCoord + 0.5, hostTile.zCoord + 0.5 ); - from = from.addVector( direction.offsetX * 0.501, direction.offsetY * 0.501, direction.offsetZ * 0.501 ); - final Vec3 to = from.addVector( direction.offsetX, direction.offsetY, direction.offsetZ ); - final MovingObjectPosition mop = hostWorld.rayTraceBlocks( from, to, true ); - if( mop != null && !BAD_BLOCKS.contains( directedBlock ) ) - { - if( mop.blockX == directedTile.xCoord && mop.blockY == directedTile.yCoord && mop.blockZ == directedTile.zCoord ) - { - final ItemStack g = directedBlock.getPickBlock( mop, hostWorld, directedTile.xCoord, directedTile.yCoord, directedTile.zCoord, null ); - if( g != null ) - { - what = g; - } - } - } - } - catch( final Throwable t ) - { - BAD_BLOCKS.add( directedBlock ); // nope! - } - - if( what.getItem() != null ) - { - return what.getUnlocalizedName(); - } - - final Item item = Item.getItemFromBlock( directedBlock ); - if( item == null ) - { - return directedBlock.getUnlocalizedName(); - } - } - } - - return "Nothing"; - } - - public long getSortValue() - { - final TileEntity te = this.iHost.getTileEntity(); - return ( te.zCoord << 24 ) ^ ( te.xCoord << 8 ) ^ te.yCoord; - } - - public void initialize() - { - this.updateCraftingList(); - } - - @Override - public int getPriority() - { - return this.priority; - } - - @Override - public void setPriority( final int newValue ) - { - this.priority = newValue; - this.markDirty(); - - try - { - this.gridProxy.getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.gridProxy.getNode() ) ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - private static class InterfaceRequestSource extends MachineSource - { - - public InterfaceRequestSource( final IActionHost v ) - { - super( v ); - } - } - - - private class InterfaceInventory extends MEMonitorIInventory - { - - public InterfaceInventory( final DualityInterface tileInterface ) - { - super( new AdaptorIInventory( tileInterface.storage ) ); - this.setActionSource( new MachineSource( DualityInterface.this.iHost ) ); - } - - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final BaseActionSource src ) - { - if( src instanceof InterfaceRequestSource ) - { - return input; - } - - return super.injectItems( input, type, src ); - } - - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable type, final BaseActionSource src ) - { - if( src instanceof InterfaceRequestSource ) - { - return null; - } - - return super.extractItems( request, type, src ); - } - } + } + + if (ad.simulateAdd(is.copy(), insertionMode) != null) { + return false; + } + } + + return true; + } + + @Override + public void provideCrafting(final ICraftingProviderHelper craftingTracker) { + if (this.gridProxy.isActive() && this.craftingList != null) { + for (final ICraftingPatternDetails details : this.craftingList) { + details.setPriority(this.priority); + craftingTracker.addCraftingOption(this, details); + } + } + } + + public void addDrops(final List drops) { + if (this.waitingToSend != null) { + for (final ItemStack is : this.waitingToSend) { + if (is != null) { + drops.add(is); + } + } + } + + for (final ItemStack is : this.upgrades) { + if (is != null) { + drops.add(is); + } + } + + for (final ItemStack is : this.storage) { + if (is != null) { + drops.add(is); + } + } + + for (final ItemStack is : this.patterns) { + if (is != null) { + drops.add(is); + } + } + } + + public IUpgradeableHost getHost() { + if (this.getPart() != null) { + return (IUpgradeableHost) this.getPart(); + } + if (this.getTile() instanceof IUpgradeableHost) { + return (IUpgradeableHost) this.getTile(); + } + return null; + } + + private IPart getPart() { + return (IPart) (this.iHost instanceof IPart ? this.iHost : null); + } + + public ImmutableSet getRequestedJobs() { + return this.craftingTracker.getRequestedJobs(); + } + + public IAEItemStack injectCraftedItems( + final ICraftingLink link, final IAEItemStack acquired, final Actionable mode) { + final int slot = this.craftingTracker.getSlot(link); + + if (acquired != null && slot >= 0 && slot <= this.requireWork.length) { + final InventoryAdaptor adaptor = this.getAdaptor(slot); + + if (mode == Actionable.SIMULATE) { + return AEItemStack.create(adaptor.simulateAdd(acquired.getItemStack())); + } else { + final IAEItemStack is = AEItemStack.create(adaptor.addItems(acquired.getItemStack())); + this.updatePlan(slot); + return is; + } + } + + return acquired; + } + + public void jobStateChange(final ICraftingLink link) { + this.craftingTracker.jobStateChange(link); + } + + public String getTermName() { + final TileEntity hostTile = this.iHost.getTileEntity(); + final World hostWorld = hostTile.getWorldObj(); + + if (((ICustomNameObject) this.iHost).hasCustomName()) { + return ((ICustomNameObject) this.iHost).getCustomName(); + } + + final EnumSet possibleDirections = this.iHost.getTargets(); + for (final ForgeDirection direction : possibleDirections) { + final int xPos = hostTile.xCoord + direction.offsetX; + final int yPos = hostTile.yCoord + direction.offsetY; + final int zPos = hostTile.zCoord + direction.offsetZ; + final TileEntity directedTile = hostWorld.getTileEntity(xPos, yPos, zPos); + + if (directedTile == null) { + continue; + } + + if (directedTile instanceof IInterfaceHost) { + try { + if (((IInterfaceHost) directedTile).getInterfaceDuality().sameGrid(this.gridProxy.getGrid())) { + continue; + } + } catch (final GridAccessException e) { + continue; + } + } + + final InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor(directedTile, direction.getOpposite()); + if (directedTile instanceof ICraftingMachine || adaptor != null) { + if (directedTile instanceof IInventory && ((IInventory) directedTile).getSizeInventory() == 0) { + continue; + } + + if (directedTile instanceof ISidedInventory) { + final int[] sides = ((ISidedInventory) directedTile) + .getAccessibleSlotsFromSide(direction.getOpposite().ordinal()); + + if (sides == null || sides.length == 0) { + continue; + } + } + + final Block directedBlock = hostWorld.getBlock(xPos, yPos, zPos); + ItemStack what = + new ItemStack(directedBlock, 1, directedBlock.getDamageValue(hostWorld, xPos, yPos, zPos)); + try { + Vec3 from = Vec3.createVectorHelper( + hostTile.xCoord + 0.5, hostTile.yCoord + 0.5, hostTile.zCoord + 0.5); + from = from.addVector( + direction.offsetX * 0.501, direction.offsetY * 0.501, direction.offsetZ * 0.501); + final Vec3 to = from.addVector(direction.offsetX, direction.offsetY, direction.offsetZ); + final MovingObjectPosition mop = hostWorld.rayTraceBlocks(from, to, true); + if (mop != null && !BAD_BLOCKS.contains(directedBlock)) { + if (mop.blockX == directedTile.xCoord + && mop.blockY == directedTile.yCoord + && mop.blockZ == directedTile.zCoord) { + final ItemStack g = directedBlock.getPickBlock( + mop, + hostWorld, + directedTile.xCoord, + directedTile.yCoord, + directedTile.zCoord, + null); + if (g != null) { + what = g; + } + } + } + } catch (final Throwable t) { + BAD_BLOCKS.add(directedBlock); // nope! + } + + if (what.getItem() != null) { + return what.getUnlocalizedName(); + } + + final Item item = Item.getItemFromBlock(directedBlock); + if (item == null) { + return directedBlock.getUnlocalizedName(); + } + } + } + + return "Nothing"; + } + + public long getSortValue() { + final TileEntity te = this.iHost.getTileEntity(); + return (te.zCoord << 24) ^ (te.xCoord << 8) ^ te.yCoord; + } + + public void initialize() { + this.updateCraftingList(); + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public void setPriority(final int newValue) { + this.priority = newValue; + this.markDirty(); + + try { + this.gridProxy.getGrid().postEvent(new MENetworkCraftingPatternChange(this, this.gridProxy.getNode())); + } catch (final GridAccessException e) { + // :P + } + } + + private static class InterfaceRequestSource extends MachineSource { + + public InterfaceRequestSource(final IActionHost v) { + super(v); + } + } + + private class InterfaceInventory extends MEMonitorIInventory { + + public InterfaceInventory(final DualityInterface tileInterface) { + super(new AdaptorIInventory(tileInterface.storage)); + this.setActionSource(new MachineSource(DualityInterface.this.iHost)); + } + + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable type, final BaseActionSource src) { + if (src instanceof InterfaceRequestSource) { + return input; + } + + return super.injectItems(input, type, src); + } + + @Override + public IAEItemStack extractItems( + final IAEItemStack request, final Actionable type, final BaseActionSource src) { + if (src instanceof InterfaceRequestSource) { + return null; + } + + return super.extractItems(request, type, src); + } + } } diff --git a/src/main/java/appeng/helpers/HighlighterHandler.java b/src/main/java/appeng/helpers/HighlighterHandler.java index 5ea8175b6a3..ce03f96cfe8 100644 --- a/src/main/java/appeng/helpers/HighlighterHandler.java +++ b/src/main/java/appeng/helpers/HighlighterHandler.java @@ -9,14 +9,13 @@ // inspired by McJtyLib -public class HighlighterHandler -{ +public class HighlighterHandler { - public static void tick( RenderWorldLastEvent event ) { + public static void tick(RenderWorldLastEvent event) { renderHilightedBlock(event); } - private static void renderHilightedBlock( RenderWorldLastEvent event ) { + private static void renderHilightedBlock(RenderWorldLastEvent event) { DimensionalCoord c = BlockPosHighlighter.getHighlightedBlock(); if (c == null) { return; @@ -25,7 +24,8 @@ private static void renderHilightedBlock( RenderWorldLastEvent event ) { int dimension = mc.theWorld.provider.dimensionId; long time = System.currentTimeMillis(); - if (time > BlockPosHighlighter.getExpireHighlight() || dimension != BlockPosHighlighter.getHighlightedBlock().getDimension()) { + if (time > BlockPosHighlighter.getExpireHighlight() + || dimension != BlockPosHighlighter.getHighlightedBlock().getDimension()) { BlockPosHighlighter.highlightBlock(null, -1); return; } @@ -39,15 +39,13 @@ private static void renderHilightedBlock( RenderWorldLastEvent event ) { double doubleY = p.lastTickPosY + (p.posY - p.lastTickPosY) * event.partialTicks; double doubleZ = p.lastTickPosZ + (p.posZ - p.lastTickPosZ) * event.partialTicks; - GL11.glPushMatrix(); - GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); GL11.glLineWidth(3); GL11.glTranslated(-doubleX, -doubleY, -doubleZ); - GL11.glDisable( GL11.GL_DEPTH_TEST ); - GL11.glDisable( GL11.GL_TEXTURE_2D ); - + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); renderHighLightedBlocksOutline(c.x, c.y, c.z); @@ -56,38 +54,37 @@ private static void renderHilightedBlock( RenderWorldLastEvent event ) { GL11.glPopMatrix(); } - static void renderHighLightedBlocksOutline(double x, double y, double z) - { + static void renderHighLightedBlocksOutline(double x, double y, double z) { GL11.glBegin(GL11.GL_LINE_STRIP); GL11.glVertex3d(x, y, z); - GL11.glVertex3d(x, y+1, z); - GL11.glVertex3d(x, y+1, z+1); - GL11.glVertex3d(x, y, z+1); + GL11.glVertex3d(x, y + 1, z); + GL11.glVertex3d(x, y + 1, z + 1); + GL11.glVertex3d(x, y, z + 1); GL11.glVertex3d(x, y, z); - GL11.glVertex3d(x+1, y, z); - GL11.glVertex3d(x+1, y+1, z); - GL11.glVertex3d(x+1, y+1, z+1); - GL11.glVertex3d(x+1, y, z+1); - GL11.glVertex3d(x+1, y, z); + GL11.glVertex3d(x + 1, y, z); + GL11.glVertex3d(x + 1, y + 1, z); + GL11.glVertex3d(x + 1, y + 1, z + 1); + GL11.glVertex3d(x + 1, y, z + 1); + GL11.glVertex3d(x + 1, y, z); GL11.glVertex3d(x, y, z); - GL11.glVertex3d(x+1, y, z); - GL11.glVertex3d(x+1, y, z+1); - GL11.glVertex3d(x, y, z+1); - GL11.glVertex3d(x, y+1, z+1); - GL11.glVertex3d(x+1, y+1, z+1); - GL11.glVertex3d(x+1, y+1, z); - GL11.glVertex3d(x+1, y, z); + GL11.glVertex3d(x + 1, y, z); + GL11.glVertex3d(x + 1, y, z + 1); + GL11.glVertex3d(x, y, z + 1); + GL11.glVertex3d(x, y + 1, z + 1); + GL11.glVertex3d(x + 1, y + 1, z + 1); + GL11.glVertex3d(x + 1, y + 1, z); + GL11.glVertex3d(x + 1, y, z); GL11.glVertex3d(x, y, z); - GL11.glVertex3d(x+1, y, z); - GL11.glVertex3d(x+1, y+1, z); - GL11.glVertex3d(x, y+1, z); - GL11.glVertex3d(x, y+1, z+1); - GL11.glVertex3d(x+1, y+1, z+1); - GL11.glVertex3d(x+1, y, z+1); - GL11.glVertex3d(x, y, z+1); + GL11.glVertex3d(x + 1, y, z); + GL11.glVertex3d(x + 1, y + 1, z); + GL11.glVertex3d(x, y + 1, z); + GL11.glVertex3d(x, y + 1, z + 1); + GL11.glVertex3d(x + 1, y + 1, z + 1); + GL11.glVertex3d(x + 1, y, z + 1); + GL11.glVertex3d(x, y, z + 1); GL11.glEnd(); } diff --git a/src/main/java/appeng/helpers/IContainerCraftingPacket.java b/src/main/java/appeng/helpers/IContainerCraftingPacket.java index 4a7a52a76bb..cbc8623abe7 100644 --- a/src/main/java/appeng/helpers/IContainerCraftingPacket.java +++ b/src/main/java/appeng/helpers/IContainerCraftingPacket.java @@ -18,39 +18,36 @@ package appeng.helpers; - import appeng.api.networking.IGridNode; import appeng.api.networking.security.BaseActionSource; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - -public interface IContainerCraftingPacket -{ - - /** - * @return gain access to network infrastructure. - */ - IGridNode getNetworkNode(); - - /** - * @param string name of inventory - * @return the inventory of the part/tile by name. - */ - IInventory getInventoryByName( String string ); - - /** - * @return who are we? - */ - BaseActionSource getActionSource(); - - /** - * @return consume items? - */ - boolean useRealItems(); - - /** - * @return array of view cells - */ - ItemStack[] getViewCells(); +public interface IContainerCraftingPacket { + + /** + * @return gain access to network infrastructure. + */ + IGridNode getNetworkNode(); + + /** + * @param string name of inventory + * @return the inventory of the part/tile by name. + */ + IInventory getInventoryByName(String string); + + /** + * @return who are we? + */ + BaseActionSource getActionSource(); + + /** + * @return consume items? + */ + boolean useRealItems(); + + /** + * @return array of view cells + */ + ItemStack[] getViewCells(); } diff --git a/src/main/java/appeng/helpers/ICustomCollision.java b/src/main/java/appeng/helpers/ICustomCollision.java index 79059c5e88b..f1127ed6926 100644 --- a/src/main/java/appeng/helpers/ICustomCollision.java +++ b/src/main/java/appeng/helpers/ICustomCollision.java @@ -18,17 +18,13 @@ package appeng.helpers; - +import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; -import java.util.List; - - -public interface ICustomCollision -{ - Iterable getSelectedBoundingBoxesFromPool( World w, int x, int y, int z, Entity thePlayer, boolean b ); +public interface ICustomCollision { + Iterable getSelectedBoundingBoxesFromPool(World w, int x, int y, int z, Entity thePlayer, boolean b); - void addCollidingBlockToList( World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e ); + void addCollidingBlockToList(World w, int x, int y, int z, AxisAlignedBB bb, List out, Entity e); } diff --git a/src/main/java/appeng/helpers/ICustomNameObject.java b/src/main/java/appeng/helpers/ICustomNameObject.java index a894bbc477b..a129b411f67 100644 --- a/src/main/java/appeng/helpers/ICustomNameObject.java +++ b/src/main/java/appeng/helpers/ICustomNameObject.java @@ -18,12 +18,10 @@ package appeng.helpers; +public interface ICustomNameObject { + String getCustomName(); -public interface ICustomNameObject -{ - String getCustomName(); + boolean hasCustomName(); - boolean hasCustomName(); - - void setCustomName(String name); + void setCustomName(String name); } diff --git a/src/main/java/appeng/helpers/IInterfaceHost.java b/src/main/java/appeng/helpers/IInterfaceHost.java index e08813c1254..25bdaa7386a 100644 --- a/src/main/java/appeng/helpers/IInterfaceHost.java +++ b/src/main/java/appeng/helpers/IInterfaceHost.java @@ -18,24 +18,20 @@ package appeng.helpers; - import appeng.api.implementations.IUpgradeableHost; import appeng.api.networking.crafting.ICraftingProvider; import appeng.api.networking.crafting.ICraftingRequester; +import java.util.EnumSet; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public interface IInterfaceHost extends ICraftingProvider, IUpgradeableHost, ICraftingRequester -{ +public interface IInterfaceHost extends ICraftingProvider, IUpgradeableHost, ICraftingRequester { - DualityInterface getInterfaceDuality(); + DualityInterface getInterfaceDuality(); - EnumSet getTargets(); + EnumSet getTargets(); - TileEntity getTileEntity(); + TileEntity getTileEntity(); - void saveChanges(); + void saveChanges(); } diff --git a/src/main/java/appeng/helpers/IMouseWheelItem.java b/src/main/java/appeng/helpers/IMouseWheelItem.java index cc223005df5..16294b70e0f 100644 --- a/src/main/java/appeng/helpers/IMouseWheelItem.java +++ b/src/main/java/appeng/helpers/IMouseWheelItem.java @@ -18,12 +18,9 @@ package appeng.helpers; - import net.minecraft.item.ItemStack; +public interface IMouseWheelItem { -public interface IMouseWheelItem -{ - - void onWheel( ItemStack is, boolean up ); + void onWheel(ItemStack is, boolean up); } diff --git a/src/main/java/appeng/helpers/IOreFilterable.java b/src/main/java/appeng/helpers/IOreFilterable.java index edbab215e46..77a5e43be88 100644 --- a/src/main/java/appeng/helpers/IOreFilterable.java +++ b/src/main/java/appeng/helpers/IOreFilterable.java @@ -1,7 +1,6 @@ package appeng.helpers; -public interface IOreFilterable -{ +public interface IOreFilterable { /** * Get oredictionary filter */ diff --git a/src/main/java/appeng/helpers/IPriorityHost.java b/src/main/java/appeng/helpers/IPriorityHost.java index 083fd8ca408..4183abafc32 100644 --- a/src/main/java/appeng/helpers/IPriorityHost.java +++ b/src/main/java/appeng/helpers/IPriorityHost.java @@ -18,17 +18,15 @@ package appeng.helpers; +public interface IPriorityHost { -public interface IPriorityHost -{ + /** + * get current priority. + */ + int getPriority(); - /** - * get current priority. - */ - int getPriority(); - - /** - * set new priority - */ - void setPriority( int newValue ); + /** + * set new priority + */ + void setPriority(int newValue); } diff --git a/src/main/java/appeng/helpers/InventoryAction.java b/src/main/java/appeng/helpers/InventoryAction.java index c22a10ead0d..11698a0c6be 100644 --- a/src/main/java/appeng/helpers/InventoryAction.java +++ b/src/main/java/appeng/helpers/InventoryAction.java @@ -18,15 +18,25 @@ package appeng.helpers; +public enum InventoryAction { + // standard vanilla mechanics. + PICKUP_OR_SET_DOWN, + SPLIT_OR_PLACE_SINGLE, + CREATIVE_DUPLICATE, + SHIFT_CLICK, -public enum InventoryAction -{ - // standard vanilla mechanics. - PICKUP_OR_SET_DOWN, SPLIT_OR_PLACE_SINGLE, CREATIVE_DUPLICATE, SHIFT_CLICK, + // crafting term + CRAFT_STACK, + CRAFT_ITEM, + CRAFT_SHIFT, - // crafting term - CRAFT_STACK, CRAFT_ITEM, CRAFT_SHIFT, - - // extra... - MOVE_REGION, PICKUP_SINGLE, UPDATE_HAND, ROLL_UP, ROLL_DOWN, AUTO_CRAFT, PLACE_SINGLE,SET_PATTERN_VALUE, + // extra... + MOVE_REGION, + PICKUP_SINGLE, + UPDATE_HAND, + ROLL_UP, + ROLL_DOWN, + AUTO_CRAFT, + PLACE_SINGLE, + SET_PATTERN_VALUE, } diff --git a/src/main/java/appeng/helpers/LocationRotation.java b/src/main/java/appeng/helpers/LocationRotation.java index a077ab5d1b3..5cb8c6d4f37 100644 --- a/src/main/java/appeng/helpers/LocationRotation.java +++ b/src/main/java/appeng/helpers/LocationRotation.java @@ -18,54 +18,43 @@ package appeng.helpers; - import appeng.api.util.IOrientable; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; - -public class LocationRotation implements IOrientable -{ - - private final IBlockAccess w; - private final int x; - private final int y; - private final int z; - - public LocationRotation( final IBlockAccess world, final int x, final int y, final int z ) - { - this.w = world; - this.x = x; - this.y = y; - this.z = z; - } - - @Override - public boolean canBeRotated() - { - return false; - } - - @Override - public ForgeDirection getForward() - { - if( this.getUp().offsetY == 0 ) - { - return ForgeDirection.UP; - } - return ForgeDirection.SOUTH; - } - - @Override - public ForgeDirection getUp() - { - final int num = Math.abs( this.x + this.y + this.z ) % 6; - return ForgeDirection.getOrientation( num ); - } - - @Override - public void setOrientation( final ForgeDirection forward, final ForgeDirection up ) - { - - } +public class LocationRotation implements IOrientable { + + private final IBlockAccess w; + private final int x; + private final int y; + private final int z; + + public LocationRotation(final IBlockAccess world, final int x, final int y, final int z) { + this.w = world; + this.x = x; + this.y = y; + this.z = z; + } + + @Override + public boolean canBeRotated() { + return false; + } + + @Override + public ForgeDirection getForward() { + if (this.getUp().offsetY == 0) { + return ForgeDirection.UP; + } + return ForgeDirection.SOUTH; + } + + @Override + public ForgeDirection getUp() { + final int num = Math.abs(this.x + this.y + this.z) % 6; + return ForgeDirection.getOrientation(num); + } + + @Override + public void setOrientation(final ForgeDirection forward, final ForgeDirection up) {} } diff --git a/src/main/java/appeng/helpers/MetaRotation.java b/src/main/java/appeng/helpers/MetaRotation.java index 9db4bca3755..36ae0540dfd 100644 --- a/src/main/java/appeng/helpers/MetaRotation.java +++ b/src/main/java/appeng/helpers/MetaRotation.java @@ -18,61 +18,49 @@ package appeng.helpers; - import appeng.api.util.IOrientable; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +public class MetaRotation implements IOrientable { -public class MetaRotation implements IOrientable -{ - - private final IBlockAccess w; - private final int x; - private final int y; - private final int z; + private final IBlockAccess w; + private final int x; + private final int y; + private final int z; - public MetaRotation( final IBlockAccess world, final int x, final int y, final int z ) - { - this.w = world; - this.x = x; - this.y = y; - this.z = z; - } + public MetaRotation(final IBlockAccess world, final int x, final int y, final int z) { + this.w = world; + this.x = x; + this.y = y; + this.z = z; + } - @Override - public boolean canBeRotated() - { - return true; - } + @Override + public boolean canBeRotated() { + return true; + } - @Override - public ForgeDirection getForward() - { - if( this.getUp().offsetY == 0 ) - { - return ForgeDirection.UP; - } - return ForgeDirection.SOUTH; - } + @Override + public ForgeDirection getForward() { + if (this.getUp().offsetY == 0) { + return ForgeDirection.UP; + } + return ForgeDirection.SOUTH; + } - @Override - public ForgeDirection getUp() - { - return ForgeDirection.getOrientation( this.w.getBlockMetadata( this.x, this.y, this.z ) ); - } + @Override + public ForgeDirection getUp() { + return ForgeDirection.getOrientation(this.w.getBlockMetadata(this.x, this.y, this.z)); + } - @Override - public void setOrientation( final ForgeDirection forward, final ForgeDirection up ) - { - if( this.w instanceof World ) - { - ( (World) this.w ).setBlockMetadataWithNotify( this.x, this.y, this.z, up.ordinal(), 1 + 2 ); - } - else - { - throw new IllegalStateException( this.w.getClass().getName() + " received, expected World" ); - } - } + @Override + public void setOrientation(final ForgeDirection forward, final ForgeDirection up) { + if (this.w instanceof World) { + ((World) this.w).setBlockMetadataWithNotify(this.x, this.y, this.z, up.ordinal(), 1 + 2); + } else { + throw new IllegalStateException(this.w.getClass().getName() + " received, expected World"); + } + } } diff --git a/src/main/java/appeng/helpers/MultiCraftingTracker.java b/src/main/java/appeng/helpers/MultiCraftingTracker.java index 014fa61d2b1..404b69149e1 100644 --- a/src/main/java/appeng/helpers/MultiCraftingTracker.java +++ b/src/main/java/appeng/helpers/MultiCraftingTracker.java @@ -18,7 +18,6 @@ package appeng.helpers; - import appeng.api.AEApi; import appeng.api.networking.IGrid; import appeng.api.networking.crafting.ICraftingGrid; @@ -29,260 +28,208 @@ import appeng.api.storage.data.IAEItemStack; import appeng.util.InventoryAdaptor; import com.google.common.collect.ImmutableSet; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; - import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; - -public class MultiCraftingTracker -{ - - private final int size; - private final ICraftingRequester owner; - - private Future[] jobs = null; - private ICraftingLink[] links = null; - - public MultiCraftingTracker( final ICraftingRequester o, final int size ) - { - this.owner = o; - this.size = size; - } - - public void readFromNBT( final NBTTagCompound extra ) - { - for( int x = 0; x < this.size; x++ ) - { - final NBTTagCompound link = extra.getCompoundTag( "links-" + x ); - - if( link != null && !link.hasNoTags() ) - { - this.setLink( x, AEApi.instance().storage().loadCraftingLink( link, this.owner ) ); - } - } - } - - public void writeToNBT( final NBTTagCompound extra ) - { - for( int x = 0; x < this.size; x++ ) - { - final ICraftingLink link = this.getLink( x ); - - if( link != null ) - { - final NBTTagCompound ln = new NBTTagCompound(); - link.writeToNBT( ln ); - extra.setTag( "links-" + x, ln ); - } - } - } - - public boolean handleCrafting( final int x, final long itemToCraft, final IAEItemStack ais, final InventoryAdaptor d, final World w, final IGrid g, final ICraftingGrid cg, final BaseActionSource mySrc ) - { - if( ais != null && d.simulateAdd( ais.getItemStack() ) == null ) - { - final Future craftingJob = this.getJob( x ); - - if( this.getLink( x ) != null ) - { - return false; - } - else if( craftingJob != null ) - { - try - { - ICraftingJob job = null; - if( craftingJob.isDone() ) - { - job = craftingJob.get(); - } - - if( job != null ) - { - final ICraftingLink link = cg.submitJob( job, this.owner, null, false, mySrc ); - - this.setJob( x, null ); - - if( link != null ) - { - this.setLink( x, link ); - - return true; - } - } - } - catch( final InterruptedException e ) - { - // :P - } - catch( final ExecutionException e ) - { - // :P - } - } - else - { - if( this.getLink( x ) == null ) - { - final IAEItemStack aisC = ais.copy(); - aisC.setStackSize( itemToCraft ); - - this.setJob( x, cg.beginCraftingJob( w, g, mySrc, aisC, null ) ); - } - } - } - return false; - } - - public ImmutableSet getRequestedJobs() - { - if( this.links == null ) - { - return ImmutableSet.of(); - } - - return ImmutableSet.copyOf( new NonNullArrayIterator( this.links ) ); - } - - public void jobStateChange( final ICraftingLink link ) - { - if( this.links != null ) - { - for( int x = 0; x < this.links.length; x++ ) - { - if( this.links[x] == link ) - { - this.setLink( x, null ); - return; - } - } - } - } - - int getSlot( final ICraftingLink link ) - { - if( this.links != null ) - { - for( int x = 0; x < this.links.length; x++ ) - { - if( this.links[x] == link ) - { - return x; - } - } - } - - return -1; - } - - void cancel() - { - if( this.links != null ) - { - for( final ICraftingLink l : this.links ) - { - if( l != null ) - { - l.cancel(); - } - } - - this.links = null; - } - - if( this.jobs != null ) - { - for( final Future l : this.jobs ) - { - if( l != null ) - { - l.cancel( true ); - } - } - - this.jobs = null; - } - } - - boolean isBusy( final int slot ) - { - return this.getLink( slot ) != null || this.getJob( slot ) != null; - } - - private ICraftingLink getLink( final int slot ) - { - if( this.links == null ) - { - return null; - } - - return this.links[slot]; - } - - private void setLink( final int slot, final ICraftingLink l ) - { - if( this.links == null ) - { - this.links = new ICraftingLink[this.size]; - } - - this.links[slot] = l; - - boolean hasStuff = false; - for( int x = 0; x < this.links.length; x++ ) - { - final ICraftingLink g = this.links[x]; - - if( g == null || g.isCanceled() || g.isDone() ) - { - this.links[x] = null; - } - else - { - hasStuff = true; - } - } - - if( !hasStuff ) - { - this.links = null; - } - } - - private Future getJob( final int slot ) - { - if( this.jobs == null ) - { - return null; - } - - return this.jobs[slot]; - } - - private void setJob( final int slot, final Future l ) - { - if( this.jobs == null ) - { - this.jobs = new Future[this.size]; - } - - this.jobs[slot] = l; - - boolean hasStuff = false; - - for( final Future job : this.jobs ) - { - if( job != null ) - { - hasStuff = true; - } - } - - if( !hasStuff ) - { - this.jobs = null; - } - } +public class MultiCraftingTracker { + + private final int size; + private final ICraftingRequester owner; + + private Future[] jobs = null; + private ICraftingLink[] links = null; + + public MultiCraftingTracker(final ICraftingRequester o, final int size) { + this.owner = o; + this.size = size; + } + + public void readFromNBT(final NBTTagCompound extra) { + for (int x = 0; x < this.size; x++) { + final NBTTagCompound link = extra.getCompoundTag("links-" + x); + + if (link != null && !link.hasNoTags()) { + this.setLink(x, AEApi.instance().storage().loadCraftingLink(link, this.owner)); + } + } + } + + public void writeToNBT(final NBTTagCompound extra) { + for (int x = 0; x < this.size; x++) { + final ICraftingLink link = this.getLink(x); + + if (link != null) { + final NBTTagCompound ln = new NBTTagCompound(); + link.writeToNBT(ln); + extra.setTag("links-" + x, ln); + } + } + } + + public boolean handleCrafting( + final int x, + final long itemToCraft, + final IAEItemStack ais, + final InventoryAdaptor d, + final World w, + final IGrid g, + final ICraftingGrid cg, + final BaseActionSource mySrc) { + if (ais != null && d.simulateAdd(ais.getItemStack()) == null) { + final Future craftingJob = this.getJob(x); + + if (this.getLink(x) != null) { + return false; + } else if (craftingJob != null) { + try { + ICraftingJob job = null; + if (craftingJob.isDone()) { + job = craftingJob.get(); + } + + if (job != null) { + final ICraftingLink link = cg.submitJob(job, this.owner, null, false, mySrc); + + this.setJob(x, null); + + if (link != null) { + this.setLink(x, link); + + return true; + } + } + } catch (final InterruptedException e) { + // :P + } catch (final ExecutionException e) { + // :P + } + } else { + if (this.getLink(x) == null) { + final IAEItemStack aisC = ais.copy(); + aisC.setStackSize(itemToCraft); + + this.setJob(x, cg.beginCraftingJob(w, g, mySrc, aisC, null)); + } + } + } + return false; + } + + public ImmutableSet getRequestedJobs() { + if (this.links == null) { + return ImmutableSet.of(); + } + + return ImmutableSet.copyOf(new NonNullArrayIterator(this.links)); + } + + public void jobStateChange(final ICraftingLink link) { + if (this.links != null) { + for (int x = 0; x < this.links.length; x++) { + if (this.links[x] == link) { + this.setLink(x, null); + return; + } + } + } + } + + int getSlot(final ICraftingLink link) { + if (this.links != null) { + for (int x = 0; x < this.links.length; x++) { + if (this.links[x] == link) { + return x; + } + } + } + + return -1; + } + + void cancel() { + if (this.links != null) { + for (final ICraftingLink l : this.links) { + if (l != null) { + l.cancel(); + } + } + + this.links = null; + } + + if (this.jobs != null) { + for (final Future l : this.jobs) { + if (l != null) { + l.cancel(true); + } + } + + this.jobs = null; + } + } + + boolean isBusy(final int slot) { + return this.getLink(slot) != null || this.getJob(slot) != null; + } + + private ICraftingLink getLink(final int slot) { + if (this.links == null) { + return null; + } + + return this.links[slot]; + } + + private void setLink(final int slot, final ICraftingLink l) { + if (this.links == null) { + this.links = new ICraftingLink[this.size]; + } + + this.links[slot] = l; + + boolean hasStuff = false; + for (int x = 0; x < this.links.length; x++) { + final ICraftingLink g = this.links[x]; + + if (g == null || g.isCanceled() || g.isDone()) { + this.links[x] = null; + } else { + hasStuff = true; + } + } + + if (!hasStuff) { + this.links = null; + } + } + + private Future getJob(final int slot) { + if (this.jobs == null) { + return null; + } + + return this.jobs[slot]; + } + + private void setJob(final int slot, final Future l) { + if (this.jobs == null) { + this.jobs = new Future[this.size]; + } + + this.jobs[slot] = l; + + boolean hasStuff = false; + + for (final Future job : this.jobs) { + if (job != null) { + hasStuff = true; + } + } + + if (!hasStuff) { + this.jobs = null; + } + } } diff --git a/src/main/java/appeng/helpers/NonNullArrayIterator.java b/src/main/java/appeng/helpers/NonNullArrayIterator.java index e2ada1003f8..ab18a4f2a58 100644 --- a/src/main/java/appeng/helpers/NonNullArrayIterator.java +++ b/src/main/java/appeng/helpers/NonNullArrayIterator.java @@ -18,46 +18,37 @@ package appeng.helpers; - -import scala.NotImplementedError; - import java.util.Iterator; +import scala.NotImplementedError; +public class NonNullArrayIterator implements Iterator { -public class NonNullArrayIterator implements Iterator -{ - - private final E[] g; - private int offset = 0; + private final E[] g; + private int offset = 0; - public NonNullArrayIterator( final E[] o ) - { - this.g = o; - } + public NonNullArrayIterator(final E[] o) { + this.g = o; + } - @Override - public boolean hasNext() - { - while( this.offset < this.g.length && this.g[this.offset] == null ) - { - this.offset++; - } + @Override + public boolean hasNext() { + while (this.offset < this.g.length && this.g[this.offset] == null) { + this.offset++; + } - return this.offset != this.g.length; - } + return this.offset != this.g.length; + } - @Override - public E next() - { - final E result = this.g[this.offset]; - this.offset++; + @Override + public E next() { + final E result = this.g[this.offset]; + this.offset++; - return result; - } + return result; + } - @Override - public void remove() - { - throw new NotImplementedError(); - } + @Override + public void remove() { + throw new NotImplementedError(); + } } diff --git a/src/main/java/appeng/helpers/NullRotation.java b/src/main/java/appeng/helpers/NullRotation.java index 342191de0d3..effa43d4d54 100644 --- a/src/main/java/appeng/helpers/NullRotation.java +++ b/src/main/java/appeng/helpers/NullRotation.java @@ -18,40 +18,28 @@ package appeng.helpers; - import appeng.api.util.IOrientable; import net.minecraftforge.common.util.ForgeDirection; +public class NullRotation implements IOrientable { -public class NullRotation implements IOrientable -{ - - public NullRotation() - { - - } - - @Override - public boolean canBeRotated() - { - return false; - } + public NullRotation() {} - @Override - public ForgeDirection getForward() - { - return ForgeDirection.SOUTH; - } + @Override + public boolean canBeRotated() { + return false; + } - @Override - public ForgeDirection getUp() - { - return ForgeDirection.UP; - } + @Override + public ForgeDirection getForward() { + return ForgeDirection.SOUTH; + } - @Override - public void setOrientation( final ForgeDirection forward, final ForgeDirection up ) - { + @Override + public ForgeDirection getUp() { + return ForgeDirection.UP; + } - } + @Override + public void setOrientation(final ForgeDirection forward, final ForgeDirection up) {} } diff --git a/src/main/java/appeng/helpers/PatternHelper.java b/src/main/java/appeng/helpers/PatternHelper.java index a13ae2565f9..428d8469eba 100644 --- a/src/main/java/appeng/helpers/PatternHelper.java +++ b/src/main/java/appeng/helpers/PatternHelper.java @@ -18,7 +18,6 @@ package appeng.helpers; - import appeng.api.AEApi; import appeng.api.networking.crafting.ICraftingPatternDetails; import appeng.api.storage.data.IAEItemStack; @@ -26,6 +25,7 @@ import appeng.util.ItemSorters; import appeng.util.Platform; import appeng.util.item.AEItemStack; +import java.util.*; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -35,430 +35,360 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.world.World; -import java.util.*; +public class PatternHelper implements ICraftingPatternDetails, Comparable { + + private final ItemStack patternItem; + private final InventoryCrafting crafting = new InventoryCrafting(new ContainerNull(), 3, 3); + private final InventoryCrafting testFrame = new InventoryCrafting(new ContainerNull(), 3, 3); + private final ItemStack correctOutput; + private final IRecipe standardRecipe; + private final IAEItemStack[] condensedInputs; + private final IAEItemStack[] condensedOutputs; + private final IAEItemStack[] inputs; + private final IAEItemStack[] outputs; + private final boolean isCrafting; + private final boolean canSubstitute; + private final Set failCache = new HashSet(); + private final Set passCache = new HashSet(); + private final IAEItemStack pattern; + private int priority = 0; + + public PatternHelper(final ItemStack is, final World w) { + final NBTTagCompound encodedValue = is.getTagCompound(); + + if (encodedValue == null) { + throw new IllegalArgumentException("No pattern here!"); + } + + final NBTTagList inTag = encodedValue.getTagList("in", 10); + final NBTTagList outTag = encodedValue.getTagList("out", 10); + this.isCrafting = encodedValue.getBoolean("crafting"); + + this.canSubstitute = encodedValue.getBoolean("substitute"); + this.patternItem = is; + this.pattern = AEItemStack.create(is); + + final List in = new ArrayList(); + final List out = new ArrayList(); + + for (int x = 0; x < inTag.tagCount(); x++) { + final NBTTagCompound tag = inTag.getCompoundTagAt(x); + final ItemStack gs = Platform.loadItemStackFromNBT(tag); + + if (gs == null && !tag.hasNoTags()) { + throw new IllegalStateException("No pattern here!"); + } + + if (this.isCrafting) // processing recipes are not looked up + { + this.crafting.setInventorySlotContents(x, gs); + } + + if (gs != null && (!this.isCrafting || !gs.hasTagCompound())) { + this.markItemAs(x, gs, TestStatus.ACCEPT); + } + + in.add(AEApi.instance().storage().createItemStack(gs)); + if (this.isCrafting) // processing recipes are not tested anyway + { + this.testFrame.setInventorySlotContents(x, gs); + } + } + + if (this.isCrafting) { + this.standardRecipe = Platform.findMatchingRecipe(this.crafting, w); + + if (this.standardRecipe != null) { + this.correctOutput = this.standardRecipe.getCraftingResult(this.crafting); + out.add(AEApi.instance().storage().createItemStack(this.correctOutput)); + } else { + throw new IllegalStateException("No pattern here!"); + } + } else { + this.standardRecipe = null; + this.correctOutput = null; + + for (int x = 0; x < outTag.tagCount(); x++) { + final NBTTagCompound tag = outTag.getCompoundTagAt(x); + final ItemStack gs = Platform.loadItemStackFromNBT(tag); + + if (gs != null) { + out.add(AEApi.instance().storage().createItemStack(gs)); + } else if (!tag.hasNoTags()) { + throw new IllegalStateException("No pattern here!"); + } + } + } + + this.outputs = out.toArray(new IAEItemStack[out.size()]); + this.inputs = in.toArray(new IAEItemStack[in.size()]); + + this.condensedInputs = convertToCondensedList(this.inputs); + this.condensedOutputs = convertToCondensedList(this.outputs); + + if (condensedInputs.length == 0 || condensedOutputs.length == 0) { + throw new IllegalStateException("No pattern here!"); + } + } + + private void markItemAs(final int slotIndex, final ItemStack i, final TestStatus b) { + if (b == TestStatus.TEST || i.hasTagCompound()) { + return; + } + + (b == TestStatus.ACCEPT ? this.passCache : this.failCache).add(new TestLookup(slotIndex, i)); + } + + @Override + public ItemStack getPattern() { + return this.patternItem; + } + + @Override + public synchronized boolean isValidItemForSlot(final int slotIndex, final ItemStack i, final World w) { + if (!this.isCrafting) { + throw new IllegalStateException("Only crafting recipes supported."); + } + + final TestStatus result = this.getStatus(slotIndex, i); + + switch (result) { + case ACCEPT: + return true; + case DECLINE: + return false; + case TEST: + default: + break; + } + + for (int x = 0; x < this.crafting.getSizeInventory(); x++) { + this.testFrame.setInventorySlotContents(x, this.crafting.getStackInSlot(x)); + } + + this.testFrame.setInventorySlotContents(slotIndex, i); + + if (this.standardRecipe.matches(this.testFrame, w)) { + final ItemStack testOutput = this.standardRecipe.getCraftingResult(this.testFrame); + + if (Platform.isSameItemPrecise(this.correctOutput, testOutput)) { + this.testFrame.setInventorySlotContents(slotIndex, this.crafting.getStackInSlot(slotIndex)); + this.markItemAs(slotIndex, i, TestStatus.ACCEPT); + return true; + } + } else { + final ItemStack testOutput = CraftingManager.getInstance().findMatchingRecipe(this.testFrame, w); + if (Platform.isSameItemPrecise(this.correctOutput, testOutput)) { + this.testFrame.setInventorySlotContents(slotIndex, this.crafting.getStackInSlot(slotIndex)); + this.markItemAs(slotIndex, i, TestStatus.ACCEPT); + return true; + } + } + + this.markItemAs(slotIndex, i, TestStatus.DECLINE); + return false; + } + + @Override + public boolean isCraftable() { + return this.isCrafting; + } + + @Override + public IAEItemStack[] getInputs() { + return this.inputs; + } + + @Override + public IAEItemStack[] getCondensedInputs() { + return this.condensedInputs; + } + + @Override + public IAEItemStack[] getCondensedOutputs() { + return this.condensedOutputs; + } + + @Override + public IAEItemStack[] getOutputs() { + return this.outputs; + } + + @Override + public boolean canSubstitute() { + return this.canSubstitute; + } + + @Override + public ItemStack getOutput(final InventoryCrafting craftingInv, final World w) { + if (!this.isCrafting) { + throw new IllegalStateException("Only crafting recipes supported."); + } + + for (int x = 0; x < craftingInv.getSizeInventory(); x++) { + if (!this.isValidItemForSlot(x, craftingInv.getStackInSlot(x), w)) { + return null; + } + } + + if (this.outputs != null && this.outputs.length > 0) { + return this.outputs[0].getItemStack(); + } + + return null; + } + + private TestStatus getStatus(final int slotIndex, final ItemStack i) { + if (this.crafting.getStackInSlot(slotIndex) == null) { + return i == null ? TestStatus.ACCEPT : TestStatus.DECLINE; + } + + if (i == null) { + return TestStatus.DECLINE; + } + + if (i.hasTagCompound()) { + return TestStatus.TEST; + } + + if (this.passCache.contains(new TestLookup(slotIndex, i))) { + return TestStatus.ACCEPT; + } + + if (this.failCache.contains(new TestLookup(slotIndex, i))) { + return TestStatus.DECLINE; + } + + return TestStatus.TEST; + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public void setPriority(final int priority) { + this.priority = priority; + } + + @Override + public int compareTo(final PatternHelper o) { + return ItemSorters.compareInt(o.priority, this.priority); + } + + @Override + public int hashCode() { + return this.pattern.hashCode(); + } + + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + + final PatternHelper other = (PatternHelper) obj; + + if (this.pattern != null && other.pattern != null) { + return this.pattern.equals(other.pattern); + } + return false; + } + + private enum TestStatus { + ACCEPT, + DECLINE, + TEST + } + + private static final class TestLookup { + + private final int slot; + private final int ref; + private final int hash; + + public TestLookup(final int slot, final ItemStack i) { + this(slot, i.getItem(), i.getItemDamage()); + } + + public TestLookup(final int slot, final Item item, final int dmg) { + this.slot = slot; + this.ref = (dmg << Platform.DEF_OFFSET) | (Item.getIdFromItem(item) & 0xffff); + final int offset = 3 * slot; + this.hash = (this.ref << offset) | (this.ref >> (offset + 32)); + } + + @Override + public int hashCode() { + return this.hash; + } + + @Override + public boolean equals(final Object obj) { + final boolean equality; + + if (obj instanceof TestLookup) { + final TestLookup b = (TestLookup) obj; + + equality = b.slot == this.slot && b.ref == this.ref; + } else { + equality = false; + } + + return equality; + } + } -public class PatternHelper implements ICraftingPatternDetails, Comparable -{ - - private final ItemStack patternItem; - private final InventoryCrafting crafting = new InventoryCrafting( new ContainerNull(), 3, 3 ); - private final InventoryCrafting testFrame = new InventoryCrafting( new ContainerNull(), 3, 3 ); - private final ItemStack correctOutput; - private final IRecipe standardRecipe; - private final IAEItemStack[] condensedInputs; - private final IAEItemStack[] condensedOutputs; - private final IAEItemStack[] inputs; - private final IAEItemStack[] outputs; - private final boolean isCrafting; - private final boolean canSubstitute; - private final Set failCache = new HashSet(); - private final Set passCache = new HashSet(); - private final IAEItemStack pattern; - private int priority = 0; - - public PatternHelper( final ItemStack is, final World w ) - { - final NBTTagCompound encodedValue = is.getTagCompound(); - - if( encodedValue == null ) - { - throw new IllegalArgumentException( "No pattern here!" ); - } - - final NBTTagList inTag = encodedValue.getTagList( "in", 10 ); - final NBTTagList outTag = encodedValue.getTagList( "out", 10 ); - this.isCrafting = encodedValue.getBoolean( "crafting" ); - - this.canSubstitute = encodedValue.getBoolean( "substitute" ); - this.patternItem = is; - this.pattern = AEItemStack.create( is ); - - final List in = new ArrayList(); - final List out = new ArrayList(); - - for( int x = 0; x < inTag.tagCount(); x++ ) - { - final NBTTagCompound tag = inTag.getCompoundTagAt( x ); - final ItemStack gs = Platform.loadItemStackFromNBT( tag ); - - if ( gs == null && !tag.hasNoTags() ) - { - throw new IllegalStateException( "No pattern here!" ); - } - - if( this.isCrafting ) // processing recipes are not looked up - { - this.crafting.setInventorySlotContents( x, gs ); - } - - if( gs != null && ( !this.isCrafting || !gs.hasTagCompound() ) ) - { - this.markItemAs( x, gs, TestStatus.ACCEPT ); - } - - in.add( AEApi.instance().storage().createItemStack( gs ) ); - if( this.isCrafting ) // processing recipes are not tested anyway - { - this.testFrame.setInventorySlotContents( x, gs ); - } - } - - if( this.isCrafting ) - { - this.standardRecipe = Platform.findMatchingRecipe( this.crafting, w ); - - if( this.standardRecipe != null ) - { - this.correctOutput = this.standardRecipe.getCraftingResult( this.crafting ); - out.add( AEApi.instance().storage().createItemStack( this.correctOutput ) ); - } - else - { - throw new IllegalStateException( "No pattern here!" ); - } - } - else - { - this.standardRecipe = null; - this.correctOutput = null; - - for( int x = 0; x < outTag.tagCount(); x++ ) - { - final NBTTagCompound tag = outTag.getCompoundTagAt(x); - final ItemStack gs = Platform.loadItemStackFromNBT( tag ); - - if( gs != null ) - { - out.add( AEApi.instance().storage().createItemStack( gs ) ); - } - else if ( !tag.hasNoTags() ) - { - throw new IllegalStateException( "No pattern here!" ); - } - } - } - - this.outputs = out.toArray( new IAEItemStack[out.size()] ); - this.inputs = in.toArray( new IAEItemStack[in.size()] ); - - this.condensedInputs = convertToCondensedList(this.inputs); - this.condensedOutputs = convertToCondensedList(this.outputs); - - if (condensedInputs.length == 0 || condensedOutputs.length == 0) { - throw new IllegalStateException( "No pattern here!" ); - } - - } - - private void markItemAs( final int slotIndex, final ItemStack i, final TestStatus b ) - { - if( b == TestStatus.TEST || i.hasTagCompound() ) - { - return; - } - - ( b == TestStatus.ACCEPT ? this.passCache : this.failCache ).add( new TestLookup( slotIndex, i ) ); - } - - @Override - public ItemStack getPattern() - { - return this.patternItem; - } - - @Override - public synchronized boolean isValidItemForSlot( final int slotIndex, final ItemStack i, final World w ) - { - if( !this.isCrafting ) - { - throw new IllegalStateException( "Only crafting recipes supported." ); - } - - final TestStatus result = this.getStatus( slotIndex, i ); - - switch( result ) - { - case ACCEPT: - return true; - case DECLINE: - return false; - case TEST: - default: - break; - } - - for( int x = 0; x < this.crafting.getSizeInventory(); x++ ) - { - this.testFrame.setInventorySlotContents( x, this.crafting.getStackInSlot( x ) ); - } - - this.testFrame.setInventorySlotContents( slotIndex, i ); - - if( this.standardRecipe.matches( this.testFrame, w ) ) - { - final ItemStack testOutput = this.standardRecipe.getCraftingResult( this.testFrame ); - - if( Platform.isSameItemPrecise( this.correctOutput, testOutput ) ) - { - this.testFrame.setInventorySlotContents( slotIndex, this.crafting.getStackInSlot( slotIndex ) ); - this.markItemAs( slotIndex, i, TestStatus.ACCEPT ); - return true; - } - } - else - { - final ItemStack testOutput = CraftingManager.getInstance().findMatchingRecipe( this.testFrame, w ); - - if( Platform.isSameItemPrecise( this.correctOutput, testOutput ) ) - { - this.testFrame.setInventorySlotContents( slotIndex, this.crafting.getStackInSlot( slotIndex ) ); - this.markItemAs( slotIndex, i, TestStatus.ACCEPT ); - return true; - } - } - - this.markItemAs( slotIndex, i, TestStatus.DECLINE ); - return false; - } - - @Override - public boolean isCraftable() - { - return this.isCrafting; - } - - @Override - public IAEItemStack[] getInputs() - { - return this.inputs; - } - - @Override - public IAEItemStack[] getCondensedInputs() - { - return this.condensedInputs; - } - - @Override - public IAEItemStack[] getCondensedOutputs() - { - return this.condensedOutputs; - } - - @Override - public IAEItemStack[] getOutputs() - { - return this.outputs; - } - - @Override - public boolean canSubstitute() - { - return this.canSubstitute; - } - - @Override - public ItemStack getOutput( final InventoryCrafting craftingInv, final World w ) - { - if( !this.isCrafting ) - { - throw new IllegalStateException( "Only crafting recipes supported." ); - } - - for( int x = 0; x < craftingInv.getSizeInventory(); x++ ) - { - if( !this.isValidItemForSlot( x, craftingInv.getStackInSlot( x ), w ) ) - { - return null; - } - } - - if( this.outputs != null && this.outputs.length > 0 ) - { - return this.outputs[0].getItemStack(); - } - - return null; - } - - private TestStatus getStatus( final int slotIndex, final ItemStack i ) - { - if( this.crafting.getStackInSlot( slotIndex ) == null ) - { - return i == null ? TestStatus.ACCEPT : TestStatus.DECLINE; - } - - if( i == null ) - { - return TestStatus.DECLINE; - } - - if( i.hasTagCompound() ) - { - return TestStatus.TEST; - } - - if( this.passCache.contains( new TestLookup( slotIndex, i ) ) ) - { - return TestStatus.ACCEPT; - } - - if( this.failCache.contains( new TestLookup( slotIndex, i ) ) ) - { - return TestStatus.DECLINE; - } - - return TestStatus.TEST; - } - - @Override - public int getPriority() - { - return this.priority; - } - - @Override - public void setPriority( final int priority ) - { - this.priority = priority; - } - - @Override - public int compareTo( final PatternHelper o ) - { - return ItemSorters.compareInt( o.priority, this.priority ); - } - - @Override - public int hashCode() - { - return this.pattern.hashCode(); - } - - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - - final PatternHelper other = (PatternHelper) obj; - - if( this.pattern != null && other.pattern != null ) - { - return this.pattern.equals( other.pattern ); - } - return false; - } - - private enum TestStatus - { - ACCEPT, DECLINE, TEST - } - - - private static final class TestLookup - { - - private final int slot; - private final int ref; - private final int hash; - - public TestLookup( final int slot, final ItemStack i ) - { - this( slot, i.getItem(), i.getItemDamage() ); - } - - public TestLookup( final int slot, final Item item, final int dmg ) - { - this.slot = slot; - this.ref = ( dmg << Platform.DEF_OFFSET ) | ( Item.getIdFromItem( item ) & 0xffff ); - final int offset = 3 * slot; - this.hash = ( this.ref << offset ) | ( this.ref >> ( offset + 32 ) ); - } - - @Override - public int hashCode() - { - return this.hash; - } - - @Override - public boolean equals( final Object obj ) - { - final boolean equality; - - if( obj instanceof TestLookup ) - { - final TestLookup b = (TestLookup) obj; - - equality = b.slot == this.slot && b.ref == this.ref; - } - else - { - equality = false; - } - - return equality; - } - } - - - public static IAEItemStack[] loadIAEItemStackFromNBT(final NBTTagList tags, boolean saveOrder, final ItemStack unknownItem) - { + public static IAEItemStack[] loadIAEItemStackFromNBT( + final NBTTagList tags, boolean saveOrder, final ItemStack unknownItem) { final List items = new ArrayList(); - for (int x = 0; x < tags.tagCount(); x++) { - final NBTTagCompound tag = tags.getCompoundTagAt(x); + for (int x = 0; x < tags.tagCount(); x++) { + final NBTTagCompound tag = tags.getCompoundTagAt(x); - if (tag.hasNoTags()) { - continue; - } + if (tag.hasNoTags()) { + continue; + } - ItemStack gs = Platform.loadItemStackFromNBT(tag); + ItemStack gs = Platform.loadItemStackFromNBT(tag); - if (gs == null && unknownItem != null) { - gs = unknownItem.copy(); - } + if (gs == null && unknownItem != null) { + gs = unknownItem.copy(); + } final IAEItemStack ae = AEApi.instance().storage().createItemStack(gs); if (ae != null || saveOrder) { items.add(ae); } + } - } - - return items.toArray( new IAEItemStack[items.size()] ); - } - - public static IAEItemStack[] convertToCondensedList(final IAEItemStack[] items) - { - final Map tmp = new HashMap(); + return items.toArray(new IAEItemStack[items.size()]); + } - for (final IAEItemStack io : items) { + public static IAEItemStack[] convertToCondensedList(final IAEItemStack[] items) { + final Map tmp = new HashMap(); - if (io == null) { - continue; - } + for (final IAEItemStack io : items) { - final IAEItemStack g = tmp.get(io); - - if (g == null) { - tmp.put(io, io.copy()); - } else { - g.add(io); - } + if (io == null) { + continue; + } - } + final IAEItemStack g = tmp.get(io); - return tmp.values().toArray(new IAEItemStack[tmp.size()]); - } + if (g == null) { + tmp.put(io, io.copy()); + } else { + g.add(io); + } + } + return tmp.values().toArray(new IAEItemStack[tmp.size()]); + } } diff --git a/src/main/java/appeng/helpers/PlayerSecurityWrapper.java b/src/main/java/appeng/helpers/PlayerSecurityWrapper.java index 0ac15515798..3a141404676 100644 --- a/src/main/java/appeng/helpers/PlayerSecurityWrapper.java +++ b/src/main/java/appeng/helpers/PlayerSecurityWrapper.java @@ -18,28 +18,22 @@ package appeng.helpers; - import appeng.api.config.SecurityPermissions; import appeng.api.networking.security.ISecurityRegistry; - import java.util.EnumSet; import java.util.HashMap; import java.util.Map; +public class PlayerSecurityWrapper implements ISecurityRegistry { -public class PlayerSecurityWrapper implements ISecurityRegistry -{ - - private final Map> target; + private final Map> target; - public PlayerSecurityWrapper( final HashMap> playerPerms ) - { - this.target = playerPerms; - } + public PlayerSecurityWrapper(final HashMap> playerPerms) { + this.target = playerPerms; + } - @Override - public void addPlayer( final int playerID, final EnumSet permissions ) - { - this.target.put( playerID, permissions ); - } + @Override + public void addPlayer(final int playerID, final EnumSet permissions) { + this.target.put(playerID, permissions); + } } diff --git a/src/main/java/appeng/helpers/Reflected.java b/src/main/java/appeng/helpers/Reflected.java index 6e0c84da8e8..0048a555c79 100644 --- a/src/main/java/appeng/helpers/Reflected.java +++ b/src/main/java/appeng/helpers/Reflected.java @@ -1,18 +1,13 @@ package appeng.helpers; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - /** * Marker interface to help identify invocation of reflection */ -@Retention( RetentionPolicy.SOURCE ) -@Target( { ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.TYPE, ElementType.METHOD } ) -public @interface Reflected -{ - -} +@Retention(RetentionPolicy.SOURCE) +@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.TYPE, ElementType.METHOD}) +public @interface Reflected {} diff --git a/src/main/java/appeng/helpers/Splotch.java b/src/main/java/appeng/helpers/Splotch.java index faddd5aa10c..223d1af1340 100644 --- a/src/main/java/appeng/helpers/Splotch.java +++ b/src/main/java/appeng/helpers/Splotch.java @@ -18,100 +18,81 @@ package appeng.helpers; - import appeng.api.util.AEColor; import io.netty.buffer.ByteBuf; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; - -public class Splotch -{ - - private final ForgeDirection side; - private final boolean lumen; - private final AEColor color; - private final int pos; - - public Splotch( final AEColor col, final boolean lit, final ForgeDirection side, final Vec3 position ) - { - this.color = col; - this.lumen = lit; - - final double x; - final double y; - - if( side == ForgeDirection.SOUTH || side == ForgeDirection.NORTH ) - { - x = position.xCoord; - y = position.yCoord; - } - - else if( side == ForgeDirection.UP || side == ForgeDirection.DOWN ) - { - x = position.xCoord; - y = position.zCoord; - } - - else - { - x = position.yCoord; - y = position.zCoord; - } - - final int a = (int) ( x * 0xF ); - final int b = (int) ( y * 0xF ); - this.pos = a | ( b << 4 ); - - this.side = side; - } - - public Splotch( final ByteBuf data ) - { - - this.pos = data.readByte(); - final int val = data.readByte(); - - this.side = ForgeDirection.getOrientation( val & 0x07 ); - this.color = AEColor.values()[( val >> 3 ) & 0x0F]; - this.lumen = ( ( val >> 7 ) & 0x01 ) > 0; - } - - public void writeToStream( final ByteBuf stream ) - { - stream.writeByte( this.pos ); - final int val = this.getSide().ordinal() | ( this.getColor().ordinal() << 3 ) | ( this.isLumen() ? 0x80 : 0x00 ); - stream.writeByte( val ); - } - - public float x() - { - return ( this.pos & 0x0f ) / 15.0f; - } - - public float y() - { - return ( ( this.pos >> 4 ) & 0x0f ) / 15.0f; - } - - public int getSeed() - { - final int val = this.getSide().ordinal() | ( this.getColor().ordinal() << 3 ) | ( this.isLumen() ? 0x80 : 0x00 ); - return Math.abs( this.pos + val ); - } - - public ForgeDirection getSide() - { - return this.side; - } - - public AEColor getColor() - { - return this.color; - } - - public boolean isLumen() - { - return this.lumen; - } +public class Splotch { + + private final ForgeDirection side; + private final boolean lumen; + private final AEColor color; + private final int pos; + + public Splotch(final AEColor col, final boolean lit, final ForgeDirection side, final Vec3 position) { + this.color = col; + this.lumen = lit; + + final double x; + final double y; + + if (side == ForgeDirection.SOUTH || side == ForgeDirection.NORTH) { + x = position.xCoord; + y = position.yCoord; + } else if (side == ForgeDirection.UP || side == ForgeDirection.DOWN) { + x = position.xCoord; + y = position.zCoord; + } else { + x = position.yCoord; + y = position.zCoord; + } + + final int a = (int) (x * 0xF); + final int b = (int) (y * 0xF); + this.pos = a | (b << 4); + + this.side = side; + } + + public Splotch(final ByteBuf data) { + + this.pos = data.readByte(); + final int val = data.readByte(); + + this.side = ForgeDirection.getOrientation(val & 0x07); + this.color = AEColor.values()[(val >> 3) & 0x0F]; + this.lumen = ((val >> 7) & 0x01) > 0; + } + + public void writeToStream(final ByteBuf stream) { + stream.writeByte(this.pos); + final int val = this.getSide().ordinal() | (this.getColor().ordinal() << 3) | (this.isLumen() ? 0x80 : 0x00); + stream.writeByte(val); + } + + public float x() { + return (this.pos & 0x0f) / 15.0f; + } + + public float y() { + return ((this.pos >> 4) & 0x0f) / 15.0f; + } + + public int getSeed() { + final int val = this.getSide().ordinal() | (this.getColor().ordinal() << 3) | (this.isLumen() ? 0x80 : 0x00); + return Math.abs(this.pos + val); + } + + public ForgeDirection getSide() { + return this.side; + } + + public AEColor getColor() { + return this.color; + } + + public boolean isLumen() { + return this.lumen; + } } diff --git a/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java b/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java index 40b60ea88a5..cf24faaf43c 100644 --- a/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java +++ b/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java @@ -18,7 +18,6 @@ package appeng.helpers; - import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -53,338 +52,280 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; - -public class WirelessTerminalGuiObject implements IPortableCell, IActionHost, IInventorySlotAware, IViewCellStorage -{ - - private final ItemStack effectiveItem; - private final IWirelessTermHandler wth; - private final String encryptionKey; - private final EntityPlayer myPlayer; - private IGrid targetGrid; - private IStorageGrid sg; - private IMEMonitor itemStorage; - private IWirelessAccessPoint myWap; - private double sqRange = Double.MAX_VALUE; - private double myRange = Double.MAX_VALUE; - private final int inventorySlot; - private final WirelessTerminalViewCells viewCells; - - public WirelessTerminalGuiObject( final IWirelessTermHandler wh, final ItemStack is, final EntityPlayer ep, final World w, final int x, final int y, final int z ) - { - this.encryptionKey = wh.getEncryptionKey( is ); - this.effectiveItem = is; - this.myPlayer = ep; - this.wth = wh; - this.inventorySlot = x; - this.viewCells = new WirelessTerminalViewCells( is ); - - ILocatable obj = null; - - try - { - final long encKey = Long.parseLong( this.encryptionKey ); - obj = AEApi.instance().registries().locatable().getLocatableBy( encKey ); - } - catch( final NumberFormatException err ) - { - // :P - } - - if( obj instanceof IGridHost ) - { - final IGridNode n = ( (IGridHost) obj ).getGridNode( ForgeDirection.UNKNOWN ); - if( n != null ) - { - this.targetGrid = n.getGrid(); - if( this.targetGrid != null ) - { - this.sg = this.targetGrid.getCache( IStorageGrid.class ); - if( this.sg != null ) - { - this.itemStorage = this.sg.getItemInventory(); - } - } - } - } - } - - public double getRange() - { - return this.myRange; - } - - @Override - public IMEMonitor getItemInventory() - { - if( this.sg == null ) - { - return null; - } - return this.sg.getItemInventory(); - } - - @Override - public IMEMonitor getFluidInventory() - { - if( this.sg == null ) - { - return null; - } - return this.sg.getFluidInventory(); - } - - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - if( this.itemStorage != null ) - { - this.itemStorage.addListener( l, verificationToken ); - } - } - - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - if( this.itemStorage != null ) - { - this.itemStorage.removeListener( l ); - } - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - if( this.itemStorage != null ) - { - return this.itemStorage.getAvailableItems( out ); - } - return out; - } - - @Override - public IItemList getStorageList() - { - if( this.itemStorage != null ) - { - return this.itemStorage.getStorageList(); - } - return null; - } - - @Override - public AccessRestriction getAccess() - { - if( this.itemStorage != null ) - { - return this.itemStorage.getAccess(); - } - return AccessRestriction.NO_ACCESS; - } - - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - if( this.itemStorage != null ) - { - return this.itemStorage.isPrioritized( input ); - } - return false; - } - - @Override - public boolean canAccept( final IAEItemStack input ) - { - if( this.itemStorage != null ) - { - return this.itemStorage.canAccept( input ); - } - return false; - } - - @Override - public int getPriority() - { - if( this.itemStorage != null ) - { - return this.itemStorage.getPriority(); - } - return 0; - } - - @Override - public int getSlot() - { - if( this.itemStorage != null ) - { - return this.itemStorage.getSlot(); - } - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return this.itemStorage.validForPass( i ); - } - - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final BaseActionSource src ) - { - if( this.itemStorage != null ) - { - return this.itemStorage.injectItems( input, type, src ); - } - return input; - } - - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - if( this.itemStorage != null ) - { - return this.itemStorage.extractItems( request, mode, src ); - } - return null; - } - - @Override - public StorageChannel getChannel() - { - if( this.itemStorage != null ) - { - return this.itemStorage.getChannel(); - } - return StorageChannel.ITEMS; - } - - @Override - public double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier ) - { - if( this.wth != null && this.effectiveItem != null ) - { - if( mode == Actionable.SIMULATE ) - { - return this.wth.hasPower( this.myPlayer, amt, this.effectiveItem ) ? amt : 0; - } - return this.wth.usePower( this.myPlayer, amt, this.effectiveItem ) ? amt : 0; - } - return 0.0; - } - - @Override - public ItemStack getItemStack() - { - return this.effectiveItem; - } - - @Override - public IConfigManager getConfigManager() - { - return this.wth.getConfigManager( this.effectiveItem ); - } - - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - return this.getActionableNode(); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.NONE; - } - - @Override - public void securityBreak() - { - - } - - @Override - public IGridNode getActionableNode() - { - this.rangeCheck(); - if( this.myWap != null ) - { - return this.myWap.getActionableNode(); - } - return null; - } - - public boolean rangeCheck() - { - this.sqRange = this.myRange = Double.MAX_VALUE; - - if( this.targetGrid != null && this.itemStorage != null ) - { - if( this.myWap != null ) - { - if( this.myWap.getGrid() == this.targetGrid ) - { - if( this.testWap( this.myWap ) ) - { - return true; - } - } - return false; - } - - final IMachineSet tw = this.targetGrid.getMachines( TileWireless.class ); - - this.myWap = null; - - for( final IGridNode n : tw ) - { - final IWirelessAccessPoint wap = (IWirelessAccessPoint) n.getMachine(); - if( this.testWap( wap ) ) - { - this.myWap = wap; - } - } - - return this.myWap != null; - } - return false; - } - - private boolean testWap( final IWirelessAccessPoint wap ) - { - double rangeLimit = wap.getRange(); - rangeLimit *= rangeLimit; - - final DimensionalCoord dc = wap.getLocation(); - - if( dc.getWorld() == this.myPlayer.worldObj ) - { - final double offX = dc.x - this.myPlayer.posX; - final double offY = dc.y - this.myPlayer.posY; - final double offZ = dc.z - this.myPlayer.posZ; - - final double r = offX * offX + offY * offY + offZ * offZ; - if( r < rangeLimit && this.sqRange > r ) - { - if( wap.isActive() ) - { - this.sqRange = r; - this.myRange = Math.sqrt( r ); - return true; - } - } - } - return false; - } - - @Override - public int getInventorySlot() - { - return this.inventorySlot; - } - - @Override - public IInventory getViewCellStorage() - { - return this.viewCells; - } +public class WirelessTerminalGuiObject implements IPortableCell, IActionHost, IInventorySlotAware, IViewCellStorage { + + private final ItemStack effectiveItem; + private final IWirelessTermHandler wth; + private final String encryptionKey; + private final EntityPlayer myPlayer; + private IGrid targetGrid; + private IStorageGrid sg; + private IMEMonitor itemStorage; + private IWirelessAccessPoint myWap; + private double sqRange = Double.MAX_VALUE; + private double myRange = Double.MAX_VALUE; + private final int inventorySlot; + private final WirelessTerminalViewCells viewCells; + + public WirelessTerminalGuiObject( + final IWirelessTermHandler wh, + final ItemStack is, + final EntityPlayer ep, + final World w, + final int x, + final int y, + final int z) { + this.encryptionKey = wh.getEncryptionKey(is); + this.effectiveItem = is; + this.myPlayer = ep; + this.wth = wh; + this.inventorySlot = x; + this.viewCells = new WirelessTerminalViewCells(is); + + ILocatable obj = null; + + try { + final long encKey = Long.parseLong(this.encryptionKey); + obj = AEApi.instance().registries().locatable().getLocatableBy(encKey); + } catch (final NumberFormatException err) { + // :P + } + + if (obj instanceof IGridHost) { + final IGridNode n = ((IGridHost) obj).getGridNode(ForgeDirection.UNKNOWN); + if (n != null) { + this.targetGrid = n.getGrid(); + if (this.targetGrid != null) { + this.sg = this.targetGrid.getCache(IStorageGrid.class); + if (this.sg != null) { + this.itemStorage = this.sg.getItemInventory(); + } + } + } + } + } + + public double getRange() { + return this.myRange; + } + + @Override + public IMEMonitor getItemInventory() { + if (this.sg == null) { + return null; + } + return this.sg.getItemInventory(); + } + + @Override + public IMEMonitor getFluidInventory() { + if (this.sg == null) { + return null; + } + return this.sg.getFluidInventory(); + } + + @Override + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + if (this.itemStorage != null) { + this.itemStorage.addListener(l, verificationToken); + } + } + + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + if (this.itemStorage != null) { + this.itemStorage.removeListener(l); + } + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + if (this.itemStorage != null) { + return this.itemStorage.getAvailableItems(out); + } + return out; + } + + @Override + public IItemList getStorageList() { + if (this.itemStorage != null) { + return this.itemStorage.getStorageList(); + } + return null; + } + + @Override + public AccessRestriction getAccess() { + if (this.itemStorage != null) { + return this.itemStorage.getAccess(); + } + return AccessRestriction.NO_ACCESS; + } + + @Override + public boolean isPrioritized(final IAEItemStack input) { + if (this.itemStorage != null) { + return this.itemStorage.isPrioritized(input); + } + return false; + } + + @Override + public boolean canAccept(final IAEItemStack input) { + if (this.itemStorage != null) { + return this.itemStorage.canAccept(input); + } + return false; + } + + @Override + public int getPriority() { + if (this.itemStorage != null) { + return this.itemStorage.getPriority(); + } + return 0; + } + + @Override + public int getSlot() { + if (this.itemStorage != null) { + return this.itemStorage.getSlot(); + } + return 0; + } + + @Override + public boolean validForPass(final int i) { + return this.itemStorage.validForPass(i); + } + + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable type, final BaseActionSource src) { + if (this.itemStorage != null) { + return this.itemStorage.injectItems(input, type, src); + } + return input; + } + + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final BaseActionSource src) { + if (this.itemStorage != null) { + return this.itemStorage.extractItems(request, mode, src); + } + return null; + } + + @Override + public StorageChannel getChannel() { + if (this.itemStorage != null) { + return this.itemStorage.getChannel(); + } + return StorageChannel.ITEMS; + } + + @Override + public double extractAEPower(final double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier) { + if (this.wth != null && this.effectiveItem != null) { + if (mode == Actionable.SIMULATE) { + return this.wth.hasPower(this.myPlayer, amt, this.effectiveItem) ? amt : 0; + } + return this.wth.usePower(this.myPlayer, amt, this.effectiveItem) ? amt : 0; + } + return 0.0; + } + + @Override + public ItemStack getItemStack() { + return this.effectiveItem; + } + + @Override + public IConfigManager getConfigManager() { + return this.wth.getConfigManager(this.effectiveItem); + } + + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + return this.getActionableNode(); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.NONE; + } + + @Override + public void securityBreak() {} + + @Override + public IGridNode getActionableNode() { + this.rangeCheck(); + if (this.myWap != null) { + return this.myWap.getActionableNode(); + } + return null; + } + + public boolean rangeCheck() { + this.sqRange = this.myRange = Double.MAX_VALUE; + + if (this.targetGrid != null && this.itemStorage != null) { + if (this.myWap != null) { + if (this.myWap.getGrid() == this.targetGrid) { + if (this.testWap(this.myWap)) { + return true; + } + } + return false; + } + + final IMachineSet tw = this.targetGrid.getMachines(TileWireless.class); + + this.myWap = null; + + for (final IGridNode n : tw) { + final IWirelessAccessPoint wap = (IWirelessAccessPoint) n.getMachine(); + if (this.testWap(wap)) { + this.myWap = wap; + } + } + + return this.myWap != null; + } + return false; + } + + private boolean testWap(final IWirelessAccessPoint wap) { + double rangeLimit = wap.getRange(); + rangeLimit *= rangeLimit; + + final DimensionalCoord dc = wap.getLocation(); + + if (dc.getWorld() == this.myPlayer.worldObj) { + final double offX = dc.x - this.myPlayer.posX; + final double offY = dc.y - this.myPlayer.posY; + final double offZ = dc.z - this.myPlayer.posZ; + + final double r = offX * offX + offY * offY + offZ * offZ; + if (r < rangeLimit && this.sqRange > r) { + if (wap.isActive()) { + this.sqRange = r; + this.myRange = Math.sqrt(r); + return true; + } + } + } + return false; + } + + @Override + public int getInventorySlot() { + return this.inventorySlot; + } + + @Override + public IInventory getViewCellStorage() { + return this.viewCells; + } } diff --git a/src/main/java/appeng/hooks/AETrading.java b/src/main/java/appeng/hooks/AETrading.java index bc56903182a..79616cb5f67 100644 --- a/src/main/java/appeng/hooks/AETrading.java +++ b/src/main/java/appeng/hooks/AETrading.java @@ -18,107 +18,103 @@ package appeng.hooks; - import appeng.api.AEApi; import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.IMaterials; import com.google.common.base.Optional; import cpw.mods.fml.common.registry.VillagerRegistry.IVillageTradeHandler; +import java.util.Random; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.village.MerchantRecipe; import net.minecraft.village.MerchantRecipeList; -import java.util.Random; - - -public class AETrading implements IVillageTradeHandler -{ - - @Override - public void manipulateTradesForVillager( final EntityVillager villager, final MerchantRecipeList recipeList, final Random random ) - { - final IMaterials materials = AEApi.instance().definitions().materials(); - - this.addMerchant( recipeList, materials.silicon(), 1, random, 2 ); - this.addMerchant( recipeList, materials.certusQuartzCrystal(), 2, random, 4 ); - this.addMerchant( recipeList, materials.certusQuartzDust(), 1, random, 3 ); - - this.addTrade( recipeList, materials.certusQuartzDust(), materials.certusQuartzCrystal(), random, 2 ); - } - - private void addMerchant( final MerchantRecipeList list, final IItemDefinition item, final int emera, final Random rand, final int greed ) - { - for( final ItemStack itemStack : item.maybeStack( 1 ).asSet() ) - { - // Sell - final ItemStack from = itemStack.copy(); - final ItemStack to = new ItemStack( Items.emerald ); - - final int multiplier = ( Math.abs( rand.nextInt() ) % 6 ); - final int emeraldCost = emera + ( Math.abs( rand.nextInt() ) % greed ) - multiplier; - final int mood = rand.nextInt() % 2; - - from.stackSize = multiplier + mood; - to.stackSize = multiplier * emeraldCost - mood; - - if( to.stackSize < 0 ) - { - from.stackSize -= to.stackSize; - to.stackSize -= to.stackSize; - } - - this.addToList( list, from, to ); - - // Buy - final ItemStack reverseTo = from.copy(); - final ItemStack reverseFrom = to.copy(); - - reverseFrom.stackSize *= rand.nextFloat() * 3.0f + 1.0f; - - this.addToList( list, reverseFrom, reverseTo ); - } - } - - private void addTrade( final MerchantRecipeList list, final IItemDefinition inputDefinition, final IItemDefinition outputDefinition, final Random rand, final int conversionVariance ) - { - final Optional maybeInputStack = inputDefinition.maybeStack( 1 ); - final Optional maybeOutputStack = outputDefinition.maybeStack( 1 ); - - if( maybeInputStack.isPresent() && maybeOutputStack.isPresent() ) - { - // Sell - final ItemStack inputStack = maybeInputStack.get().copy(); - final ItemStack outputStack = maybeOutputStack.get().copy(); - - inputStack.stackSize = 1 + ( Math.abs( rand.nextInt() ) % ( 1 + conversionVariance ) ); - outputStack.stackSize = 1; - - this.addToList( list, inputStack, outputStack ); - } - } - - private void addToList( final MerchantRecipeList l, final ItemStack a, final ItemStack b ) - { - if( a.stackSize < 1 ) - { - a.stackSize = 1; - } - if( b.stackSize < 1 ) - { - b.stackSize = 1; - } - - if( a.stackSize > a.getMaxStackSize() ) - { - a.stackSize = a.getMaxStackSize(); - } - if( b.stackSize > b.getMaxStackSize() ) - { - b.stackSize = b.getMaxStackSize(); - } - - l.add( new MerchantRecipe( a, b ) ); - } +public class AETrading implements IVillageTradeHandler { + + @Override + public void manipulateTradesForVillager( + final EntityVillager villager, final MerchantRecipeList recipeList, final Random random) { + final IMaterials materials = AEApi.instance().definitions().materials(); + + this.addMerchant(recipeList, materials.silicon(), 1, random, 2); + this.addMerchant(recipeList, materials.certusQuartzCrystal(), 2, random, 4); + this.addMerchant(recipeList, materials.certusQuartzDust(), 1, random, 3); + + this.addTrade(recipeList, materials.certusQuartzDust(), materials.certusQuartzCrystal(), random, 2); + } + + private void addMerchant( + final MerchantRecipeList list, + final IItemDefinition item, + final int emera, + final Random rand, + final int greed) { + for (final ItemStack itemStack : item.maybeStack(1).asSet()) { + // Sell + final ItemStack from = itemStack.copy(); + final ItemStack to = new ItemStack(Items.emerald); + + final int multiplier = (Math.abs(rand.nextInt()) % 6); + final int emeraldCost = emera + (Math.abs(rand.nextInt()) % greed) - multiplier; + final int mood = rand.nextInt() % 2; + + from.stackSize = multiplier + mood; + to.stackSize = multiplier * emeraldCost - mood; + + if (to.stackSize < 0) { + from.stackSize -= to.stackSize; + to.stackSize -= to.stackSize; + } + + this.addToList(list, from, to); + + // Buy + final ItemStack reverseTo = from.copy(); + final ItemStack reverseFrom = to.copy(); + + reverseFrom.stackSize *= rand.nextFloat() * 3.0f + 1.0f; + + this.addToList(list, reverseFrom, reverseTo); + } + } + + private void addTrade( + final MerchantRecipeList list, + final IItemDefinition inputDefinition, + final IItemDefinition outputDefinition, + final Random rand, + final int conversionVariance) { + final Optional maybeInputStack = inputDefinition.maybeStack(1); + final Optional maybeOutputStack = outputDefinition.maybeStack(1); + + if (maybeInputStack.isPresent() && maybeOutputStack.isPresent()) { + // Sell + final ItemStack inputStack = maybeInputStack.get().copy(); + final ItemStack outputStack = maybeOutputStack.get().copy(); + + inputStack.stackSize = 1 + (Math.abs(rand.nextInt()) % (1 + conversionVariance)); + outputStack.stackSize = 1; + + this.addToList(list, inputStack, outputStack); + } + } + + private void addToList(final MerchantRecipeList l, final ItemStack a, final ItemStack b) { + if (a.stackSize < 1) { + a.stackSize = 1; + } + if (b.stackSize < 1) { + b.stackSize = 1; + } + + if (a.stackSize > a.getMaxStackSize()) { + a.stackSize = a.getMaxStackSize(); + } + if (b.stackSize > b.getMaxStackSize()) { + b.stackSize = b.getMaxStackSize(); + } + + l.add(new MerchantRecipe(a, b)); + } } diff --git a/src/main/java/appeng/hooks/CompassManager.java b/src/main/java/appeng/hooks/CompassManager.java index 4c49cdf7c93..30d3514b791 100644 --- a/src/main/java/appeng/hooks/CompassManager.java +++ b/src/main/java/appeng/hooks/CompassManager.java @@ -18,104 +18,91 @@ package appeng.hooks; - import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketCompassRequest; - import java.util.HashMap; import java.util.Iterator; - -public class CompassManager -{ - - public static final CompassManager INSTANCE = new CompassManager(); - private final HashMap requests = new HashMap(); - - public void postResult( final long attunement, final int x, final int y, final int z, final CompassResult result ) - { - final CompassRequest r = new CompassRequest( attunement, x, y, z ); - this.requests.put( r, result ); - } - - public CompassResult getCompassDirection( final long attunement, final int x, final int y, final int z ) - { - final long now = System.currentTimeMillis(); - - final Iterator i = this.requests.values().iterator(); - while( i.hasNext() ) - { - final CompassResult res = i.next(); - final long diff = now - res.getTime(); - if( diff > 20000 ) - { - i.remove(); - } - } - - final CompassRequest r = new CompassRequest( attunement, x, y, z ); - CompassResult res = this.requests.get( r ); - - if( res == null ) - { - res = new CompassResult( false, true, 0 ); - this.requests.put( r, res ); - this.requestUpdate( r ); - } - else if( now - res.getTime() > 1000 * 3 ) - { - if( !res.isRequested() ) - { - res.setRequested( true ); - this.requestUpdate( r ); - } - } - - return res; - } - - private void requestUpdate( final CompassRequest r ) - { - NetworkHandler.instance.sendToServer( new PacketCompassRequest( r.attunement, r.cx, r.cz, r.cdy ) ); - } - - private static class CompassRequest - { - - private final int hash; - private final long attunement; - private final int cx; - private final int cdy; - private final int cz; - - public CompassRequest( final long attunement, final int x, final int y, final int z ) - { - this.attunement = attunement; - this.cx = x >> 4; - this.cdy = y >> 5; - this.cz = z >> 4; - this.hash = ( (Integer) this.cx ).hashCode() ^ ( (Integer) this.cdy ).hashCode() ^ ( (Integer) this.cz ).hashCode() ^ ( (Long) attunement ).hashCode(); - } - - @Override - public int hashCode() - { - return this.hash; - } - - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - final CompassRequest other = (CompassRequest) obj; - return this.attunement == other.attunement && this.cx == other.cx && this.cdy == other.cdy && this.cz == other.cz; - } - } +public class CompassManager { + + public static final CompassManager INSTANCE = new CompassManager(); + private final HashMap requests = new HashMap(); + + public void postResult(final long attunement, final int x, final int y, final int z, final CompassResult result) { + final CompassRequest r = new CompassRequest(attunement, x, y, z); + this.requests.put(r, result); + } + + public CompassResult getCompassDirection(final long attunement, final int x, final int y, final int z) { + final long now = System.currentTimeMillis(); + + final Iterator i = this.requests.values().iterator(); + while (i.hasNext()) { + final CompassResult res = i.next(); + final long diff = now - res.getTime(); + if (diff > 20000) { + i.remove(); + } + } + + final CompassRequest r = new CompassRequest(attunement, x, y, z); + CompassResult res = this.requests.get(r); + + if (res == null) { + res = new CompassResult(false, true, 0); + this.requests.put(r, res); + this.requestUpdate(r); + } else if (now - res.getTime() > 1000 * 3) { + if (!res.isRequested()) { + res.setRequested(true); + this.requestUpdate(r); + } + } + + return res; + } + + private void requestUpdate(final CompassRequest r) { + NetworkHandler.instance.sendToServer(new PacketCompassRequest(r.attunement, r.cx, r.cz, r.cdy)); + } + + private static class CompassRequest { + + private final int hash; + private final long attunement; + private final int cx; + private final int cdy; + private final int cz; + + public CompassRequest(final long attunement, final int x, final int y, final int z) { + this.attunement = attunement; + this.cx = x >> 4; + this.cdy = y >> 5; + this.cz = z >> 4; + this.hash = ((Integer) this.cx).hashCode() + ^ ((Integer) this.cdy).hashCode() + ^ ((Integer) this.cz).hashCode() + ^ ((Long) attunement).hashCode(); + } + + @Override + public int hashCode() { + return this.hash; + } + + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final CompassRequest other = (CompassRequest) obj; + return this.attunement == other.attunement + && this.cx == other.cx + && this.cdy == other.cdy + && this.cz == other.cz; + } + } } diff --git a/src/main/java/appeng/hooks/CompassResult.java b/src/main/java/appeng/hooks/CompassResult.java index 53c0982cbce..a4bce671c71 100644 --- a/src/main/java/appeng/hooks/CompassResult.java +++ b/src/main/java/appeng/hooks/CompassResult.java @@ -18,51 +18,42 @@ package appeng.hooks; - -public class CompassResult -{ - - private final boolean hasResult; - private final boolean spin; - private final double rad; - private final long time; - private boolean requested = false; - - public CompassResult( final boolean hasResult, final boolean spin, final double rad ) - { - this.hasResult = hasResult; - this.spin = spin; - this.rad = rad; - this.time = System.currentTimeMillis(); - } - - public boolean isValidResult() - { - return this.hasResult; - } - - public boolean isSpin() - { - return this.spin; - } - - public double getRad() - { - return this.rad; - } - - boolean isRequested() - { - return this.requested; - } - - void setRequested( final boolean requested ) - { - this.requested = requested; - } - - long getTime() - { - return this.time; - } +public class CompassResult { + + private final boolean hasResult; + private final boolean spin; + private final double rad; + private final long time; + private boolean requested = false; + + public CompassResult(final boolean hasResult, final boolean spin, final double rad) { + this.hasResult = hasResult; + this.spin = spin; + this.rad = rad; + this.time = System.currentTimeMillis(); + } + + public boolean isValidResult() { + return this.hasResult; + } + + public boolean isSpin() { + return this.spin; + } + + public double getRad() { + return this.rad; + } + + boolean isRequested() { + return this.requested; + } + + void setRequested(final boolean requested) { + this.requested = requested; + } + + long getTime() { + return this.time; + } } diff --git a/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java b/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java index 8ce43c6476c..594baf8a88c 100644 --- a/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java +++ b/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java @@ -18,7 +18,6 @@ package appeng.hooks; - import appeng.entity.EntityTinyTNTPrimed; import net.minecraft.block.BlockDispenser; import net.minecraft.dispenser.BehaviorDefaultDispenseItem; @@ -27,21 +26,19 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.World; +public final class DispenserBehaviorTinyTNT extends BehaviorDefaultDispenseItem { -public final class DispenserBehaviorTinyTNT extends BehaviorDefaultDispenseItem -{ - - @Override - protected ItemStack dispenseStack( final IBlockSource dispenser, final ItemStack dispensedItem ) - { - final EnumFacing enumfacing = BlockDispenser.func_149937_b( dispenser.getBlockMetadata() ); - final World world = dispenser.getWorld(); - final int i = dispenser.getXInt() + enumfacing.getFrontOffsetX(); - final int j = dispenser.getYInt() + enumfacing.getFrontOffsetY(); - final int k = dispenser.getZInt() + enumfacing.getFrontOffsetZ(); - final EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed( world, i + 0.5F, j + 0.5F, k + 0.5F, null ); - world.spawnEntityInWorld( primedTinyTNTEntity ); - --dispensedItem.stackSize; - return dispensedItem; - } + @Override + protected ItemStack dispenseStack(final IBlockSource dispenser, final ItemStack dispensedItem) { + final EnumFacing enumfacing = BlockDispenser.func_149937_b(dispenser.getBlockMetadata()); + final World world = dispenser.getWorld(); + final int i = dispenser.getXInt() + enumfacing.getFrontOffsetX(); + final int j = dispenser.getYInt() + enumfacing.getFrontOffsetY(); + final int k = dispenser.getZInt() + enumfacing.getFrontOffsetZ(); + final EntityTinyTNTPrimed primedTinyTNTEntity = + new EntityTinyTNTPrimed(world, i + 0.5F, j + 0.5F, k + 0.5F, null); + world.spawnEntityInWorld(primedTinyTNTEntity); + --dispensedItem.stackSize; + return dispensedItem; + } } diff --git a/src/main/java/appeng/hooks/DispenserBlockTool.java b/src/main/java/appeng/hooks/DispenserBlockTool.java index 45fbc6d442b..71ada39973b 100644 --- a/src/main/java/appeng/hooks/DispenserBlockTool.java +++ b/src/main/java/appeng/hooks/DispenserBlockTool.java @@ -18,7 +18,6 @@ package appeng.hooks; - import appeng.util.Platform; import net.minecraft.block.BlockDispenser; import net.minecraft.dispenser.BehaviorDefaultDispenseItem; @@ -29,29 +28,34 @@ import net.minecraft.world.World; import net.minecraft.world.WorldServer; - -public final class DispenserBlockTool extends BehaviorDefaultDispenseItem -{ - - @Override - protected ItemStack dispenseStack( final IBlockSource dispenser, final ItemStack dispensedItem ) - { - final Item i = dispensedItem.getItem(); - if( i instanceof IBlockTool ) - { - final EnumFacing enumfacing = BlockDispenser.func_149937_b( dispenser.getBlockMetadata() ); - final IBlockTool tm = (IBlockTool) i; - - final World w = dispenser.getWorld(); - if( w instanceof WorldServer ) - { - final int x = dispenser.getXInt() + enumfacing.getFrontOffsetX(); - final int y = dispenser.getYInt() + enumfacing.getFrontOffsetY(); - final int z = dispenser.getZInt() + enumfacing.getFrontOffsetZ(); - - tm.onItemUse( dispensedItem, Platform.getPlayer( (WorldServer) w ), w, x, y, z, enumfacing.ordinal(), 0.5f, 0.5f, 0.5f ); - } - } - return dispensedItem; - } +public final class DispenserBlockTool extends BehaviorDefaultDispenseItem { + + @Override + protected ItemStack dispenseStack(final IBlockSource dispenser, final ItemStack dispensedItem) { + final Item i = dispensedItem.getItem(); + if (i instanceof IBlockTool) { + final EnumFacing enumfacing = BlockDispenser.func_149937_b(dispenser.getBlockMetadata()); + final IBlockTool tm = (IBlockTool) i; + + final World w = dispenser.getWorld(); + if (w instanceof WorldServer) { + final int x = dispenser.getXInt() + enumfacing.getFrontOffsetX(); + final int y = dispenser.getYInt() + enumfacing.getFrontOffsetY(); + final int z = dispenser.getZInt() + enumfacing.getFrontOffsetZ(); + + tm.onItemUse( + dispensedItem, + Platform.getPlayer((WorldServer) w), + w, + x, + y, + z, + enumfacing.ordinal(), + 0.5f, + 0.5f, + 0.5f); + } + } + return dispensedItem; + } } diff --git a/src/main/java/appeng/hooks/DispenserMatterCannon.java b/src/main/java/appeng/hooks/DispenserMatterCannon.java index 187d51e8244..dd325a4abd9 100644 --- a/src/main/java/appeng/hooks/DispenserMatterCannon.java +++ b/src/main/java/appeng/hooks/DispenserMatterCannon.java @@ -18,7 +18,6 @@ package appeng.hooks; - import appeng.items.tools.powered.ToolMassCannon; import appeng.util.Platform; import net.minecraft.block.BlockDispenser; @@ -32,41 +31,36 @@ import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.ForgeDirection; +public final class DispenserMatterCannon extends BehaviorDefaultDispenseItem { -public final class DispenserMatterCannon extends BehaviorDefaultDispenseItem -{ - - @Override - protected ItemStack dispenseStack( final IBlockSource dispenser, ItemStack dispensedItem ) - { - final Item i = dispensedItem.getItem(); - if( i instanceof ToolMassCannon ) - { - final EnumFacing enumfacing = BlockDispenser.func_149937_b( dispenser.getBlockMetadata() ); - ForgeDirection dir = ForgeDirection.UNKNOWN; - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - if( enumfacing.getFrontOffsetX() == d.offsetX && enumfacing.getFrontOffsetY() == d.offsetY && enumfacing.getFrontOffsetZ() == d.offsetZ ) - { - dir = d; - } - } + @Override + protected ItemStack dispenseStack(final IBlockSource dispenser, ItemStack dispensedItem) { + final Item i = dispensedItem.getItem(); + if (i instanceof ToolMassCannon) { + final EnumFacing enumfacing = BlockDispenser.func_149937_b(dispenser.getBlockMetadata()); + ForgeDirection dir = ForgeDirection.UNKNOWN; + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + if (enumfacing.getFrontOffsetX() == d.offsetX + && enumfacing.getFrontOffsetY() == d.offsetY + && enumfacing.getFrontOffsetZ() == d.offsetZ) { + dir = d; + } + } - final ToolMassCannon tm = (ToolMassCannon) i; + final ToolMassCannon tm = (ToolMassCannon) i; - final World w = dispenser.getWorld(); - if( w instanceof WorldServer ) - { - final EntityPlayer p = Platform.getPlayer( (WorldServer) w ); - Platform.configurePlayer( p, dir, dispenser.getBlockTileEntity() ); + final World w = dispenser.getWorld(); + if (w instanceof WorldServer) { + final EntityPlayer p = Platform.getPlayer((WorldServer) w); + Platform.configurePlayer(p, dir, dispenser.getBlockTileEntity()); - p.posX += dir.offsetX; - p.posY += dir.offsetY; - p.posZ += dir.offsetZ; + p.posX += dir.offsetX; + p.posY += dir.offsetY; + p.posZ += dir.offsetZ; - dispensedItem = tm.onItemRightClick( dispensedItem, w, p ); - } - } - return dispensedItem; - } + dispensedItem = tm.onItemRightClick(dispensedItem, w, p); + } + } + return dispensedItem; + } } diff --git a/src/main/java/appeng/hooks/IBlockTool.java b/src/main/java/appeng/hooks/IBlockTool.java index 9bff76a99ce..0b9ef03b47b 100644 --- a/src/main/java/appeng/hooks/IBlockTool.java +++ b/src/main/java/appeng/hooks/IBlockTool.java @@ -18,14 +18,21 @@ package appeng.hooks; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; +public interface IBlockTool { -public interface IBlockTool -{ - - boolean onItemUse( ItemStack dispensedItem, EntityPlayer player, World w, int x, int y, int z, int ordinal, float hitX, float hitY, float hitZ ); + boolean onItemUse( + ItemStack dispensedItem, + EntityPlayer player, + World w, + int x, + int y, + int z, + int ordinal, + float hitX, + float hitY, + float hitZ); } diff --git a/src/main/java/appeng/hooks/TickHandler.java b/src/main/java/appeng/hooks/TickHandler.java index 75fc92f044e..d988691b4f5 100644 --- a/src/main/java/appeng/hooks/TickHandler.java +++ b/src/main/java/appeng/hooks/TickHandler.java @@ -18,7 +18,6 @@ package appeng.hooks; - import appeng.api.AEApi; import appeng.api.networking.IGridNode; import appeng.api.parts.CableRenderMode; @@ -42,294 +41,239 @@ import cpw.mods.fml.common.gameevent.TickEvent.Phase; import cpw.mods.fml.common.gameevent.TickEvent.Type; import cpw.mods.fml.common.gameevent.TickEvent.WorldTickEvent; +import java.util.*; +import java.util.concurrent.TimeUnit; import net.minecraft.world.World; import net.minecraftforge.event.world.ChunkEvent; import net.minecraftforge.event.world.WorldEvent; -import java.util.*; -import java.util.concurrent.TimeUnit; - - -public class TickHandler -{ - - public static final TickHandler INSTANCE = new TickHandler(); - private final Queue> serverQueue = new LinkedList>(); - private final Multimap craftingJobs = LinkedListMultimap.create(); - private final WeakHashMap>> callQueue = new WeakHashMap>>(); - private final HandlerRep server = new HandlerRep(); - private final HandlerRep client = new HandlerRep(); - private final HashMap cliPlayerColors = new HashMap(); - private final HashMap srvPlayerColors = new HashMap(); - private CableRenderMode crm = CableRenderMode.Standard; - - public HashMap getPlayerColors() - { - if( Platform.isServer() ) - { - return this.srvPlayerColors; - } - return this.cliPlayerColors; - } - - public void addCallable( final World w, final IWorldCallable c ) - { - if( w == null ) - { - this.serverQueue.add( c ); - } - else - { - Queue> queue = this.callQueue.get( w ); - - if( queue == null ) - { - queue = new LinkedList>(); - this.callQueue.put( w, queue ); - } - - queue.add( c ); - } - } - - public void addInit( final AEBaseTile tile ) - { - if( Platform.isServer() ) // for no there is no reason to care about this on the client... - { - this.getRepo().tiles.add( tile ); - } - } - - private HandlerRep getRepo() - { - if( Platform.isServer() ) - { - return this.server; - } - return this.client; - } - - public void addNetwork( final Grid grid ) - { - if( Platform.isServer() ) // for no there is no reason to care about this on the client... - { - this.getRepo().networks.add( grid ); - } - } - - public void removeNetwork( final Grid grid ) - { - if( Platform.isServer() ) // for no there is no reason to care about this on the client... - { - this.getRepo().networks.remove( grid ); - } - } - - public Iterable getGridList() - { - return this.getRepo().networks; - } - - public void shutdown() - { - this.getRepo().clear(); - } - - @SubscribeEvent - public void unloadWorld( final WorldEvent.Unload ev ) - { - if( Platform.isServer() ) // for no there is no reason to care about this on the client... - { - final LinkedList toDestroy = new LinkedList(); - - for( final Grid g : this.getRepo().networks ) - { - for( final IGridNode n : g.getNodes() ) - { - if( n.getWorld() == ev.world ) - { - toDestroy.add( n ); - } - } - } - - for( final IGridNode n : toDestroy ) - { - n.destroy(); - } - } - } - - @SubscribeEvent - public void onChunkLoad( final ChunkEvent.Load load ) - { - for( final Object te : load.getChunk().chunkTileEntityMap.values() ) - { - if( te instanceof AEBaseTile ) - { - ( (AEBaseTile) te ).onChunkLoad(); - } - } - } - - @SubscribeEvent - public void onTick( final TickEvent ev ) - { - - if( ev.type == Type.CLIENT && ev.phase == Phase.START ) - { - this.tickColors( this.cliPlayerColors ); - EntityFloatingItem.ageStatic = ( EntityFloatingItem.ageStatic + 1 ) % 60000; - final CableRenderMode currentMode = AEApi.instance().partHelper().getCableRenderMode(); - if( currentMode != this.crm ) - { - this.crm = currentMode; - CommonHelper.proxy.triggerUpdates(); - } - } - - if( ev.type == Type.WORLD && ev.phase == Phase.END ) - { - final WorldTickEvent wte = (WorldTickEvent) ev; - synchronized( this.craftingJobs ) - { - final Collection jobSet = this.craftingJobs.get( wte.world ); - if( !jobSet.isEmpty() ) - { - final int simTime = Math.max( 1, AEConfig.instance.craftingCalculationTimePerTick / jobSet.size() ); - final Iterator i = jobSet.iterator(); - while( i.hasNext() ) - { - final CraftingJob cj = i.next(); - if( !cj.simulateFor( simTime ) ) - { - i.remove(); - } - } - } - } - } - - // for no there is no reason to care about this on the client... - else if( ev.type == Type.SERVER && ev.phase == Phase.END ) - { - this.tickColors( this.srvPlayerColors ); - // ready tiles. - final HandlerRep repo = this.getRepo(); - while( !repo.tiles.isEmpty() ) - { - final AEBaseTile bt = repo.tiles.poll(); - if( !bt.isInvalid() ) - { - bt.onReady(); - } - } - - // tick networks. - for( final Grid g : this.getRepo().networks ) - { - g.update(); - } - - // cross world queue. - this.processQueue( this.serverQueue, null ); - } - - // world synced queue(s) - if( ev.type == Type.WORLD && ev.phase == Phase.START ) - { - final World world = ( (WorldTickEvent) ev ).world; - final Queue> queue = this.callQueue.get( world ); - this.processQueue( queue, world ); - } - } - - private void tickColors( final HashMap playerSet ) - { - final Iterator i = playerSet.values().iterator(); - while( i.hasNext() ) - { - final PlayerColor pc = i.next(); - if( pc.ticksLeft <= 0 ) - { - i.remove(); - } - pc.ticksLeft--; - } - } - - private void processQueue( final Queue> queue, final World world ) - { - if( queue == null ) - { - return; - } - - final Stopwatch sw = Stopwatch.createStarted(); - - IWorldCallable c = null; - while( ( c = queue.poll() ) != null ) - { - try - { - c.call( world ); - - if( sw.elapsed( TimeUnit.MILLISECONDS ) > 50 ) - { - break; - } - } - catch( final Exception e ) - { - AELog.debug( e ); - } - } - - // long time = sw.elapsed( TimeUnit.MILLISECONDS ); - // if ( time > 0 ) - // AELog.info( "processQueue Time: " + time + "ms" ); - } - - public void registerCraftingSimulation( final World world, final CraftingJob craftingJob ) - { - synchronized( this.craftingJobs ) - { - this.craftingJobs.put( world, craftingJob ); - } - } - - private static class HandlerRep - { - - private Queue tiles = new LinkedList(); - - private Collection networks = new NetworkList(); - - private void clear() - { - this.tiles = new LinkedList(); - this.networks = new NetworkList(); - } - } - - - public static class PlayerColor - { - - public final AEColor myColor; - private final int myEntity; - private int ticksLeft; - - public PlayerColor( final int id, final AEColor col, final int ticks ) - { - this.myEntity = id; - this.myColor = col; - this.ticksLeft = ticks; - } - - public PacketPaintedEntity getPacket() - { - return new PacketPaintedEntity( this.myEntity, this.myColor, this.ticksLeft ); - } - } +public class TickHandler { + + public static final TickHandler INSTANCE = new TickHandler(); + private final Queue> serverQueue = new LinkedList>(); + private final Multimap craftingJobs = LinkedListMultimap.create(); + private final WeakHashMap>> callQueue = + new WeakHashMap>>(); + private final HandlerRep server = new HandlerRep(); + private final HandlerRep client = new HandlerRep(); + private final HashMap cliPlayerColors = new HashMap(); + private final HashMap srvPlayerColors = new HashMap(); + private CableRenderMode crm = CableRenderMode.Standard; + + public HashMap getPlayerColors() { + if (Platform.isServer()) { + return this.srvPlayerColors; + } + return this.cliPlayerColors; + } + + public void addCallable(final World w, final IWorldCallable c) { + if (w == null) { + this.serverQueue.add(c); + } else { + Queue> queue = this.callQueue.get(w); + + if (queue == null) { + queue = new LinkedList>(); + this.callQueue.put(w, queue); + } + + queue.add(c); + } + } + + public void addInit(final AEBaseTile tile) { + if (Platform.isServer()) // for no there is no reason to care about this on the client... + { + this.getRepo().tiles.add(tile); + } + } + + private HandlerRep getRepo() { + if (Platform.isServer()) { + return this.server; + } + return this.client; + } + + public void addNetwork(final Grid grid) { + if (Platform.isServer()) // for no there is no reason to care about this on the client... + { + this.getRepo().networks.add(grid); + } + } + + public void removeNetwork(final Grid grid) { + if (Platform.isServer()) // for no there is no reason to care about this on the client... + { + this.getRepo().networks.remove(grid); + } + } + + public Iterable getGridList() { + return this.getRepo().networks; + } + + public void shutdown() { + this.getRepo().clear(); + } + + @SubscribeEvent + public void unloadWorld(final WorldEvent.Unload ev) { + if (Platform.isServer()) // for no there is no reason to care about this on the client... + { + final LinkedList toDestroy = new LinkedList(); + + for (final Grid g : this.getRepo().networks) { + for (final IGridNode n : g.getNodes()) { + if (n.getWorld() == ev.world) { + toDestroy.add(n); + } + } + } + + for (final IGridNode n : toDestroy) { + n.destroy(); + } + } + } + + @SubscribeEvent + public void onChunkLoad(final ChunkEvent.Load load) { + for (final Object te : load.getChunk().chunkTileEntityMap.values()) { + if (te instanceof AEBaseTile) { + ((AEBaseTile) te).onChunkLoad(); + } + } + } + + @SubscribeEvent + public void onTick(final TickEvent ev) { + + if (ev.type == Type.CLIENT && ev.phase == Phase.START) { + this.tickColors(this.cliPlayerColors); + EntityFloatingItem.ageStatic = (EntityFloatingItem.ageStatic + 1) % 60000; + final CableRenderMode currentMode = AEApi.instance().partHelper().getCableRenderMode(); + if (currentMode != this.crm) { + this.crm = currentMode; + CommonHelper.proxy.triggerUpdates(); + } + } + + if (ev.type == Type.WORLD && ev.phase == Phase.END) { + final WorldTickEvent wte = (WorldTickEvent) ev; + synchronized (this.craftingJobs) { + final Collection jobSet = this.craftingJobs.get(wte.world); + if (!jobSet.isEmpty()) { + final int simTime = Math.max(1, AEConfig.instance.craftingCalculationTimePerTick / jobSet.size()); + final Iterator i = jobSet.iterator(); + while (i.hasNext()) { + final CraftingJob cj = i.next(); + if (!cj.simulateFor(simTime)) { + i.remove(); + } + } + } + } + } + + // for no there is no reason to care about this on the client... + else if (ev.type == Type.SERVER && ev.phase == Phase.END) { + this.tickColors(this.srvPlayerColors); + // ready tiles. + final HandlerRep repo = this.getRepo(); + while (!repo.tiles.isEmpty()) { + final AEBaseTile bt = repo.tiles.poll(); + if (!bt.isInvalid()) { + bt.onReady(); + } + } + + // tick networks. + for (final Grid g : this.getRepo().networks) { + g.update(); + } + + // cross world queue. + this.processQueue(this.serverQueue, null); + } + + // world synced queue(s) + if (ev.type == Type.WORLD && ev.phase == Phase.START) { + final World world = ((WorldTickEvent) ev).world; + final Queue> queue = this.callQueue.get(world); + this.processQueue(queue, world); + } + } + + private void tickColors(final HashMap playerSet) { + final Iterator i = playerSet.values().iterator(); + while (i.hasNext()) { + final PlayerColor pc = i.next(); + if (pc.ticksLeft <= 0) { + i.remove(); + } + pc.ticksLeft--; + } + } + + private void processQueue(final Queue> queue, final World world) { + if (queue == null) { + return; + } + + final Stopwatch sw = Stopwatch.createStarted(); + + IWorldCallable c = null; + while ((c = queue.poll()) != null) { + try { + c.call(world); + + if (sw.elapsed(TimeUnit.MILLISECONDS) > 50) { + break; + } + } catch (final Exception e) { + AELog.debug(e); + } + } + + // long time = sw.elapsed( TimeUnit.MILLISECONDS ); + // if ( time > 0 ) + // AELog.info( "processQueue Time: " + time + "ms" ); + } + + public void registerCraftingSimulation(final World world, final CraftingJob craftingJob) { + synchronized (this.craftingJobs) { + this.craftingJobs.put(world, craftingJob); + } + } + + private static class HandlerRep { + + private Queue tiles = new LinkedList(); + + private Collection networks = new NetworkList(); + + private void clear() { + this.tiles = new LinkedList(); + this.networks = new NetworkList(); + } + } + + public static class PlayerColor { + + public final AEColor myColor; + private final int myEntity; + private int ticksLeft; + + public PlayerColor(final int id, final AEColor col, final int ticks) { + this.myEntity = id; + this.myColor = col; + this.ticksLeft = ticks; + } + + public PacketPaintedEntity getPacket() { + return new PacketPaintedEntity(this.myEntity, this.myColor, this.ticksLeft); + } + } } diff --git a/src/main/java/appeng/integration/IIntegrationModule.java b/src/main/java/appeng/integration/IIntegrationModule.java index 64a7a8ae54b..37a554c88ed 100644 --- a/src/main/java/appeng/integration/IIntegrationModule.java +++ b/src/main/java/appeng/integration/IIntegrationModule.java @@ -18,10 +18,8 @@ package appeng.integration; +public interface IIntegrationModule { + void init() throws Throwable; -public interface IIntegrationModule -{ - void init() throws Throwable; - - void postInit(); + void postInit(); } diff --git a/src/main/java/appeng/integration/IntegrationHelper.java b/src/main/java/appeng/integration/IntegrationHelper.java index 783bbd48a5c..125bfb83b64 100644 --- a/src/main/java/appeng/integration/IntegrationHelper.java +++ b/src/main/java/appeng/integration/IntegrationHelper.java @@ -18,12 +18,9 @@ package appeng.integration; +public class IntegrationHelper { -public class IntegrationHelper -{ - - public static void testClassExistence( final Object o, final Class clz ) - { - clz.isInstance( o ); - } + public static void testClassExistence(final Object o, final Class clz) { + clz.isInstance(o); + } } diff --git a/src/main/java/appeng/integration/IntegrationNode.java b/src/main/java/appeng/integration/IntegrationNode.java index cd01e1b8018..002f4ebdb6e 100644 --- a/src/main/java/appeng/integration/IntegrationNode.java +++ b/src/main/java/appeng/integration/IntegrationNode.java @@ -18,161 +18,138 @@ package appeng.integration; - import appeng.api.exceptions.ModNotInstalled; import appeng.core.AEConfig; import appeng.core.AELog; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.ModAPIManager; - import java.lang.reflect.Field; - -public final class IntegrationNode -{ - - private final String displayName; - private final String modID; - private final IntegrationType shortName; - private IntegrationStage state = IntegrationStage.PRE_INIT; - private IntegrationStage failedStage = IntegrationStage.PRE_INIT; - private Throwable exception = null; - private String name = null; - private Class classValue = null; - private Object instance; - private IIntegrationModule mod = null; - - public IntegrationNode( final String displayName, final String modID, final IntegrationType shortName, final String name ) - { - this.displayName = displayName; - this.shortName = shortName; - this.modID = modID; - this.name = name; - } - - @Override - public String toString() - { - return this.getShortName().name() + ':' + this.getState().name(); - } - - boolean isActive() - { - if( this.getState() == IntegrationStage.PRE_INIT ) - { - this.call( IntegrationStage.PRE_INIT ); - } - - return this.getState() != IntegrationStage.FAILED; - } - - void call( final IntegrationStage stage ) - { - if( this.getState() != IntegrationStage.FAILED ) - { - if( this.getState().ordinal() > stage.ordinal() ) - { - return; - } - - try - { - switch( stage ) - { - case PRE_INIT: - final ModAPIManager apiManager = ModAPIManager.INSTANCE; - boolean enabled = this.modID == null || Loader.isModLoaded( this.modID ) || apiManager.hasAPI( this.modID ); - - AEConfig.instance.addCustomCategoryComment( "ModIntegration", "Valid Values are 'AUTO', 'ON', or 'OFF' - defaults to 'AUTO' ; Suggested that you leave this alone unless your experiencing an issue, or wish to disable the integration for a reason." ); - final String mode = AEConfig.instance.get( "ModIntegration", this.displayName.replace( " ", "" ), "AUTO" ).getString(); - - if( mode.toUpperCase().equals( "ON" ) ) - { - enabled = true; - } - if( mode.toUpperCase().equals( "OFF" ) ) - { - enabled = false; - } - - if( enabled ) - { - this.classValue = this.getClass().getClassLoader().loadClass( this.name ); - this.mod = (IIntegrationModule) this.classValue.getConstructor().newInstance(); - final Field f = this.classValue.getField( "instance" ); - f.set( this.classValue, this.setInstance( this.mod ) ); - } - else - { - throw new ModNotInstalled( this.modID ); - } - - this.setState( IntegrationStage.INIT ); - - break; - case INIT: - this.mod.init(); - this.setState( IntegrationStage.POST_INIT ); - - break; - case POST_INIT: - this.mod.postInit(); - this.setState( IntegrationStage.READY ); - - break; - case FAILED: - default: - break; - } - } - catch( final Throwable t ) - { - this.failedStage = stage; - this.exception = t; - this.setState( IntegrationStage.FAILED ); - } - } - - if( stage == IntegrationStage.POST_INIT ) - { - if( this.getState() == IntegrationStage.FAILED ) - { - AELog.info( this.displayName + " - Integration Disabled" ); - if( !( this.exception instanceof ModNotInstalled ) ) - { - AELog.integration( this.exception ); - } - } - else - { - AELog.info( this.displayName + " - Integration Enable" ); - } - } - } - - Object getInstance() - { - return this.instance; - } - - private Object setInstance( final Object instance ) - { - this.instance = instance; - return instance; - } - - IntegrationType getShortName() - { - return this.shortName; - } - - IntegrationStage getState() - { - return this.state; - } - - private void setState( final IntegrationStage state ) - { - this.state = state; - } +public final class IntegrationNode { + + private final String displayName; + private final String modID; + private final IntegrationType shortName; + private IntegrationStage state = IntegrationStage.PRE_INIT; + private IntegrationStage failedStage = IntegrationStage.PRE_INIT; + private Throwable exception = null; + private String name = null; + private Class classValue = null; + private Object instance; + private IIntegrationModule mod = null; + + public IntegrationNode( + final String displayName, final String modID, final IntegrationType shortName, final String name) { + this.displayName = displayName; + this.shortName = shortName; + this.modID = modID; + this.name = name; + } + + @Override + public String toString() { + return this.getShortName().name() + ':' + this.getState().name(); + } + + boolean isActive() { + if (this.getState() == IntegrationStage.PRE_INIT) { + this.call(IntegrationStage.PRE_INIT); + } + + return this.getState() != IntegrationStage.FAILED; + } + + void call(final IntegrationStage stage) { + if (this.getState() != IntegrationStage.FAILED) { + if (this.getState().ordinal() > stage.ordinal()) { + return; + } + + try { + switch (stage) { + case PRE_INIT: + final ModAPIManager apiManager = ModAPIManager.INSTANCE; + boolean enabled = + this.modID == null || Loader.isModLoaded(this.modID) || apiManager.hasAPI(this.modID); + + AEConfig.instance.addCustomCategoryComment( + "ModIntegration", + "Valid Values are 'AUTO', 'ON', or 'OFF' - defaults to 'AUTO' ; Suggested that you leave this alone unless your experiencing an issue, or wish to disable the integration for a reason."); + final String mode = AEConfig.instance + .get("ModIntegration", this.displayName.replace(" ", ""), "AUTO") + .getString(); + + if (mode.toUpperCase().equals("ON")) { + enabled = true; + } + if (mode.toUpperCase().equals("OFF")) { + enabled = false; + } + + if (enabled) { + this.classValue = this.getClass().getClassLoader().loadClass(this.name); + this.mod = (IIntegrationModule) + this.classValue.getConstructor().newInstance(); + final Field f = this.classValue.getField("instance"); + f.set(this.classValue, this.setInstance(this.mod)); + } else { + throw new ModNotInstalled(this.modID); + } + + this.setState(IntegrationStage.INIT); + + break; + case INIT: + this.mod.init(); + this.setState(IntegrationStage.POST_INIT); + + break; + case POST_INIT: + this.mod.postInit(); + this.setState(IntegrationStage.READY); + + break; + case FAILED: + default: + break; + } + } catch (final Throwable t) { + this.failedStage = stage; + this.exception = t; + this.setState(IntegrationStage.FAILED); + } + } + + if (stage == IntegrationStage.POST_INIT) { + if (this.getState() == IntegrationStage.FAILED) { + AELog.info(this.displayName + " - Integration Disabled"); + if (!(this.exception instanceof ModNotInstalled)) { + AELog.integration(this.exception); + } + } else { + AELog.info(this.displayName + " - Integration Enable"); + } + } + } + + Object getInstance() { + return this.instance; + } + + private Object setInstance(final Object instance) { + this.instance = instance; + return instance; + } + + IntegrationType getShortName() { + return this.shortName; + } + + IntegrationStage getState() { + return this.state; + } + + private void setState(final IntegrationStage state) { + this.state = state; + } } diff --git a/src/main/java/appeng/integration/IntegrationRegistry.java b/src/main/java/appeng/integration/IntegrationRegistry.java index 4e89feff3fb..00d12afa6dc 100644 --- a/src/main/java/appeng/integration/IntegrationRegistry.java +++ b/src/main/java/appeng/integration/IntegrationRegistry.java @@ -18,101 +18,80 @@ package appeng.integration; - import cpw.mods.fml.relauncher.FMLLaunchHandler; import cpw.mods.fml.relauncher.Side; - -import javax.annotation.Nonnull; import java.util.Collection; import java.util.LinkedList; +import javax.annotation.Nonnull; - -public enum IntegrationRegistry -{ - INSTANCE; - - private static final String PACKAGE_PREFIX = "appeng.integration.modules."; - - private final Collection modules = new LinkedList(); - - public void add( final IntegrationType type ) - { - if( type.side == IntegrationSide.CLIENT && FMLLaunchHandler.side() == Side.SERVER ) - { - return; - } - - if( type.side == IntegrationSide.SERVER && FMLLaunchHandler.side() == Side.CLIENT ) - { - return; - } - - this.modules.add( new IntegrationNode( type.dspName, type.modID, type, PACKAGE_PREFIX + type.name() ) ); - } - - public void init() - { - for( final IntegrationNode node : this.modules ) - { - node.call( IntegrationStage.PRE_INIT ); - } - - for( final IntegrationNode node : this.modules ) - { - node.call( IntegrationStage.INIT ); - } - } - - public void postInit() - { - for( final IntegrationNode node : this.modules ) - { - node.call( IntegrationStage.POST_INIT ); - } - } - - public String getStatus() - { - final StringBuilder builder = new StringBuilder( this.modules.size() * 3 ); - - for( final IntegrationNode node : this.modules ) - { - if( builder.length() != 0 ) - { - builder.append( ", " ); - } - - final String integrationState = node.getShortName() + ":" + ( node.getState() == IntegrationStage.FAILED ? "OFF" : "ON" ); - builder.append( integrationState ); - } - - return builder.toString(); - } - - public boolean isEnabled( final IntegrationType name ) - { - for( final IntegrationNode node : this.modules ) - { - if( node.getShortName() == name ) - { - return node.isActive(); - } - } - return false; - } - - @Nonnull - public Object getInstance( final IntegrationType name ) - { - for( final IntegrationNode node : this.modules ) - { - if( node.getShortName() == name && node.isActive() ) - { - return node.getInstance(); - } - } - - throw new IllegalStateException( "integration with " + name.name() + " is disabled." ); - } - +public enum IntegrationRegistry { + INSTANCE; + + private static final String PACKAGE_PREFIX = "appeng.integration.modules."; + + private final Collection modules = new LinkedList(); + + public void add(final IntegrationType type) { + if (type.side == IntegrationSide.CLIENT && FMLLaunchHandler.side() == Side.SERVER) { + return; + } + + if (type.side == IntegrationSide.SERVER && FMLLaunchHandler.side() == Side.CLIENT) { + return; + } + + this.modules.add(new IntegrationNode(type.dspName, type.modID, type, PACKAGE_PREFIX + type.name())); + } + + public void init() { + for (final IntegrationNode node : this.modules) { + node.call(IntegrationStage.PRE_INIT); + } + + for (final IntegrationNode node : this.modules) { + node.call(IntegrationStage.INIT); + } + } + + public void postInit() { + for (final IntegrationNode node : this.modules) { + node.call(IntegrationStage.POST_INIT); + } + } + + public String getStatus() { + final StringBuilder builder = new StringBuilder(this.modules.size() * 3); + + for (final IntegrationNode node : this.modules) { + if (builder.length() != 0) { + builder.append(", "); + } + + final String integrationState = + node.getShortName() + ":" + (node.getState() == IntegrationStage.FAILED ? "OFF" : "ON"); + builder.append(integrationState); + } + + return builder.toString(); + } + + public boolean isEnabled(final IntegrationType name) { + for (final IntegrationNode node : this.modules) { + if (node.getShortName() == name) { + return node.isActive(); + } + } + return false; + } + + @Nonnull + public Object getInstance(final IntegrationType name) { + for (final IntegrationNode node : this.modules) { + if (node.getShortName() == name && node.isActive()) { + return node.getInstance(); + } + } + + throw new IllegalStateException("integration with " + name.name() + " is disabled."); + } } diff --git a/src/main/java/appeng/integration/IntegrationSide.java b/src/main/java/appeng/integration/IntegrationSide.java index 25fd40a4dab..88d5580abe5 100644 --- a/src/main/java/appeng/integration/IntegrationSide.java +++ b/src/main/java/appeng/integration/IntegrationSide.java @@ -18,8 +18,8 @@ package appeng.integration; - -public enum IntegrationSide -{ - CLIENT, SERVER, BOTH +public enum IntegrationSide { + CLIENT, + SERVER, + BOTH } diff --git a/src/main/java/appeng/integration/IntegrationStage.java b/src/main/java/appeng/integration/IntegrationStage.java index 628cf5d4f0b..c589d3e8590 100644 --- a/src/main/java/appeng/integration/IntegrationStage.java +++ b/src/main/java/appeng/integration/IntegrationStage.java @@ -18,12 +18,11 @@ package appeng.integration; +public enum IntegrationStage { + PRE_INIT, + INIT, + POST_INIT, -public enum IntegrationStage -{ - - PRE_INIT, INIT, POST_INIT, - - FAILED, READY - + FAILED, + READY } diff --git a/src/main/java/appeng/integration/IntegrationType.java b/src/main/java/appeng/integration/IntegrationType.java index 043e38ea8f7..53ff1007dfd 100644 --- a/src/main/java/appeng/integration/IntegrationType.java +++ b/src/main/java/appeng/integration/IntegrationType.java @@ -18,71 +18,66 @@ package appeng.integration; +public enum IntegrationType { + IC2(IntegrationSide.BOTH, "Industrial Craft 2", "IC2"), -public enum IntegrationType -{ - IC2( IntegrationSide.BOTH, "Industrial Craft 2", "IC2" ), + RotaryCraft(IntegrationSide.BOTH, "Rotary Craft", "RotaryCraft"), - RotaryCraft( IntegrationSide.BOTH, "Rotary Craft", "RotaryCraft" ), + RC(IntegrationSide.BOTH, "Railcraft", "Railcraft"), - RC( IntegrationSide.BOTH, "Railcraft", "Railcraft" ), + BuildCraftCore(IntegrationSide.BOTH, "BuildCraft Core", "BuildCraft|Core"), - BuildCraftCore( IntegrationSide.BOTH, "BuildCraft Core", "BuildCraft|Core" ), + BuildCraftTransport(IntegrationSide.BOTH, "BuildCraft Transport", "BuildCraft|Transport"), - BuildCraftTransport( IntegrationSide.BOTH, "BuildCraft Transport", "BuildCraft|Transport" ), + BuildCraftBuilder(IntegrationSide.BOTH, "BuildCraft Builders", "BuildCraft|Builders"), - BuildCraftBuilder( IntegrationSide.BOTH, "BuildCraft Builders", "BuildCraft|Builders" ), + RF(IntegrationSide.BOTH, "RedstoneFlux Power - Tiles", "CoFHAPI"), - RF( IntegrationSide.BOTH, "RedstoneFlux Power - Tiles", "CoFHAPI" ), + RFItem(IntegrationSide.BOTH, "RedstoneFlux Power - Items", "CoFHAPI"), - RFItem( IntegrationSide.BOTH, "RedstoneFlux Power - Items", "CoFHAPI" ), + MFR(IntegrationSide.BOTH, "Mine Factory Reloaded", "MineFactoryReloaded"), - MFR( IntegrationSide.BOTH, "Mine Factory Reloaded", "MineFactoryReloaded" ), + DSU(IntegrationSide.BOTH, "Deep Storage Unit", null), - DSU( IntegrationSide.BOTH, "Deep Storage Unit", null ), + FZ(IntegrationSide.BOTH, "Factorization", "factorization"), - FZ( IntegrationSide.BOTH, "Factorization", "factorization" ), + FMP(IntegrationSide.BOTH, "Forge MultiPart", "McMultipart"), - FMP( IntegrationSide.BOTH, "Forge MultiPart", "McMultipart" ), + RB(IntegrationSide.BOTH, "Rotatable Blocks", "RotatableBlocks"), - RB( IntegrationSide.BOTH, "Rotatable Blocks", "RotatableBlocks" ), + CLApi(IntegrationSide.BOTH, "Colored Lights Core", "coloredlightscore"), - CLApi( IntegrationSide.BOTH, "Colored Lights Core", "coloredlightscore" ), + Waila(IntegrationSide.BOTH, "Waila", "Waila"), - Waila( IntegrationSide.BOTH, "Waila", "Waila" ), + InvTweaks(IntegrationSide.CLIENT, "Inventory Tweaks", "inventorytweaks"), - InvTweaks( IntegrationSide.CLIENT, "Inventory Tweaks", "inventorytweaks" ), + NEI(IntegrationSide.CLIENT, "Not Enough Items", "NotEnoughItems"), - NEI( IntegrationSide.CLIENT, "Not Enough Items", "NotEnoughItems" ), + CraftGuide(IntegrationSide.CLIENT, "Craft Guide", "craftguide"), - CraftGuide( IntegrationSide.CLIENT, "Craft Guide", "craftguide" ), + Mekanism(IntegrationSide.BOTH, "Mekanism", "Mekanism"), - Mekanism( IntegrationSide.BOTH, "Mekanism", "Mekanism" ), + ImmibisMicroblocks(IntegrationSide.BOTH, "ImmibisMicroblocks", "ImmibisMicroblocks"), - ImmibisMicroblocks( IntegrationSide.BOTH, "ImmibisMicroblocks", "ImmibisMicroblocks" ), + BetterStorage(IntegrationSide.BOTH, "BetterStorage", "betterstorage"), - BetterStorage( IntegrationSide.BOTH, "BetterStorage", "betterstorage" ), + OpenComputers(IntegrationSide.BOTH, "OpenComputers", "OpenComputers"), - OpenComputers( IntegrationSide.BOTH, "OpenComputers", "OpenComputers" ), + PneumaticCraft(IntegrationSide.BOTH, "PneumaticCraft", "PneumaticCraft"), - PneumaticCraft( IntegrationSide.BOTH, "PneumaticCraft", "PneumaticCraft" ), + GT(IntegrationSide.BOTH, "GregTech", "gregtech"), - GT( IntegrationSide.BOTH, "GregTech", "gregtech" ), + Chisel(IntegrationSide.BOTH, "Chisel", "chisel"), - Chisel(IntegrationSide.BOTH, "Chisel", "chisel"), + Jabba(IntegrationSide.BOTH, "Jabba", "JABBA"); - Jabba(IntegrationSide.BOTH, "Jabba", "JABBA") - ; - - public final IntegrationSide side; - public final String dspName; - public final String modID; - - IntegrationType( final IntegrationSide side, final String name, final String modid ) - { - this.side = side; - this.dspName = name; - this.modID = modid; - } + public final IntegrationSide side; + public final String dspName; + public final String modID; + IntegrationType(final IntegrationSide side, final String name, final String modid) { + this.side = side; + this.dspName = name; + this.modID = modid; + } } diff --git a/src/main/java/appeng/integration/abstraction/IBetterStorage.java b/src/main/java/appeng/integration/abstraction/IBetterStorage.java index 3f467c5828f..f8a04f23d6f 100644 --- a/src/main/java/appeng/integration/abstraction/IBetterStorage.java +++ b/src/main/java/appeng/integration/abstraction/IBetterStorage.java @@ -18,15 +18,12 @@ package appeng.integration.abstraction; - import appeng.util.InventoryAdaptor; import net.minecraftforge.common.util.ForgeDirection; +public interface IBetterStorage { -public interface IBetterStorage -{ - - boolean isStorageCrate( Object te ); + boolean isStorageCrate(Object te); - InventoryAdaptor getAdaptor( Object te, ForgeDirection d ); + InventoryAdaptor getAdaptor(Object te, ForgeDirection d); } diff --git a/src/main/java/appeng/integration/abstraction/IBuildCraftCore.java b/src/main/java/appeng/integration/abstraction/IBuildCraftCore.java index 1c2f8a46872..61be6447b4a 100644 --- a/src/main/java/appeng/integration/abstraction/IBuildCraftCore.java +++ b/src/main/java/appeng/integration/abstraction/IBuildCraftCore.java @@ -18,13 +18,10 @@ package appeng.integration.abstraction; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; - import javax.annotation.Nonnull; import javax.annotation.Nullable; - +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; /** * Contains wrench behaviour @@ -38,34 +35,33 @@ * @version rv3 * @since rv0 */ -public interface IBuildCraftCore -{ - /** - * @param eq to be checked item, can be {@code null} - * @return {@code true} if it is an {@link buildcraft.api.tools.IToolWrench} - */ - boolean isWrench( @Nullable Item eq ); +public interface IBuildCraftCore { + /** + * @param eq to be checked item, can be {@code null} + * @return {@code true} if it is an {@link buildcraft.api.tools.IToolWrench} + */ + boolean isWrench(@Nullable Item eq); - /** - * @param wrench to be checked item, must be an {@link buildcraft.api.tools.IToolWrench} - * @param wrencher wrenching player, can be probably {@code null}, but not sure - * @param x x pos - * @param y y pos - * @param z z pos - * @return {@code true} if player can wrench with that {@code wrench} - * @throws NullPointerException if {@code wrench} is {@code null} - * @throws ClassCastException if {@code wrench} is not an {@link buildcraft.api.tools.IToolWrench} - */ - boolean canWrench( @Nonnull Item wrench, EntityPlayer wrencher, int x, int y, int z ); + /** + * @param wrench to be checked item, must be an {@link buildcraft.api.tools.IToolWrench} + * @param wrencher wrenching player, can be probably {@code null}, but not sure + * @param x x pos + * @param y y pos + * @param z z pos + * @return {@code true} if player can wrench with that {@code wrench} + * @throws NullPointerException if {@code wrench} is {@code null} + * @throws ClassCastException if {@code wrench} is not an {@link buildcraft.api.tools.IToolWrench} + */ + boolean canWrench(@Nonnull Item wrench, EntityPlayer wrencher, int x, int y, int z); - /** - * @param wrench to be checked item, must be an {@link buildcraft.api.tools.IToolWrench} - * @param wrencher wrenching player, can be probably {@code null}, but not sure - * @param x x pos - * @param y y pos - * @param z z pos - * @throws NullPointerException if {@code wrench} is {@code null} - * @throws ClassCastException if {@code wrench} is not an {@link buildcraft.api.tools.IToolWrench} - */ - void wrenchUsed( @Nonnull Item wrench, EntityPlayer wrencher, int x, int y, int z ); + /** + * @param wrench to be checked item, must be an {@link buildcraft.api.tools.IToolWrench} + * @param wrencher wrenching player, can be probably {@code null}, but not sure + * @param x x pos + * @param y y pos + * @param z z pos + * @throws NullPointerException if {@code wrench} is {@code null} + * @throws ClassCastException if {@code wrench} is not an {@link buildcraft.api.tools.IToolWrench} + */ + void wrenchUsed(@Nonnull Item wrench, EntityPlayer wrencher, int x, int y, int z); } diff --git a/src/main/java/appeng/integration/abstraction/IBuildCraftTransport.java b/src/main/java/appeng/integration/abstraction/IBuildCraftTransport.java index f54014df416..06e34d9bd24 100644 --- a/src/main/java/appeng/integration/abstraction/IBuildCraftTransport.java +++ b/src/main/java/appeng/integration/abstraction/IBuildCraftTransport.java @@ -18,18 +18,15 @@ package appeng.integration.abstraction; - import appeng.api.parts.IFacadePart; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - - /** * Contains facade logic to interchange BC facades with AE facades, *

@@ -43,70 +40,69 @@ * @version rv3 - 12.06.2015 * @since rv3 12.06.2015 */ -public interface IBuildCraftTransport -{ - /** - * @param is to be checked item - * @return {@code true} if the checked item is a {@link buildcraft.api.facades.IFacadeItem} - */ - boolean isFacade( @Nullable ItemStack is ); +public interface IBuildCraftTransport { + /** + * @param is to be checked item + * @return {@code true} if the checked item is a {@link buildcraft.api.facades.IFacadeItem} + */ + boolean isFacade(@Nullable ItemStack is); - /** - * @param blk block used for the ae facade - * @param meta meta of the block - * @param side side of the ae facade - * @return ae facade through bc facade system - */ - @Nullable - IFacadePart createFacadePart( @Nullable Block blk, int meta, @Nonnull ForgeDirection side ); + /** + * @param blk block used for the ae facade + * @param meta meta of the block + * @param side side of the ae facade + * @return ae facade through bc facade system + */ + @Nullable + IFacadePart createFacadePart(@Nullable Block blk, int meta, @Nonnull ForgeDirection side); - /** - * @param held create facade for that item - * @param side on which side should the part be rendered, should rather be not {@code null} - * @return new instance using the {@code held} and side as direct argument, no logic in between - * @throws IllegalArgumentException if {@code held} is {@code null} - */ - IFacadePart createFacadePart( @Nonnull ItemStack held, @Nonnull ForgeDirection side ); + /** + * @param held create facade for that item + * @param side on which side should the part be rendered, should rather be not {@code null} + * @return new instance using the {@code held} and side as direct argument, no logic in between + * @throws IllegalArgumentException if {@code held} is {@code null} + */ + IFacadePart createFacadePart(@Nonnull ItemStack held, @Nonnull ForgeDirection side); - /** - * @param facade buildcraft facade - * @return item with the block and metadata based on the facade or {@code null} if {@code facade} was not a facade - * @throws NullPointerException if {@code facade} is {@code null} - */ - @Nullable - ItemStack getTextureForFacade( @Nonnull ItemStack facade ); + /** + * @param facade buildcraft facade + * @return item with the block and metadata based on the facade or {@code null} if {@code facade} was not a facade + * @throws NullPointerException if {@code facade} is {@code null} + */ + @Nullable + ItemStack getTextureForFacade(@Nonnull ItemStack facade); - /** - * @return texture of buildcraft cobblestone structure pipe or null if something bad happens - */ - @Nullable - IIcon getCobbleStructurePipeTexture(); + /** + * @return texture of buildcraft cobblestone structure pipe or null if something bad happens + */ + @Nullable + IIcon getCobbleStructurePipeTexture(); - /** - * @param te the to be checked {@link TileEntity} - * @param dir direction of the {@link TileEntity} - * @return {@code true} if {@code te} is a buildcraft pipe, but not plugged - * @throws NullPointerException if {@code dir} is {@code null} - */ - boolean isPipe( @Nullable TileEntity te, @Nonnull ForgeDirection dir ); + /** + * @param te the to be checked {@link TileEntity} + * @param dir direction of the {@link TileEntity} + * @return {@code true} if {@code te} is a buildcraft pipe, but not plugged + * @throws NullPointerException if {@code dir} is {@code null} + */ + boolean isPipe(@Nullable TileEntity te, @Nonnull ForgeDirection dir); - /** - * checks weather if the {@code te} is injectable and simulates to inject the item - * - * @param te preferred something like a buildcraft injectable, can handle anything, just fails that way - * @param is to be injected item - * @param dir direction of the pipe - * @return {@code true} if items were simulated successfully being added - */ - boolean canAddItemsToPipe( TileEntity te, ItemStack is, ForgeDirection dir ); + /** + * checks weather if the {@code te} is injectable and simulates to inject the item + * + * @param te preferred something like a buildcraft injectable, can handle anything, just fails that way + * @param is to be injected item + * @param dir direction of the pipe + * @return {@code true} if items were simulated successfully being added + */ + boolean canAddItemsToPipe(TileEntity te, ItemStack is, ForgeDirection dir); - /** - * checks weather if the {@code te} is injectable, simulates the inject and tries to inject the item - * - * @param te preferred something like a buildcraft injectable, can handle anything, just fails that way - * @param is to be injected item - * @param dir direction of the pipe - * @return {@code true} if items were added to the buildcraft pipe - */ - boolean addItemsToPipe( @Nullable TileEntity te, @Nullable ItemStack is, @Nonnull ForgeDirection dir ); + /** + * checks weather if the {@code te} is injectable, simulates the inject and tries to inject the item + * + * @param te preferred something like a buildcraft injectable, can handle anything, just fails that way + * @param is to be injected item + * @param dir direction of the pipe + * @return {@code true} if items were added to the buildcraft pipe + */ + boolean addItemsToPipe(@Nullable TileEntity te, @Nullable ItemStack is, @Nonnull ForgeDirection dir); } diff --git a/src/main/java/appeng/integration/abstraction/ICLApi.java b/src/main/java/appeng/integration/abstraction/ICLApi.java index d3184ecc495..faa7c085d79 100644 --- a/src/main/java/appeng/integration/abstraction/ICLApi.java +++ b/src/main/java/appeng/integration/abstraction/ICLApi.java @@ -18,12 +18,9 @@ package appeng.integration.abstraction; - import appeng.api.util.AEColor; +public interface ICLApi { -public interface ICLApi -{ - - int colorLight( AEColor color, int light ); + int colorLight(AEColor color, int light); } diff --git a/src/main/java/appeng/integration/abstraction/IDSU.java b/src/main/java/appeng/integration/abstraction/IDSU.java index 67ff00ecd89..ffa3f267eaf 100644 --- a/src/main/java/appeng/integration/abstraction/IDSU.java +++ b/src/main/java/appeng/integration/abstraction/IDSU.java @@ -18,15 +18,12 @@ package appeng.integration.abstraction; - import appeng.api.storage.IMEInventory; import net.minecraft.tileentity.TileEntity; +public interface IDSU { -public interface IDSU -{ - - IMEInventory getDSU( TileEntity te ); + IMEInventory getDSU(TileEntity te); - boolean isDSU( TileEntity te ); + boolean isDSU(TileEntity te); } diff --git a/src/main/java/appeng/integration/abstraction/IFMP.java b/src/main/java/appeng/integration/abstraction/IFMP.java index 24b51c63d1f..f9ab99d67ff 100644 --- a/src/main/java/appeng/integration/abstraction/IFMP.java +++ b/src/main/java/appeng/integration/abstraction/IFMP.java @@ -18,22 +18,19 @@ package appeng.integration.abstraction; - import appeng.api.parts.IPartHost; import appeng.parts.CableBusContainer; import cpw.mods.fml.common.eventhandler.Event; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.tileentity.TileEntity; +public interface IFMP { -public interface IFMP -{ - - IPartHost getOrCreateHost( TileEntity tile ); + IPartHost getOrCreateHost(TileEntity tile); - CableBusContainer getCableContainer( TileEntity te ); + CableBusContainer getCableContainer(TileEntity te); - void registerPassThrough( Class layerInterface ); + void registerPassThrough(Class layerInterface); - Event newFMPPacketEvent( EntityPlayerMP sender ); + Event newFMPPacketEvent(EntityPlayerMP sender); } diff --git a/src/main/java/appeng/integration/abstraction/IFZ.java b/src/main/java/appeng/integration/abstraction/IFZ.java index a6f68eafb00..d21ac85ca10 100644 --- a/src/main/java/appeng/integration/abstraction/IFZ.java +++ b/src/main/java/appeng/integration/abstraction/IFZ.java @@ -18,28 +18,25 @@ package appeng.integration.abstraction; - import appeng.api.storage.IMEInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +public interface IFZ { -public interface IFZ -{ - - ItemStack barrelGetItem( TileEntity te ); + ItemStack barrelGetItem(TileEntity te); - int barrelGetMaxItemCount( TileEntity te ); + int barrelGetMaxItemCount(TileEntity te); - int barrelGetItemCount( TileEntity te ); + int barrelGetItemCount(TileEntity te); - void setItemType( TileEntity te, ItemStack input ); + void setItemType(TileEntity te, ItemStack input); - void barrelSetCount( TileEntity te, int max ); + void barrelSetCount(TileEntity te, int max); - IMEInventory getFactorizationBarrel( TileEntity te ); + IMEInventory getFactorizationBarrel(TileEntity te); - boolean isBarrel( TileEntity te ); + boolean isBarrel(TileEntity te); - void grinderRecipe( ItemStack is, ItemStack itemStack ); + void grinderRecipe(ItemStack is, ItemStack itemStack); } diff --git a/src/main/java/appeng/integration/abstraction/IForestry.java b/src/main/java/appeng/integration/abstraction/IForestry.java index 816583c0d54..b1d1184eb10 100644 --- a/src/main/java/appeng/integration/abstraction/IForestry.java +++ b/src/main/java/appeng/integration/abstraction/IForestry.java @@ -18,12 +18,9 @@ package appeng.integration.abstraction; - import appeng.api.features.IItemComparisonProvider; +public interface IForestry { -public interface IForestry -{ - - IItemComparisonProvider getGeneticsComparisonProvider(); -} \ No newline at end of file + IItemComparisonProvider getGeneticsComparisonProvider(); +} diff --git a/src/main/java/appeng/integration/abstraction/IGT.java b/src/main/java/appeng/integration/abstraction/IGT.java index 7cc990bbc06..e377606f11f 100644 --- a/src/main/java/appeng/integration/abstraction/IGT.java +++ b/src/main/java/appeng/integration/abstraction/IGT.java @@ -18,15 +18,12 @@ package appeng.integration.abstraction; - import appeng.api.storage.IMEInventory; import net.minecraft.tileentity.TileEntity; +public interface IGT { -public interface IGT -{ - - boolean isQuantumChest( TileEntity te ); + boolean isQuantumChest(TileEntity te); - IMEInventory getQuantumChest( TileEntity te ); + IMEInventory getQuantumChest(TileEntity te); } diff --git a/src/main/java/appeng/integration/abstraction/IIC2.java b/src/main/java/appeng/integration/abstraction/IIC2.java index 655bc109386..bde96dd2c19 100644 --- a/src/main/java/appeng/integration/abstraction/IIC2.java +++ b/src/main/java/appeng/integration/abstraction/IIC2.java @@ -18,19 +18,16 @@ package appeng.integration.abstraction; - import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +public interface IIC2 { -public interface IIC2 -{ - - void addToEnergyNet( TileEntity appEngTile ); + void addToEnergyNet(TileEntity appEngTile); - void removeFromEnergyNet( TileEntity appEngTile ); + void removeFromEnergyNet(TileEntity appEngTile); - ItemStack getItem( String string ); + ItemStack getItem(String string); - void maceratorRecipe( ItemStack in, ItemStack out ); + void maceratorRecipe(ItemStack in, ItemStack out); } diff --git a/src/main/java/appeng/integration/abstraction/IImmibisMicroblocks.java b/src/main/java/appeng/integration/abstraction/IImmibisMicroblocks.java index 77059ee2c63..1d65e7f33d6 100644 --- a/src/main/java/appeng/integration/abstraction/IImmibisMicroblocks.java +++ b/src/main/java/appeng/integration/abstraction/IImmibisMicroblocks.java @@ -18,20 +18,17 @@ package appeng.integration.abstraction; - import appeng.api.parts.IPartHost; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; +public interface IImmibisMicroblocks { -public interface IImmibisMicroblocks -{ - - IPartHost getOrCreateHost( EntityPlayer player, int side, TileEntity te ); + IPartHost getOrCreateHost(EntityPlayer player, int side, TileEntity te); - /** - * @param te to be left tile entity - * @return true if this worked.. - */ - boolean leaveParts( TileEntity te ); + /** + * @param te to be left tile entity + * @return true if this worked.. + */ + boolean leaveParts(TileEntity te); } diff --git a/src/main/java/appeng/integration/abstraction/IInvTweaks.java b/src/main/java/appeng/integration/abstraction/IInvTweaks.java index e493123f909..9d6bd36bc8b 100644 --- a/src/main/java/appeng/integration/abstraction/IInvTweaks.java +++ b/src/main/java/appeng/integration/abstraction/IInvTweaks.java @@ -18,12 +18,9 @@ package appeng.integration.abstraction; - import net.minecraft.item.ItemStack; +public interface IInvTweaks { -public interface IInvTweaks -{ - - int compareItems( ItemStack i, ItemStack j ); + int compareItems(ItemStack i, ItemStack j); } diff --git a/src/main/java/appeng/integration/abstraction/ILP.java b/src/main/java/appeng/integration/abstraction/ILP.java index fc26e8040e0..c2d1d9704eb 100644 --- a/src/main/java/appeng/integration/abstraction/ILP.java +++ b/src/main/java/appeng/integration/abstraction/ILP.java @@ -18,32 +18,28 @@ package appeng.integration.abstraction; - import appeng.api.storage.IMEInventory; +import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -import java.util.List; - - -public interface ILP -{ +public interface ILP { - List getCraftedItems( TileEntity te ); + List getCraftedItems(TileEntity te); - List getProvidedItems( TileEntity te ); + List getProvidedItems(TileEntity te); - boolean isRequestPipe( TileEntity te ); + boolean isRequestPipe(TileEntity te); - List performRequest( TileEntity te, ItemStack wanted ); + List performRequest(TileEntity te, ItemStack wanted); - IMEInventory getInv( TileEntity te ); + IMEInventory getInv(TileEntity te); - Object getGetPowerPipe( TileEntity te ); + Object getGetPowerPipe(TileEntity te); - boolean isPowerSource( TileEntity tt ); + boolean isPowerSource(TileEntity tt); - boolean canUseEnergy( Object pp, int ceil, List providersToIgnore ); + boolean canUseEnergy(Object pp, int ceil, List providersToIgnore); - boolean useEnergy( Object pp, int ceil, List providersToIgnore ); + boolean useEnergy(Object pp, int ceil, List providersToIgnore); } diff --git a/src/main/java/appeng/integration/abstraction/IMekanism.java b/src/main/java/appeng/integration/abstraction/IMekanism.java index 8f56d415cf7..7116e5df1bc 100644 --- a/src/main/java/appeng/integration/abstraction/IMekanism.java +++ b/src/main/java/appeng/integration/abstraction/IMekanism.java @@ -18,14 +18,11 @@ package appeng.integration.abstraction; - import net.minecraft.item.ItemStack; +public interface IMekanism { -public interface IMekanism -{ - - void addCrusherRecipe( ItemStack in, ItemStack out ); + void addCrusherRecipe(ItemStack in, ItemStack out); - void addEnrichmentChamberRecipe( ItemStack in, ItemStack out ); + void addEnrichmentChamberRecipe(ItemStack in, ItemStack out); } diff --git a/src/main/java/appeng/integration/abstraction/INEI.java b/src/main/java/appeng/integration/abstraction/INEI.java index 817ef8b4293..6860022f947 100644 --- a/src/main/java/appeng/integration/abstraction/INEI.java +++ b/src/main/java/appeng/integration/abstraction/INEI.java @@ -18,15 +18,12 @@ package appeng.integration.abstraction; - import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.inventory.Slot; +public interface INEI { -public interface INEI -{ - - void drawSlot( Slot s ); + void drawSlot(Slot s); - RenderItem setItemRender( RenderItem renderItem ); + RenderItem setItemRender(RenderItem renderItem); } diff --git a/src/main/java/appeng/integration/abstraction/IRC.java b/src/main/java/appeng/integration/abstraction/IRC.java index 857a5cc02d0..b60be4a4796 100644 --- a/src/main/java/appeng/integration/abstraction/IRC.java +++ b/src/main/java/appeng/integration/abstraction/IRC.java @@ -18,12 +18,9 @@ package appeng.integration.abstraction; - import net.minecraft.item.ItemStack; +public interface IRC { -public interface IRC -{ - - void rockCrusher( ItemStack input, ItemStack output ); + void rockCrusher(ItemStack input, ItemStack output); } diff --git a/src/main/java/appeng/integration/abstraction/ITE.java b/src/main/java/appeng/integration/abstraction/ITE.java index 7aca71e7df5..1bebd51abf0 100644 --- a/src/main/java/appeng/integration/abstraction/ITE.java +++ b/src/main/java/appeng/integration/abstraction/ITE.java @@ -18,20 +18,17 @@ package appeng.integration.abstraction; - import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +public interface ITE { -public interface ITE -{ - - void addPulverizerRecipe( int i, ItemStack blkQuartz, ItemStack blockDust ); + void addPulverizerRecipe(int i, ItemStack blkQuartz, ItemStack blockDust); - void addPulverizerRecipe( int i, ItemStack blkQuartzOre, ItemStack matQuartz, ItemStack matQuartzDust ); + void addPulverizerRecipe(int i, ItemStack blkQuartzOre, ItemStack matQuartz, ItemStack matQuartzDust); - boolean isPipe( TileEntity te, ForgeDirection opposite ); + boolean isPipe(TileEntity te, ForgeDirection opposite); - ItemStack addItemsToPipe( TileEntity ad, ItemStack itemstack, ForgeDirection dir ); + ItemStack addItemsToPipe(TileEntity ad, ItemStack itemstack, ForgeDirection dir); } diff --git a/src/main/java/appeng/integration/modules/BCHelpers/AECableSchematicTile.java b/src/main/java/appeng/integration/modules/BCHelpers/AECableSchematicTile.java index 456cd85f068..696ccc8a931 100644 --- a/src/main/java/appeng/integration/modules/BCHelpers/AECableSchematicTile.java +++ b/src/main/java/appeng/integration/modules/BCHelpers/AECableSchematicTile.java @@ -18,12 +18,12 @@ package appeng.integration.modules.BCHelpers; - import appeng.api.parts.*; import appeng.api.util.AEColor; import appeng.api.util.DimensionalCoord; import appeng.parts.CableBusContainer; import buildcraft.api.blueprints.IBuilderContext; +import java.util.Set; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -31,141 +31,102 @@ import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Set; +public class AECableSchematicTile extends AEGenericSchematicTile implements IPartHost { + + @Override + public void rotateLeft(final IBuilderContext context) { + final CableBusContainer cbc = new CableBusContainer(this); + cbc.readFromNBT(this.tileNBT); + + cbc.rotateLeft(); + + this.tileNBT = new NBTTagCompound(); + cbc.writeToNBT(this.tileNBT); + } + + @Override + public IFacadeContainer getFacadeContainer() { + return null; + } + + @Override + public boolean canAddPart(final ItemStack part, final ForgeDirection side) { + return false; + } + + @Override + public ForgeDirection addPart(final ItemStack is, final ForgeDirection side, final EntityPlayer owner) { + return null; + } + + @Override + public IPart getPart(final ForgeDirection side) { + return null; + } + + @Override + public void removePart(final ForgeDirection side, final boolean suppressUpdate) {} + + @Override + public void markForUpdate() {} + + @Override + public DimensionalCoord getLocation() { + return null; + } + + @Override + public TileEntity getTile() { + return null; + } + + @Override + public AEColor getColor() { + return null; + } + + @Override + public void clearContainer() {} + + @Override + public boolean isBlocked(final ForgeDirection side) { + return false; + } + + @Override + public SelectedPart selectPart(final Vec3 pos) { + return null; + } + + @Override + public void markForSave() {} + + @Override + public void partChanged() {} + + @Override + public boolean hasRedstone(final ForgeDirection side) { + return false; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public Set getLayerFlags() { + return null; + } + + @Override + public void cleanup() {} + @Override + public void notifyNeighbors() {} -public class AECableSchematicTile extends AEGenericSchematicTile implements IPartHost -{ - - @Override - public void rotateLeft( final IBuilderContext context ) - { - final CableBusContainer cbc = new CableBusContainer( this ); - cbc.readFromNBT( this.tileNBT ); - - cbc.rotateLeft(); - - this.tileNBT = new NBTTagCompound(); - cbc.writeToNBT( this.tileNBT ); - } - - @Override - public IFacadeContainer getFacadeContainer() - { - return null; - } - - @Override - public boolean canAddPart( final ItemStack part, final ForgeDirection side ) - { - return false; - } - - @Override - public ForgeDirection addPart( final ItemStack is, final ForgeDirection side, final EntityPlayer owner ) - { - return null; - } - - @Override - public IPart getPart( final ForgeDirection side ) - { - return null; - } - - @Override - public void removePart( final ForgeDirection side, final boolean suppressUpdate ) - { - - } - - @Override - public void markForUpdate() - { - - } - - @Override - public DimensionalCoord getLocation() - { - return null; - } - - @Override - public TileEntity getTile() - { - return null; - } - - @Override - public AEColor getColor() - { - return null; - } - - @Override - public void clearContainer() - { - - } - - @Override - public boolean isBlocked( final ForgeDirection side ) - { - return false; - } - - @Override - public SelectedPart selectPart( final Vec3 pos ) - { - return null; - } - - @Override - public void markForSave() - { - - } - - @Override - public void partChanged() - { - - } - - @Override - public boolean hasRedstone( final ForgeDirection side ) - { - return false; - } - - @Override - public boolean isEmpty() - { - return false; - } - - @Override - public Set getLayerFlags() - { - return null; - } - - @Override - public void cleanup() - { - - } - - @Override - public void notifyNeighbors() - { - - } - - @Override - public boolean isInWorld() - { - return false; - } + @Override + public boolean isInWorld() { + return false; + } } diff --git a/src/main/java/appeng/integration/modules/BCHelpers/AEGenericSchematicTile.java b/src/main/java/appeng/integration/modules/BCHelpers/AEGenericSchematicTile.java index b856b53f2cf..57ff403b650 100644 --- a/src/main/java/appeng/integration/modules/BCHelpers/AEGenericSchematicTile.java +++ b/src/main/java/appeng/integration/modules/BCHelpers/AEGenericSchematicTile.java @@ -18,62 +18,50 @@ package appeng.integration.modules.BCHelpers; - import appeng.api.util.ICommonTile; import appeng.tile.AEBaseTile; import appeng.util.Platform; import buildcraft.api.blueprints.IBuilderContext; import buildcraft.api.blueprints.SchematicTile; +import java.util.ArrayList; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; - - -public class AEGenericSchematicTile extends SchematicTile -{ +public class AEGenericSchematicTile extends SchematicTile { - @Override - public void storeRequirements( final IBuilderContext context, final int x, final int y, final int z ) - { - final TileEntity tile = context.world().getTileEntity( x, y, z ); - final ArrayList list = new ArrayList(); - if( tile instanceof AEBaseTile ) - { - final ICommonTile tcb = (ICommonTile) tile; - tcb.getDrops( tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, list ); - } + @Override + public void storeRequirements(final IBuilderContext context, final int x, final int y, final int z) { + final TileEntity tile = context.world().getTileEntity(x, y, z); + final ArrayList list = new ArrayList(); + if (tile instanceof AEBaseTile) { + final ICommonTile tcb = (ICommonTile) tile; + tcb.getDrops(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, list); + } - this.storedRequirements = list.toArray( new ItemStack[list.size()] ); - } + this.storedRequirements = list.toArray(new ItemStack[list.size()]); + } - @Override - public void rotateLeft( final IBuilderContext context ) - { - if( this.tileNBT.hasKey( "orientation_forward" ) && this.tileNBT.hasKey( "orientation_up" ) ) - { - final String forward = this.tileNBT.getString( "orientation_forward" ); - final String up = this.tileNBT.getString( "orientation_up" ); + @Override + public void rotateLeft(final IBuilderContext context) { + if (this.tileNBT.hasKey("orientation_forward") && this.tileNBT.hasKey("orientation_up")) { + final String forward = this.tileNBT.getString("orientation_forward"); + final String up = this.tileNBT.getString("orientation_up"); - if( forward != null && up != null ) - { - try - { - ForgeDirection fdForward = ForgeDirection.valueOf( forward ); - ForgeDirection fdUp = ForgeDirection.valueOf( up ); + if (forward != null && up != null) { + try { + ForgeDirection fdForward = ForgeDirection.valueOf(forward); + ForgeDirection fdUp = ForgeDirection.valueOf(up); - fdForward = Platform.rotateAround( fdForward, ForgeDirection.DOWN ); - fdUp = Platform.rotateAround( fdUp, ForgeDirection.DOWN ); + fdForward = Platform.rotateAround(fdForward, ForgeDirection.DOWN); + fdUp = Platform.rotateAround(fdUp, ForgeDirection.DOWN); - this.tileNBT.setString( "orientation_forward", fdForward.name() ); - this.tileNBT.setString( "orientation_up", fdUp.name() ); - } - catch( final Throwable ignored ) - { + this.tileNBT.setString("orientation_forward", fdForward.name()); + this.tileNBT.setString("orientation_up", fdUp.name()); + } catch (final Throwable ignored) { - } - } - } - } + } + } + } + } } diff --git a/src/main/java/appeng/integration/modules/BCHelpers/AERotatableBlockSchematic.java b/src/main/java/appeng/integration/modules/BCHelpers/AERotatableBlockSchematic.java index 7697cf79a03..2fb436c46ed 100644 --- a/src/main/java/appeng/integration/modules/BCHelpers/AERotatableBlockSchematic.java +++ b/src/main/java/appeng/integration/modules/BCHelpers/AERotatableBlockSchematic.java @@ -18,23 +18,18 @@ package appeng.integration.modules.BCHelpers; - import appeng.util.Platform; import buildcraft.api.blueprints.IBuilderContext; import buildcraft.api.blueprints.SchematicBlock; import net.minecraftforge.common.util.ForgeDirection; +public class AERotatableBlockSchematic extends SchematicBlock { -public class AERotatableBlockSchematic extends SchematicBlock -{ - - @Override - public void rotateLeft( final IBuilderContext context ) - { - if( this.meta < 6 ) - { - final ForgeDirection d = Platform.rotateAround( ForgeDirection.values()[this.meta], ForgeDirection.DOWN ); - this.meta = d.ordinal(); - } - } + @Override + public void rotateLeft(final IBuilderContext context) { + if (this.meta < 6) { + final ForgeDirection d = Platform.rotateAround(ForgeDirection.values()[this.meta], ForgeDirection.DOWN); + this.meta = d.ordinal(); + } + } } diff --git a/src/main/java/appeng/integration/modules/BCHelpers/BCPipeHandler.java b/src/main/java/appeng/integration/modules/BCHelpers/BCPipeHandler.java index c067ca33958..0dccf44a3e3 100644 --- a/src/main/java/appeng/integration/modules/BCHelpers/BCPipeHandler.java +++ b/src/main/java/appeng/integration/modules/BCHelpers/BCPipeHandler.java @@ -18,7 +18,6 @@ package appeng.integration.modules.BCHelpers; - import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageHandler; import appeng.api.storage.IMEInventory; @@ -29,30 +28,27 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; - -public class BCPipeHandler implements IExternalStorageHandler -{ - - @Override - public boolean canHandle( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource mySrc ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport bc = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - - return chan == StorageChannel.ITEMS && bc.isPipe( te, d ); - } - - return false; - } - - @Override - public IMEInventory getInventory( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource src ) - { - if( chan == StorageChannel.ITEMS ) - { - return new BCPipeInventory( te, d ); - } - return null; - } +public class BCPipeHandler implements IExternalStorageHandler { + + @Override + public boolean canHandle( + final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource mySrc) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport)) { + final IBuildCraftTransport bc = (IBuildCraftTransport) + IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport); + + return chan == StorageChannel.ITEMS && bc.isPipe(te, d); + } + + return false; + } + + @Override + public IMEInventory getInventory( + final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource src) { + if (chan == StorageChannel.ITEMS) { + return new BCPipeInventory(te, d); + } + return null; + } } diff --git a/src/main/java/appeng/integration/modules/BCHelpers/BCPipeInventory.java b/src/main/java/appeng/integration/modules/BCHelpers/BCPipeInventory.java index f4bcec50faf..0570ec97c6e 100644 --- a/src/main/java/appeng/integration/modules/BCHelpers/BCPipeInventory.java +++ b/src/main/java/appeng/integration/modules/BCHelpers/BCPipeInventory.java @@ -18,7 +18,6 @@ package appeng.integration.modules.BCHelpers; - import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IMEInventory; @@ -31,59 +30,49 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +public class BCPipeInventory implements IMEInventory { -public class BCPipeInventory implements IMEInventory -{ - - private final TileEntity te; - private final ForgeDirection direction; + private final TileEntity te; + private final ForgeDirection direction; - public BCPipeInventory( final TileEntity te, final ForgeDirection direction ) - { - this.te = te; - this.direction = direction; - } + public BCPipeInventory(final TileEntity te, final ForgeDirection direction) { + this.te = te; + this.direction = direction; + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport registry = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode, final BaseActionSource src) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport)) { + final IBuildCraftTransport registry = (IBuildCraftTransport) + IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport); - if( mode == Actionable.SIMULATE ) - { - if( registry.canAddItemsToPipe( this.te, input.getItemStack(), this.direction ) ) - { - return null; - } - return input; - } + if (mode == Actionable.SIMULATE) { + if (registry.canAddItemsToPipe(this.te, input.getItemStack(), this.direction)) { + return null; + } + return input; + } - if( registry.addItemsToPipe( this.te, input.getItemStack(), this.direction ) ) - { - return null; - } - } + if (registry.addItemsToPipe(this.te, input.getItemStack(), this.direction)) { + return null; + } + } - return input; - } + return input; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - return null; - } + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final BaseActionSource src) { + return null; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return out; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + return out; + } - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } } diff --git a/src/main/java/appeng/integration/modules/BetterStorage.java b/src/main/java/appeng/integration/modules/BetterStorage.java index dd6e8219865..28184462500 100644 --- a/src/main/java/appeng/integration/modules/BetterStorage.java +++ b/src/main/java/appeng/integration/modules/BetterStorage.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; @@ -30,42 +29,33 @@ import net.mcft.copy.betterstorage.api.crate.ICrateStorage; import net.minecraftforge.common.util.ForgeDirection; - -public class BetterStorage implements IIntegrationModule, IBetterStorage -{ - @Reflected - public static BetterStorage instance; - - @Reflected - public BetterStorage() - { - IntegrationHelper.testClassExistence( this, net.mcft.copy.betterstorage.api.crate.ICrateStorage.class ); - } - - @Override - public boolean isStorageCrate( final Object te ) - { - return te instanceof ICrateStorage; - } - - @Override - public InventoryAdaptor getAdaptor( final Object te, final ForgeDirection d ) - { - if( te instanceof ICrateStorage ) - { - return new BSCrateStorageAdaptor( te ); - } - return null; - } - - @Override - public void init() - { - } - - @Override - public void postInit() - { - AEApi.instance().registries().externalStorage().addExternalStorageInterface( new BSCrateHandler() ); - } +public class BetterStorage implements IIntegrationModule, IBetterStorage { + @Reflected + public static BetterStorage instance; + + @Reflected + public BetterStorage() { + IntegrationHelper.testClassExistence(this, net.mcft.copy.betterstorage.api.crate.ICrateStorage.class); + } + + @Override + public boolean isStorageCrate(final Object te) { + return te instanceof ICrateStorage; + } + + @Override + public InventoryAdaptor getAdaptor(final Object te, final ForgeDirection d) { + if (te instanceof ICrateStorage) { + return new BSCrateStorageAdaptor(te); + } + return null; + } + + @Override + public void init() {} + + @Override + public void postInit() { + AEApi.instance().registries().externalStorage().addExternalStorageInterface(new BSCrateHandler()); + } } diff --git a/src/main/java/appeng/integration/modules/BuildCraftBuilder.java b/src/main/java/appeng/integration/modules/BuildCraftBuilder.java index d8f997dd5c5..6287d5eeac0 100644 --- a/src/main/java/appeng/integration/modules/BuildCraftBuilder.java +++ b/src/main/java/appeng/integration/modules/BuildCraftBuilder.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IBlocks; @@ -34,12 +33,10 @@ import buildcraft.api.blueprints.BuilderAPI; import buildcraft.api.blueprints.ISchematicRegistry; import com.google.common.base.Optional; -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; - import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; - +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; /** * The builder has no interface, because it provides no functionality @@ -49,79 +46,64 @@ * @since rv3 12.06.2015 */ @Reflected -public class BuildCraftBuilder implements IIntegrationModule -{ - @Reflected - public static BuildCraftBuilder instance; +public class BuildCraftBuilder implements IIntegrationModule { + @Reflected + public static BuildCraftBuilder instance; - @Reflected - public BuildCraftBuilder() - { - IntegrationHelper.testClassExistence( this, buildcraft.api.blueprints.BuilderAPI.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.blueprints.IBuilderContext.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.blueprints.ISchematicRegistry.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.blueprints.SchematicTile.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.blueprints.SchematicBlock.class ); - } + @Reflected + public BuildCraftBuilder() { + IntegrationHelper.testClassExistence(this, buildcraft.api.blueprints.BuilderAPI.class); + IntegrationHelper.testClassExistence(this, buildcraft.api.blueprints.IBuilderContext.class); + IntegrationHelper.testClassExistence(this, buildcraft.api.blueprints.ISchematicRegistry.class); + IntegrationHelper.testClassExistence(this, buildcraft.api.blueprints.SchematicTile.class); + IntegrationHelper.testClassExistence(this, buildcraft.api.blueprints.SchematicBlock.class); + } - @Override - public void init() throws Throwable - { - try - { - this.initBuilderSupport(); - } - catch( final Exception builderSupport ) - { - // not supported? - } - } + @Override + public void init() throws Throwable { + try { + this.initBuilderSupport(); + } catch (final Exception builderSupport) { + // not supported? + } + } - @Override - public void postInit() - { - } + @Override + public void postInit() {} - private void initBuilderSupport() - { - final ISchematicRegistry schematicRegistry = BuilderAPI.schematicRegistry; + private void initBuilderSupport() { + final ISchematicRegistry schematicRegistry = BuilderAPI.schematicRegistry; - final IBlocks blocks = AEApi.instance().definitions().blocks(); - final IBlockDefinition maybeMultiPart = blocks.multiPart(); + final IBlocks blocks = AEApi.instance().definitions().blocks(); + final IBlockDefinition maybeMultiPart = blocks.multiPart(); - for( final Method blockDefinition : blocks.getClass().getMethods() ) - { - try - { - final IBlockDefinition def = (IBlockDefinition) blockDefinition.invoke( blocks ); - final Optional maybeBlock = def.maybeBlock(); - if( !maybeBlock.isPresent() ) - { - continue; - } + for (final Method blockDefinition : blocks.getClass().getMethods()) { + try { + final IBlockDefinition def = (IBlockDefinition) blockDefinition.invoke(blocks); + final Optional maybeBlock = def.maybeBlock(); + if (!maybeBlock.isPresent()) { + continue; + } - final Block block = maybeBlock.get(); - if( block instanceof IOrientableBlock && ( (IOrientableBlock) block ).usesMetadata() && !( def instanceof ITileDefinition ) ) - { - schematicRegistry.registerSchematicBlock( block, AERotatableBlockSchematic.class ); - } - else if( maybeMultiPart.isSameAs( new ItemStack( block ) ) ) - { - schematicRegistry.registerSchematicBlock( block, AECableSchematicTile.class ); - } - else if( def instanceof ITileDefinition ) - { - schematicRegistry.registerSchematicBlock( block, AEGenericSchematicTile.class ); - } - } - catch( final InvocationTargetException ignore ) - { - AELog.warn( "Encountered problems while initializing the BuildCraft Builder support. Can not invoke the method %s", blockDefinition ); - } - catch( final IllegalAccessException ignore ) - { - AELog.warn( "Encountered problems while initializing the BuildCraft Builder support. Can not access the method %s", blockDefinition ); - } - } - } + final Block block = maybeBlock.get(); + if (block instanceof IOrientableBlock + && ((IOrientableBlock) block).usesMetadata() + && !(def instanceof ITileDefinition)) { + schematicRegistry.registerSchematicBlock(block, AERotatableBlockSchematic.class); + } else if (maybeMultiPart.isSameAs(new ItemStack(block))) { + schematicRegistry.registerSchematicBlock(block, AECableSchematicTile.class); + } else if (def instanceof ITileDefinition) { + schematicRegistry.registerSchematicBlock(block, AEGenericSchematicTile.class); + } + } catch (final InvocationTargetException ignore) { + AELog.warn( + "Encountered problems while initializing the BuildCraft Builder support. Can not invoke the method %s", + blockDefinition); + } catch (final IllegalAccessException ignore) { + AELog.warn( + "Encountered problems while initializing the BuildCraft Builder support. Can not access the method %s", + blockDefinition); + } + } + } } diff --git a/src/main/java/appeng/integration/modules/BuildCraftCore.java b/src/main/java/appeng/integration/modules/BuildCraftCore.java index 9dd6d26ee7c..45839dc888b 100644 --- a/src/main/java/appeng/integration/modules/BuildCraftCore.java +++ b/src/main/java/appeng/integration/modules/BuildCraftCore.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.config.TunnelType; import appeng.api.features.IP2PTunnelRegistry; @@ -27,62 +26,53 @@ import appeng.integration.IntegrationHelper; import appeng.integration.abstraction.IBuildCraftCore; import buildcraft.api.tools.IToolWrench; +import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import javax.annotation.Nonnull; - - @Reflected -public final class BuildCraftCore implements IBuildCraftCore, IIntegrationModule -{ - @Reflected - public static BuildCraftCore instance; +public final class BuildCraftCore implements IBuildCraftCore, IIntegrationModule { + @Reflected + public static BuildCraftCore instance; - @Reflected - public BuildCraftCore() - { - IntegrationHelper.testClassExistence( this, buildcraft.BuildCraftCore.class ); - IntegrationHelper.testClassExistence( this, buildcraft.BuildCraftTransport.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.tools.IToolWrench.class ); - } + @Reflected + public BuildCraftCore() { + IntegrationHelper.testClassExistence(this, buildcraft.BuildCraftCore.class); + IntegrationHelper.testClassExistence(this, buildcraft.BuildCraftTransport.class); + IntegrationHelper.testClassExistence(this, buildcraft.api.tools.IToolWrench.class); + } - @Override - public boolean isWrench( final Item eq ) - { - return eq instanceof IToolWrench; - } + @Override + public boolean isWrench(final Item eq) { + return eq instanceof IToolWrench; + } - @Override - public boolean canWrench( @Nonnull final Item wrench, final EntityPlayer wrencher, final int x, final int y, final int z ) - { - return ( (IToolWrench) wrench ).canWrench( wrencher, x, y, z ); - } + @Override + public boolean canWrench( + @Nonnull final Item wrench, final EntityPlayer wrencher, final int x, final int y, final int z) { + return ((IToolWrench) wrench).canWrench(wrencher, x, y, z); + } - @Override - public void wrenchUsed( @Nonnull final Item wrench, final EntityPlayer wrencher, final int x, final int y, final int z ) - { - ( (IToolWrench) wrench ).wrenchUsed( wrencher, x, y, z ); - } + @Override + public void wrenchUsed( + @Nonnull final Item wrench, final EntityPlayer wrencher, final int x, final int y, final int z) { + ((IToolWrench) wrench).wrenchUsed(wrencher, x, y, z); + } - @Override - public void init() - { - } + @Override + public void init() {} - @Override - public void postInit() - { - this.registerPowerP2P(); - } + @Override + public void postInit() { + this.registerPowerP2P(); + } - private void registerPowerP2P() - { - final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); + private void registerPowerP2P() { + final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftCore.engineBlock, 1, 0 ), TunnelType.RF_POWER ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftCore.engineBlock, 1, 1 ), TunnelType.RF_POWER ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftCore.engineBlock, 1, 2 ), TunnelType.RF_POWER ); - } + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftCore.engineBlock, 1, 0), TunnelType.RF_POWER); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftCore.engineBlock, 1, 1), TunnelType.RF_POWER); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftCore.engineBlock, 1, 2), TunnelType.RF_POWER); + } } diff --git a/src/main/java/appeng/integration/modules/BuildCraftTransport.java b/src/main/java/appeng/integration/modules/BuildCraftTransport.java index 5c011dc5029..0448c7153d7 100644 --- a/src/main/java/appeng/integration/modules/BuildCraftTransport.java +++ b/src/main/java/appeng/integration/modules/BuildCraftTransport.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.IAppEngApi; import appeng.api.config.TunnelType; @@ -38,6 +37,8 @@ import buildcraft.transport.ItemFacade; import buildcraft.transport.PipeIconProvider; import cpw.mods.fml.common.event.FMLInterModComms; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -45,255 +46,218 @@ import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - - /** * @author thatsIch * @version rv3 - 12.06.2015 * @since rv3 12.06.2015 */ @Reflected -public class BuildCraftTransport implements IBuildCraftTransport, IIntegrationModule -{ - @Reflected - public static BuildCraftTransport instance; - - @Reflected - public BuildCraftTransport() - { - IntegrationHelper.testClassExistence( this, buildcraft.BuildCraftTransport.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.facades.IFacadeItem.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.transport.IInjectable.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.transport.IPipeConnection.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.transport.IPipeTile.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.transport.IPipeTile.PipeType.class ); - IntegrationHelper.testClassExistence( this, buildcraft.transport.ItemFacade.class ); - IntegrationHelper.testClassExistence( this, buildcraft.transport.PipeIconProvider.class ); - } - - @Override - public boolean isFacade( final ItemStack is ) - { - if( is == null ) - { - return false; - } - - return is.getItem() instanceof IFacadeItem; - } - - @Nullable - @Override - public IFacadePart createFacadePart( final Block blk, final int meta, @Nonnull final ForgeDirection side ) - { - try - { - final ItemFacade.FacadeState state = ItemFacade.FacadeState.create( blk, meta ); - final ItemStack facade = ItemFacade.getFacade( state ); - - return new FacadePart( facade, side ); - } - catch( final Exception ignored ) - { - - } - - return null; - } - - @Override - public IFacadePart createFacadePart( @Nonnull final ItemStack fs, @Nonnull final ForgeDirection side ) - { - return new FacadePart( fs, side ); - } - - @Nullable - @Override - public ItemStack getTextureForFacade( @Nonnull final ItemStack facade ) - { - final Item maybeFacadeItem = facade.getItem(); - - if( maybeFacadeItem instanceof IFacadeItem ) - { - final IFacadeItem facadeItem = (IFacadeItem) maybeFacadeItem; - - final Block[] blocks = facadeItem.getBlocksForFacade( facade ); - final int[] metas = facadeItem.getMetaValuesForFacade( facade ); - - if( blocks.length > 0 && metas.length > 0 ) - { - return new ItemStack( blocks[0], 1, metas[0] ); - } - } - - return null; - } - - @Nullable - @Override - public IIcon getCobbleStructurePipeTexture() - { - try - { - return buildcraft.BuildCraftTransport.instance.pipeIconProvider.getIcon( PipeIconProvider.TYPE.PipeStructureCobblestone.ordinal() ); // Structure - } - catch( final Exception ignored ) - { - } - return null; - // Pipe - } - - @Override - public boolean isPipe( final TileEntity te, @Nonnull final ForgeDirection dir ) - { - if( te instanceof IPipeTile ) - { - final IPipeTile pipeTile = (IPipeTile) te; - return !pipeTile.hasPipePluggable( dir.getOpposite() ); - } - - return false; - } - - @Override - public boolean canAddItemsToPipe( final TileEntity te, final ItemStack is, final ForgeDirection dir ) - { - if( is != null && te != null && te instanceof IInjectable ) - { - final IInjectable pt = (IInjectable) te; - if( pt.canInjectItems( dir ) ) - { - final int amt = pt.injectItem( is, false, dir, null ); - if( amt == is.stackSize ) - { - return true; - } - } - } - - return false; - } - - @Override - public boolean addItemsToPipe( @Nullable final TileEntity te, @Nullable final ItemStack is, @Nonnull final ForgeDirection dir ) - { - if( is != null && te != null && te instanceof IInjectable ) - { - final IInjectable pt = (IInjectable) te; - if( pt.canInjectItems( dir ) ) - { - final int amt = pt.injectItem( is, false, dir, null ); - if( amt == is.stackSize ) - { - pt.injectItem( is, true, dir, null ); - return true; - } - } - } - - return false; - } - - private void addFacade( final ItemStack item ) - { - if( item != null ) - { - FMLInterModComms.sendMessage( "BuildCraft|Transport", "add-facade", item ); - } - } - - private void registerPowerP2P() - { - final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); - - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipePowerCobblestone ), TunnelType.RF_POWER ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipePowerDiamond ), TunnelType.RF_POWER ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipePowerGold ), TunnelType.RF_POWER ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipePowerQuartz ), TunnelType.RF_POWER ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipePowerStone ), TunnelType.RF_POWER ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipePowerWood ), TunnelType.RF_POWER ); - } - - private void registerItemP2P() - { - final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); - - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsWood ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsVoid ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsSandstone ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsQuartz ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsObsidian ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsIron ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsGold ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsEmerald ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsDiamond ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsStone ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsCobblestone ), TunnelType.ITEM ); - } - - private void registerLiquidsP2P() - { - final IP2PTunnelRegistry reg = AEApi.instance().registries().p2pTunnel(); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsCobblestone ), TunnelType.FLUID ); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsEmerald ), TunnelType.FLUID ); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsGold ), TunnelType.FLUID ); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsIron ), TunnelType.FLUID ); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsSandstone ), TunnelType.FLUID ); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsStone ), TunnelType.FLUID ); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsVoid ), TunnelType.FLUID ); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsWood ), TunnelType.FLUID ); - } - - @Override - public void init() throws Throwable - { - this.initPipeConnection(); - this.initFacades(); - } - - @Override - public void postInit() - { - this.registerPowerP2P(); - this.registerItemP2P(); - this.registerLiquidsP2P(); - } - - private void initPipeConnection() - { - final IAppEngApi api = AEApi.instance(); - - api.partHelper().registerNewLayer( "appeng.parts.layers.LayerIPipeConnection", "buildcraft.api.transport.IPipeConnection" ); - api.registries().externalStorage().addExternalStorageInterface( new BCPipeHandler() ); - } - - private void initFacades() - { - final IAppEngApi api = AEApi.instance(); - final IBlocks blocks = api.definitions().blocks(); - - this.addFacadeStack( blocks.fluix() ); - this.addFacadeStack( blocks.quartz() ); - this.addFacadeStack( blocks.quartzChiseled() ); - this.addFacadeStack( blocks.quartzPillar() ); - - for( final Block skyStoneBlock : blocks.skyStone().maybeBlock().asSet() ) - { - this.addFacade( new ItemStack( skyStoneBlock, 1, 0 ) ); - this.addFacade( new ItemStack( skyStoneBlock, 1, 1 ) ); - this.addFacade( new ItemStack( skyStoneBlock, 1, 2 ) ); - this.addFacade( new ItemStack( skyStoneBlock, 1, 3 ) ); - } - } - - private void addFacadeStack( final IItemDefinition definition ) - { - for( final ItemStack facadeStack : definition.maybeStack( 1 ).asSet() ) - { - this.addFacade( facadeStack ); - } - } +public class BuildCraftTransport implements IBuildCraftTransport, IIntegrationModule { + @Reflected + public static BuildCraftTransport instance; + + @Reflected + public BuildCraftTransport() { + IntegrationHelper.testClassExistence(this, buildcraft.BuildCraftTransport.class); + IntegrationHelper.testClassExistence(this, buildcraft.api.facades.IFacadeItem.class); + IntegrationHelper.testClassExistence(this, buildcraft.api.transport.IInjectable.class); + IntegrationHelper.testClassExistence(this, buildcraft.api.transport.IPipeConnection.class); + IntegrationHelper.testClassExistence(this, buildcraft.api.transport.IPipeTile.class); + IntegrationHelper.testClassExistence(this, buildcraft.api.transport.IPipeTile.PipeType.class); + IntegrationHelper.testClassExistence(this, buildcraft.transport.ItemFacade.class); + IntegrationHelper.testClassExistence(this, buildcraft.transport.PipeIconProvider.class); + } + + @Override + public boolean isFacade(final ItemStack is) { + if (is == null) { + return false; + } + + return is.getItem() instanceof IFacadeItem; + } + + @Nullable + @Override + public IFacadePart createFacadePart(final Block blk, final int meta, @Nonnull final ForgeDirection side) { + try { + final ItemFacade.FacadeState state = ItemFacade.FacadeState.create(blk, meta); + final ItemStack facade = ItemFacade.getFacade(state); + + return new FacadePart(facade, side); + } catch (final Exception ignored) { + + } + + return null; + } + + @Override + public IFacadePart createFacadePart(@Nonnull final ItemStack fs, @Nonnull final ForgeDirection side) { + return new FacadePart(fs, side); + } + + @Nullable + @Override + public ItemStack getTextureForFacade(@Nonnull final ItemStack facade) { + final Item maybeFacadeItem = facade.getItem(); + + if (maybeFacadeItem instanceof IFacadeItem) { + final IFacadeItem facadeItem = (IFacadeItem) maybeFacadeItem; + + final Block[] blocks = facadeItem.getBlocksForFacade(facade); + final int[] metas = facadeItem.getMetaValuesForFacade(facade); + + if (blocks.length > 0 && metas.length > 0) { + return new ItemStack(blocks[0], 1, metas[0]); + } + } + + return null; + } + + @Nullable + @Override + public IIcon getCobbleStructurePipeTexture() { + try { + return buildcraft.BuildCraftTransport.instance.pipeIconProvider.getIcon( + PipeIconProvider.TYPE.PipeStructureCobblestone.ordinal()); // Structure + } catch (final Exception ignored) { + } + return null; + // Pipe + } + + @Override + public boolean isPipe(final TileEntity te, @Nonnull final ForgeDirection dir) { + if (te instanceof IPipeTile) { + final IPipeTile pipeTile = (IPipeTile) te; + return !pipeTile.hasPipePluggable(dir.getOpposite()); + } + + return false; + } + + @Override + public boolean canAddItemsToPipe(final TileEntity te, final ItemStack is, final ForgeDirection dir) { + if (is != null && te != null && te instanceof IInjectable) { + final IInjectable pt = (IInjectable) te; + if (pt.canInjectItems(dir)) { + final int amt = pt.injectItem(is, false, dir, null); + if (amt == is.stackSize) { + return true; + } + } + } + + return false; + } + + @Override + public boolean addItemsToPipe( + @Nullable final TileEntity te, @Nullable final ItemStack is, @Nonnull final ForgeDirection dir) { + if (is != null && te != null && te instanceof IInjectable) { + final IInjectable pt = (IInjectable) te; + if (pt.canInjectItems(dir)) { + final int amt = pt.injectItem(is, false, dir, null); + if (amt == is.stackSize) { + pt.injectItem(is, true, dir, null); + return true; + } + } + } + + return false; + } + + private void addFacade(final ItemStack item) { + if (item != null) { + FMLInterModComms.sendMessage("BuildCraft|Transport", "add-facade", item); + } + } + + private void registerPowerP2P() { + final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); + + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipePowerCobblestone), TunnelType.RF_POWER); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipePowerDiamond), TunnelType.RF_POWER); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipePowerGold), TunnelType.RF_POWER); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipePowerQuartz), TunnelType.RF_POWER); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipePowerStone), TunnelType.RF_POWER); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipePowerWood), TunnelType.RF_POWER); + } + + private void registerItemP2P() { + final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); + + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeItemsWood), TunnelType.ITEM); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeItemsVoid), TunnelType.ITEM); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeItemsSandstone), TunnelType.ITEM); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeItemsQuartz), TunnelType.ITEM); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeItemsObsidian), TunnelType.ITEM); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeItemsIron), TunnelType.ITEM); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeItemsGold), TunnelType.ITEM); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeItemsEmerald), TunnelType.ITEM); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeItemsDiamond), TunnelType.ITEM); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeItemsStone), TunnelType.ITEM); + registry.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeItemsCobblestone), TunnelType.ITEM); + } + + private void registerLiquidsP2P() { + final IP2PTunnelRegistry reg = AEApi.instance().registries().p2pTunnel(); + reg.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsCobblestone), TunnelType.FLUID); + reg.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsEmerald), TunnelType.FLUID); + reg.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsGold), TunnelType.FLUID); + reg.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsIron), TunnelType.FLUID); + reg.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsSandstone), TunnelType.FLUID); + reg.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsStone), TunnelType.FLUID); + reg.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsVoid), TunnelType.FLUID); + reg.addNewAttunement(new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsWood), TunnelType.FLUID); + } + + @Override + public void init() throws Throwable { + this.initPipeConnection(); + this.initFacades(); + } + + @Override + public void postInit() { + this.registerPowerP2P(); + this.registerItemP2P(); + this.registerLiquidsP2P(); + } + + private void initPipeConnection() { + final IAppEngApi api = AEApi.instance(); + + api.partHelper() + .registerNewLayer( + "appeng.parts.layers.LayerIPipeConnection", "buildcraft.api.transport.IPipeConnection"); + api.registries().externalStorage().addExternalStorageInterface(new BCPipeHandler()); + } + + private void initFacades() { + final IAppEngApi api = AEApi.instance(); + final IBlocks blocks = api.definitions().blocks(); + + this.addFacadeStack(blocks.fluix()); + this.addFacadeStack(blocks.quartz()); + this.addFacadeStack(blocks.quartzChiseled()); + this.addFacadeStack(blocks.quartzPillar()); + + for (final Block skyStoneBlock : blocks.skyStone().maybeBlock().asSet()) { + this.addFacade(new ItemStack(skyStoneBlock, 1, 0)); + this.addFacade(new ItemStack(skyStoneBlock, 1, 1)); + this.addFacade(new ItemStack(skyStoneBlock, 1, 2)); + this.addFacade(new ItemStack(skyStoneBlock, 1, 3)); + } + } + + private void addFacadeStack(final IItemDefinition definition) { + for (final ItemStack facadeStack : definition.maybeStack(1).asSet()) { + this.addFacade(facadeStack); + } + } } diff --git a/src/main/java/appeng/integration/modules/CLApi.java b/src/main/java/appeng/integration/modules/CLApi.java index 12cf54d9c8f..9441fc8b563 100644 --- a/src/main/java/appeng/integration/modules/CLApi.java +++ b/src/main/java/appeng/integration/modules/CLApi.java @@ -1,4 +1,4 @@ -///* +/// * // * This file is part of Applied Energistics 2. // * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. // * @@ -16,18 +16,18 @@ // * along with Applied Energistics 2. If not, see . // */ // -//package appeng.integration.modules; +// package appeng.integration.modules; // // -//import appeng.api.util.AEColor; -//import appeng.helpers.Reflected; -//import appeng.integration.IIntegrationModule; -//import appeng.integration.IntegrationHelper; -//import appeng.integration.abstraction.ICLApi; +// import appeng.api.util.AEColor; +// import appeng.helpers.Reflected; +// import appeng.integration.IIntegrationModule; +// import appeng.integration.IntegrationHelper; +// import appeng.integration.abstraction.ICLApi; // // -//public class CLApi implements ICLApi, IIntegrationModule -//{ +// public class CLApi implements ICLApi, IIntegrationModule +// { // @Reflected // public static CLApi instance; // @@ -59,4 +59,4 @@ // // return coloredlightscore.src.api.CLApi.makeRGBLightValue( r / 255.0f, g / 255.0f, b / 255.0f, light / 15.0f ); // } -//} +// } diff --git a/src/main/java/appeng/integration/modules/Chisel.java b/src/main/java/appeng/integration/modules/Chisel.java index 47c8599bc99..09edac2fc50 100644 --- a/src/main/java/appeng/integration/modules/Chisel.java +++ b/src/main/java/appeng/integration/modules/Chisel.java @@ -12,23 +12,27 @@ public class Chisel implements IIntegrationModule { @Reflected public static Chisel instance; + @Reflected - public Chisel(){} + public Chisel() {} private static final String chiselModID = "chisel"; private static final String addVariation = "variation:add"; private static final String groupOre = "group:ore"; static void registerBlock(final Block block, final int meta, final String blockGroupName) { - FMLInterModComms.sendMessage(chiselModID, addVariation, String.join("|", - blockGroupName, - GameRegistry.findUniqueIdentifierFor(block).toString(), - Integer.toString(meta))); + FMLInterModComms.sendMessage( + chiselModID, + addVariation, + String.join( + "|", + blockGroupName, + GameRegistry.findUniqueIdentifierFor(block).toString(), + Integer.toString(meta))); } + static void registerOre(final String groupOreName, final String blockGroupName) { - FMLInterModComms.sendMessage(chiselModID, groupOre, String.join("|", - blockGroupName, - groupOreName)); + FMLInterModComms.sendMessage(chiselModID, groupOre, String.join("|", blockGroupName, groupOreName)); } @Override @@ -52,7 +56,5 @@ public void init() { } @Override - public void postInit() { - - } + public void postInit() {} } diff --git a/src/main/java/appeng/integration/modules/CraftGuide.java b/src/main/java/appeng/integration/modules/CraftGuide.java index 9cb0b1deb0c..58580e87d19 100644 --- a/src/main/java/appeng/integration/modules/CraftGuide.java +++ b/src/main/java/appeng/integration/modules/CraftGuide.java @@ -1,4 +1,4 @@ -///* +/// * // * This file is part of Applied Energistics 2. // * Copyright (c) 2013 - 2015, AlgorithmX2, All rights reserved. // * @@ -16,41 +16,41 @@ // * along with Applied Energistics 2. If not, see . // */ // -//package appeng.integration.modules; -// -// -//import appeng.api.AEApi; -//import appeng.api.IAppEngApi; -//import appeng.api.definitions.IBlocks; -//import appeng.api.exceptions.MissingIngredientError; -//import appeng.api.exceptions.RegistrationError; -//import appeng.api.features.IGrinderEntry; -//import appeng.api.features.IInscriberRecipe; -//import appeng.api.recipes.IIngredient; -//import appeng.helpers.Reflected; -//import appeng.integration.IIntegrationModule; -//import appeng.integration.IntegrationHelper; -//import appeng.recipes.game.ShapedRecipe; -//import appeng.recipes.game.ShapelessRecipe; -//import com.google.common.base.Optional; -//import cpw.mods.fml.relauncher.ReflectionHelper; -//import net.minecraft.item.ItemStack; -//import net.minecraft.item.crafting.CraftingManager; -//import net.minecraft.item.crafting.IRecipe; -//import uristqwerty.CraftGuide.CraftGuideLog; -//import uristqwerty.CraftGuide.DefaultRecipeTemplate; -//import uristqwerty.CraftGuide.RecipeGeneratorImplementation; -//import uristqwerty.CraftGuide.api.*; -//import uristqwerty.gui_craftguide.texture.DynamicTexture; -//import uristqwerty.gui_craftguide.texture.TextureClip; -// -//import javax.annotation.Nullable; -//import java.util.Arrays; -//import java.util.List; -// -// -//public final class CraftGuide extends CraftGuideAPIObject implements IIntegrationModule, RecipeProvider -//{ +// package appeng.integration.modules; +// +// +// import appeng.api.AEApi; +// import appeng.api.IAppEngApi; +// import appeng.api.definitions.IBlocks; +// import appeng.api.exceptions.MissingIngredientError; +// import appeng.api.exceptions.RegistrationError; +// import appeng.api.features.IGrinderEntry; +// import appeng.api.features.IInscriberRecipe; +// import appeng.api.recipes.IIngredient; +// import appeng.helpers.Reflected; +// import appeng.integration.IIntegrationModule; +// import appeng.integration.IntegrationHelper; +// import appeng.recipes.game.ShapedRecipe; +// import appeng.recipes.game.ShapelessRecipe; +// import com.google.common.base.Optional; +// import cpw.mods.fml.relauncher.ReflectionHelper; +// import net.minecraft.item.ItemStack; +// import net.minecraft.item.crafting.CraftingManager; +// import net.minecraft.item.crafting.IRecipe; +// import uristqwerty.CraftGuide.CraftGuideLog; +// import uristqwerty.CraftGuide.DefaultRecipeTemplate; +// import uristqwerty.CraftGuide.RecipeGeneratorImplementation; +// import uristqwerty.CraftGuide.api.*; +// import uristqwerty.gui_craftguide.texture.DynamicTexture; +// import uristqwerty.gui_craftguide.texture.TextureClip; +// +// import javax.annotation.Nullable; +// import java.util.Arrays; +// import java.util.List; +// +// +// public final class CraftGuide extends CraftGuideAPIObject implements IIntegrationModule, RecipeProvider +// { // private static final int SLOT_SIZE = 16; // private static final int TEXTURE_WIDTH = 79; // private static final int TEXTURE_HEIGHT = 58; @@ -59,8 +59,10 @@ // private static final Slot[] GRINDER_SLOTS = { // new ItemSlot( 3, 21, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), // new ItemSlot( 41, 21, SLOT_SIZE, SLOT_SIZE, true ).drawOwnBackground().setSlotType( SlotType.OUTPUT_SLOT ), -// new ChanceSlot( 59, 12, SLOT_SIZE, SLOT_SIZE, true ).setRatio( GRINDER_RATIO ).setFormatString( " (%1$.2f%% chance)" ).drawOwnBackground().setSlotType( SlotType.OUTPUT_SLOT ), -// new ChanceSlot( 59, 30, SLOT_SIZE, SLOT_SIZE, true ).setRatio( GRINDER_RATIO ).setFormatString( " (%1$.2f%% chance)" ).drawOwnBackground().setSlotType( SlotType.OUTPUT_SLOT ), +// new ChanceSlot( 59, 12, SLOT_SIZE, SLOT_SIZE, true ).setRatio( GRINDER_RATIO ).setFormatString( " (%1$.2f%% +// chance)" ).drawOwnBackground().setSlotType( SlotType.OUTPUT_SLOT ), +// new ChanceSlot( 59, 30, SLOT_SIZE, SLOT_SIZE, true ).setRatio( GRINDER_RATIO ).setFormatString( " (%1$.2f%% +// chance)" ).drawOwnBackground().setSlotType( SlotType.OUTPUT_SLOT ), // new ItemSlot( 22, 12, SLOT_SIZE, SLOT_SIZE ).setSlotType( SlotType.MACHINE_SLOT ), // new ItemSlot( 22, 30, SLOT_SIZE, SLOT_SIZE ).setSlotType( SlotType.MACHINE_SLOT ) // }; @@ -165,18 +167,27 @@ // } // else // { -// final TextureClip craftingBG = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 1, 1, TEXTURE_WIDTH, TEXTURE_HEIGHT ); -// final TextureClip craftingSelected = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 1, TEXTURE_WIDTH, TEXTURE_HEIGHT ); -// craftingTemplate = new DefaultRecipeTemplate( CRTAFTING_SLOTS, RecipeGeneratorImplementation.workbench, craftingBG, craftingSelected ); -// -// final TextureClip smallBG = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 1, 61, TEXTURE_WIDTH, TEXTURE_HEIGHT ); -// final TextureClip smallSelected = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 61, TEXTURE_WIDTH, TEXTURE_HEIGHT ); -// smallTemplate = new DefaultRecipeTemplate( SMALL_CRAFTING_SLOTS, RecipeGeneratorImplementation.workbench, smallBG, smallSelected ); +// final TextureClip craftingBG = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 1, 1, +// TEXTURE_WIDTH, TEXTURE_HEIGHT ); +// final TextureClip craftingSelected = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 1, +// TEXTURE_WIDTH, TEXTURE_HEIGHT ); +// craftingTemplate = new DefaultRecipeTemplate( CRTAFTING_SLOTS, RecipeGeneratorImplementation.workbench, craftingBG, +// craftingSelected ); +// +// final TextureClip smallBG = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 1, 61, TEXTURE_WIDTH, +// TEXTURE_HEIGHT ); +// final TextureClip smallSelected = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 61, +// TEXTURE_WIDTH, TEXTURE_HEIGHT ); +// smallTemplate = new DefaultRecipeTemplate( SMALL_CRAFTING_SLOTS, RecipeGeneratorImplementation.workbench, smallBG, +// smallSelected ); // } // -// final TextureClip shapelessBG = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 1, 121, TEXTURE_WIDTH, TEXTURE_HEIGHT ); -// final TextureClip shapelessSelected = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 121, TEXTURE_WIDTH, TEXTURE_HEIGHT ); -// final RecipeTemplate shapelessTemplate = new DefaultRecipeTemplate( SHAPELESS_CRAFTING_SLOTS, RecipeGeneratorImplementation.workbench, shapelessBG, shapelessSelected ); +// final TextureClip shapelessBG = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 1, 121, +// TEXTURE_WIDTH, TEXTURE_HEIGHT ); +// final TextureClip shapelessSelected = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 121, +// TEXTURE_WIDTH, TEXTURE_HEIGHT ); +// final RecipeTemplate shapelessTemplate = new DefaultRecipeTemplate( SHAPELESS_CRAFTING_SLOTS, +// RecipeGeneratorImplementation.workbench, shapelessBG, shapelessSelected ); // // this.addCraftingRecipes( craftingTemplate, smallTemplate, shapelessTemplate, generator ); // @@ -202,7 +213,8 @@ // return (List) CraftingManager.getInstance().getRecipeList(); // } // -// private void addCraftingRecipes( final RecipeTemplate template, final RecipeTemplate templateSmall, final RecipeTemplate templateShapeless, final RecipeGenerator generator ) +// private void addCraftingRecipes( final RecipeTemplate template, final RecipeTemplate templateSmall, final +// RecipeTemplate templateShapeless, final RecipeGenerator generator ) // { // final List recipes = this.getUncheckedRecipes(); // @@ -235,7 +247,9 @@ // { // if( errCount >= 5 ) // { -// CraftGuideLog.log( "AppEng CraftGuide integration: Stack trace limit reached, further stack traces from this invocation will not be logged to the console. They will still be logged to (.minecraft)/config/CraftGuide/CraftGuide.log", true ); +// CraftGuideLog.log( "AppEng CraftGuide integration: Stack trace limit reached, further stack traces from this +// invocation will not be logged to the console. They will still be logged to +// (.minecraft)/config/CraftGuide/CraftGuide.log", true ); // } // else // { @@ -323,7 +337,8 @@ // return output; // } // -// private Object[] getSmallShapedRecipe( final int width, final int height, final Object[] items, final ItemStack recipeOutput ) +// private Object[] getSmallShapedRecipe( final int width, final int height, final Object[] items, final ItemStack +// recipeOutput ) // { // final Object[] output = new Object[5]; // @@ -362,7 +377,8 @@ // return output; // } // -// private Object[] getCraftingShapedRecipe( final int width, final int height, final Object[] items, final ItemStack recipeOutput ) +// private Object[] getCraftingShapedRecipe( final int width, final int height, final Object[] items, final ItemStack +// recipeOutput ) // { // final Object[] output = new Object[10]; // @@ -422,7 +438,8 @@ // { // if( recipe instanceof ShapelessRecipe ) // { -// final List items = ReflectionHelper.getPrivateValue( ShapelessRecipe.class, (ShapelessRecipe) recipe, "input" ); +// final List items = ReflectionHelper.getPrivateValue( ShapelessRecipe.class, (ShapelessRecipe) recipe, +// "input" ); // // return this.getCraftingShapelessRecipe( items, recipe.getRecipeOutput() ); // } @@ -444,4 +461,4 @@ // // return null; // } -//} +// } diff --git a/src/main/java/appeng/integration/modules/DSU.java b/src/main/java/appeng/integration/modules/DSU.java index bc8ed1efe63..5296673f212 100644 --- a/src/main/java/appeng/integration/modules/DSU.java +++ b/src/main/java/appeng/integration/modules/DSU.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.storage.IMEInventory; import appeng.helpers.Reflected; @@ -30,38 +29,30 @@ import net.minecraft.tileentity.TileEntity; import powercrystals.minefactoryreloaded.api.IDeepStorageUnit; +public class DSU implements IDSU, IIntegrationModule { + @Reflected + public static DSU instance; -public class DSU implements IDSU, IIntegrationModule -{ - @Reflected - public static DSU instance; - - @Reflected - public DSU() - { - IntegrationHelper.testClassExistence( this, powercrystals.minefactoryreloaded.api.IDeepStorageUnit.class ); - } + @Reflected + public DSU() { + IntegrationHelper.testClassExistence(this, powercrystals.minefactoryreloaded.api.IDeepStorageUnit.class); + } - @Override - public IMEInventory getDSU( final TileEntity te ) - { - return new MinefactoryReloadedDeepStorageUnit( te ); - } + @Override + public IMEInventory getDSU(final TileEntity te) { + return new MinefactoryReloadedDeepStorageUnit(te); + } - @Override - public boolean isDSU( final TileEntity te ) - { - return te instanceof IDeepStorageUnit; - } + @Override + public boolean isDSU(final TileEntity te) { + return te instanceof IDeepStorageUnit; + } - @Override - public void init() - { - } + @Override + public void init() {} - @Override - public void postInit() - { - AEApi.instance().registries().externalStorage().addExternalStorageInterface( new MFRDSUHandler() ); - } + @Override + public void postInit() { + AEApi.instance().registries().externalStorage().addExternalStorageInterface(new MFRDSUHandler()); + } } diff --git a/src/main/java/appeng/integration/modules/FMP.java b/src/main/java/appeng/integration/modules/FMP.java index 9af4b9a78cb..1777989b66a 100644 --- a/src/main/java/appeng/integration/modules/FMP.java +++ b/src/main/java/appeng/integration/modules/FMP.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IBlocks; @@ -43,178 +42,147 @@ import codechicken.multipart.TileMultipart; import com.google.common.collect.Lists; import cpw.mods.fml.common.eventhandler.Event; +import java.util.Collection; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; -import java.util.Collection; -import java.util.List; - - -public class FMP implements IIntegrationModule, IPartFactory, IPartConverter, IFMP -{ - @Reflected - public static FMP instance; - - @Override - public TMultiPart createPart( final String name, final boolean client ) - { - for( final PartRegistry pr : PartRegistry.values() ) - { - if( pr.getName().equals( name ) ) - { - return pr.construct( 0 ); - } - } - - return null; - } - - @Override - public TMultiPart convert( final World world, final BlockCoord pos ) - { - final Block blk = world.getBlock( pos.x, pos.y, pos.z ); - final int meta = world.getBlockMetadata( pos.x, pos.y, pos.z ); - - final TMultiPart part = PartRegistry.getPartByBlock( blk, meta ); - if( part instanceof CableBusPart ) - { - final CableBusPart cbp = (CableBusPart) part; - cbp.convertFromTile( world.getTileEntity( pos.x, pos.y, pos.z ) ); - } - - return part; - } - - @Override - public Iterable blockTypes() - { - final IBlocks blocks = AEApi.instance().definitions().blocks(); - final List blockTypes = Lists.newArrayListWithCapacity( 2 ); - - this.addBlockTypes( blockTypes, blocks.multiPart() ); - this.addBlockTypes( blockTypes, blocks.quartzTorch() ); - - return blockTypes; - } - - private void addBlockTypes( final Collection blockTypes, final IBlockDefinition definition ) - { - for( final Block block : definition.maybeBlock().asSet() ) - { - blockTypes.add( block ); - } - } - - @Override - public void init() throws Throwable - { - final IBlocks blocks = AEApi.instance().definitions().blocks(); - - this.createAndRegister( blocks.quartz(), 0 ); - this.createAndRegister( blocks.quartzPillar(), 0 ); - this.createAndRegister( blocks.quartzChiseled(), 0 ); - this.createAndRegister( blocks.skyStone(), 0 ); - this.createAndRegister( blocks.skyStone(), 1 ); - this.createAndRegister( blocks.skyStone(), 2 ); - this.createAndRegister( blocks.skyStone(), 3 ); - - final PartRegistry[] reg = PartRegistry.values(); - - final String[] data = new String[reg.length]; - for( int x = 0; x < data.length; x++ ) - { - data[x] = reg[x].getName(); - } - - MultiPartRegistry.registerConverter( this ); - MultiPartRegistry.registerParts( this, data ); - - MultipartGenerator.registerPassThroughInterface( "appeng.helpers.AEMultiTile" ); - } - - private void createAndRegister( final IBlockDefinition definition, final int i ) - { - for( final Block block : definition.maybeBlock().asSet() ) - { - BlockMicroMaterial.createAndRegister( block, i ); - } - } - - @Override - public void postInit() - { - MinecraftForge.EVENT_BUS.register( new FMPEvent() ); - } - - @Override - public IPartHost getOrCreateHost( final TileEntity tile ) - { - try - { - final BlockCoord loc = new BlockCoord( tile.xCoord, tile.yCoord, tile.zCoord ); - - final TileMultipart mp = TileMultipart.getOrConvertTile( tile.getWorldObj(), loc ); - if( mp != null ) - { - final scala.collection.Iterator i = mp.partList().iterator(); - while( i.hasNext() ) - { - final TMultiPart p = i.next(); - if( p instanceof CableBusPart ) - { - return (IPartHost) p; - } - } - - return new FMPPlacementHelper( mp ); - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - return null; - } - - @Override - public CableBusContainer getCableContainer( final TileEntity te ) - { - if( te instanceof TileMultipart ) - { - final TileMultipart mp = (TileMultipart) te; - final scala.collection.Iterator i = mp.partList().iterator(); - while( i.hasNext() ) - { - final TMultiPart p = i.next(); - if( p instanceof CableBusPart ) - { - return ( (CableBusPart) p ).getCableBus(); - } - } - } - return null; - } - - @Override - public void registerPassThrough( final Class layerInterface ) - { - try - { - MultipartGenerator.registerPassThroughInterface( layerInterface.getName() ); - } - catch( final Throwable t ) - { - AELog.error( "Failed to register " + layerInterface.getName() + " with FMP, some features may not work with MultiParts." ); - AELog.debug( t ); - } - } - - @Override - public Event newFMPPacketEvent( final EntityPlayerMP sender ) - { - return new FMPPacketEvent( sender ); - } +public class FMP implements IIntegrationModule, IPartFactory, IPartConverter, IFMP { + @Reflected + public static FMP instance; + + @Override + public TMultiPart createPart(final String name, final boolean client) { + for (final PartRegistry pr : PartRegistry.values()) { + if (pr.getName().equals(name)) { + return pr.construct(0); + } + } + + return null; + } + + @Override + public TMultiPart convert(final World world, final BlockCoord pos) { + final Block blk = world.getBlock(pos.x, pos.y, pos.z); + final int meta = world.getBlockMetadata(pos.x, pos.y, pos.z); + + final TMultiPart part = PartRegistry.getPartByBlock(blk, meta); + if (part instanceof CableBusPart) { + final CableBusPart cbp = (CableBusPart) part; + cbp.convertFromTile(world.getTileEntity(pos.x, pos.y, pos.z)); + } + + return part; + } + + @Override + public Iterable blockTypes() { + final IBlocks blocks = AEApi.instance().definitions().blocks(); + final List blockTypes = Lists.newArrayListWithCapacity(2); + + this.addBlockTypes(blockTypes, blocks.multiPart()); + this.addBlockTypes(blockTypes, blocks.quartzTorch()); + + return blockTypes; + } + + private void addBlockTypes(final Collection blockTypes, final IBlockDefinition definition) { + for (final Block block : definition.maybeBlock().asSet()) { + blockTypes.add(block); + } + } + + @Override + public void init() throws Throwable { + final IBlocks blocks = AEApi.instance().definitions().blocks(); + + this.createAndRegister(blocks.quartz(), 0); + this.createAndRegister(blocks.quartzPillar(), 0); + this.createAndRegister(blocks.quartzChiseled(), 0); + this.createAndRegister(blocks.skyStone(), 0); + this.createAndRegister(blocks.skyStone(), 1); + this.createAndRegister(blocks.skyStone(), 2); + this.createAndRegister(blocks.skyStone(), 3); + + final PartRegistry[] reg = PartRegistry.values(); + + final String[] data = new String[reg.length]; + for (int x = 0; x < data.length; x++) { + data[x] = reg[x].getName(); + } + + MultiPartRegistry.registerConverter(this); + MultiPartRegistry.registerParts(this, data); + + MultipartGenerator.registerPassThroughInterface("appeng.helpers.AEMultiTile"); + } + + private void createAndRegister(final IBlockDefinition definition, final int i) { + for (final Block block : definition.maybeBlock().asSet()) { + BlockMicroMaterial.createAndRegister(block, i); + } + } + + @Override + public void postInit() { + MinecraftForge.EVENT_BUS.register(new FMPEvent()); + } + + @Override + public IPartHost getOrCreateHost(final TileEntity tile) { + try { + final BlockCoord loc = new BlockCoord(tile.xCoord, tile.yCoord, tile.zCoord); + + final TileMultipart mp = TileMultipart.getOrConvertTile(tile.getWorldObj(), loc); + if (mp != null) { + final scala.collection.Iterator i = mp.partList().iterator(); + while (i.hasNext()) { + final TMultiPart p = i.next(); + if (p instanceof CableBusPart) { + return (IPartHost) p; + } + } + + return new FMPPlacementHelper(mp); + } + } catch (final Throwable t) { + AELog.debug(t); + } + return null; + } + + @Override + public CableBusContainer getCableContainer(final TileEntity te) { + if (te instanceof TileMultipart) { + final TileMultipart mp = (TileMultipart) te; + final scala.collection.Iterator i = mp.partList().iterator(); + while (i.hasNext()) { + final TMultiPart p = i.next(); + if (p instanceof CableBusPart) { + return ((CableBusPart) p).getCableBus(); + } + } + } + return null; + } + + @Override + public void registerPassThrough(final Class layerInterface) { + try { + MultipartGenerator.registerPassThroughInterface(layerInterface.getName()); + } catch (final Throwable t) { + AELog.error("Failed to register " + layerInterface.getName() + + " with FMP, some features may not work with MultiParts."); + AELog.debug(t); + } + } + + @Override + public Event newFMPPacketEvent(final EntityPlayerMP sender) { + return new FMPPacketEvent(sender); + } } diff --git a/src/main/java/appeng/integration/modules/FZ.java b/src/main/java/appeng/integration/modules/FZ.java index 240e15ac8a6..3744c01a0e9 100644 --- a/src/main/java/appeng/integration/modules/FZ.java +++ b/src/main/java/appeng/integration/modules/FZ.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.storage.IMEInventory; import appeng.helpers.Reflected; @@ -27,187 +26,134 @@ import appeng.integration.modules.helpers.FactorizationBarrel; import appeng.integration.modules.helpers.FactorizationHandler; import appeng.util.Platform; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; - +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; /** * 100% Hacks. */ -public class FZ implements IFZ, IIntegrationModule -{ - @Reflected - public static FZ instance; - - private static Class day_BarrelClass; - private static Method day_getItemCount; - private static Method day_setItemCount; - private static Method day_getMaxSize; - private static Field day_item; - - @Override - public ItemStack barrelGetItem( final TileEntity te ) - { - try - { - ItemStack i = null; - - if( day_BarrelClass.isInstance( te ) ) - { - i = (ItemStack) day_item.get( te ); - } - - if( i != null ) - { - i = Platform.cloneItemStack( i ); - } - - return i; - } - catch( final IllegalArgumentException ignored ) - { - } - catch( final IllegalAccessException ignored ) - { - } - return null; - } - - @Override - public int barrelGetMaxItemCount( final TileEntity te ) - { - try - { - if( day_BarrelClass.isInstance( te ) ) - { - return (Integer) day_getMaxSize.invoke( te ); - } - } - catch( final IllegalAccessException ignored ) - { - } - catch( final IllegalArgumentException ignored ) - { - } - catch( final InvocationTargetException ignored ) - { - } - return 0; - } - - @Override - public int barrelGetItemCount( final TileEntity te ) - { - try - { - if( day_BarrelClass.isInstance( te ) ) - { - return (Integer) day_getItemCount.invoke( te ); - } - } - catch( final IllegalAccessException ignored ) - { - } - catch( final IllegalArgumentException ignored ) - { - } - catch( final InvocationTargetException ignored ) - { - } - return 0; - } - - @Override - public void setItemType( final TileEntity te, final ItemStack input ) - { - try - { - if( day_BarrelClass.isInstance( te ) ) - { - day_item.set( te, input == null ? null : input.copy() ); - } - } - catch( final IllegalArgumentException ignored ) - { - } - catch( final IllegalAccessException ignored ) - { - } - } - - @Override - public void barrelSetCount( final TileEntity te, final int max ) - { - try - { - if( day_BarrelClass.isInstance( te ) ) - { - day_setItemCount.invoke( te, max ); - } - - te.markDirty(); - } - catch( final IllegalAccessException ignored ) - { - } - catch( final IllegalArgumentException ignored ) - { - } - catch( final InvocationTargetException ignored ) - { - } - } - - @Override - public IMEInventory getFactorizationBarrel( final TileEntity te ) - { - return new FactorizationBarrel( this, te ); - } - - @Override - public boolean isBarrel( final TileEntity te ) - { - return day_BarrelClass.isAssignableFrom( te.getClass() ); - } - - @Override - public void grinderRecipe( final ItemStack in, final ItemStack out ) - { - try - { - final Class c = Class.forName( "factorization.oreprocessing.TileEntityGrinder" ); - final Method m = c.getMethod( "addRecipe", Object.class, ItemStack.class, float.class ); - - final float amt = out.stackSize; - out.stackSize = 1; - - m.invoke( c, in, out, amt ); - } - catch( final Throwable t ) - { - // AELog.info( "" ); - // throw new RuntimeException( t ); - } - } - - @Override - public void init() throws Throwable - { - day_BarrelClass = Class.forName( "factorization.weird.TileEntityDayBarrel" ); - - day_getItemCount = day_BarrelClass.getDeclaredMethod( "getItemCount" ); - day_setItemCount = day_BarrelClass.getDeclaredMethod( "setItemCount", int.class ); - day_getMaxSize = day_BarrelClass.getDeclaredMethod( "getMaxSize" ); - day_item = day_BarrelClass.getDeclaredField( "item" ); - } - - @Override - public void postInit() - { - AEApi.instance().registries().externalStorage().addExternalStorageInterface( new FactorizationHandler() ); - } +public class FZ implements IFZ, IIntegrationModule { + @Reflected + public static FZ instance; + + private static Class day_BarrelClass; + private static Method day_getItemCount; + private static Method day_setItemCount; + private static Method day_getMaxSize; + private static Field day_item; + + @Override + public ItemStack barrelGetItem(final TileEntity te) { + try { + ItemStack i = null; + + if (day_BarrelClass.isInstance(te)) { + i = (ItemStack) day_item.get(te); + } + + if (i != null) { + i = Platform.cloneItemStack(i); + } + + return i; + } catch (final IllegalArgumentException ignored) { + } catch (final IllegalAccessException ignored) { + } + return null; + } + + @Override + public int barrelGetMaxItemCount(final TileEntity te) { + try { + if (day_BarrelClass.isInstance(te)) { + return (Integer) day_getMaxSize.invoke(te); + } + } catch (final IllegalAccessException ignored) { + } catch (final IllegalArgumentException ignored) { + } catch (final InvocationTargetException ignored) { + } + return 0; + } + + @Override + public int barrelGetItemCount(final TileEntity te) { + try { + if (day_BarrelClass.isInstance(te)) { + return (Integer) day_getItemCount.invoke(te); + } + } catch (final IllegalAccessException ignored) { + } catch (final IllegalArgumentException ignored) { + } catch (final InvocationTargetException ignored) { + } + return 0; + } + + @Override + public void setItemType(final TileEntity te, final ItemStack input) { + try { + if (day_BarrelClass.isInstance(te)) { + day_item.set(te, input == null ? null : input.copy()); + } + } catch (final IllegalArgumentException ignored) { + } catch (final IllegalAccessException ignored) { + } + } + + @Override + public void barrelSetCount(final TileEntity te, final int max) { + try { + if (day_BarrelClass.isInstance(te)) { + day_setItemCount.invoke(te, max); + } + + te.markDirty(); + } catch (final IllegalAccessException ignored) { + } catch (final IllegalArgumentException ignored) { + } catch (final InvocationTargetException ignored) { + } + } + + @Override + public IMEInventory getFactorizationBarrel(final TileEntity te) { + return new FactorizationBarrel(this, te); + } + + @Override + public boolean isBarrel(final TileEntity te) { + return day_BarrelClass.isAssignableFrom(te.getClass()); + } + + @Override + public void grinderRecipe(final ItemStack in, final ItemStack out) { + try { + final Class c = Class.forName("factorization.oreprocessing.TileEntityGrinder"); + final Method m = c.getMethod("addRecipe", Object.class, ItemStack.class, float.class); + + final float amt = out.stackSize; + out.stackSize = 1; + + m.invoke(c, in, out, amt); + } catch (final Throwable t) { + // AELog.info( "" ); + // throw new RuntimeException( t ); + } + } + + @Override + public void init() throws Throwable { + day_BarrelClass = Class.forName("factorization.weird.TileEntityDayBarrel"); + + day_getItemCount = day_BarrelClass.getDeclaredMethod("getItemCount"); + day_setItemCount = day_BarrelClass.getDeclaredMethod("setItemCount", int.class); + day_getMaxSize = day_BarrelClass.getDeclaredMethod("getMaxSize"); + day_item = day_BarrelClass.getDeclaredField("item"); + } + + @Override + public void postInit() { + AEApi.instance().registries().externalStorage().addExternalStorageInterface(new FactorizationHandler()); + } } diff --git a/src/main/java/appeng/integration/modules/GT.java b/src/main/java/appeng/integration/modules/GT.java index 93dea1e7990..8111f418e58 100644 --- a/src/main/java/appeng/integration/modules/GT.java +++ b/src/main/java/appeng/integration/modules/GT.java @@ -16,24 +16,22 @@ public class GT implements IIntegrationModule { @Reflected public GT() throws Throwable { - IntegrationHelper.testClassExistence( this, gregtech.api.interfaces.tileentity.IEnergyConnected.class ); + IntegrationHelper.testClassExistence(this, gregtech.api.interfaces.tileentity.IEnergyConnected.class); String ver = Loader.instance().getIndexedModList().get("gregtech").getVersion(); - if (!ver.equals("MC1710")) - throw new ModNotInstalled( "gregtech" ); + if (!ver.equals("MC1710")) throw new ModNotInstalled("gregtech"); } @Override public void init() throws Throwable { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.GT ) ) - { - AEApi.instance().partHelper().registerNewLayer( - "appeng.parts.layers.LayerIEnergyConnected", - "gregtech.api.interfaces.tileentity.IEnergyConnected"); - + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.GT)) { + AEApi.instance() + .partHelper() + .registerNewLayer( + "appeng.parts.layers.LayerIEnergyConnected", + "gregtech.api.interfaces.tileentity.IEnergyConnected"); } } @Override - public void postInit() { - } + public void postInit() {} } diff --git a/src/main/java/appeng/integration/modules/IC2.java b/src/main/java/appeng/integration/modules/IC2.java index 91ee75d1f5f..976b2b7fd1b 100644 --- a/src/main/java/appeng/integration/modules/IC2.java +++ b/src/main/java/appeng/integration/modules/IC2.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.IAppEngApi; import appeng.api.config.TunnelType; @@ -36,80 +35,68 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.MinecraftForge; +public class IC2 implements IIC2, IIntegrationModule { + @Reflected + public static IC2 instance; -public class IC2 implements IIC2, IIntegrationModule -{ - @Reflected - public static IC2 instance; - - @Reflected - public IC2() - { - IntegrationHelper.testClassExistence( this, ic2.api.energy.tile.IEnergyTile.class ); - IntegrationHelper.testClassExistence( this, ic2.api.recipe.RecipeInputItemStack.class ); - } + @Reflected + public IC2() { + IntegrationHelper.testClassExistence(this, ic2.api.energy.tile.IEnergyTile.class); + IntegrationHelper.testClassExistence(this, ic2.api.recipe.RecipeInputItemStack.class); + } - @Override - public void init() - { - final IAppEngApi api = AEApi.instance(); - final IPartHelper partHelper = api.partHelper(); + @Override + public void init() { + final IAppEngApi api = AEApi.instance(); + final IPartHelper partHelper = api.partHelper(); - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.IC2 ) ) - { - partHelper.registerNewLayer( "appeng.parts.layers.LayerIEnergySink", "ic2.api.energy.tile.IEnergySink" ); - partHelper.registerNewLayer( "appeng.parts.layers.LayerIEnergySource", "ic2.api.energy.tile.IEnergySource" ); - } - } + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.IC2)) { + partHelper.registerNewLayer("appeng.parts.layers.LayerIEnergySink", "ic2.api.energy.tile.IEnergySink"); + partHelper.registerNewLayer("appeng.parts.layers.LayerIEnergySource", "ic2.api.energy.tile.IEnergySource"); + } + } - @Override - public void postInit() - { - final IP2PTunnelRegistry reg = AEApi.instance().registries().p2pTunnel(); - reg.addNewAttunement( this.getItem( "copperCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "insulatedCopperCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "goldCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "insulatedGoldCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "ironCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "insulatedIronCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "insulatedTinCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "glassFiberCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "tinCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "detectorCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "splitterCableItem" ), TunnelType.IC2_POWER ); + @Override + public void postInit() { + final IP2PTunnelRegistry reg = AEApi.instance().registries().p2pTunnel(); + reg.addNewAttunement(this.getItem("copperCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement(this.getItem("insulatedCopperCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement(this.getItem("goldCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement(this.getItem("insulatedGoldCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement(this.getItem("ironCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement(this.getItem("insulatedIronCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement(this.getItem("insulatedTinCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement(this.getItem("glassFiberCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement(this.getItem("tinCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement(this.getItem("detectorCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement(this.getItem("splitterCableItem"), TunnelType.IC2_POWER); - try - { - AEApi.instance().registries().movable().whiteListTileEntity((Class) Class.forName("ic2.core.crop.TileEntityCrop")); - } - catch (ClassNotFoundException ignored) - { - } - // this is gone? - // AEApi.INSTANCE().registries().matterCannon().registerAmmo( getItem( "uraniumDrop" ), 238.0289 ); - } + try { + AEApi.instance().registries().movable().whiteListTileEntity((Class) + Class.forName("ic2.core.crop.TileEntityCrop")); + } catch (ClassNotFoundException ignored) { + } + // this is gone? + // AEApi.INSTANCE().registries().matterCannon().registerAmmo( getItem( "uraniumDrop" ), 238.0289 ); + } - @Override - public void addToEnergyNet( final TileEntity appEngTile ) - { - MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileLoadEvent( (IEnergyTile) appEngTile ) ); - } + @Override + public void addToEnergyNet(final TileEntity appEngTile) { + MinecraftForge.EVENT_BUS.post(new ic2.api.energy.event.EnergyTileLoadEvent((IEnergyTile) appEngTile)); + } - @Override - public void removeFromEnergyNet( final TileEntity appEngTile ) - { - MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileUnloadEvent( (IEnergyTile) appEngTile ) ); - } + @Override + public void removeFromEnergyNet(final TileEntity appEngTile) { + MinecraftForge.EVENT_BUS.post(new ic2.api.energy.event.EnergyTileUnloadEvent((IEnergyTile) appEngTile)); + } - @Override - public ItemStack getItem( final String name ) - { - return ic2.api.item.IC2Items.getItem( name ); - } + @Override + public ItemStack getItem(final String name) { + return ic2.api.item.IC2Items.getItem(name); + } - @Override - public void maceratorRecipe( final ItemStack in, final ItemStack out ) - { - ic2.api.recipe.Recipes.macerator.addRecipe( new RecipeInputItemStack( in, in.stackSize ), null, out ); - } + @Override + public void maceratorRecipe(final ItemStack in, final ItemStack out) { + ic2.api.recipe.Recipes.macerator.addRecipe(new RecipeInputItemStack(in, in.stackSize), null, out); + } } diff --git a/src/main/java/appeng/integration/modules/ImmibisMicroblocks.java b/src/main/java/appeng/integration/modules/ImmibisMicroblocks.java index 7a7f532bb5e..cf69f6664e0 100644 --- a/src/main/java/appeng/integration/modules/ImmibisMicroblocks.java +++ b/src/main/java/appeng/integration/modules/ImmibisMicroblocks.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; import appeng.api.parts.IPartHost; @@ -29,6 +28,7 @@ import appeng.integration.IntegrationHelper; import appeng.integration.abstraction.IImmibisMicroblocks; import com.google.common.base.Optional; +import java.lang.reflect.Method; import mods.immibis.core.api.multipart.ICoverSystem; import mods.immibis.core.api.multipart.IMultipartTile; import net.minecraft.block.Block; @@ -37,106 +37,98 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.lang.reflect.Method; - - -public class ImmibisMicroblocks implements IImmibisMicroblocks, IIntegrationModule -{ - @Reflected - public static ImmibisMicroblocks instance; - - private boolean canConvertTiles = false; - - private Class MicroblockAPIUtils; - private Method mergeIntoMicroblockContainer; - - @Reflected - public ImmibisMicroblocks() - { - IntegrationHelper.testClassExistence( this, mods.immibis.core.api.multipart.IMultipartTile.class ); - IntegrationHelper.testClassExistence( this, mods.immibis.core.api.multipart.ICoverSystem.class ); - IntegrationHelper.testClassExistence( this, mods.immibis.core.api.multipart.IPartContainer.class ); - } - - @Override - public void init() throws Throwable - { - try - { - this.MicroblockAPIUtils = Class.forName( "mods.immibis.microblocks.api.MicroblockAPIUtils" ); - this.mergeIntoMicroblockContainer = this.MicroblockAPIUtils.getMethod( "mergeIntoMicroblockContainer", ItemStack.class, EntityPlayer.class, World.class, int.class, int.class, int.class, int.class, Block.class, int.class ); - this.canConvertTiles = true; - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - } - - @Override - public void postInit() - { - - } - - @Override - public IPartHost getOrCreateHost( final EntityPlayer player, final int side, final TileEntity te ) - { - final World w = te.getWorldObj(); - final int x = te.xCoord; - final int y = te.yCoord; - final int z = te.zCoord; - final boolean isPartItem = player != null && player.getHeldItem() != null && player.getHeldItem().getItem() instanceof IPartItem; - - if( te instanceof IMultipartTile && this.canConvertTiles && isPartItem ) - { - final IBlockDefinition multiPart = AEApi.instance().definitions().blocks().multiPart(); - final Optional maybeMultiPartBlock = multiPart.maybeBlock(); - final Optional maybeMultiPartStack = multiPart.maybeStack( 1 ); - - final boolean multiPartPresent = maybeMultiPartBlock.isPresent() && maybeMultiPartStack.isPresent(); - - if( multiPartPresent ) - { - final Block multiPartBlock = maybeMultiPartBlock.get(); - final ItemStack multiPartStack = maybeMultiPartStack.get(); - - try - { - // ItemStack.class, EntityPlayer.class, World.class, - // int.class, int.class, int.class, int.class, Block.class, int.class ); - this.mergeIntoMicroblockContainer.invoke( null, multiPartStack, player, w, x, y, z, side, multiPartBlock, 0 ); - } - catch( final Throwable e ) - { - this.canConvertTiles = false; - return null; - } - } - } - - final TileEntity tx = w.getTileEntity( x, y, z ); - if( tx instanceof IPartHost ) - { - return (IPartHost) tx; - } - - return null; - } - - @Override - public boolean leaveParts( final TileEntity te ) - { - if( te instanceof IMultipartTile ) - { - final ICoverSystem ci = ( (IMultipartTile) te ).getCoverSystem(); - if( ci != null ) - { - ci.convertToContainerBlock(); - } - - return true; - } - return false; - } +public class ImmibisMicroblocks implements IImmibisMicroblocks, IIntegrationModule { + @Reflected + public static ImmibisMicroblocks instance; + + private boolean canConvertTiles = false; + + private Class MicroblockAPIUtils; + private Method mergeIntoMicroblockContainer; + + @Reflected + public ImmibisMicroblocks() { + IntegrationHelper.testClassExistence(this, mods.immibis.core.api.multipart.IMultipartTile.class); + IntegrationHelper.testClassExistence(this, mods.immibis.core.api.multipart.ICoverSystem.class); + IntegrationHelper.testClassExistence(this, mods.immibis.core.api.multipart.IPartContainer.class); + } + + @Override + public void init() throws Throwable { + try { + this.MicroblockAPIUtils = Class.forName("mods.immibis.microblocks.api.MicroblockAPIUtils"); + this.mergeIntoMicroblockContainer = this.MicroblockAPIUtils.getMethod( + "mergeIntoMicroblockContainer", + ItemStack.class, + EntityPlayer.class, + World.class, + int.class, + int.class, + int.class, + int.class, + Block.class, + int.class); + this.canConvertTiles = true; + } catch (final Throwable t) { + AELog.debug(t); + } + } + + @Override + public void postInit() {} + + @Override + public IPartHost getOrCreateHost(final EntityPlayer player, final int side, final TileEntity te) { + final World w = te.getWorldObj(); + final int x = te.xCoord; + final int y = te.yCoord; + final int z = te.zCoord; + final boolean isPartItem = player != null + && player.getHeldItem() != null + && player.getHeldItem().getItem() instanceof IPartItem; + + if (te instanceof IMultipartTile && this.canConvertTiles && isPartItem) { + final IBlockDefinition multiPart = + AEApi.instance().definitions().blocks().multiPart(); + final Optional maybeMultiPartBlock = multiPart.maybeBlock(); + final Optional maybeMultiPartStack = multiPart.maybeStack(1); + + final boolean multiPartPresent = maybeMultiPartBlock.isPresent() && maybeMultiPartStack.isPresent(); + + if (multiPartPresent) { + final Block multiPartBlock = maybeMultiPartBlock.get(); + final ItemStack multiPartStack = maybeMultiPartStack.get(); + + try { + // ItemStack.class, EntityPlayer.class, World.class, + // int.class, int.class, int.class, int.class, Block.class, int.class ); + this.mergeIntoMicroblockContainer.invoke( + null, multiPartStack, player, w, x, y, z, side, multiPartBlock, 0); + } catch (final Throwable e) { + this.canConvertTiles = false; + return null; + } + } + } + + final TileEntity tx = w.getTileEntity(x, y, z); + if (tx instanceof IPartHost) { + return (IPartHost) tx; + } + + return null; + } + + @Override + public boolean leaveParts(final TileEntity te) { + if (te instanceof IMultipartTile) { + final ICoverSystem ci = ((IMultipartTile) te).getCoverSystem(); + if (ci != null) { + ci.convertToContainerBlock(); + } + + return true; + } + return false; + } } diff --git a/src/main/java/appeng/integration/modules/InvTweaks.java b/src/main/java/appeng/integration/modules/InvTweaks.java index d4039be7c69..27ea59d8b08 100644 --- a/src/main/java/appeng/integration/modules/InvTweaks.java +++ b/src/main/java/appeng/integration/modules/InvTweaks.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; import appeng.integration.IntegrationHelper; @@ -27,38 +26,32 @@ import invtweaks.api.InvTweaksAPI; import net.minecraft.item.ItemStack; - -public class InvTweaks implements IInvTweaks, IIntegrationModule -{ - @Reflected - public static InvTweaks instance; - - static InvTweaksAPI api; - - @Reflected - public InvTweaks() - { - IntegrationHelper.testClassExistence( this, invtweaks.api.InvTweaksAPI.class ); - } - - @Override - public void init() - { - api = (InvTweaksAPI) Loader.instance().getIndexedModList().get( "inventorytweaks" ).getMod(); - } - - @Override - public void postInit() - { - if( api == null ) - { - throw new IllegalStateException( "InvTweaks API Instance Failed." ); - } - } - - @Override - public int compareItems( final ItemStack i, final ItemStack j ) - { - return api.compareItems( i, j ); - } +public class InvTweaks implements IInvTweaks, IIntegrationModule { + @Reflected + public static InvTweaks instance; + + static InvTweaksAPI api; + + @Reflected + public InvTweaks() { + IntegrationHelper.testClassExistence(this, invtweaks.api.InvTweaksAPI.class); + } + + @Override + public void init() { + api = (InvTweaksAPI) + Loader.instance().getIndexedModList().get("inventorytweaks").getMod(); + } + + @Override + public void postInit() { + if (api == null) { + throw new IllegalStateException("InvTweaks API Instance Failed."); + } + } + + @Override + public int compareItems(final ItemStack i, final ItemStack j) { + return api.compareItems(i, j); + } } diff --git a/src/main/java/appeng/integration/modules/Jabba.java b/src/main/java/appeng/integration/modules/Jabba.java index e017e840376..0cf654800cf 100644 --- a/src/main/java/appeng/integration/modules/Jabba.java +++ b/src/main/java/appeng/integration/modules/Jabba.java @@ -14,29 +14,25 @@ public class Jabba implements IIntegrationModule { @Reflected public static Jabba instance; + @Reflected - public Jabba() - { - IntegrationHelper.testClassExistence( this, mcp.mobius.betterbarrels.common.blocks.TileEntityBarrel.class ); + public Jabba() { + IntegrationHelper.testClassExistence(this, mcp.mobius.betterbarrels.common.blocks.TileEntityBarrel.class); } - public boolean isBarrel( final TileEntity te ) - { + + public boolean isBarrel(final TileEntity te) { return te instanceof TileEntityBarrel; } - public IMEInventory getBarrel( final TileEntity te ) - { - return new JabbaBarrel( te ); + public IMEInventory getBarrel(final TileEntity te) { + return new JabbaBarrel(te); } @Override - public void init() - { - } + public void init() {} @Override - public void postInit() - { - AEApi.instance().registries().externalStorage().addExternalStorageInterface( new JabbaStorageHandler() ); + public void postInit() { + AEApi.instance().registries().externalStorage().addExternalStorageInterface(new JabbaStorageHandler()); } } diff --git a/src/main/java/appeng/integration/modules/MFR.java b/src/main/java/appeng/integration/modules/MFR.java index 26ab2bbc7bc..397dc7a869d 100644 --- a/src/main/java/appeng/integration/modules/MFR.java +++ b/src/main/java/appeng/integration/modules/MFR.java @@ -18,30 +18,23 @@ package appeng.integration.modules; - import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; import appeng.integration.IntegrationHelper; +public class MFR implements IIntegrationModule { + @Reflected + public static MFR instance; -public class MFR implements IIntegrationModule -{ - @Reflected - public static MFR instance; - - @Reflected - public MFR() - { - IntegrationHelper.testClassExistence( this, powercrystals.minefactoryreloaded.api.rednet.connectivity.IRedNetConnection.class ); - } + @Reflected + public MFR() { + IntegrationHelper.testClassExistence( + this, powercrystals.minefactoryreloaded.api.rednet.connectivity.IRedNetConnection.class); + } - @Override - public void init() throws Throwable - { - } + @Override + public void init() throws Throwable {} - @Override - public void postInit() - { - } + @Override + public void postInit() {} } diff --git a/src/main/java/appeng/integration/modules/Mekanism.java b/src/main/java/appeng/integration/modules/Mekanism.java index 6e15c498252..13a570e3129 100644 --- a/src/main/java/appeng/integration/modules/Mekanism.java +++ b/src/main/java/appeng/integration/modules/Mekanism.java @@ -18,65 +18,53 @@ package appeng.integration.modules; - import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; -import appeng.integration.IntegrationHelper; import appeng.integration.abstraction.IMekanism; import cpw.mods.fml.common.event.FMLInterModComms; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +public final class Mekanism implements IMekanism, IIntegrationModule { + @Reflected + public static Mekanism instance; -public final class Mekanism implements IMekanism, IIntegrationModule -{ - @Reflected - public static Mekanism instance; - - @Reflected - public Mekanism() - { - //IntegrationHelper.testClassExistence( this, mekanism.api.energy.IStrictEnergyAcceptor.class ); - } + @Reflected + public Mekanism() { + // IntegrationHelper.testClassExistence( this, mekanism.api.energy.IStrictEnergyAcceptor.class ); + } - @Override - public void init() throws Throwable - { - } + @Override + public void init() throws Throwable {} - @Override - public void postInit() - { - } + @Override + public void postInit() {} - @Override - public void addCrusherRecipe( final ItemStack in, final ItemStack out ) - { - final NBTTagCompound sendTag = this.convertToSimpleRecipe( in, out ); + @Override + public void addCrusherRecipe(final ItemStack in, final ItemStack out) { + final NBTTagCompound sendTag = this.convertToSimpleRecipe(in, out); - FMLInterModComms.sendMessage( "mekanism", "CrusherRecipe", sendTag ); - } + FMLInterModComms.sendMessage("mekanism", "CrusherRecipe", sendTag); + } - @Override - public void addEnrichmentChamberRecipe( final ItemStack in, final ItemStack out ) - { - final NBTTagCompound sendTag = this.convertToSimpleRecipe( in, out ); + @Override + public void addEnrichmentChamberRecipe(final ItemStack in, final ItemStack out) { + final NBTTagCompound sendTag = this.convertToSimpleRecipe(in, out); - FMLInterModComms.sendMessage( "mekanism", "EnrichmentChamberRecipe", sendTag ); - } + FMLInterModComms.sendMessage("mekanism", "EnrichmentChamberRecipe", sendTag); + } - private NBTTagCompound convertToSimpleRecipe( final ItemStack in, final ItemStack out ) - { - final NBTTagCompound sendTag = new NBTTagCompound(); - final NBTTagCompound inputTagDummy = new NBTTagCompound(); - final NBTTagCompound outputTagDummy = new NBTTagCompound(); + private NBTTagCompound convertToSimpleRecipe(final ItemStack in, final ItemStack out) { + final NBTTagCompound sendTag = new NBTTagCompound(); + final NBTTagCompound inputTagDummy = new NBTTagCompound(); + final NBTTagCompound outputTagDummy = new NBTTagCompound(); - final NBTTagCompound inputTag = in.writeToNBT( inputTagDummy ); - final NBTTagCompound outputTag = out.writeToNBT( outputTagDummy ); + final NBTTagCompound inputTag = in.writeToNBT(inputTagDummy); + final NBTTagCompound outputTag = out.writeToNBT(outputTagDummy); - sendTag.setTag( "input", inputTag ); - sendTag.setTag( "output", outputTag ); + sendTag.setTag("input", inputTag); + sendTag.setTag("output", outputTag); - return sendTag; - } + return sendTag; + } } diff --git a/src/main/java/appeng/integration/modules/NEI.java b/src/main/java/appeng/integration/modules/NEI.java index cd6607bd5f3..ee063841b3f 100644 --- a/src/main/java/appeng/integration/modules/NEI.java +++ b/src/main/java/appeng/integration/modules/NEI.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.client.gui.AEBaseMEGui; import appeng.client.gui.implementations.GuiCraftConfirm; import appeng.client.gui.implementations.GuiCraftingCPU; @@ -34,8 +33,12 @@ import codechicken.nei.api.INEIGuiHandler; import codechicken.nei.api.IStackPositioner; import codechicken.nei.guihook.GuiContainerManager; -import codechicken.nei.guihook.IContainerTooltipHandler; import codechicken.nei.guihook.IContainerObjectHandler; +import codechicken.nei.guihook.IContainerTooltipHandler; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.inventory.GuiContainer; @@ -43,184 +46,163 @@ import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.List; - - -public class NEI implements INEI, IContainerTooltipHandler, IIntegrationModule, IContainerObjectHandler -{ - @Reflected - public static NEI instance; - - private final Class apiClass; - - // recipe handler... - private Method registerRecipeHandler; - private Method registerUsageHandler; - private Method registerNEIGuiHandler; - - @Reflected - public NEI() throws ClassNotFoundException - { - IntegrationHelper.testClassExistence( this, codechicken.nei.api.API.class ); - IntegrationHelper.testClassExistence( this, codechicken.nei.api.IStackPositioner.class ); - IntegrationHelper.testClassExistence( this, codechicken.nei.guihook.GuiContainerManager.class ); - IntegrationHelper.testClassExistence( this, codechicken.nei.guihook.IContainerTooltipHandler.class ); - IntegrationHelper.testClassExistence( this, codechicken.nei.recipe.ICraftingHandler.class ); - IntegrationHelper.testClassExistence( this, codechicken.nei.recipe.IUsageHandler.class ); - - this.apiClass = Class.forName( "codechicken.nei.api.API" ); - } - - @Override - public void init() throws Throwable - { - this.registerRecipeHandler = this.apiClass.getDeclaredMethod( "registerRecipeHandler", codechicken.nei.recipe.ICraftingHandler.class ); - this.registerUsageHandler = this.apiClass.getDeclaredMethod( "registerUsageHandler", codechicken.nei.recipe.IUsageHandler.class ); - this.registerNEIGuiHandler = this.apiClass.getDeclaredMethod("registerNEIGuiHandler", INEIGuiHandler.class); - registerNEIGuiHandler.invoke(apiClass, new NEIGuiHandler()); - - this.registerRecipeHandler( new NEIAEShapedRecipeHandler() ); - this.registerRecipeHandler( new NEIAEShapelessRecipeHandler() ); - this.registerRecipeHandler( new NEIInscriberRecipeHandler() ); - this.registerRecipeHandler( new NEIWorldCraftingHandler() ); - if ( AEConfig.instance.isFeatureEnabled( AEFeature.GrindStone ) ) - { - this.registerRecipeHandler(new NEIGrinderRecipeHandler()); - } - if( AEConfig.instance.isFeatureEnabled( AEFeature.Facades ) && AEConfig.instance.isFeatureEnabled( AEFeature.EnableFacadeCrafting ) ) - { - this.registerRecipeHandler( new NEIFacadeRecipeHandler() ); - } - - // large stack tooltips - GuiContainerManager.addTooltipHandler( this ); - GuiContainerManager.addObjectHandler(this); - - // crafting terminal... - final Method registerGuiOverlay = this.apiClass.getDeclaredMethod( "registerGuiOverlay", Class.class, String.class, IStackPositioner.class ); - final Class overlayHandler = Class.forName( "codechicken.nei.api.IOverlayHandler" ); - - final Method registrar = this.apiClass.getDeclaredMethod( "registerGuiOverlayHandler", Class.class, overlayHandler, String.class ); - registerGuiOverlay.invoke( this.apiClass, GuiCraftingTerm.class, "crafting", new TerminalCraftingSlotFinder() ); - registerGuiOverlay.invoke( this.apiClass, GuiPatternTerm.class, "crafting", new TerminalCraftingSlotFinder() ); - - final Class defaultHandler = NEICraftingHandler.class; - final Constructor defaultConstructor = defaultHandler.getConstructor( int.class, int.class ); - registrar.invoke( this.apiClass, GuiCraftingTerm.class, defaultConstructor.newInstance( 6, 75 ), "crafting" ); - registrar.invoke( this.apiClass, GuiPatternTerm.class, defaultConstructor.newInstance( 6, 75 ), "crafting" ); - } - - public void registerRecipeHandler( final Object o ) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException - { - this.registerRecipeHandler.invoke( this.apiClass, o ); - this.registerUsageHandler.invoke( this.apiClass, o ); - } - - @Override - public void postInit() - { - - } - - @Override - public void drawSlot( final Slot s ) - { - if( s == null ) - { - return; - } - - final ItemStack stack = s.getStack(); - - if( stack == null ) - { - return; - } - - final Minecraft mc = Minecraft.getMinecraft(); - final FontRenderer fontRenderer = mc.fontRenderer; - final int x = s.xDisplayPosition; - final int y = s.yDisplayPosition; - - GuiContainerManager.drawItems.renderItemAndEffectIntoGUI( fontRenderer, mc.getTextureManager(), stack, x, y ); - GuiContainerManager.drawItems.renderItemOverlayIntoGUI( fontRenderer, mc.getTextureManager(), stack, x, y, String.valueOf( stack.stackSize ) ); - } - - @Override - public RenderItem setItemRender( final RenderItem renderItem ) - { - try - { - final RenderItem ri = GuiContainerManager.drawItems; - GuiContainerManager.drawItems = renderItem; - return ri; - } - catch( final Throwable t ) - { - throw new IllegalStateException( "Invalid version of NEI, please update", t ); - } - } - - @Override - public List handleTooltip( final GuiContainer arg0, final int arg1, final int arg2, final List current ) - { - return current; - } - - @Override - public List handleItemDisplayName( final GuiContainer arg0, final ItemStack arg1, final List current ) - { - return current; - } - - @Override - public List handleItemTooltip( final GuiContainer guiScreen, final ItemStack stack, final int mouseX, final int mouseY, final List currentToolTip ) - { - if( guiScreen instanceof AEBaseMEGui ) - { - return ( (AEBaseMEGui) guiScreen ).handleItemTooltip( stack, mouseX, mouseY, currentToolTip ); - } - - return currentToolTip; - } - @Override - public void guiTick(GuiContainer gui) { - - } - - @Override - public void refresh(GuiContainer gui) { - - } - - @Override - public void load(GuiContainer gui) { - - } - - @Override - public ItemStack getStackUnderMouse(GuiContainer gui, int mousex, int mousey) { - if (gui instanceof GuiCraftConfirm) - return ((GuiCraftConfirm)gui).getHoveredStack(); - else if (gui instanceof GuiCraftingCPU) - return ((GuiCraftingCPU)gui).getHoveredStack(); - return null; - } - - @Override - public boolean objectUnderMouse(GuiContainer gui, int mousex, int mousey) { - return false; - } - - @Override - public boolean shouldShowTooltip(GuiContainer gui) { - if (gui instanceof GuiCraftConfirm) - return ((GuiCraftConfirm)gui).getHoveredStack() == null; - if (gui instanceof GuiCraftingCPU) - return ((GuiCraftingCPU)gui).getHoveredStack() == null; - return true; - } +public class NEI implements INEI, IContainerTooltipHandler, IIntegrationModule, IContainerObjectHandler { + @Reflected + public static NEI instance; + + private final Class apiClass; + + // recipe handler... + private Method registerRecipeHandler; + private Method registerUsageHandler; + private Method registerNEIGuiHandler; + + @Reflected + public NEI() throws ClassNotFoundException { + IntegrationHelper.testClassExistence(this, codechicken.nei.api.API.class); + IntegrationHelper.testClassExistence(this, codechicken.nei.api.IStackPositioner.class); + IntegrationHelper.testClassExistence(this, codechicken.nei.guihook.GuiContainerManager.class); + IntegrationHelper.testClassExistence(this, codechicken.nei.guihook.IContainerTooltipHandler.class); + IntegrationHelper.testClassExistence(this, codechicken.nei.recipe.ICraftingHandler.class); + IntegrationHelper.testClassExistence(this, codechicken.nei.recipe.IUsageHandler.class); + + this.apiClass = Class.forName("codechicken.nei.api.API"); + } + + @Override + public void init() throws Throwable { + this.registerRecipeHandler = + this.apiClass.getDeclaredMethod("registerRecipeHandler", codechicken.nei.recipe.ICraftingHandler.class); + this.registerUsageHandler = + this.apiClass.getDeclaredMethod("registerUsageHandler", codechicken.nei.recipe.IUsageHandler.class); + this.registerNEIGuiHandler = this.apiClass.getDeclaredMethod("registerNEIGuiHandler", INEIGuiHandler.class); + registerNEIGuiHandler.invoke(apiClass, new NEIGuiHandler()); + + this.registerRecipeHandler(new NEIAEShapedRecipeHandler()); + this.registerRecipeHandler(new NEIAEShapelessRecipeHandler()); + this.registerRecipeHandler(new NEIInscriberRecipeHandler()); + this.registerRecipeHandler(new NEIWorldCraftingHandler()); + if (AEConfig.instance.isFeatureEnabled(AEFeature.GrindStone)) { + this.registerRecipeHandler(new NEIGrinderRecipeHandler()); + } + if (AEConfig.instance.isFeatureEnabled(AEFeature.Facades) + && AEConfig.instance.isFeatureEnabled(AEFeature.EnableFacadeCrafting)) { + this.registerRecipeHandler(new NEIFacadeRecipeHandler()); + } + + // large stack tooltips + GuiContainerManager.addTooltipHandler(this); + GuiContainerManager.addObjectHandler(this); + + // crafting terminal... + final Method registerGuiOverlay = this.apiClass.getDeclaredMethod( + "registerGuiOverlay", Class.class, String.class, IStackPositioner.class); + final Class overlayHandler = Class.forName("codechicken.nei.api.IOverlayHandler"); + + final Method registrar = + this.apiClass.getDeclaredMethod("registerGuiOverlayHandler", Class.class, overlayHandler, String.class); + registerGuiOverlay.invoke(this.apiClass, GuiCraftingTerm.class, "crafting", new TerminalCraftingSlotFinder()); + registerGuiOverlay.invoke(this.apiClass, GuiPatternTerm.class, "crafting", new TerminalCraftingSlotFinder()); + + final Class defaultHandler = NEICraftingHandler.class; + final Constructor defaultConstructor = defaultHandler.getConstructor(int.class, int.class); + registrar.invoke(this.apiClass, GuiCraftingTerm.class, defaultConstructor.newInstance(6, 75), "crafting"); + registrar.invoke(this.apiClass, GuiPatternTerm.class, defaultConstructor.newInstance(6, 75), "crafting"); + } + + public void registerRecipeHandler(final Object o) + throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { + this.registerRecipeHandler.invoke(this.apiClass, o); + this.registerUsageHandler.invoke(this.apiClass, o); + } + + @Override + public void postInit() {} + + @Override + public void drawSlot(final Slot s) { + if (s == null) { + return; + } + + final ItemStack stack = s.getStack(); + + if (stack == null) { + return; + } + + final Minecraft mc = Minecraft.getMinecraft(); + final FontRenderer fontRenderer = mc.fontRenderer; + final int x = s.xDisplayPosition; + final int y = s.yDisplayPosition; + + GuiContainerManager.drawItems.renderItemAndEffectIntoGUI(fontRenderer, mc.getTextureManager(), stack, x, y); + GuiContainerManager.drawItems.renderItemOverlayIntoGUI( + fontRenderer, mc.getTextureManager(), stack, x, y, String.valueOf(stack.stackSize)); + } + + @Override + public RenderItem setItemRender(final RenderItem renderItem) { + try { + final RenderItem ri = GuiContainerManager.drawItems; + GuiContainerManager.drawItems = renderItem; + return ri; + } catch (final Throwable t) { + throw new IllegalStateException("Invalid version of NEI, please update", t); + } + } + + @Override + public List handleTooltip( + final GuiContainer arg0, final int arg1, final int arg2, final List current) { + return current; + } + + @Override + public List handleItemDisplayName( + final GuiContainer arg0, final ItemStack arg1, final List current) { + return current; + } + + @Override + public List handleItemTooltip( + final GuiContainer guiScreen, + final ItemStack stack, + final int mouseX, + final int mouseY, + final List currentToolTip) { + if (guiScreen instanceof AEBaseMEGui) { + return ((AEBaseMEGui) guiScreen).handleItemTooltip(stack, mouseX, mouseY, currentToolTip); + } + + return currentToolTip; + } + + @Override + public void guiTick(GuiContainer gui) {} + + @Override + public void refresh(GuiContainer gui) {} + + @Override + public void load(GuiContainer gui) {} + + @Override + public ItemStack getStackUnderMouse(GuiContainer gui, int mousex, int mousey) { + if (gui instanceof GuiCraftConfirm) return ((GuiCraftConfirm) gui).getHoveredStack(); + else if (gui instanceof GuiCraftingCPU) return ((GuiCraftingCPU) gui).getHoveredStack(); + return null; + } + + @Override + public boolean objectUnderMouse(GuiContainer gui, int mousex, int mousey) { + return false; + } + + @Override + public boolean shouldShowTooltip(GuiContainer gui) { + if (gui instanceof GuiCraftConfirm) return ((GuiCraftConfirm) gui).getHoveredStack() == null; + if (gui instanceof GuiCraftingCPU) return ((GuiCraftingCPU) gui).getHoveredStack() == null; + return true; + } } diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapedRecipeHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapedRecipeHandler.java index 7de64672662..e8e163d7f3a 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapedRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapedRecipeHandler.java @@ -18,7 +18,6 @@ package appeng.integration.modules.NEIHelpers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; import appeng.api.recipes.IIngredient; @@ -34,6 +33,9 @@ import codechicken.nei.api.IStackPositioner; import codechicken.nei.recipe.RecipeInfo; import codechicken.nei.recipe.TemplateRecipeHandler; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.gui.inventory.GuiCrafting; import net.minecraft.inventory.Container; @@ -41,221 +43,174 @@ import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; -import java.awt.*; -import java.util.ArrayList; -import java.util.List; - - -public class NEIAEShapedRecipeHandler extends TemplateRecipeHandler -{ - - @Override - public void loadTransferRects() - { - this.transferRects.add( new TemplateRecipeHandler.RecipeTransferRect( new Rectangle( 84, 23, 24, 18 ), "crafting" ) ); - } - - @Override - public void loadCraftingRecipes( final String outputId, final Object... results ) - { - if( ( outputId.equals( "crafting" ) ) && ( this.getClass() == NEIAEShapedRecipeHandler.class ) ) - { - final List recipes = CraftingManager.getInstance().getRecipeList(); - for( final IRecipe recipe : recipes ) - { - if( ( recipe instanceof ShapedRecipe ) ) - { - if( ( (ShapedRecipe) recipe ).isEnabled() ) - { - final CachedShapedRecipe cachedRecipe = new CachedShapedRecipe( (ShapedRecipe) recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - } - } - else - { - super.loadCraftingRecipes( outputId, results ); - } - } - - @Override - public void loadCraftingRecipes( final ItemStack result ) - { - final List recipes = CraftingManager.getInstance().getRecipeList(); - for( final IRecipe recipe : recipes ) - { - if( ( recipe instanceof ShapedRecipe ) ) - { - if( ( (ShapedRecipe) recipe ).isEnabled() && NEIServerUtils.areStacksSameTypeCrafting( recipe.getRecipeOutput(), result ) ) - { - final CachedShapedRecipe cachedRecipe = new CachedShapedRecipe( (ShapedRecipe) recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - } - } - - @Override - public void loadUsageRecipes( final ItemStack ingredient ) - { - final List recipes = CraftingManager.getInstance().getRecipeList(); - for( final IRecipe recipe : recipes ) - { - if( ( recipe instanceof ShapedRecipe ) ) - { - final CachedShapedRecipe cachedRecipe = new CachedShapedRecipe( (ShapedRecipe) recipe ); - - if( ( (ShapedRecipe) recipe ).isEnabled() && cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) - { - cachedRecipe.computeVisuals(); - if( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) - { - cachedRecipe.setIngredientPermutation( cachedRecipe.ingredients, ingredient ); - this.arecipes.add( cachedRecipe ); - } - } - } - } - } - - @Override - public String getGuiTexture() - { - return "textures/gui/container/crafting_table.png"; - } - - @Override - public String getOverlayIdentifier() - { - return "crafting"; - } - - @Override - public Class getGuiClass() - { - return GuiCrafting.class; - } - - @Override - public boolean hasOverlay( final GuiContainer gui, final Container container, final int recipe ) - { - return ( super.hasOverlay( gui, container, recipe ) ) || ( ( this.isRecipe2x2( recipe ) ) && ( RecipeInfo.hasDefaultOverlay( gui, "crafting2x2" ) ) ); - } - - @Override - public IRecipeOverlayRenderer getOverlayRenderer( final GuiContainer gui, final int recipe ) - { - final IRecipeOverlayRenderer renderer = super.getOverlayRenderer( gui, recipe ); - if( renderer != null ) - { - return renderer; - } - - final IStackPositioner positioner = RecipeInfo.getStackPositioner( gui, "crafting2x2" ); - if( positioner == null ) - { - return null; - } - - return new DefaultOverlayRenderer( this.getIngredientStacks( recipe ), positioner ); - } - - @Override - public IOverlayHandler getOverlayHandler( final GuiContainer gui, final int recipe ) - { - final IOverlayHandler handler = super.getOverlayHandler( gui, recipe ); - if( handler != null ) - { - return handler; - } - - return RecipeInfo.getOverlayHandler( gui, "crafting2x2" ); - } - - private boolean isRecipe2x2( final int recipe ) - { - for( final PositionedStack stack : this.getIngredientStacks( recipe ) ) - { - if( ( stack.relx > 43 ) || ( stack.rely > 24 ) ) - { - return false; - } - } - return true; - } - - @Override - public String getRecipeName() - { - return NEIClientUtils.translate( "recipe.shaped" ); - } - - private class CachedShapedRecipe extends TemplateRecipeHandler.CachedRecipe - { - - private final List ingredients; - private final PositionedStack result; - - public CachedShapedRecipe( final ShapedRecipe recipe ) - { - this.result = new PositionedStack( recipe.getRecipeOutput(), 119, 24 ); - this.ingredients = new ArrayList(); - this.setIngredients( recipe.getWidth(), recipe.getHeight(), recipe.getIngredients() ); - } - - private void setIngredients( final int width, final int height, final Object[] items ) - { - final boolean useSingleItems = AEConfig.instance.disableColoredCableRecipesInNEI(); - for( int x = 0; x < width; x++ ) - { - for( int y = 0; y < height; y++ ) - { - if( items[( y * width + x )] != null ) - { - final IIngredient ing = (IIngredient) items[( y * width + x )]; - - try - { - final ItemStack[] is = ing.getItemStackSet(); - final PositionedStack stack = new PositionedStack( useSingleItems ? Platform.findPreferred( is ) : is, 25 + x * 18, 6 + y * 18, false ); - stack.setMaxSize( 1 ); - this.ingredients.add( stack ); - } - catch( final RegistrationError ignored ) - { - - } - catch( final MissingIngredientError ignored ) - { - - } - } - } - } - } - - @Override - public PositionedStack getResult() - { - return this.result; - } - - @Override - public List getIngredients() - { - return this.getCycledIngredients( NEIAEShapedRecipeHandler.this.cycleticks / 20, this.ingredients ); - } - - private void computeVisuals() - { - for( final PositionedStack p : this.ingredients ) - { - p.generatePermutations(); - } - this.result.generatePermutations(); - } - } -} \ No newline at end of file +public class NEIAEShapedRecipeHandler extends TemplateRecipeHandler { + + @Override + public void loadTransferRects() { + this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect(new Rectangle(84, 23, 24, 18), "crafting")); + } + + @Override + public void loadCraftingRecipes(final String outputId, final Object... results) { + if ((outputId.equals("crafting")) && (this.getClass() == NEIAEShapedRecipeHandler.class)) { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for (final IRecipe recipe : recipes) { + if ((recipe instanceof ShapedRecipe)) { + if (((ShapedRecipe) recipe).isEnabled()) { + final CachedShapedRecipe cachedRecipe = new CachedShapedRecipe((ShapedRecipe) recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } + } + } else { + super.loadCraftingRecipes(outputId, results); + } + } + + @Override + public void loadCraftingRecipes(final ItemStack result) { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for (final IRecipe recipe : recipes) { + if ((recipe instanceof ShapedRecipe)) { + if (((ShapedRecipe) recipe).isEnabled() + && NEIServerUtils.areStacksSameTypeCrafting(recipe.getRecipeOutput(), result)) { + final CachedShapedRecipe cachedRecipe = new CachedShapedRecipe((ShapedRecipe) recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } + } + } + + @Override + public void loadUsageRecipes(final ItemStack ingredient) { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for (final IRecipe recipe : recipes) { + if ((recipe instanceof ShapedRecipe)) { + final CachedShapedRecipe cachedRecipe = new CachedShapedRecipe((ShapedRecipe) recipe); + + if (((ShapedRecipe) recipe).isEnabled() + && cachedRecipe.contains(cachedRecipe.ingredients, ingredient.getItem())) { + cachedRecipe.computeVisuals(); + if (cachedRecipe.contains(cachedRecipe.ingredients, ingredient)) { + cachedRecipe.setIngredientPermutation(cachedRecipe.ingredients, ingredient); + this.arecipes.add(cachedRecipe); + } + } + } + } + } + + @Override + public String getGuiTexture() { + return "textures/gui/container/crafting_table.png"; + } + + @Override + public String getOverlayIdentifier() { + return "crafting"; + } + + @Override + public Class getGuiClass() { + return GuiCrafting.class; + } + + @Override + public boolean hasOverlay(final GuiContainer gui, final Container container, final int recipe) { + return (super.hasOverlay(gui, container, recipe)) + || ((this.isRecipe2x2(recipe)) && (RecipeInfo.hasDefaultOverlay(gui, "crafting2x2"))); + } + + @Override + public IRecipeOverlayRenderer getOverlayRenderer(final GuiContainer gui, final int recipe) { + final IRecipeOverlayRenderer renderer = super.getOverlayRenderer(gui, recipe); + if (renderer != null) { + return renderer; + } + + final IStackPositioner positioner = RecipeInfo.getStackPositioner(gui, "crafting2x2"); + if (positioner == null) { + return null; + } + + return new DefaultOverlayRenderer(this.getIngredientStacks(recipe), positioner); + } + + @Override + public IOverlayHandler getOverlayHandler(final GuiContainer gui, final int recipe) { + final IOverlayHandler handler = super.getOverlayHandler(gui, recipe); + if (handler != null) { + return handler; + } + + return RecipeInfo.getOverlayHandler(gui, "crafting2x2"); + } + + private boolean isRecipe2x2(final int recipe) { + for (final PositionedStack stack : this.getIngredientStacks(recipe)) { + if ((stack.relx > 43) || (stack.rely > 24)) { + return false; + } + } + return true; + } + + @Override + public String getRecipeName() { + return NEIClientUtils.translate("recipe.shaped"); + } + + private class CachedShapedRecipe extends TemplateRecipeHandler.CachedRecipe { + + private final List ingredients; + private final PositionedStack result; + + public CachedShapedRecipe(final ShapedRecipe recipe) { + this.result = new PositionedStack(recipe.getRecipeOutput(), 119, 24); + this.ingredients = new ArrayList(); + this.setIngredients(recipe.getWidth(), recipe.getHeight(), recipe.getIngredients()); + } + + private void setIngredients(final int width, final int height, final Object[] items) { + final boolean useSingleItems = AEConfig.instance.disableColoredCableRecipesInNEI(); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + if (items[(y * width + x)] != null) { + final IIngredient ing = (IIngredient) items[(y * width + x)]; + + try { + final ItemStack[] is = ing.getItemStackSet(); + final PositionedStack stack = new PositionedStack( + useSingleItems ? Platform.findPreferred(is) : is, 25 + x * 18, 6 + y * 18, false); + stack.setMaxSize(1); + this.ingredients.add(stack); + } catch (final RegistrationError ignored) { + + } catch (final MissingIngredientError ignored) { + + } + } + } + } + } + + @Override + public PositionedStack getResult() { + return this.result; + } + + @Override + public List getIngredients() { + return this.getCycledIngredients(NEIAEShapedRecipeHandler.this.cycleticks / 20, this.ingredients); + } + + private void computeVisuals() { + for (final PositionedStack p : this.ingredients) { + p.generatePermutations(); + } + this.result.generatePermutations(); + } + } +} diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapelessRecipeHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapelessRecipeHandler.java index 148f57533b5..27cd5850c80 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapelessRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapelessRecipeHandler.java @@ -18,7 +18,6 @@ package appeng.integration.modules.NEIHelpers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; import appeng.api.recipes.IIngredient; @@ -34,6 +33,9 @@ import codechicken.nei.api.IStackPositioner; import codechicken.nei.recipe.RecipeInfo; import codechicken.nei.recipe.TemplateRecipeHandler; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.gui.inventory.GuiCrafting; import net.minecraft.inventory.Container; @@ -41,222 +43,178 @@ import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; -import java.awt.*; -import java.util.ArrayList; -import java.util.List; - - -public class NEIAEShapelessRecipeHandler extends TemplateRecipeHandler -{ - - @Override - public void loadTransferRects() - { - this.transferRects.add( new TemplateRecipeHandler.RecipeTransferRect( new Rectangle( 84, 23, 24, 18 ), "crafting" ) ); - } - - @Override - public void loadCraftingRecipes( final String outputId, final Object... results ) - { - if( ( outputId.equals( "crafting" ) ) && ( this.getClass() == NEIAEShapelessRecipeHandler.class ) ) - { - final List recipes = CraftingManager.getInstance().getRecipeList(); - for( final IRecipe recipe : recipes ) - { - if( ( recipe instanceof ShapelessRecipe ) ) - { - if( ( (ShapelessRecipe) recipe ).isEnabled() ) - { - final CachedShapelessRecipe cachedRecipe = new CachedShapelessRecipe( (ShapelessRecipe) recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - } - } - else - { - super.loadCraftingRecipes( outputId, results ); - } - } - - @Override - public void loadCraftingRecipes( final ItemStack result ) - { - final List recipes = CraftingManager.getInstance().getRecipeList(); - for( final IRecipe recipe : recipes ) - { - if( ( recipe instanceof ShapelessRecipe ) ) - { - if( ( (ShapelessRecipe) recipe ).isEnabled() && NEIServerUtils.areStacksSameTypeCrafting( recipe.getRecipeOutput(), result ) ) - { - final CachedShapelessRecipe cachedRecipe = new CachedShapelessRecipe( (ShapelessRecipe) recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - } - } - - @Override - public void loadUsageRecipes( final ItemStack ingredient ) - { - final List recipes = CraftingManager.getInstance().getRecipeList(); - for( final IRecipe recipe : recipes ) - { - if( ( recipe instanceof ShapelessRecipe ) ) - { - final CachedShapelessRecipe cachedRecipe = new CachedShapelessRecipe( (ShapelessRecipe) recipe ); - - if( ( (ShapelessRecipe) recipe ).isEnabled() && cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) - { - cachedRecipe.computeVisuals(); - if( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) - { - cachedRecipe.setIngredientPermutation( cachedRecipe.ingredients, ingredient ); - this.arecipes.add( cachedRecipe ); - } - } - } - } - } - - @Override - public String getGuiTexture() - { - return "textures/gui/container/crafting_table.png"; - } - - @Override - public String getOverlayIdentifier() - { - return "crafting"; - } - - @Override - public Class getGuiClass() - { - return GuiCrafting.class; - } - - @Override - public boolean hasOverlay( final GuiContainer gui, final Container container, final int recipe ) - { - return ( super.hasOverlay( gui, container, recipe ) ) || ( ( this.isRecipe2x2( recipe ) ) && ( RecipeInfo.hasDefaultOverlay( gui, "crafting2x2" ) ) ); - } - - @Override - public IRecipeOverlayRenderer getOverlayRenderer( final GuiContainer gui, final int recipe ) - { - final IRecipeOverlayRenderer renderer = super.getOverlayRenderer( gui, recipe ); - if( renderer != null ) - { - return renderer; - } - - final IStackPositioner positioner = RecipeInfo.getStackPositioner( gui, "crafting2x2" ); - if( positioner == null ) - { - return null; - } - - return new DefaultOverlayRenderer( this.getIngredientStacks( recipe ), positioner ); - } - - @Override - public IOverlayHandler getOverlayHandler( final GuiContainer gui, final int recipe ) - { - final IOverlayHandler handler = super.getOverlayHandler( gui, recipe ); - if( handler != null ) - { - return handler; - } - - return RecipeInfo.getOverlayHandler( gui, "crafting2x2" ); - } - - private boolean isRecipe2x2( final int recipe ) - { - for( final PositionedStack stack : this.getIngredientStacks( recipe ) ) - { - if( ( stack.relx > 43 ) || ( stack.rely > 24 ) ) - { - return false; - } - } - return true; - } - - @Override - public String getRecipeName() - { - return NEIClientUtils.translate( "recipe.shapeless" ); - } - - private class CachedShapelessRecipe extends TemplateRecipeHandler.CachedRecipe - { - - private final List ingredients; - private final PositionedStack result; - - public CachedShapelessRecipe( final ShapelessRecipe recipe ) - { - this.result = new PositionedStack( recipe.getRecipeOutput(), 119, 24 ); - this.ingredients = new ArrayList(); - this.setIngredients( recipe.getInput().toArray() ); - } - - @Override - public PositionedStack getResult() - { - return this.result; - } - - @Override - public List getIngredients() - { - return this.getCycledIngredients( NEIAEShapelessRecipeHandler.this.cycleticks / 20, this.ingredients ); - } - - private void setIngredients( final Object[] items ) - { - final boolean useSingleItems = AEConfig.instance.disableColoredCableRecipesInNEI(); - for( int x = 0; x < 3; x++ ) - { - for( int y = 0; y < 3; y++ ) - { - if( items.length > ( y * 3 + x ) ) - { - final IIngredient ing = (IIngredient) items[( y * 3 + x )]; - - try - { - final ItemStack[] is = ing.getItemStackSet(); - final PositionedStack stack = new PositionedStack( useSingleItems ? Platform.findPreferred( is ) : ing.getItemStackSet(), 25 + x * 18, 6 + y * 18, false ); - stack.setMaxSize( 1 ); - this.ingredients.add( stack ); - } - catch( final RegistrationError ignored ) - { - - } - catch( final MissingIngredientError ignored ) - { - - } - } - } - } - } - - private void computeVisuals() - { - for( final PositionedStack p : this.ingredients ) - { - p.generatePermutations(); - } - - this.result.generatePermutations(); - } - } -} \ No newline at end of file +public class NEIAEShapelessRecipeHandler extends TemplateRecipeHandler { + + @Override + public void loadTransferRects() { + this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect(new Rectangle(84, 23, 24, 18), "crafting")); + } + + @Override + public void loadCraftingRecipes(final String outputId, final Object... results) { + if ((outputId.equals("crafting")) && (this.getClass() == NEIAEShapelessRecipeHandler.class)) { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for (final IRecipe recipe : recipes) { + if ((recipe instanceof ShapelessRecipe)) { + if (((ShapelessRecipe) recipe).isEnabled()) { + final CachedShapelessRecipe cachedRecipe = new CachedShapelessRecipe((ShapelessRecipe) recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } + } + } else { + super.loadCraftingRecipes(outputId, results); + } + } + + @Override + public void loadCraftingRecipes(final ItemStack result) { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for (final IRecipe recipe : recipes) { + if ((recipe instanceof ShapelessRecipe)) { + if (((ShapelessRecipe) recipe).isEnabled() + && NEIServerUtils.areStacksSameTypeCrafting(recipe.getRecipeOutput(), result)) { + final CachedShapelessRecipe cachedRecipe = new CachedShapelessRecipe((ShapelessRecipe) recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } + } + } + + @Override + public void loadUsageRecipes(final ItemStack ingredient) { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for (final IRecipe recipe : recipes) { + if ((recipe instanceof ShapelessRecipe)) { + final CachedShapelessRecipe cachedRecipe = new CachedShapelessRecipe((ShapelessRecipe) recipe); + + if (((ShapelessRecipe) recipe).isEnabled() + && cachedRecipe.contains(cachedRecipe.ingredients, ingredient.getItem())) { + cachedRecipe.computeVisuals(); + if (cachedRecipe.contains(cachedRecipe.ingredients, ingredient)) { + cachedRecipe.setIngredientPermutation(cachedRecipe.ingredients, ingredient); + this.arecipes.add(cachedRecipe); + } + } + } + } + } + + @Override + public String getGuiTexture() { + return "textures/gui/container/crafting_table.png"; + } + + @Override + public String getOverlayIdentifier() { + return "crafting"; + } + + @Override + public Class getGuiClass() { + return GuiCrafting.class; + } + + @Override + public boolean hasOverlay(final GuiContainer gui, final Container container, final int recipe) { + return (super.hasOverlay(gui, container, recipe)) + || ((this.isRecipe2x2(recipe)) && (RecipeInfo.hasDefaultOverlay(gui, "crafting2x2"))); + } + + @Override + public IRecipeOverlayRenderer getOverlayRenderer(final GuiContainer gui, final int recipe) { + final IRecipeOverlayRenderer renderer = super.getOverlayRenderer(gui, recipe); + if (renderer != null) { + return renderer; + } + + final IStackPositioner positioner = RecipeInfo.getStackPositioner(gui, "crafting2x2"); + if (positioner == null) { + return null; + } + + return new DefaultOverlayRenderer(this.getIngredientStacks(recipe), positioner); + } + + @Override + public IOverlayHandler getOverlayHandler(final GuiContainer gui, final int recipe) { + final IOverlayHandler handler = super.getOverlayHandler(gui, recipe); + if (handler != null) { + return handler; + } + + return RecipeInfo.getOverlayHandler(gui, "crafting2x2"); + } + + private boolean isRecipe2x2(final int recipe) { + for (final PositionedStack stack : this.getIngredientStacks(recipe)) { + if ((stack.relx > 43) || (stack.rely > 24)) { + return false; + } + } + return true; + } + + @Override + public String getRecipeName() { + return NEIClientUtils.translate("recipe.shapeless"); + } + + private class CachedShapelessRecipe extends TemplateRecipeHandler.CachedRecipe { + + private final List ingredients; + private final PositionedStack result; + + public CachedShapelessRecipe(final ShapelessRecipe recipe) { + this.result = new PositionedStack(recipe.getRecipeOutput(), 119, 24); + this.ingredients = new ArrayList(); + this.setIngredients(recipe.getInput().toArray()); + } + + @Override + public PositionedStack getResult() { + return this.result; + } + + @Override + public List getIngredients() { + return this.getCycledIngredients(NEIAEShapelessRecipeHandler.this.cycleticks / 20, this.ingredients); + } + + private void setIngredients(final Object[] items) { + final boolean useSingleItems = AEConfig.instance.disableColoredCableRecipesInNEI(); + for (int x = 0; x < 3; x++) { + for (int y = 0; y < 3; y++) { + if (items.length > (y * 3 + x)) { + final IIngredient ing = (IIngredient) items[(y * 3 + x)]; + + try { + final ItemStack[] is = ing.getItemStackSet(); + final PositionedStack stack = new PositionedStack( + useSingleItems ? Platform.findPreferred(is) : ing.getItemStackSet(), + 25 + x * 18, + 6 + y * 18, + false); + stack.setMaxSize(1); + this.ingredients.add(stack); + } catch (final RegistrationError ignored) { + + } catch (final MissingIngredientError ignored) { + + } + } + } + } + } + + private void computeVisuals() { + for (final PositionedStack p : this.ingredients) { + p.generatePermutations(); + } + + this.result.generatePermutations(); + } + } +} diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEICraftingHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEICraftingHandler.java index 8c1834177cc..4620f4a4fb6 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEICraftingHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEICraftingHandler.java @@ -18,7 +18,6 @@ package appeng.integration.modules.NEIHelpers; - import appeng.client.gui.implementations.GuiCraftingTerm; import appeng.client.gui.implementations.GuiPatternTerm; import appeng.container.slot.SlotCraftingMatrix; @@ -30,6 +29,11 @@ import codechicken.nei.PositionedStack; import codechicken.nei.api.IOverlayHandler; import codechicken.nei.recipe.IRecipeHandler; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; @@ -37,106 +41,77 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; - - -public class NEICraftingHandler implements IOverlayHandler -{ +public class NEICraftingHandler implements IOverlayHandler { - public NEICraftingHandler( final int x, final int y ) - { - } + public NEICraftingHandler(final int x, final int y) {} - @Override - public void overlayRecipe( final GuiContainer gui, final IRecipeHandler recipe, final int recipeIndex, final boolean shift ) - { - try - { - final List ingredients = recipe.getIngredientStacks( recipeIndex ); - if (gui instanceof GuiCraftingTerm || gui instanceof GuiPatternTerm) - { - PacketNEIRecipe packet = new PacketNEIRecipe(packIngredients(gui, ingredients, false)); - if (packet.size() >= 32*1024) - { - AELog.warn("Recipe for " + recipe.getRecipeName() + " has too many variants, reduced version will be used"); - packet = new PacketNEIRecipe(packIngredients(gui, ingredients, true)); - } - NetworkHandler.instance.sendToServer(packet); - } - } - catch( final Exception ignored ) - { - } - catch( final Error ignored ) - { - } - } + @Override + public void overlayRecipe( + final GuiContainer gui, final IRecipeHandler recipe, final int recipeIndex, final boolean shift) { + try { + final List ingredients = recipe.getIngredientStacks(recipeIndex); + if (gui instanceof GuiCraftingTerm || gui instanceof GuiPatternTerm) { + PacketNEIRecipe packet = new PacketNEIRecipe(packIngredients(gui, ingredients, false)); + if (packet.size() >= 32 * 1024) { + AELog.warn("Recipe for " + recipe.getRecipeName() + + " has too many variants, reduced version will be used"); + packet = new PacketNEIRecipe(packIngredients(gui, ingredients, true)); + } + NetworkHandler.instance.sendToServer(packet); + } + } catch (final Exception ignored) { + } catch (final Error ignored) { + } + } - // if the packet becomes too large, limit each slot contents to 3k - private boolean testSize(final NBTTagCompound recipe) throws IOException - { - final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - final DataOutputStream outputStream = new DataOutputStream( bytes ); - CompressedStreamTools.writeCompressed( recipe, outputStream ); - return bytes.size() > 3*1024; - } + // if the packet becomes too large, limit each slot contents to 3k + private boolean testSize(final NBTTagCompound recipe) throws IOException { + final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + final DataOutputStream outputStream = new DataOutputStream(bytes); + CompressedStreamTools.writeCompressed(recipe, outputStream); + return bytes.size() > 3 * 1024; + } - private NBTTagCompound packIngredients(GuiContainer gui, List ingredients, boolean limited) throws IOException - { - final NBTTagCompound recipe = new NBTTagCompound(); - for( final PositionedStack positionedStack : ingredients ) - { - final int col = ( positionedStack.relx - 25 ) / 18; - final int row = ( positionedStack.rely - 6 ) / 18; - if( positionedStack.items != null && positionedStack.items.length > 0 ) - { - for( final Slot slot : (List) gui.inventorySlots.inventorySlots ) - { - if( slot instanceof SlotCraftingMatrix || slot instanceof SlotFakeCraftingMatrix) - { - if( slot.getSlotIndex() == col + row * 3 ) - { - final NBTTagList tags = new NBTTagList(); - final List list = new LinkedList(); + private NBTTagCompound packIngredients(GuiContainer gui, List ingredients, boolean limited) + throws IOException { + final NBTTagCompound recipe = new NBTTagCompound(); + for (final PositionedStack positionedStack : ingredients) { + final int col = (positionedStack.relx - 25) / 18; + final int row = (positionedStack.rely - 6) / 18; + if (positionedStack.items != null && positionedStack.items.length > 0) { + for (final Slot slot : (List) gui.inventorySlots.inventorySlots) { + if (slot instanceof SlotCraftingMatrix || slot instanceof SlotFakeCraftingMatrix) { + if (slot.getSlotIndex() == col + row * 3) { + final NBTTagList tags = new NBTTagList(); + final List list = new LinkedList(); - // prefer pure crystals. - for( int x = 0; x < positionedStack.items.length; x++ ) - { - if( Platform.isRecipePrioritized( positionedStack.items[x] ) ) - { - list.add( 0, positionedStack.items[x] ); - } - else - { - list.add( positionedStack.items[x] ); - } - } + // prefer pure crystals. + for (int x = 0; x < positionedStack.items.length; x++) { + if (Platform.isRecipePrioritized(positionedStack.items[x])) { + list.add(0, positionedStack.items[x]); + } else { + list.add(positionedStack.items[x]); + } + } - for( final ItemStack is : list ) - { - final NBTTagCompound tag = new NBTTagCompound(); - is.writeToNBT( tag ); - tags.appendTag( tag ); - if (limited) - { - final NBTTagCompound test = new NBTTagCompound(); - test.setTag( "#" + slot.getSlotIndex(), tags ); - if (testSize(test)) - break; - } - } + for (final ItemStack is : list) { + final NBTTagCompound tag = new NBTTagCompound(); + is.writeToNBT(tag); + tags.appendTag(tag); + if (limited) { + final NBTTagCompound test = new NBTTagCompound(); + test.setTag("#" + slot.getSlotIndex(), tags); + if (testSize(test)) break; + } + } - recipe.setTag( "#" + slot.getSlotIndex(), tags ); - break; - } - } - } - } - } - return recipe; - } + recipe.setTag("#" + slot.getSlotIndex(), tags); + break; + } + } + } + } + } + return recipe; + } } diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIFacadeRecipeHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIFacadeRecipeHandler.java index 76a98b9a28d..88236410514 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIFacadeRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIFacadeRecipeHandler.java @@ -18,7 +18,6 @@ package appeng.integration.modules.NEIHelpers; - import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; import appeng.api.definitions.IItemDefinition; @@ -32,216 +31,177 @@ import codechicken.nei.api.IStackPositioner; import codechicken.nei.recipe.RecipeInfo; import codechicken.nei.recipe.TemplateRecipeHandler; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.gui.inventory.GuiCrafting; import net.minecraft.inventory.Container; import net.minecraft.item.ItemStack; -import java.awt.*; -import java.util.ArrayList; -import java.util.List; - - -public class NEIFacadeRecipeHandler extends TemplateRecipeHandler -{ - private final ItemFacade facade; - private final IItemDefinition anchorDefinition; - - public NEIFacadeRecipeHandler() - { - final IDefinitions definitions = AEApi.instance().definitions(); - - this.facade = (ItemFacade) definitions.items().facade().maybeItem().get(); - this.anchorDefinition = definitions.parts().cableAnchor(); - } - - @Override - public void loadTransferRects() - { - this.transferRects.add( new TemplateRecipeHandler.RecipeTransferRect( new Rectangle( 84, 23, 24, 18 ), "crafting" ) ); - } - - @Override - public void loadCraftingRecipes( final String outputId, final Object... results ) - { - if( ( outputId.equals( "crafting" ) ) && ( this.getClass() == NEIFacadeRecipeHandler.class ) ) - { - final List facades = this.facade.getFacades(); - for( final ItemStack anchorStack : this.anchorDefinition.maybeStack( 1 ).asSet() ) - { - for( final ItemStack is : facades ) - { - final CachedShapedRecipe recipe = new CachedShapedRecipe( this.facade, anchorStack, is ); - recipe.computeVisuals(); - this.arecipes.add( recipe ); - } - } - } - else - { - super.loadCraftingRecipes( outputId, results ); - } - } - - @Override - public void loadCraftingRecipes( final ItemStack result ) - { - if( result.getItem() == this.facade ) - { - for( final ItemStack anchorStack : this.anchorDefinition.maybeStack( 1 ).asSet() ) - { - final CachedShapedRecipe recipe = new CachedShapedRecipe( this.facade, anchorStack, result ); - recipe.computeVisuals(); - this.arecipes.add( recipe ); - } - } - } - - @Override - public void loadUsageRecipes( final ItemStack ingredient ) - { - final List facades = this.facade.getFacades(); - for( final ItemStack anchorStack : this.anchorDefinition.maybeStack( 1 ).asSet() ) - { - for( final ItemStack is : facades ) - { - final CachedShapedRecipe recipe = new CachedShapedRecipe( this.facade, anchorStack, is ); - - if( recipe.contains( recipe.ingredients, ingredient.getItem() ) ) - { - recipe.computeVisuals(); - if( recipe.contains( recipe.ingredients, ingredient ) ) - { - recipe.setIngredientPermutation( recipe.ingredients, ingredient ); - this.arecipes.add( recipe ); - } - } - } - } - } - - @Override - public String getGuiTexture() - { - return "textures/gui/container/crafting_table.png"; - } - - @Override - public String getOverlayIdentifier() - { - return "AEFacadeCrafting"; - } - - @Override - public Class getGuiClass() - { - return GuiCrafting.class; - } - - @Override - public boolean hasOverlay( final GuiContainer gui, final Container container, final int recipe ) - { - return ( super.hasOverlay( gui, container, recipe ) ) || ( ( this.isRecipe2x2( recipe ) ) && ( RecipeInfo.hasDefaultOverlay( gui, "crafting2x2" ) ) ); - } - - @Override - public IRecipeOverlayRenderer getOverlayRenderer( final GuiContainer gui, final int recipe ) - { - final IRecipeOverlayRenderer renderer = super.getOverlayRenderer( gui, recipe ); - if( renderer != null ) - { - return renderer; - } - - final IStackPositioner positioner = RecipeInfo.getStackPositioner( gui, "crafting2x2" ); - if( positioner == null ) - { - return null; - } - - return new DefaultOverlayRenderer( this.getIngredientStacks( recipe ), positioner ); - } - - @Override - public IOverlayHandler getOverlayHandler( final GuiContainer gui, final int recipe ) - { - final IOverlayHandler handler = super.getOverlayHandler( gui, recipe ); - if( handler != null ) - { - return handler; - } - - return RecipeInfo.getOverlayHandler( gui, "crafting2x2" ); - } - - private boolean isRecipe2x2( final int recipe ) - { - for( final PositionedStack stack : this.getIngredientStacks( recipe ) ) - { - if( ( stack.relx > 43 ) || ( stack.rely > 24 ) ) - { - return false; - } - } - return true; - } - - @Override - public String getRecipeName() - { - return GuiText.FacadeCrafting.getLocal(); - } - - private final class CachedShapedRecipe extends TemplateRecipeHandler.CachedRecipe - { - public final List ingredients; - public final PositionedStack result; - - public CachedShapedRecipe( final IFacadeItem facade, final ItemStack anchor, final ItemStack output ) - { - output.stackSize = 4; - this.result = new PositionedStack( output, 119, 24 ); - this.ingredients = new ArrayList(); - final ItemStack in = facade.getTextureItem( output ); - this.setIngredients( 3, 3, new Object[] { null, anchor, null, anchor, in, anchor, null, anchor, null } ); - } - - public void setIngredients( final int width, final int height, final Object[] items ) - { - for( int x = 0; x < width; x++ ) - { - for( int y = 0; y < height; y++ ) - { - if( items[( y * width + x )] != null ) - { - final ItemStack is = (ItemStack) items[( y * width + x )]; - final PositionedStack stack = new PositionedStack( is, 25 + x * 18, 6 + y * 18, false ); - stack.setMaxSize( 1 ); - this.ingredients.add( stack ); - } - } - } - } - - @Override - public PositionedStack getResult() - { - return this.result; - } - - @Override - public List getIngredients() - { - return this.getCycledIngredients( NEIFacadeRecipeHandler.this.cycleticks / 20, this.ingredients ); - } - - public void computeVisuals() - { - for( final PositionedStack p : this.ingredients ) - { - p.generatePermutations(); - } - this.result.generatePermutations(); - } - } -} \ No newline at end of file +public class NEIFacadeRecipeHandler extends TemplateRecipeHandler { + private final ItemFacade facade; + private final IItemDefinition anchorDefinition; + + public NEIFacadeRecipeHandler() { + final IDefinitions definitions = AEApi.instance().definitions(); + + this.facade = (ItemFacade) definitions.items().facade().maybeItem().get(); + this.anchorDefinition = definitions.parts().cableAnchor(); + } + + @Override + public void loadTransferRects() { + this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect(new Rectangle(84, 23, 24, 18), "crafting")); + } + + @Override + public void loadCraftingRecipes(final String outputId, final Object... results) { + if ((outputId.equals("crafting")) && (this.getClass() == NEIFacadeRecipeHandler.class)) { + final List facades = this.facade.getFacades(); + for (final ItemStack anchorStack : + this.anchorDefinition.maybeStack(1).asSet()) { + for (final ItemStack is : facades) { + final CachedShapedRecipe recipe = new CachedShapedRecipe(this.facade, anchorStack, is); + recipe.computeVisuals(); + this.arecipes.add(recipe); + } + } + } else { + super.loadCraftingRecipes(outputId, results); + } + } + + @Override + public void loadCraftingRecipes(final ItemStack result) { + if (result.getItem() == this.facade) { + for (final ItemStack anchorStack : + this.anchorDefinition.maybeStack(1).asSet()) { + final CachedShapedRecipe recipe = new CachedShapedRecipe(this.facade, anchorStack, result); + recipe.computeVisuals(); + this.arecipes.add(recipe); + } + } + } + + @Override + public void loadUsageRecipes(final ItemStack ingredient) { + final List facades = this.facade.getFacades(); + for (final ItemStack anchorStack : this.anchorDefinition.maybeStack(1).asSet()) { + for (final ItemStack is : facades) { + final CachedShapedRecipe recipe = new CachedShapedRecipe(this.facade, anchorStack, is); + + if (recipe.contains(recipe.ingredients, ingredient.getItem())) { + recipe.computeVisuals(); + if (recipe.contains(recipe.ingredients, ingredient)) { + recipe.setIngredientPermutation(recipe.ingredients, ingredient); + this.arecipes.add(recipe); + } + } + } + } + } + + @Override + public String getGuiTexture() { + return "textures/gui/container/crafting_table.png"; + } + + @Override + public String getOverlayIdentifier() { + return "AEFacadeCrafting"; + } + + @Override + public Class getGuiClass() { + return GuiCrafting.class; + } + + @Override + public boolean hasOverlay(final GuiContainer gui, final Container container, final int recipe) { + return (super.hasOverlay(gui, container, recipe)) + || ((this.isRecipe2x2(recipe)) && (RecipeInfo.hasDefaultOverlay(gui, "crafting2x2"))); + } + + @Override + public IRecipeOverlayRenderer getOverlayRenderer(final GuiContainer gui, final int recipe) { + final IRecipeOverlayRenderer renderer = super.getOverlayRenderer(gui, recipe); + if (renderer != null) { + return renderer; + } + + final IStackPositioner positioner = RecipeInfo.getStackPositioner(gui, "crafting2x2"); + if (positioner == null) { + return null; + } + + return new DefaultOverlayRenderer(this.getIngredientStacks(recipe), positioner); + } + + @Override + public IOverlayHandler getOverlayHandler(final GuiContainer gui, final int recipe) { + final IOverlayHandler handler = super.getOverlayHandler(gui, recipe); + if (handler != null) { + return handler; + } + + return RecipeInfo.getOverlayHandler(gui, "crafting2x2"); + } + + private boolean isRecipe2x2(final int recipe) { + for (final PositionedStack stack : this.getIngredientStacks(recipe)) { + if ((stack.relx > 43) || (stack.rely > 24)) { + return false; + } + } + return true; + } + + @Override + public String getRecipeName() { + return GuiText.FacadeCrafting.getLocal(); + } + + private final class CachedShapedRecipe extends TemplateRecipeHandler.CachedRecipe { + public final List ingredients; + public final PositionedStack result; + + public CachedShapedRecipe(final IFacadeItem facade, final ItemStack anchor, final ItemStack output) { + output.stackSize = 4; + this.result = new PositionedStack(output, 119, 24); + this.ingredients = new ArrayList(); + final ItemStack in = facade.getTextureItem(output); + this.setIngredients(3, 3, new Object[] {null, anchor, null, anchor, in, anchor, null, anchor, null}); + } + + public void setIngredients(final int width, final int height, final Object[] items) { + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + if (items[(y * width + x)] != null) { + final ItemStack is = (ItemStack) items[(y * width + x)]; + final PositionedStack stack = new PositionedStack(is, 25 + x * 18, 6 + y * 18, false); + stack.setMaxSize(1); + this.ingredients.add(stack); + } + } + } + } + + @Override + public PositionedStack getResult() { + return this.result; + } + + @Override + public List getIngredients() { + return this.getCycledIngredients(NEIFacadeRecipeHandler.this.cycleticks / 20, this.ingredients); + } + + public void computeVisuals() { + for (final PositionedStack p : this.ingredients) { + p.generatePermutations(); + } + this.result.generatePermutations(); + } + } +} diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIGrinderRecipeHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIGrinderRecipeHandler.java index 7cbefc200f2..519bb959eec 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIGrinderRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIGrinderRecipeHandler.java @@ -18,18 +18,20 @@ package appeng.integration.modules.NEIHelpers; - import appeng.api.AEApi; import appeng.api.features.IGrinderEntry; import appeng.client.gui.implementations.GuiGrinder; -import appeng.core.localization.GuiText; import appeng.core.localization.GuiColors; +import appeng.core.localization.GuiText; import codechicken.lib.gui.GuiDraw; import codechicken.nei.NEIServerUtils; import codechicken.nei.PositionedStack; import codechicken.nei.api.IOverlayHandler; import codechicken.nei.api.IRecipeOverlayRenderer; import codechicken.nei.recipe.TemplateRecipeHandler; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.inventory.GuiContainer; @@ -38,204 +40,175 @@ import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; -import java.awt.*; -import java.util.ArrayList; -import java.util.List; - - -public class NEIGrinderRecipeHandler extends TemplateRecipeHandler -{ - - @Override - public void loadTransferRects() - { - this.transferRects.add( new TemplateRecipeHandler.RecipeTransferRect( new Rectangle( 84, 23, 24, 18 ), "grindstone" ) ); - } - - @Override - public void loadCraftingRecipes( final String outputId, final Object... results ) - { - if( ( outputId.equals( "grindstone" ) ) && ( this.getClass() == NEIGrinderRecipeHandler.class ) ) - { - for( final IGrinderEntry recipe : AEApi.instance().registries().grinder().getRecipes() ) - { - final CachedGrindStoneRecipe cachedRecipe = new CachedGrindStoneRecipe( recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - else - { - super.loadCraftingRecipes( outputId, results ); - } - } - - @Override - public void loadCraftingRecipes( final ItemStack result ) - { - for( final IGrinderEntry recipe : AEApi.instance().registries().grinder().getRecipes() ) - { - if( NEIServerUtils.areStacksSameTypeCrafting( recipe.getOutput(), result ) ) - { - final CachedGrindStoneRecipe cachedRecipe = new CachedGrindStoneRecipe( recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - } - - @Override - public void loadUsageRecipes( final ItemStack ingredient ) - { - for( final IGrinderEntry recipe : AEApi.instance().registries().grinder().getRecipes() ) - { - final CachedGrindStoneRecipe cachedRecipe = new CachedGrindStoneRecipe( recipe ); - - if( ( cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) ) - { - cachedRecipe.computeVisuals(); - if( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) - { - cachedRecipe.setIngredientPermutation( cachedRecipe.ingredients, ingredient ); - this.arecipes.add( cachedRecipe ); - } - } - } - } - - @Override - public String getGuiTexture() - { - final ResourceLocation loc = new ResourceLocation( "appliedenergistics2", "textures/guis/grinder.png" ); - - return loc.toString(); - } - - @Override - public String getOverlayIdentifier() - { - return "grindstone"; - } - - @Override - public Class getGuiClass() - { - return GuiGrinder.class; - } - - @Override - public void drawBackground( final int recipe ) - { - GL11.glColor4f( 1, 1, 1, 1 ); - GuiDraw.changeTexture( this.getGuiTexture() ); - GuiDraw.drawTexturedModalRect( 40, 10, 75, 16 + 10, 90, 66 ); - } - - @Override - public void drawForeground( final int recipe ) - { - super.drawForeground( recipe ); - if( this.arecipes.size() > recipe ) - { - final CachedRecipe cr = this.arecipes.get( recipe ); - if( cr instanceof CachedGrindStoneRecipe ) - { - final CachedGrindStoneRecipe cachedRecipe = (CachedGrindStoneRecipe) cr; - if( cachedRecipe.hasOptional ) - { - final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - final int width = fr.getStringWidth( cachedRecipe.displayChance ); - fr.drawString( cachedRecipe.displayChance, ( 168 - width ) / 2, 5, GuiColors.NEIGrindstoneRecipeChance.getColor() ); - } - else - { - final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - final int width = fr.getStringWidth( GuiText.NoSecondOutput.getLocal() ); - fr.drawString( GuiText.NoSecondOutput.getLocal(), ( 168 - width ) / 2, 5, GuiColors.NEIGrindstoneNoSecondOutput.getColor() ); - } - } - } - } - - @Override - public boolean hasOverlay( final GuiContainer gui, final Container container, final int recipe ) - { - return false; - } - - @Override - public IRecipeOverlayRenderer getOverlayRenderer( final GuiContainer gui, final int recipe ) - { - return null; - } - - @Override - public IOverlayHandler getOverlayHandler( final GuiContainer gui, final int recipe ) - { - return null; - } - - @Override - public String getRecipeName() - { - return GuiText.GrindStone.getLocal(); - } - - private class CachedGrindStoneRecipe extends TemplateRecipeHandler.CachedRecipe - { - private final List ingredients; - private final PositionedStack result; - private String displayChance; - private boolean hasOptional = false; - - public CachedGrindStoneRecipe( final IGrinderEntry recipe ) - { - this.result = new PositionedStack( recipe.getOutput(), -30 + 107, 47 ); - this.ingredients = new ArrayList(); - - final ItemStack optionalOutput = recipe.getOptionalOutput(); - final int optionalChancePercent = (int) ( recipe.getOptionalChance() * 100 ); - if( optionalOutput != null ) - { - this.hasOptional = true; - this.displayChance = String.format( GuiText.OfSecondOutput.getLocal(), optionalChancePercent ); - this.ingredients.add( new PositionedStack( optionalOutput, -30 + 107 + 18, 47 ) ); - } - - final ItemStack secondOptionalOutput = recipe.getSecondOptionalOutput(); - final int secondOptionalChancePercent = (int) ( recipe.getSecondOptionalChance() * 100 ); - if( secondOptionalOutput != null ) - { - this.hasOptional = true; - this.displayChance = String.format( GuiText.MultipleOutputs.getLocal(), optionalChancePercent, secondOptionalChancePercent ); - this.ingredients.add( new PositionedStack( secondOptionalOutput, -30 + 107 + 18 + 18, 47 ) ); - } - - if( recipe.getInput() != null ) - { - this.ingredients.add( new PositionedStack( recipe.getInput(), 45, 24 ) ); - } - } - - @Override - public PositionedStack getResult() - { - return this.result; - } - - @Override - public List getIngredients() - { - return this.getCycledIngredients( NEIGrinderRecipeHandler.this.cycleticks / 20, this.ingredients ); - } - - private void computeVisuals() - { - for( final PositionedStack p : this.ingredients ) - { - p.generatePermutations(); - } - this.result.generatePermutations(); - } - } -} \ No newline at end of file +public class NEIGrinderRecipeHandler extends TemplateRecipeHandler { + + @Override + public void loadTransferRects() { + this.transferRects.add( + new TemplateRecipeHandler.RecipeTransferRect(new Rectangle(84, 23, 24, 18), "grindstone")); + } + + @Override + public void loadCraftingRecipes(final String outputId, final Object... results) { + if ((outputId.equals("grindstone")) && (this.getClass() == NEIGrinderRecipeHandler.class)) { + for (final IGrinderEntry recipe : + AEApi.instance().registries().grinder().getRecipes()) { + final CachedGrindStoneRecipe cachedRecipe = new CachedGrindStoneRecipe(recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } else { + super.loadCraftingRecipes(outputId, results); + } + } + + @Override + public void loadCraftingRecipes(final ItemStack result) { + for (final IGrinderEntry recipe : + AEApi.instance().registries().grinder().getRecipes()) { + if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getOutput(), result)) { + final CachedGrindStoneRecipe cachedRecipe = new CachedGrindStoneRecipe(recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } + } + + @Override + public void loadUsageRecipes(final ItemStack ingredient) { + for (final IGrinderEntry recipe : + AEApi.instance().registries().grinder().getRecipes()) { + final CachedGrindStoneRecipe cachedRecipe = new CachedGrindStoneRecipe(recipe); + + if ((cachedRecipe.contains(cachedRecipe.ingredients, ingredient.getItem()))) { + cachedRecipe.computeVisuals(); + if (cachedRecipe.contains(cachedRecipe.ingredients, ingredient)) { + cachedRecipe.setIngredientPermutation(cachedRecipe.ingredients, ingredient); + this.arecipes.add(cachedRecipe); + } + } + } + } + + @Override + public String getGuiTexture() { + final ResourceLocation loc = new ResourceLocation("appliedenergistics2", "textures/guis/grinder.png"); + + return loc.toString(); + } + + @Override + public String getOverlayIdentifier() { + return "grindstone"; + } + + @Override + public Class getGuiClass() { + return GuiGrinder.class; + } + + @Override + public void drawBackground(final int recipe) { + GL11.glColor4f(1, 1, 1, 1); + GuiDraw.changeTexture(this.getGuiTexture()); + GuiDraw.drawTexturedModalRect(40, 10, 75, 16 + 10, 90, 66); + } + + @Override + public void drawForeground(final int recipe) { + super.drawForeground(recipe); + if (this.arecipes.size() > recipe) { + final CachedRecipe cr = this.arecipes.get(recipe); + if (cr instanceof CachedGrindStoneRecipe) { + final CachedGrindStoneRecipe cachedRecipe = (CachedGrindStoneRecipe) cr; + if (cachedRecipe.hasOptional) { + final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + final int width = fr.getStringWidth(cachedRecipe.displayChance); + fr.drawString( + cachedRecipe.displayChance, + (168 - width) / 2, + 5, + GuiColors.NEIGrindstoneRecipeChance.getColor()); + } else { + final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + final int width = fr.getStringWidth(GuiText.NoSecondOutput.getLocal()); + fr.drawString( + GuiText.NoSecondOutput.getLocal(), + (168 - width) / 2, + 5, + GuiColors.NEIGrindstoneNoSecondOutput.getColor()); + } + } + } + } + + @Override + public boolean hasOverlay(final GuiContainer gui, final Container container, final int recipe) { + return false; + } + + @Override + public IRecipeOverlayRenderer getOverlayRenderer(final GuiContainer gui, final int recipe) { + return null; + } + + @Override + public IOverlayHandler getOverlayHandler(final GuiContainer gui, final int recipe) { + return null; + } + + @Override + public String getRecipeName() { + return GuiText.GrindStone.getLocal(); + } + + private class CachedGrindStoneRecipe extends TemplateRecipeHandler.CachedRecipe { + private final List ingredients; + private final PositionedStack result; + private String displayChance; + private boolean hasOptional = false; + + public CachedGrindStoneRecipe(final IGrinderEntry recipe) { + this.result = new PositionedStack(recipe.getOutput(), -30 + 107, 47); + this.ingredients = new ArrayList(); + + final ItemStack optionalOutput = recipe.getOptionalOutput(); + final int optionalChancePercent = (int) (recipe.getOptionalChance() * 100); + if (optionalOutput != null) { + this.hasOptional = true; + this.displayChance = String.format(GuiText.OfSecondOutput.getLocal(), optionalChancePercent); + this.ingredients.add(new PositionedStack(optionalOutput, -30 + 107 + 18, 47)); + } + + final ItemStack secondOptionalOutput = recipe.getSecondOptionalOutput(); + final int secondOptionalChancePercent = (int) (recipe.getSecondOptionalChance() * 100); + if (secondOptionalOutput != null) { + this.hasOptional = true; + this.displayChance = String.format( + GuiText.MultipleOutputs.getLocal(), optionalChancePercent, secondOptionalChancePercent); + this.ingredients.add(new PositionedStack(secondOptionalOutput, -30 + 107 + 18 + 18, 47)); + } + + if (recipe.getInput() != null) { + this.ingredients.add(new PositionedStack(recipe.getInput(), 45, 24)); + } + } + + @Override + public PositionedStack getResult() { + return this.result; + } + + @Override + public List getIngredients() { + return this.getCycledIngredients(NEIGrinderRecipeHandler.this.cycleticks / 20, this.ingredients); + } + + private void computeVisuals() { + for (final PositionedStack p : this.ingredients) { + p.generatePermutations(); + } + this.result.generatePermutations(); + } + } +} diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIGuiHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIGuiHandler.java index 73fef68747e..14a9fe1f0f1 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIGuiHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIGuiHandler.java @@ -5,40 +5,36 @@ import appeng.client.gui.implementations.GuiMEMonitorable; import appeng.client.gui.widgets.IDropToFillTextField; import codechicken.nei.api.INEIGuiAdapter; +import java.util.regex.Pattern; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumChatFormatting; -import java.util.regex.Pattern; - -public class NEIGuiHandler extends INEIGuiAdapter -{ +public class NEIGuiHandler extends INEIGuiAdapter { protected static final Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]"); @Override - public boolean handleDragNDrop(GuiContainer gui, int mousex, int mousey, ItemStack draggedStack, int button) - { + public boolean handleDragNDrop(GuiContainer gui, int mousex, int mousey, ItemStack draggedStack, int button) { if (draggedStack != null && draggedStack.getItem() != null && gui instanceof IDropToFillTextField) { - IDropToFillTextField gmm = (IDropToFillTextField)gui; + IDropToFillTextField gmm = (IDropToFillTextField) gui; if (gmm.isOverTextField(mousex, mousey)) { - gmm.setTextFieldValue(formattingText(draggedStack.getDisplayName()), mousex, mousey, draggedStack.copy()); + gmm.setTextFieldValue( + formattingText(draggedStack.getDisplayName()), mousex, mousey, draggedStack.copy()); return true; } - } return super.handleDragNDrop(gui, mousex, mousey, draggedStack, button); } @Override - public boolean hideItemPanelSlot( GuiContainer gui, int x, int y, int w, int h ) - { + public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h) { if (gui instanceof GuiCraftingStatus) { return ((GuiCraftingStatus) gui).hideItemPanelSlot(x, y, w, h); - } else if (gui instanceof GuiCraftConfirm ) { + } else if (gui instanceof GuiCraftConfirm) { return ((GuiCraftConfirm) gui).hideItemPanelSlot(x, y, w, h); } else if (gui instanceof GuiMEMonitorable) { return ((GuiMEMonitorable) gui).hideItemPanelSlot(x, y, w, h); @@ -47,9 +43,9 @@ public boolean hideItemPanelSlot( GuiContainer gui, int x, int y, int w, int h ) return false; } - private String formattingText(final String displayName) - { - return SPECIAL_REGEX_CHARS.matcher(EnumChatFormatting.getTextWithoutFormattingCodes(displayName)).replaceAll("\\\\$0"); + private String formattingText(final String displayName) { + return SPECIAL_REGEX_CHARS + .matcher(EnumChatFormatting.getTextWithoutFormattingCodes(displayName)) + .replaceAll("\\\\$0"); } - } diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIInscriberRecipeHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIInscriberRecipeHandler.java index 9ff755e98b4..41f40805471 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIInscriberRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIInscriberRecipeHandler.java @@ -18,7 +18,6 @@ package appeng.integration.modules.NEIHelpers; - import appeng.api.AEApi; import appeng.api.features.IInscriberRecipe; import appeng.client.gui.implementations.GuiInscriber; @@ -29,177 +28,149 @@ import codechicken.nei.api.IOverlayHandler; import codechicken.nei.api.IRecipeOverlayRenderer; import codechicken.nei.recipe.TemplateRecipeHandler; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.inventory.Container; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; -import java.awt.*; -import java.util.ArrayList; -import java.util.List; - - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class NEIInscriberRecipeHandler extends TemplateRecipeHandler -{ - - @Override - public void loadTransferRects() - { - this.transferRects.add( new TemplateRecipeHandler.RecipeTransferRect( new Rectangle( 84, 23, 24, 18 ), "inscriber" ) ); - } - - @Override - public void loadCraftingRecipes( final String outputId, final Object... results ) - { - if( ( outputId.equals( "inscriber" ) ) && ( this.getClass() == NEIInscriberRecipeHandler.class ) ) - { - for( final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes() ) - { - final CachedInscriberRecipe cachedRecipe = new CachedInscriberRecipe( recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - else - { - super.loadCraftingRecipes( outputId, results ); - } - } - - @Override - public void loadCraftingRecipes( final ItemStack result ) - { - for( final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes() ) - { - if( NEIServerUtils.areStacksSameTypeCrafting( recipe.getOutput(), result ) ) - { - final CachedInscriberRecipe cachedRecipe = new CachedInscriberRecipe( recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - } - - @Override - public void loadUsageRecipes( final ItemStack ingredient ) - { - for( final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes() ) - { - final CachedInscriberRecipe cachedRecipe = new CachedInscriberRecipe( recipe ); - - if( ( cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) ) - { - cachedRecipe.computeVisuals(); - if( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) - { - cachedRecipe.setIngredientPermutation( cachedRecipe.ingredients, ingredient ); - this.arecipes.add( cachedRecipe ); - } - } - } - } - - @Override - public String getGuiTexture() - { - final ResourceLocation loc = new ResourceLocation( "appliedenergistics2", "textures/guis/inscriber.png" ); - return loc.toString(); - } - - @Override - public String getOverlayIdentifier() - { - return "inscriber"; - } - - @Override - public Class getGuiClass() - { - return GuiInscriber.class; - } - - @Override - public void drawBackground( final int recipe ) - { - GL11.glColor4f( 1, 1, 1, 1 ); - GuiDraw.changeTexture( this.getGuiTexture() ); - GuiDraw.drawTexturedModalRect( 0, 0, 5, 11, 166, 75 ); - } - - @Override - public boolean hasOverlay( final GuiContainer gui, final Container container, final int recipe ) - { - return false; - } - - @Override - public IRecipeOverlayRenderer getOverlayRenderer( final GuiContainer gui, final int recipe ) - { - return null; - } - - @Override - public IOverlayHandler getOverlayHandler( final GuiContainer gui, final int recipe ) - { - return null; - } - - @Override - public String getRecipeName() - { - return GuiText.Inscriber.getLocal(); - } - - private class CachedInscriberRecipe extends TemplateRecipeHandler.CachedRecipe - { - - private final List ingredients; - private final PositionedStack result; - - public CachedInscriberRecipe( final IInscriberRecipe recipe ) - { - this.result = new PositionedStack( recipe.getOutput(), 108, 29 ); - this.ingredients = new ArrayList(); - - for( final ItemStack top : recipe.getTopOptional().asSet() ) - { - this.ingredients.add( new PositionedStack( top, 40, 5 ) ); - } - - this.ingredients.add( new PositionedStack( recipe.getInputs(), 40 + 18, 28 ) ); - - for( final ItemStack bot : recipe.getBottomOptional().asSet() ) - { - this.ingredients.add( new PositionedStack( bot, 40, 51 ) ); - } - } - - @Override - public PositionedStack getResult() - { - return this.result; - } - - @Override - public List getIngredients() - { - return this.getCycledIngredients( NEIInscriberRecipeHandler.this.cycleticks / 20, this.ingredients ); - } - - private void computeVisuals() - { - for( final PositionedStack p : this.ingredients ) - { - p.generatePermutations(); - } - this.result.generatePermutations(); - } - } -} \ No newline at end of file +public class NEIInscriberRecipeHandler extends TemplateRecipeHandler { + + @Override + public void loadTransferRects() { + this.transferRects.add( + new TemplateRecipeHandler.RecipeTransferRect(new Rectangle(84, 23, 24, 18), "inscriber")); + } + + @Override + public void loadCraftingRecipes(final String outputId, final Object... results) { + if ((outputId.equals("inscriber")) && (this.getClass() == NEIInscriberRecipeHandler.class)) { + for (final IInscriberRecipe recipe : + AEApi.instance().registries().inscriber().getRecipes()) { + final CachedInscriberRecipe cachedRecipe = new CachedInscriberRecipe(recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } else { + super.loadCraftingRecipes(outputId, results); + } + } + + @Override + public void loadCraftingRecipes(final ItemStack result) { + for (final IInscriberRecipe recipe : + AEApi.instance().registries().inscriber().getRecipes()) { + if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getOutput(), result)) { + final CachedInscriberRecipe cachedRecipe = new CachedInscriberRecipe(recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } + } + + @Override + public void loadUsageRecipes(final ItemStack ingredient) { + for (final IInscriberRecipe recipe : + AEApi.instance().registries().inscriber().getRecipes()) { + final CachedInscriberRecipe cachedRecipe = new CachedInscriberRecipe(recipe); + + if ((cachedRecipe.contains(cachedRecipe.ingredients, ingredient.getItem()))) { + cachedRecipe.computeVisuals(); + if (cachedRecipe.contains(cachedRecipe.ingredients, ingredient)) { + cachedRecipe.setIngredientPermutation(cachedRecipe.ingredients, ingredient); + this.arecipes.add(cachedRecipe); + } + } + } + } + + @Override + public String getGuiTexture() { + final ResourceLocation loc = new ResourceLocation("appliedenergistics2", "textures/guis/inscriber.png"); + return loc.toString(); + } + + @Override + public String getOverlayIdentifier() { + return "inscriber"; + } + + @Override + public Class getGuiClass() { + return GuiInscriber.class; + } + + @Override + public void drawBackground(final int recipe) { + GL11.glColor4f(1, 1, 1, 1); + GuiDraw.changeTexture(this.getGuiTexture()); + GuiDraw.drawTexturedModalRect(0, 0, 5, 11, 166, 75); + } + + @Override + public boolean hasOverlay(final GuiContainer gui, final Container container, final int recipe) { + return false; + } + + @Override + public IRecipeOverlayRenderer getOverlayRenderer(final GuiContainer gui, final int recipe) { + return null; + } + + @Override + public IOverlayHandler getOverlayHandler(final GuiContainer gui, final int recipe) { + return null; + } + + @Override + public String getRecipeName() { + return GuiText.Inscriber.getLocal(); + } + + private class CachedInscriberRecipe extends TemplateRecipeHandler.CachedRecipe { + + private final List ingredients; + private final PositionedStack result; + + public CachedInscriberRecipe(final IInscriberRecipe recipe) { + this.result = new PositionedStack(recipe.getOutput(), 108, 29); + this.ingredients = new ArrayList(); + + for (final ItemStack top : recipe.getTopOptional().asSet()) { + this.ingredients.add(new PositionedStack(top, 40, 5)); + } + + this.ingredients.add(new PositionedStack(recipe.getInputs(), 40 + 18, 28)); + + for (final ItemStack bot : recipe.getBottomOptional().asSet()) { + this.ingredients.add(new PositionedStack(bot, 40, 51)); + } + } + + @Override + public PositionedStack getResult() { + return this.result; + } + + @Override + public List getIngredients() { + return this.getCycledIngredients(NEIInscriberRecipeHandler.this.cycleticks / 20, this.ingredients); + } + + private void computeVisuals() { + for (final PositionedStack p : this.ingredients) { + p.generatePermutations(); + } + this.result.generatePermutations(); + } + } +} diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIWorldCraftingHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIWorldCraftingHandler.java index 1f2d1689fff..eb85dcb579d 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIWorldCraftingHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIWorldCraftingHandler.java @@ -18,7 +18,6 @@ package appeng.integration.modules.NEIHelpers; - import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; import appeng.api.definitions.IItemDefinition; @@ -33,6 +32,7 @@ import codechicken.nei.recipe.GuiRecipe; import codechicken.nei.recipe.ICraftingHandler; import codechicken.nei.recipe.IUsageHandler; +import java.util.*; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.inventory.GuiContainer; @@ -40,208 +40,166 @@ import net.minecraft.item.ItemStack; import org.lwjgl.opengl.GL11; -import java.util.*; - - -public class NEIWorldCraftingHandler implements ICraftingHandler, IUsageHandler -{ - - private final Map details = new HashMap(); - private final List offsets = new LinkedList(); - private final List outputs = new LinkedList(); - - private ItemStack target; - - @Override - public String getRecipeName() - { - return GuiText.InWorldCrafting.getLocal(); - } - - @Override - public int numRecipes() - { - return this.offsets.size(); - } - - @Override - public void drawBackground( final int recipe ) - { - GL11.glColor4f( 1, 1, 1, 1 );// nothing. - } - - @Override - public void drawForeground( final int recipe ) - { - if( this.outputs.size() > recipe ) - { - // PositionedStack cr = this.outputs.get( recipe ); - final String details = this.details.get( this.offsets.get( recipe ) ); - - final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - fr.drawSplitString( details, 10, 25, 150, 0 ); - } - } - - @Override - public List getIngredientStacks( final int recipeIndex ) - { - return new ArrayList(); - } - - @Override - public List getOtherStacks( final int recipeIndex ) - { - return new ArrayList(); - } - - @Override - public PositionedStack getResultStack( final int recipe ) - { - return this.outputs.get( recipe ); - } - - @Override - public void onUpdate() - { - - } - - @Override - public boolean hasOverlay( final GuiContainer gui, final Container container, final int recipe ) - { - return false; - } - - @Override - public IRecipeOverlayRenderer getOverlayRenderer( final GuiContainer gui, final int recipe ) - { - return null; - } - - @Override - public IOverlayHandler getOverlayHandler( final GuiContainer gui, final int recipe ) - { - return null; - } - - @Override - public int recipiesPerPage() - { - return 1; - } - - @Override - public List handleTooltip( final GuiRecipe gui, final List currentToolTip, final int recipe ) - { - return currentToolTip; - } - - @Override - public List handleItemTooltip( final GuiRecipe gui, final ItemStack stack, final List currentToolTip, final int recipe ) - { - return currentToolTip; - } - - @Override - public boolean keyTyped( final GuiRecipe gui, final char keyChar, final int keyCode, final int recipe ) - { - return false; - } - - @Override - public boolean mouseClicked( final GuiRecipe gui, final int button, final int recipe ) - { - return false; - } - - @Override - public IUsageHandler getUsageHandler( final String inputId, final Object... ingredients ) - { - return this; - } - - @Override - public ICraftingHandler getRecipeHandler( final String outputId, final Object... results ) - { - final NEIWorldCraftingHandler g = this.newInstance(); - if( results.length > 0 && results[0] instanceof ItemStack ) - { - g.target = (ItemStack) results[0]; - g.addRecipes(); - return g; - } - return this; - } - - private NEIWorldCraftingHandler newInstance() - { - try - { - return this.getClass().newInstance(); - } - catch( final InstantiationException e ) - { - throw new IllegalStateException( e ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( e ); - } - } - - private void addRecipes() - { - final IDefinitions definitions = AEApi.instance().definitions(); - final IMaterials materials = definitions.materials(); - - final String message; - if( AEConfig.instance.isFeatureEnabled( AEFeature.CertusQuartzWorldGen ) ) - { - message = GuiText.ChargedQuartz.getLocal() + "\n\n" + GuiText.ChargedQuartzFind.getLocal(); - } - else - { - message = GuiText.ChargedQuartzFind.getLocal(); - } - - this.addRecipe( materials.certusQuartzCrystalCharged(), message ); - - if( AEConfig.instance.isFeatureEnabled( AEFeature.MeteoriteWorldGen ) ) - { - this.addRecipe( materials.logicProcessorPress(), GuiText.inWorldCraftingPresses.getLocal() ); - this.addRecipe( materials.calcProcessorPress(), GuiText.inWorldCraftingPresses.getLocal() ); - this.addRecipe( materials.engProcessorPress(), GuiText.inWorldCraftingPresses.getLocal() ); - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.InWorldFluix ) ) - { - this.addRecipe( materials.fluixCrystal(), GuiText.inWorldFluix.getLocal() ); - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.InWorldSingularity ) ) - { - this.addRecipe( materials.qESingularity(), GuiText.inWorldSingularity.getLocal() ); - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.InWorldPurification ) ) - { - this.addRecipe( materials.purifiedCertusQuartzCrystal(), GuiText.inWorldPurificationCertus.getLocal() ); - this.addRecipe( materials.purifiedNetherQuartzCrystal(), GuiText.inWorldPurificationNether.getLocal() ); - this.addRecipe( materials.purifiedFluixCrystal(), GuiText.inWorldPurificationFluix.getLocal() ); - } - } - - private void addRecipe( final IItemDefinition def, final String msg ) - { - for( final ItemStack definitionStack : def.maybeStack( 1 ).asSet() ) - { - if( NEIServerUtils.areStacksSameTypeCrafting( definitionStack, this.target ) ) - { - this.offsets.add( def ); - this.outputs.add( new PositionedStack( definitionStack, 75, 4 ) ); - this.details.put( def, msg ); - } - } - } -} \ No newline at end of file +public class NEIWorldCraftingHandler implements ICraftingHandler, IUsageHandler { + + private final Map details = new HashMap(); + private final List offsets = new LinkedList(); + private final List outputs = new LinkedList(); + + private ItemStack target; + + @Override + public String getRecipeName() { + return GuiText.InWorldCrafting.getLocal(); + } + + @Override + public int numRecipes() { + return this.offsets.size(); + } + + @Override + public void drawBackground(final int recipe) { + GL11.glColor4f(1, 1, 1, 1); // nothing. + } + + @Override + public void drawForeground(final int recipe) { + if (this.outputs.size() > recipe) { + // PositionedStack cr = this.outputs.get( recipe ); + final String details = this.details.get(this.offsets.get(recipe)); + + final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + fr.drawSplitString(details, 10, 25, 150, 0); + } + } + + @Override + public List getIngredientStacks(final int recipeIndex) { + return new ArrayList(); + } + + @Override + public List getOtherStacks(final int recipeIndex) { + return new ArrayList(); + } + + @Override + public PositionedStack getResultStack(final int recipe) { + return this.outputs.get(recipe); + } + + @Override + public void onUpdate() {} + + @Override + public boolean hasOverlay(final GuiContainer gui, final Container container, final int recipe) { + return false; + } + + @Override + public IRecipeOverlayRenderer getOverlayRenderer(final GuiContainer gui, final int recipe) { + return null; + } + + @Override + public IOverlayHandler getOverlayHandler(final GuiContainer gui, final int recipe) { + return null; + } + + @Override + public int recipiesPerPage() { + return 1; + } + + @Override + public List handleTooltip(final GuiRecipe gui, final List currentToolTip, final int recipe) { + return currentToolTip; + } + + @Override + public List handleItemTooltip( + final GuiRecipe gui, final ItemStack stack, final List currentToolTip, final int recipe) { + return currentToolTip; + } + + @Override + public boolean keyTyped(final GuiRecipe gui, final char keyChar, final int keyCode, final int recipe) { + return false; + } + + @Override + public boolean mouseClicked(final GuiRecipe gui, final int button, final int recipe) { + return false; + } + + @Override + public IUsageHandler getUsageHandler(final String inputId, final Object... ingredients) { + return this; + } + + @Override + public ICraftingHandler getRecipeHandler(final String outputId, final Object... results) { + final NEIWorldCraftingHandler g = this.newInstance(); + if (results.length > 0 && results[0] instanceof ItemStack) { + g.target = (ItemStack) results[0]; + g.addRecipes(); + return g; + } + return this; + } + + private NEIWorldCraftingHandler newInstance() { + try { + return this.getClass().newInstance(); + } catch (final InstantiationException e) { + throw new IllegalStateException(e); + } catch (final IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + + private void addRecipes() { + final IDefinitions definitions = AEApi.instance().definitions(); + final IMaterials materials = definitions.materials(); + + final String message; + if (AEConfig.instance.isFeatureEnabled(AEFeature.CertusQuartzWorldGen)) { + message = GuiText.ChargedQuartz.getLocal() + "\n\n" + GuiText.ChargedQuartzFind.getLocal(); + } else { + message = GuiText.ChargedQuartzFind.getLocal(); + } + + this.addRecipe(materials.certusQuartzCrystalCharged(), message); + + if (AEConfig.instance.isFeatureEnabled(AEFeature.MeteoriteWorldGen)) { + this.addRecipe(materials.logicProcessorPress(), GuiText.inWorldCraftingPresses.getLocal()); + this.addRecipe(materials.calcProcessorPress(), GuiText.inWorldCraftingPresses.getLocal()); + this.addRecipe(materials.engProcessorPress(), GuiText.inWorldCraftingPresses.getLocal()); + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.InWorldFluix)) { + this.addRecipe(materials.fluixCrystal(), GuiText.inWorldFluix.getLocal()); + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.InWorldSingularity)) { + this.addRecipe(materials.qESingularity(), GuiText.inWorldSingularity.getLocal()); + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.InWorldPurification)) { + this.addRecipe(materials.purifiedCertusQuartzCrystal(), GuiText.inWorldPurificationCertus.getLocal()); + this.addRecipe(materials.purifiedNetherQuartzCrystal(), GuiText.inWorldPurificationNether.getLocal()); + this.addRecipe(materials.purifiedFluixCrystal(), GuiText.inWorldPurificationFluix.getLocal()); + } + } + + private void addRecipe(final IItemDefinition def, final String msg) { + for (final ItemStack definitionStack : def.maybeStack(1).asSet()) { + if (NEIServerUtils.areStacksSameTypeCrafting(definitionStack, this.target)) { + this.offsets.add(def); + this.outputs.add(new PositionedStack(definitionStack, 75, 4)); + this.details.put(def, msg); + } + } + } +} diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/TerminalCraftingSlotFinder.java b/src/main/java/appeng/integration/modules/NEIHelpers/TerminalCraftingSlotFinder.java index 737db30ed5a..4598fc2a601 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/TerminalCraftingSlotFinder.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/TerminalCraftingSlotFinder.java @@ -18,28 +18,21 @@ package appeng.integration.modules.NEIHelpers; - import appeng.client.gui.implementations.GuiMEMonitorable; import codechicken.nei.PositionedStack; import codechicken.nei.api.IStackPositioner; - import java.util.ArrayList; +public class TerminalCraftingSlotFinder implements IStackPositioner { -public class TerminalCraftingSlotFinder implements IStackPositioner -{ - - @Override - public ArrayList positionStacks( final ArrayList a ) - { - for( final PositionedStack ps : a ) - { - if( ps != null ) - { - ps.relx += GuiMEMonitorable.craftingGridOffsetX; - ps.rely += GuiMEMonitorable.craftingGridOffsetY; - } - } - return a; - } + @Override + public ArrayList positionStacks(final ArrayList a) { + for (final PositionedStack ps : a) { + if (ps != null) { + ps.relx += GuiMEMonitorable.craftingGridOffsetX; + ps.rely += GuiMEMonitorable.craftingGridOffsetY; + } + } + return a; + } } diff --git a/src/main/java/appeng/integration/modules/OpenComputers.java b/src/main/java/appeng/integration/modules/OpenComputers.java index 3c05fbaa833..faa273e2bc5 100644 --- a/src/main/java/appeng/integration/modules/OpenComputers.java +++ b/src/main/java/appeng/integration/modules/OpenComputers.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.IAppEngApi; import appeng.api.config.TunnelType; @@ -31,47 +30,42 @@ import appeng.integration.IntegrationType; import li.cil.oc.api.Items; +public class OpenComputers implements IIntegrationModule { + @Reflected + public static OpenComputers instance; -public class OpenComputers implements IIntegrationModule -{ - @Reflected - public static OpenComputers instance; - - @Reflected - public OpenComputers() - { - IntegrationHelper.testClassExistence( this, li.cil.oc.api.Items.class ); - IntegrationHelper.testClassExistence( this, li.cil.oc.api.Network.class ); - IntegrationHelper.testClassExistence( this, li.cil.oc.api.network.Environment.class ); - IntegrationHelper.testClassExistence( this, li.cil.oc.api.network.SidedEnvironment.class ); - IntegrationHelper.testClassExistence( this, li.cil.oc.api.network.Node.class ); - IntegrationHelper.testClassExistence( this, li.cil.oc.api.network.Message.class ); - } + @Reflected + public OpenComputers() { + IntegrationHelper.testClassExistence(this, li.cil.oc.api.Items.class); + IntegrationHelper.testClassExistence(this, li.cil.oc.api.Network.class); + IntegrationHelper.testClassExistence(this, li.cil.oc.api.network.Environment.class); + IntegrationHelper.testClassExistence(this, li.cil.oc.api.network.SidedEnvironment.class); + IntegrationHelper.testClassExistence(this, li.cil.oc.api.network.Node.class); + IntegrationHelper.testClassExistence(this, li.cil.oc.api.network.Message.class); + } - @Override - public void init() - { - final IAppEngApi api = AEApi.instance(); - final IPartHelper partHelper = api.partHelper(); + @Override + public void init() { + final IAppEngApi api = AEApi.instance(); + final IPartHelper partHelper = api.partHelper(); - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.OpenComputers ) ) - { - partHelper.registerNewLayer( "appeng.parts.layers.LayerSidedEnvironment", "li.cil.oc.api.network.SidedEnvironment" ); - } - } + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.OpenComputers)) { + partHelper.registerNewLayer( + "appeng.parts.layers.LayerSidedEnvironment", "li.cil.oc.api.network.SidedEnvironment"); + } + } - @Override - public void postInit() - { - final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); + @Override + public void postInit() { + final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); - registry.addNewAttunement( Items.get( "cable" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - registry.addNewAttunement( Items.get( "adapter" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - registry.addNewAttunement( Items.get( "switch" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - registry.addNewAttunement( Items.get( "accessPoint" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - registry.addNewAttunement( Items.get( "lanCard" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - registry.addNewAttunement( Items.get( "linkedCard" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - registry.addNewAttunement( Items.get( "wlanCard" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - registry.addNewAttunement( Items.get( "analyzer" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - } + registry.addNewAttunement(Items.get("cable").createItemStack(1), TunnelType.COMPUTER_MESSAGE); + registry.addNewAttunement(Items.get("adapter").createItemStack(1), TunnelType.COMPUTER_MESSAGE); + registry.addNewAttunement(Items.get("switch").createItemStack(1), TunnelType.COMPUTER_MESSAGE); + registry.addNewAttunement(Items.get("accessPoint").createItemStack(1), TunnelType.COMPUTER_MESSAGE); + registry.addNewAttunement(Items.get("lanCard").createItemStack(1), TunnelType.COMPUTER_MESSAGE); + registry.addNewAttunement(Items.get("linkedCard").createItemStack(1), TunnelType.COMPUTER_MESSAGE); + registry.addNewAttunement(Items.get("wlanCard").createItemStack(1), TunnelType.COMPUTER_MESSAGE); + registry.addNewAttunement(Items.get("analyzer").createItemStack(1), TunnelType.COMPUTER_MESSAGE); + } } diff --git a/src/main/java/appeng/integration/modules/PneumaticCraft.java b/src/main/java/appeng/integration/modules/PneumaticCraft.java index 75c0f7bd2db..d81a6244049 100644 --- a/src/main/java/appeng/integration/modules/PneumaticCraft.java +++ b/src/main/java/appeng/integration/modules/PneumaticCraft.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.IAppEngApi; import appeng.api.config.TunnelType; @@ -33,51 +32,45 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; +public class PneumaticCraft implements IIntegrationModule { + @Reflected + public static PneumaticCraft instance; -public class PneumaticCraft implements IIntegrationModule -{ - @Reflected - public static PneumaticCraft instance; - - private static final String PNEUMATIC_CRAFT_MOD_ID = "PneumaticCraft"; + private static final String PNEUMATIC_CRAFT_MOD_ID = "PneumaticCraft"; - @Reflected - public PneumaticCraft() - { - IntegrationHelper.testClassExistence( this, pneumaticCraft.api.block.BlockSupplier.class ); - IntegrationHelper.testClassExistence( this, pneumaticCraft.api.tileentity.ISidedPneumaticMachine.class ); - IntegrationHelper.testClassExistence( this, pneumaticCraft.api.tileentity.AirHandlerSupplier.class ); - IntegrationHelper.testClassExistence( this, pneumaticCraft.api.tileentity.IAirHandler.class ); - } + @Reflected + public PneumaticCraft() { + IntegrationHelper.testClassExistence(this, pneumaticCraft.api.block.BlockSupplier.class); + IntegrationHelper.testClassExistence(this, pneumaticCraft.api.tileentity.ISidedPneumaticMachine.class); + IntegrationHelper.testClassExistence(this, pneumaticCraft.api.tileentity.AirHandlerSupplier.class); + IntegrationHelper.testClassExistence(this, pneumaticCraft.api.tileentity.IAirHandler.class); + } - @Override - public void init() - { - final IAppEngApi api = AEApi.instance(); - final IPartHelper partHelper = api.partHelper(); + @Override + public void init() { + final IAppEngApi api = AEApi.instance(); + final IPartHelper partHelper = api.partHelper(); - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.PneumaticCraft ) ) - { - partHelper.registerNewLayer( appeng.parts.layers.LayerPressure.class.getName(), pneumaticCraft.api.tileentity.ISidedPneumaticMachine.class.getName() ); - } - } + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.PneumaticCraft)) { + partHelper.registerNewLayer( + appeng.parts.layers.LayerPressure.class.getName(), + pneumaticCraft.api.tileentity.ISidedPneumaticMachine.class.getName()); + } + } - @Override - public void postInit() - { - this.registerPressureAttunement( "pressureTube" ); - this.registerPressureAttunement( "advancedPressureTube" ); - } + @Override + public void postInit() { + this.registerPressureAttunement("pressureTube"); + this.registerPressureAttunement("advancedPressureTube"); + } - private void registerPressureAttunement( final String itemID ) - { - final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); - final ItemStack modItem = GameRegistry.findItemStack( PNEUMATIC_CRAFT_MOD_ID, itemID, 1 ); + private void registerPressureAttunement(final String itemID) { + final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); + final ItemStack modItem = GameRegistry.findItemStack(PNEUMATIC_CRAFT_MOD_ID, itemID, 1); - if( modItem != null ) - { - modItem.setItemDamage( OreDictionary.WILDCARD_VALUE ); - registry.addNewAttunement( modItem, TunnelType.PRESSURE ); - } - } + if (modItem != null) { + modItem.setItemDamage(OreDictionary.WILDCARD_VALUE); + registry.addNewAttunement(modItem, TunnelType.PRESSURE); + } + } } diff --git a/src/main/java/appeng/integration/modules/RC.java b/src/main/java/appeng/integration/modules/RC.java index 107b57d6072..79bd12fcd1d 100644 --- a/src/main/java/appeng/integration/modules/RC.java +++ b/src/main/java/appeng/integration/modules/RC.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; import appeng.integration.IntegrationHelper; @@ -27,33 +26,25 @@ import mods.railcraft.api.crafting.RailcraftCraftingManager; import net.minecraft.item.ItemStack; +public class RC implements IRC, IIntegrationModule { + @Reflected + public static RC instance; -public class RC implements IRC, IIntegrationModule -{ - @Reflected - public static RC instance; - - @Reflected - public RC() - { - IntegrationHelper.testClassExistence( this, mods.railcraft.api.crafting.RailcraftCraftingManager.class ); - IntegrationHelper.testClassExistence( this, mods.railcraft.api.crafting.IRockCrusherRecipe.class ); - } + @Reflected + public RC() { + IntegrationHelper.testClassExistence(this, mods.railcraft.api.crafting.RailcraftCraftingManager.class); + IntegrationHelper.testClassExistence(this, mods.railcraft.api.crafting.IRockCrusherRecipe.class); + } - @Override - public void rockCrusher( final ItemStack input, final ItemStack output ) - { - final IRockCrusherRecipe re = RailcraftCraftingManager.rockCrusher.createNewRecipe( input, true, true ); - re.addOutput( output, 1.0f ); - } + @Override + public void rockCrusher(final ItemStack input, final ItemStack output) { + final IRockCrusherRecipe re = RailcraftCraftingManager.rockCrusher.createNewRecipe(input, true, true); + re.addOutput(output, 1.0f); + } - @Override - public void init() - { - } + @Override + public void init() {} - @Override - public void postInit() - { - } + @Override + public void postInit() {} } diff --git a/src/main/java/appeng/integration/modules/RF.java b/src/main/java/appeng/integration/modules/RF.java index 15f075b7c02..5ca23d8e6ef 100644 --- a/src/main/java/appeng/integration/modules/RF.java +++ b/src/main/java/appeng/integration/modules/RF.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.IAppEngApi; import appeng.api.config.TunnelType; @@ -32,65 +31,57 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; +public final class RF implements IIntegrationModule { + @Reflected + public static RF instance; -public final class RF implements IIntegrationModule -{ - @Reflected - public static RF instance; - - @Reflected - public RF() - { - IntegrationHelper.testClassExistence( this, cofh.api.energy.IEnergyReceiver.class ); - IntegrationHelper.testClassExistence( this, cofh.api.energy.IEnergyProvider.class ); - IntegrationHelper.testClassExistence( this, cofh.api.energy.IEnergyHandler.class ); - IntegrationHelper.testClassExistence( this, cofh.api.energy.IEnergyConnection.class ); - } + @Reflected + public RF() { + IntegrationHelper.testClassExistence(this, cofh.api.energy.IEnergyReceiver.class); + IntegrationHelper.testClassExistence(this, cofh.api.energy.IEnergyProvider.class); + IntegrationHelper.testClassExistence(this, cofh.api.energy.IEnergyHandler.class); + IntegrationHelper.testClassExistence(this, cofh.api.energy.IEnergyConnection.class); + } - @Override - public void init() - { - final IAppEngApi api = AEApi.instance(); - final IPartHelper partHelper = api.partHelper(); + @Override + public void init() { + final IAppEngApi api = AEApi.instance(); + final IPartHelper partHelper = api.partHelper(); - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.RF ) ) - { - partHelper.registerNewLayer( "appeng.parts.layers.LayerIEnergyHandler", "cofh.api.energy.IEnergyReceiver" ); - } - } + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.RF)) { + partHelper.registerNewLayer("appeng.parts.layers.LayerIEnergyHandler", "cofh.api.energy.IEnergyReceiver"); + } + } - @Override - public void postInit() - { - this.registerRFAttunement( "ExtraUtilities", "extractor_base", 12 ); - this.registerRFAttunement( "ExtraUtilities", "pipes", 11 ); - this.registerRFAttunement( "ExtraUtilities", "pipes", 14 ); - this.registerRFAttunement( "ExtraUtilities", "generator", OreDictionary.WILDCARD_VALUE ); + @Override + public void postInit() { + this.registerRFAttunement("ExtraUtilities", "extractor_base", 12); + this.registerRFAttunement("ExtraUtilities", "pipes", 11); + this.registerRFAttunement("ExtraUtilities", "pipes", 14); + this.registerRFAttunement("ExtraUtilities", "generator", OreDictionary.WILDCARD_VALUE); - this.registerRFAttunement( "ThermalExpansion", "Cell", OreDictionary.WILDCARD_VALUE ); - this.registerRFAttunement( "ThermalExpansion", "Dynamo", OreDictionary.WILDCARD_VALUE ); + this.registerRFAttunement("ThermalExpansion", "Cell", OreDictionary.WILDCARD_VALUE); + this.registerRFAttunement("ThermalExpansion", "Dynamo", OreDictionary.WILDCARD_VALUE); - // Fluxduct - this.registerRFAttunement( "ThermalDynamics", "ThermalDynamics_0", 0 ); + // Fluxduct + this.registerRFAttunement("ThermalDynamics", "ThermalDynamics_0", 0); - this.registerRFAttunement( "EnderIO", "itemPowerConduit", OreDictionary.WILDCARD_VALUE ); - this.registerRFAttunement( "EnderIO", "blockCapacitorBank", 0 ); - this.registerRFAttunement( "EnderIO", "blockPowerMonitor", 0 ); - } + this.registerRFAttunement("EnderIO", "itemPowerConduit", OreDictionary.WILDCARD_VALUE); + this.registerRFAttunement("EnderIO", "blockCapacitorBank", 0); + this.registerRFAttunement("EnderIO", "blockPowerMonitor", 0); + } - private void registerRFAttunement( final String mod, final String name, final int dmg ) - { - assert mod != null; - assert !mod.isEmpty(); - assert name != null; - assert !name.isEmpty(); - assert dmg >= 0; + private void registerRFAttunement(final String mod, final String name, final int dmg) { + assert mod != null; + assert !mod.isEmpty(); + assert name != null; + assert !name.isEmpty(); + assert dmg >= 0; - final ItemStack modItem = GameRegistry.findItemStack( mod, name, 1 ); - if( modItem != null ) - { - modItem.setItemDamage( dmg ); - AEApi.instance().registries().p2pTunnel().addNewAttunement( modItem, TunnelType.RF_POWER ); - } - } + final ItemStack modItem = GameRegistry.findItemStack(mod, name, 1); + if (modItem != null) { + modItem.setItemDamage(dmg); + AEApi.instance().registries().p2pTunnel().addNewAttunement(modItem, TunnelType.RF_POWER); + } + } } diff --git a/src/main/java/appeng/integration/modules/RFItem.java b/src/main/java/appeng/integration/modules/RFItem.java index d2ded2c895c..d5c5bfe8876 100644 --- a/src/main/java/appeng/integration/modules/RFItem.java +++ b/src/main/java/appeng/integration/modules/RFItem.java @@ -18,30 +18,22 @@ package appeng.integration.modules; - import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; import appeng.integration.IntegrationHelper; +public class RFItem implements IIntegrationModule { + @Reflected + public static RFItem instance; -public class RFItem implements IIntegrationModule -{ - @Reflected - public static RFItem instance; - - @Reflected - public RFItem() - { - IntegrationHelper.testClassExistence( this, cofh.api.energy.IEnergyContainerItem.class ); - } + @Reflected + public RFItem() { + IntegrationHelper.testClassExistence(this, cofh.api.energy.IEnergyContainerItem.class); + } - @Override - public void init() - { - } + @Override + public void init() {} - @Override - public void postInit() - { - } + @Override + public void postInit() {} } diff --git a/src/main/java/appeng/integration/modules/Waila.java b/src/main/java/appeng/integration/modules/Waila.java index c766043640d..8473667412e 100644 --- a/src/main/java/appeng/integration/modules/Waila.java +++ b/src/main/java/appeng/integration/modules/Waila.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; import appeng.integration.IntegrationHelper; @@ -29,44 +28,37 @@ import mcp.mobius.waila.api.IWailaDataProvider; import mcp.mobius.waila.api.IWailaRegistrar; +public class Waila implements IIntegrationModule { + @Reflected + public static Waila instance; -public class Waila implements IIntegrationModule -{ - @Reflected - public static Waila instance; - - @Reflected - public Waila() - { - IntegrationHelper.testClassExistence( this, mcp.mobius.waila.api.IWailaDataProvider.class ); - IntegrationHelper.testClassExistence( this, mcp.mobius.waila.api.IWailaRegistrar.class ); - IntegrationHelper.testClassExistence( this, mcp.mobius.waila.api.IWailaConfigHandler.class ); - IntegrationHelper.testClassExistence( this, mcp.mobius.waila.api.IWailaDataAccessor.class ); - IntegrationHelper.testClassExistence( this, mcp.mobius.waila.api.ITaggedList.class ); - } + @Reflected + public Waila() { + IntegrationHelper.testClassExistence(this, mcp.mobius.waila.api.IWailaDataProvider.class); + IntegrationHelper.testClassExistence(this, mcp.mobius.waila.api.IWailaRegistrar.class); + IntegrationHelper.testClassExistence(this, mcp.mobius.waila.api.IWailaConfigHandler.class); + IntegrationHelper.testClassExistence(this, mcp.mobius.waila.api.IWailaDataAccessor.class); + IntegrationHelper.testClassExistence(this, mcp.mobius.waila.api.ITaggedList.class); + } - public static void register( final IWailaRegistrar registrar ) - { - final IWailaDataProvider partHost = new PartWailaDataProvider(); + public static void register(final IWailaRegistrar registrar) { + final IWailaDataProvider partHost = new PartWailaDataProvider(); - registrar.registerStackProvider( partHost, AEBaseTile.class ); - registrar.registerBodyProvider( partHost, AEBaseTile.class ); - registrar.registerNBTProvider( partHost, AEBaseTile.class ); + registrar.registerStackProvider(partHost, AEBaseTile.class); + registrar.registerBodyProvider(partHost, AEBaseTile.class); + registrar.registerNBTProvider(partHost, AEBaseTile.class); - final IWailaDataProvider tile = new TileWailaDataProvider(); + final IWailaDataProvider tile = new TileWailaDataProvider(); - registrar.registerBodyProvider( tile, AEBaseTile.class ); - registrar.registerNBTProvider( tile, AEBaseTile.class ); - } + registrar.registerBodyProvider(tile, AEBaseTile.class); + registrar.registerNBTProvider(tile, AEBaseTile.class); + } - @Override - public void init() throws Throwable - { - FMLInterModComms.sendMessage( "Waila", "register", this.getClass().getName() + ".register" ); - } + @Override + public void init() throws Throwable { + FMLInterModComms.sendMessage("Waila", "register", this.getClass().getName() + ".register"); + } - @Override - public void postInit() - { - } + @Override + public void postInit() {} } diff --git a/src/main/java/appeng/integration/modules/helpers/BSCrate.java b/src/main/java/appeng/integration/modules/helpers/BSCrate.java index d0b6674329a..e50386b52f4 100644 --- a/src/main/java/appeng/integration/modules/helpers/BSCrate.java +++ b/src/main/java/appeng/integration/modules/helpers/BSCrate.java @@ -18,7 +18,6 @@ package appeng.integration.modules.helpers; - import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IMEInventory; @@ -29,59 +28,48 @@ import net.mcft.copy.betterstorage.api.crate.ICrateStorage; import net.minecraft.item.ItemStack; +public class BSCrate implements IMEInventory { + private final ICrateStorage crateStorage; -public class BSCrate implements IMEInventory -{ - private final ICrateStorage crateStorage; - - public BSCrate( final Object object ) - { - this.crateStorage = (ICrateStorage) object; - } + public BSCrate(final Object object) { + this.crateStorage = (ICrateStorage) object; + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - if( mode == Actionable.SIMULATE ) - { - return null; - } + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode, final BaseActionSource src) { + if (mode == Actionable.SIMULATE) { + return null; + } - final ItemStack failed = this.crateStorage.insertItems( input.getItemStack() ); - if( failed == null ) - { - return null; - } - input.setStackSize( failed.stackSize ); - return input; - } + final ItemStack failed = this.crateStorage.insertItems(input.getItemStack()); + if (failed == null) { + return null; + } + input.setStackSize(failed.stackSize); + return input; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - if( mode == Actionable.SIMULATE ) - { - final int howMany = this.crateStorage.getItemCount( request.getItemStack() ); - return howMany > request.getStackSize() ? request : request.copy().setStackSize( howMany ); - } + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final BaseActionSource src) { + if (mode == Actionable.SIMULATE) { + final int howMany = this.crateStorage.getItemCount(request.getItemStack()); + return howMany > request.getStackSize() ? request : request.copy().setStackSize(howMany); + } - final ItemStack obtained = this.crateStorage.extractItems( request.getItemStack(), (int) request.getStackSize() ); - return AEItemStack.create( obtained ); - } + final ItemStack obtained = this.crateStorage.extractItems(request.getItemStack(), (int) request.getStackSize()); + return AEItemStack.create(obtained); + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final ItemStack is : this.crateStorage.getContents() ) - { - out.add( AEItemStack.create( is ) ); - } - return out; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final ItemStack is : this.crateStorage.getContents()) { + out.add(AEItemStack.create(is)); + } + return out; + } - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } } diff --git a/src/main/java/appeng/integration/modules/helpers/BSCrateHandler.java b/src/main/java/appeng/integration/modules/helpers/BSCrateHandler.java index 3a92d6dac53..1ca28df35d4 100644 --- a/src/main/java/appeng/integration/modules/helpers/BSCrateHandler.java +++ b/src/main/java/appeng/integration/modules/helpers/BSCrateHandler.java @@ -18,7 +18,6 @@ package appeng.integration.modules.helpers; - import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageHandler; import appeng.api.storage.IMEInventory; @@ -27,23 +26,20 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +public class BSCrateHandler implements IExternalStorageHandler { -public class BSCrateHandler implements IExternalStorageHandler -{ - - @Override - public boolean canHandle( final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource mySrc ) - { - return channel == StorageChannel.ITEMS && te instanceof ICrateStorage; - } + @Override + public boolean canHandle( + final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource mySrc) { + return channel == StorageChannel.ITEMS && te instanceof ICrateStorage; + } - @Override - public IMEInventory getInventory( final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource src ) - { - if( channel == StorageChannel.ITEMS ) - { - return new BSCrate( te ); - } - return null; - } + @Override + public IMEInventory getInventory( + final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource src) { + if (channel == StorageChannel.ITEMS) { + return new BSCrate(te); + } + return null; + } } diff --git a/src/main/java/appeng/integration/modules/helpers/BSCrateStorageAdaptor.java b/src/main/java/appeng/integration/modules/helpers/BSCrateStorageAdaptor.java index f16c7fdecfd..bf99bd8aaa6 100644 --- a/src/main/java/appeng/integration/modules/helpers/BSCrateStorageAdaptor.java +++ b/src/main/java/appeng/integration/modules/helpers/BSCrateStorageAdaptor.java @@ -18,195 +18,165 @@ package appeng.integration.modules.helpers; - import appeng.api.config.FuzzyMode; import appeng.util.InventoryAdaptor; import appeng.util.Platform; import appeng.util.inv.IInventoryDestination; import appeng.util.inv.ItemSlot; import appeng.util.iterators.StackToSlotIterator; +import java.util.Iterator; import net.mcft.copy.betterstorage.api.crate.ICrateStorage; import net.minecraft.item.ItemStack; -import java.util.Iterator; - - -public class BSCrateStorageAdaptor extends InventoryAdaptor -{ - - private final ICrateStorage cs; - - public BSCrateStorageAdaptor( final Object te ) - { - this.cs = (ICrateStorage) te; - } - - @Override - public ItemStack removeItems( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - ItemStack target = null; - - for( final ItemStack is : this.cs.getContents() ) - { - if( is != null ) - { - if( is.stackSize > 0 && ( filter == null || Platform.isSameItem( filter, is ) ) ) - { - if( destination == null || destination.canInsert( is ) ) - { - target = is; - break; - } - } - } - } - - if( target != null ) - { - final ItemStack f = Platform.cloneItemStack( target ); - f.stackSize = amount; - return this.cs.extractItems( f, amount ); - } - - return null; - } - - @Override - public ItemStack simulateRemove( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - ItemStack target = null; - - for( final ItemStack is : this.cs.getContents() ) - { - if( is != null ) - { - if( is.stackSize > 0 && ( filter == null || Platform.isSameItem( filter, is ) ) ) - { - if( destination == null || destination.canInsert( is ) ) - { - target = is; - break; - } - } - } - } - - if( target != null ) - { - int cnt = this.cs.getItemCount( target ); - if( cnt == 0 ) - { - return null; - } - if( cnt > amount ) - { - cnt = amount; - } - final ItemStack c = target.copy(); - c.stackSize = cnt; - return c; - } - - return null; - } - - @Override - public ItemStack removeSimilarItems( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - ItemStack target = null; - - for( final ItemStack is : this.cs.getContents() ) - { - if( is != null ) - { - if( is.stackSize > 0 && ( filter == null || Platform.isSameItemFuzzy( filter, is, fuzzyMode ) ) ) - { - if( destination == null || destination.canInsert( is ) ) - { - target = is; - break; - } - } - } - } - - if( target != null ) - { - final ItemStack f = Platform.cloneItemStack( target ); - f.stackSize = amount; - return this.cs.extractItems( f, amount ); - } - - return null; - } - - @Override - public ItemStack simulateSimilarRemove( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - ItemStack target = null; - - for( final ItemStack is : this.cs.getContents() ) - { - if( is != null ) - { - if( is.stackSize > 0 && ( filter == null || Platform.isSameItemFuzzy( filter, is, fuzzyMode ) ) ) - { - if( destination == null || destination.canInsert( is ) ) - { - target = is; - break; - } - } - } - } - - if( target != null ) - { - int cnt = this.cs.getItemCount( target ); - if( cnt == 0 ) - { - return null; - } - if( cnt > amount ) - { - cnt = amount; - } - final ItemStack c = target.copy(); - c.stackSize = cnt; - return c; - } - - return null; - } - - @Override - public ItemStack addItems( final ItemStack toBeAdded ) - { - return this.cs.insertItems( toBeAdded ); - } - - @Override - public ItemStack simulateAdd( final ItemStack toBeSimulated ) - { - final int items = this.cs.getSpaceForItem( toBeSimulated ); - final ItemStack cloned = Platform.cloneItemStack( toBeSimulated ); - if( toBeSimulated.stackSize <= items ) - { - return null; - } - cloned.stackSize -= items; - return cloned; - } - - @Override - public boolean containsItems() - { - return this.cs.getUniqueItems() > 0; - } - - @Override - public Iterator iterator() - { - return new StackToSlotIterator( this.cs.getContents().iterator() ); - } +public class BSCrateStorageAdaptor extends InventoryAdaptor { + + private final ICrateStorage cs; + + public BSCrateStorageAdaptor(final Object te) { + this.cs = (ICrateStorage) te; + } + + @Override + public ItemStack removeItems(final int amount, final ItemStack filter, final IInventoryDestination destination) { + ItemStack target = null; + + for (final ItemStack is : this.cs.getContents()) { + if (is != null) { + if (is.stackSize > 0 && (filter == null || Platform.isSameItem(filter, is))) { + if (destination == null || destination.canInsert(is)) { + target = is; + break; + } + } + } + } + + if (target != null) { + final ItemStack f = Platform.cloneItemStack(target); + f.stackSize = amount; + return this.cs.extractItems(f, amount); + } + + return null; + } + + @Override + public ItemStack simulateRemove(final int amount, final ItemStack filter, final IInventoryDestination destination) { + ItemStack target = null; + + for (final ItemStack is : this.cs.getContents()) { + if (is != null) { + if (is.stackSize > 0 && (filter == null || Platform.isSameItem(filter, is))) { + if (destination == null || destination.canInsert(is)) { + target = is; + break; + } + } + } + } + + if (target != null) { + int cnt = this.cs.getItemCount(target); + if (cnt == 0) { + return null; + } + if (cnt > amount) { + cnt = amount; + } + final ItemStack c = target.copy(); + c.stackSize = cnt; + return c; + } + + return null; + } + + @Override + public ItemStack removeSimilarItems( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination) { + ItemStack target = null; + + for (final ItemStack is : this.cs.getContents()) { + if (is != null) { + if (is.stackSize > 0 && (filter == null || Platform.isSameItemFuzzy(filter, is, fuzzyMode))) { + if (destination == null || destination.canInsert(is)) { + target = is; + break; + } + } + } + } + + if (target != null) { + final ItemStack f = Platform.cloneItemStack(target); + f.stackSize = amount; + return this.cs.extractItems(f, amount); + } + + return null; + } + + @Override + public ItemStack simulateSimilarRemove( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination) { + ItemStack target = null; + + for (final ItemStack is : this.cs.getContents()) { + if (is != null) { + if (is.stackSize > 0 && (filter == null || Platform.isSameItemFuzzy(filter, is, fuzzyMode))) { + if (destination == null || destination.canInsert(is)) { + target = is; + break; + } + } + } + } + + if (target != null) { + int cnt = this.cs.getItemCount(target); + if (cnt == 0) { + return null; + } + if (cnt > amount) { + cnt = amount; + } + final ItemStack c = target.copy(); + c.stackSize = cnt; + return c; + } + + return null; + } + + @Override + public ItemStack addItems(final ItemStack toBeAdded) { + return this.cs.insertItems(toBeAdded); + } + + @Override + public ItemStack simulateAdd(final ItemStack toBeSimulated) { + final int items = this.cs.getSpaceForItem(toBeSimulated); + final ItemStack cloned = Platform.cloneItemStack(toBeSimulated); + if (toBeSimulated.stackSize <= items) { + return null; + } + cloned.stackSize -= items; + return cloned; + } + + @Override + public boolean containsItems() { + return this.cs.getUniqueItems() > 0; + } + + @Override + public Iterator iterator() { + return new StackToSlotIterator(this.cs.getContents().iterator()); + } } diff --git a/src/main/java/appeng/integration/modules/helpers/FMPPacketEvent.java b/src/main/java/appeng/integration/modules/helpers/FMPPacketEvent.java index 21f9eb7c8d4..cc9afce7a45 100644 --- a/src/main/java/appeng/integration/modules/helpers/FMPPacketEvent.java +++ b/src/main/java/appeng/integration/modules/helpers/FMPPacketEvent.java @@ -18,23 +18,18 @@ package appeng.integration.modules.helpers; - import cpw.mods.fml.common.eventhandler.Event; import net.minecraft.entity.player.EntityPlayerMP; +public class FMPPacketEvent extends Event { -public class FMPPacketEvent extends Event -{ - - private final EntityPlayerMP sender; + private final EntityPlayerMP sender; - public FMPPacketEvent( final EntityPlayerMP sender ) - { - this.sender = sender; - } + public FMPPacketEvent(final EntityPlayerMP sender) { + this.sender = sender; + } - public EntityPlayerMP getSender() - { - return this.sender; - } + public EntityPlayerMP getSender() { + return this.sender; + } } diff --git a/src/main/java/appeng/integration/modules/helpers/FactorizationBarrel.java b/src/main/java/appeng/integration/modules/helpers/FactorizationBarrel.java index c78a9e785d9..b088a118c6a 100644 --- a/src/main/java/appeng/integration/modules/helpers/FactorizationBarrel.java +++ b/src/main/java/appeng/integration/modules/helpers/FactorizationBarrel.java @@ -18,7 +18,6 @@ package appeng.integration.modules.helpers; - import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IMEInventory; @@ -30,146 +29,116 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; - -public class FactorizationBarrel implements IMEInventory -{ - - private final IFZ fProxy; - private final TileEntity te; - - public FactorizationBarrel( final IFZ proxy, final TileEntity tile ) - { - this.te = tile; - this.fProxy = proxy; - } - - public long remainingItemCount() - { - return this.fProxy.barrelGetMaxItemCount( this.te ) - this.fProxy.barrelGetItemCount( this.te ); - } - - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - if( input == null ) - { - return null; - } - if( input.getStackSize() == 0 ) - { - return null; - } - - final ItemStack shared = input.getItemStack(); - if( shared.isItemDamaged() ) - { - return input; - } - - if( this.remainingItemTypes() > 0 ) - { - if( mode == Actionable.MODULATE ) - { - this.fProxy.setItemType( this.te, input.getItemStack() ); - } - } - - if( this.containsItemType( input, mode == Actionable.SIMULATE ) ) - { - final int max = this.fProxy.barrelGetMaxItemCount( this.te ); - final int newTotal = (int) this.storedItemCount() + (int) input.getStackSize(); - if( newTotal > max ) - { - if( mode == Actionable.MODULATE ) - { - this.fProxy.barrelSetCount( this.te, max ); - } - final IAEItemStack result = input.copy(); - result.setStackSize( newTotal - max ); - return result; - } - else - { - if( mode == Actionable.MODULATE ) - { - this.fProxy.barrelSetCount( this.te, newTotal ); - } - return null; - } - } - - return input; - } - - private long remainingItemTypes() - { - return this.fProxy.barrelGetItem( this.te ) == null ? 1 : 0; - } - - private boolean containsItemType( final IAEItemStack i, final boolean acceptEmpty ) - { - final ItemStack currentItem = this.fProxy.barrelGetItem( this.te ); - - // empty barrels want your love too! - if( acceptEmpty && currentItem == null ) - { - return true; - } - - return i.equals( currentItem ); - } - - private long storedItemCount() - { - return this.fProxy.barrelGetItemCount( this.te ); - } - - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - if( this.containsItemType( request, false ) ) - { - final int howMany = (int) this.storedItemCount(); - if( request.getStackSize() >= howMany ) - { - if( mode == Actionable.MODULATE ) - { - this.fProxy.setItemType( this.te, null ); - this.fProxy.barrelSetCount( this.te, 0 ); - } - - final IAEItemStack r = request.copy(); - r.setStackSize( howMany ); - return r; - } - else - { - if( mode == Actionable.MODULATE ) - { - this.fProxy.barrelSetCount( this.te, (int) ( howMany - request.getStackSize() ) ); - } - return request.copy(); - } - } - return null; - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - final ItemStack i = this.fProxy.barrelGetItem( this.te ); - if( i != null ) - { - i.stackSize = this.fProxy.barrelGetItemCount( this.te ); - out.addStorage( AEItemStack.create( i ) ); - } - - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } -} \ No newline at end of file +public class FactorizationBarrel implements IMEInventory { + + private final IFZ fProxy; + private final TileEntity te; + + public FactorizationBarrel(final IFZ proxy, final TileEntity tile) { + this.te = tile; + this.fProxy = proxy; + } + + public long remainingItemCount() { + return this.fProxy.barrelGetMaxItemCount(this.te) - this.fProxy.barrelGetItemCount(this.te); + } + + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode, final BaseActionSource src) { + if (input == null) { + return null; + } + if (input.getStackSize() == 0) { + return null; + } + + final ItemStack shared = input.getItemStack(); + if (shared.isItemDamaged()) { + return input; + } + + if (this.remainingItemTypes() > 0) { + if (mode == Actionable.MODULATE) { + this.fProxy.setItemType(this.te, input.getItemStack()); + } + } + + if (this.containsItemType(input, mode == Actionable.SIMULATE)) { + final int max = this.fProxy.barrelGetMaxItemCount(this.te); + final int newTotal = (int) this.storedItemCount() + (int) input.getStackSize(); + if (newTotal > max) { + if (mode == Actionable.MODULATE) { + this.fProxy.barrelSetCount(this.te, max); + } + final IAEItemStack result = input.copy(); + result.setStackSize(newTotal - max); + return result; + } else { + if (mode == Actionable.MODULATE) { + this.fProxy.barrelSetCount(this.te, newTotal); + } + return null; + } + } + + return input; + } + + private long remainingItemTypes() { + return this.fProxy.barrelGetItem(this.te) == null ? 1 : 0; + } + + private boolean containsItemType(final IAEItemStack i, final boolean acceptEmpty) { + final ItemStack currentItem = this.fProxy.barrelGetItem(this.te); + + // empty barrels want your love too! + if (acceptEmpty && currentItem == null) { + return true; + } + + return i.equals(currentItem); + } + + private long storedItemCount() { + return this.fProxy.barrelGetItemCount(this.te); + } + + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final BaseActionSource src) { + if (this.containsItemType(request, false)) { + final int howMany = (int) this.storedItemCount(); + if (request.getStackSize() >= howMany) { + if (mode == Actionable.MODULATE) { + this.fProxy.setItemType(this.te, null); + this.fProxy.barrelSetCount(this.te, 0); + } + + final IAEItemStack r = request.copy(); + r.setStackSize(howMany); + return r; + } else { + if (mode == Actionable.MODULATE) { + this.fProxy.barrelSetCount(this.te, (int) (howMany - request.getStackSize())); + } + return request.copy(); + } + } + return null; + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + final ItemStack i = this.fProxy.barrelGetItem(this.te); + if (i != null) { + i.stackSize = this.fProxy.barrelGetItemCount(this.te); + out.addStorage(AEItemStack.create(i)); + } + + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } +} diff --git a/src/main/java/appeng/integration/modules/helpers/FactorizationHandler.java b/src/main/java/appeng/integration/modules/helpers/FactorizationHandler.java index a5da4b3724a..41ee8123731 100644 --- a/src/main/java/appeng/integration/modules/helpers/FactorizationHandler.java +++ b/src/main/java/appeng/integration/modules/helpers/FactorizationHandler.java @@ -18,7 +18,6 @@ package appeng.integration.modules.helpers; - import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageHandler; import appeng.api.storage.IMEInventory; @@ -29,23 +28,20 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +public class FactorizationHandler implements IExternalStorageHandler { -public class FactorizationHandler implements IExternalStorageHandler -{ - - @Override - public boolean canHandle( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource mySrc ) - { - return chan == StorageChannel.ITEMS && FZ.instance.isBarrel( te ); - } + @Override + public boolean canHandle( + final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource mySrc) { + return chan == StorageChannel.ITEMS && FZ.instance.isBarrel(te); + } - @Override - public IMEInventory getInventory( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource src ) - { - if( chan == StorageChannel.ITEMS ) - { - return new MEMonitorIInventory( new IMEAdaptor( FZ.instance.getFactorizationBarrel( te ), src ) ); - } - return null; - } + @Override + public IMEInventory getInventory( + final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource src) { + if (chan == StorageChannel.ITEMS) { + return new MEMonitorIInventory(new IMEAdaptor(FZ.instance.getFactorizationBarrel(te), src)); + } + return null; + } } diff --git a/src/main/java/appeng/integration/modules/helpers/JabbaBarrel.java b/src/main/java/appeng/integration/modules/helpers/JabbaBarrel.java index 37a642bdf54..b4aedd3a92a 100644 --- a/src/main/java/appeng/integration/modules/helpers/JabbaBarrel.java +++ b/src/main/java/appeng/integration/modules/helpers/JabbaBarrel.java @@ -13,67 +13,52 @@ public class JabbaBarrel implements IMEInventory { private final TileEntityBarrel barrel; - public JabbaBarrel( final TileEntity te ) - { - barrel = (TileEntityBarrel)te; + + public JabbaBarrel(final TileEntity te) { + barrel = (TileEntityBarrel) te; } + @Override - public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { + public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode, final BaseActionSource src) { final ItemStack is = this.barrel.getStoredItemType(); - if( is != null ) - { - if( input.equals( is ) ) - { + if (is != null) { + if (input.equals(is)) { final long max = this.barrel.getMaxStoredCount(); long storedItems = is.stackSize; - if( max == storedItems ) - { + if (max == storedItems) { return input; } storedItems += input.getStackSize(); - if( storedItems > max && !barrel.getStorage().isVoid() ) - { - final IAEItemStack overflow = AEItemStack.create( is ); - overflow.setStackSize( storedItems - max ); - if( mode == Actionable.MODULATE ) - { - this.barrel.setStoredItemCount( (int) max ); + if (storedItems > max && !barrel.getStorage().isVoid()) { + final IAEItemStack overflow = AEItemStack.create(is); + overflow.setStackSize(storedItems - max); + if (mode == Actionable.MODULATE) { + this.barrel.setStoredItemCount((int) max); } return overflow; - } - else - { - if( mode == Actionable.MODULATE ) - { - this.barrel.setStoredItemCount( is.stackSize + (int) input.getStackSize() ); + } else { + if (mode == Actionable.MODULATE) { + this.barrel.setStoredItemCount(is.stackSize + (int) input.getStackSize()); } return null; } } - } - else - { - if( input.getTagCompound() != null ) - { + } else { + if (input.getTagCompound() != null) { return input; } - long max = ((long)this.barrel.getStorage().getMaxStacks()) * input.getItemStack().getMaxStackSize(); - if( input.getStackSize() <= max || barrel.getStorage().isVoid() ) - { - if( mode == Actionable.MODULATE ) - { - this.barrel.setStoredItemType( input.getItemStack(), (int) input.getStackSize() ); + long max = ((long) this.barrel.getStorage().getMaxStacks()) + * input.getItemStack().getMaxStackSize(); + if (input.getStackSize() <= max || barrel.getStorage().isVoid()) { + if (mode == Actionable.MODULATE) { + this.barrel.setStoredItemType(input.getItemStack(), (int) input.getStackSize()); } - } - else - { + } else { final IAEItemStack overflow = AEItemStack.create(input.getItemStack()); overflow.setStackSize(input.getStackSize() - max); - if( mode == Actionable.MODULATE ) - { - this.barrel.setStoredItemType( input.getItemStack(), (int) max ); + if (mode == Actionable.MODULATE) { + this.barrel.setStoredItemType(input.getItemStack(), (int) max); } return overflow; } @@ -83,25 +68,18 @@ public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode, } @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final BaseActionSource src) { ItemStack is = this.barrel.getStoredItemType(); - if( request.equals( is ) ) - { - if( request.getStackSize() >= is.stackSize ) - { + if (request.equals(is)) { + if (request.getStackSize() >= is.stackSize) { is = is.copy(); - if( mode == Actionable.MODULATE ) - { - this.barrel.setStoredItemCount( 0 ); + if (mode == Actionable.MODULATE) { + this.barrel.setStoredItemCount(0); } - return AEItemStack.create( is ); - } - else - { - if( mode == Actionable.MODULATE ) - { - this.barrel.setStoredItemCount( is.stackSize - (int) request.getStackSize() ); + return AEItemStack.create(is); + } else { + if (mode == Actionable.MODULATE) { + this.barrel.setStoredItemCount(is.stackSize - (int) request.getStackSize()); } return request.copy(); } @@ -110,19 +88,16 @@ public IAEItemStack extractItems( final IAEItemStack request, final Actionable m } @Override - public IItemList getAvailableItems(final IItemList out ) - { + public IItemList getAvailableItems(final IItemList out) { final ItemStack is = this.barrel.getStoredItemType(); - if( is != null ) - { - out.add( AEItemStack.create( is ) ); + if (is != null) { + out.add(AEItemStack.create(is)); } return out; } @Override - public StorageChannel getChannel() - { + public StorageChannel getChannel() { return StorageChannel.ITEMS; } } diff --git a/src/main/java/appeng/integration/modules/helpers/JabbaStorageHandler.java b/src/main/java/appeng/integration/modules/helpers/JabbaStorageHandler.java index 6d1148f6bec..6ead9791dad 100644 --- a/src/main/java/appeng/integration/modules/helpers/JabbaStorageHandler.java +++ b/src/main/java/appeng/integration/modules/helpers/JabbaStorageHandler.java @@ -11,20 +11,18 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -public class JabbaStorageHandler implements IExternalStorageHandler -{ +public class JabbaStorageHandler implements IExternalStorageHandler { @Override - public boolean canHandle( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource mySrc ) - { - return chan == StorageChannel.ITEMS && Jabba.instance.isBarrel( te ); + public boolean canHandle( + final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource mySrc) { + return chan == StorageChannel.ITEMS && Jabba.instance.isBarrel(te); } @Override - public IMEInventory getInventory( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource src ) - { - if( chan == StorageChannel.ITEMS ) - { - return new MEMonitorIInventory( new IMEAdaptor( Jabba.instance.getBarrel( te ), src ) ); + public IMEInventory getInventory( + final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource src) { + if (chan == StorageChannel.ITEMS) { + return new MEMonitorIInventory(new IMEAdaptor(Jabba.instance.getBarrel(te), src)); } return null; diff --git a/src/main/java/appeng/integration/modules/helpers/MFRDSUHandler.java b/src/main/java/appeng/integration/modules/helpers/MFRDSUHandler.java index 62f278237aa..66545b81e3f 100644 --- a/src/main/java/appeng/integration/modules/helpers/MFRDSUHandler.java +++ b/src/main/java/appeng/integration/modules/helpers/MFRDSUHandler.java @@ -18,7 +18,6 @@ package appeng.integration.modules.helpers; - import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageHandler; import appeng.api.storage.IMEInventory; @@ -29,24 +28,21 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +public class MFRDSUHandler implements IExternalStorageHandler { -public class MFRDSUHandler implements IExternalStorageHandler -{ - - @Override - public boolean canHandle( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource mySrc ) - { - return chan == StorageChannel.ITEMS && DSU.instance.isDSU( te ); - } + @Override + public boolean canHandle( + final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource mySrc) { + return chan == StorageChannel.ITEMS && DSU.instance.isDSU(te); + } - @Override - public IMEInventory getInventory( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource src ) - { - if( chan == StorageChannel.ITEMS ) - { - return new MEMonitorIInventory( new IMEAdaptor( DSU.instance.getDSU( te ), src ) ); - } + @Override + public IMEInventory getInventory( + final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource src) { + if (chan == StorageChannel.ITEMS) { + return new MEMonitorIInventory(new IMEAdaptor(DSU.instance.getDSU(te), src)); + } - return null; - } + return null; + } } diff --git a/src/main/java/appeng/integration/modules/helpers/MinefactoryReloadedDeepStorageUnit.java b/src/main/java/appeng/integration/modules/helpers/MinefactoryReloadedDeepStorageUnit.java index 25725efc1b0..611977e3fc9 100644 --- a/src/main/java/appeng/integration/modules/helpers/MinefactoryReloadedDeepStorageUnit.java +++ b/src/main/java/appeng/integration/modules/helpers/MinefactoryReloadedDeepStorageUnit.java @@ -18,7 +18,6 @@ package appeng.integration.modules.helpers; - import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IMEInventory; @@ -30,109 +29,83 @@ import net.minecraft.tileentity.TileEntity; import powercrystals.minefactoryreloaded.api.IDeepStorageUnit; +public class MinefactoryReloadedDeepStorageUnit implements IMEInventory { -public class MinefactoryReloadedDeepStorageUnit implements IMEInventory -{ - - private final IDeepStorageUnit dsu; + private final IDeepStorageUnit dsu; - public MinefactoryReloadedDeepStorageUnit( final TileEntity ta ) - { - this.dsu = (IDeepStorageUnit) ta; - } + public MinefactoryReloadedDeepStorageUnit(final TileEntity ta) { + this.dsu = (IDeepStorageUnit) ta; + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - final ItemStack is = this.dsu.getStoredItemType(); - if( is != null ) - { - if( input.equals( is ) ) - { - final long max = this.dsu.getMaxStoredCount(); - long storedItems = is.stackSize; - if( max == storedItems ) - { - return input; - } + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode, final BaseActionSource src) { + final ItemStack is = this.dsu.getStoredItemType(); + if (is != null) { + if (input.equals(is)) { + final long max = this.dsu.getMaxStoredCount(); + long storedItems = is.stackSize; + if (max == storedItems) { + return input; + } - storedItems += input.getStackSize(); - if( storedItems > max ) - { - final IAEItemStack overflow = AEItemStack.create( is ); - overflow.setStackSize( (int) ( storedItems - max ) ); - if( mode == Actionable.MODULATE ) - { - this.dsu.setStoredItemCount( (int) max ); - } - return overflow; - } - else - { - if( mode == Actionable.MODULATE ) - { - this.dsu.setStoredItemCount( is.stackSize + (int) input.getStackSize() ); - } - return null; - } - } - } - else - { - if( input.getTagCompound() != null ) - { - return input; - } - if( mode == Actionable.MODULATE ) - { - this.dsu.setStoredItemType( input.getItemStack(), (int) input.getStackSize() ); - } - return null; - } - return input; - } + storedItems += input.getStackSize(); + if (storedItems > max) { + final IAEItemStack overflow = AEItemStack.create(is); + overflow.setStackSize((int) (storedItems - max)); + if (mode == Actionable.MODULATE) { + this.dsu.setStoredItemCount((int) max); + } + return overflow; + } else { + if (mode == Actionable.MODULATE) { + this.dsu.setStoredItemCount(is.stackSize + (int) input.getStackSize()); + } + return null; + } + } + } else { + if (input.getTagCompound() != null) { + return input; + } + if (mode == Actionable.MODULATE) { + this.dsu.setStoredItemType(input.getItemStack(), (int) input.getStackSize()); + } + return null; + } + return input; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - ItemStack is = this.dsu.getStoredItemType(); - if( request.equals( is ) ) - { - if( request.getStackSize() >= is.stackSize ) - { - is = is.copy(); - if( mode == Actionable.MODULATE ) - { - this.dsu.setStoredItemCount( 0 ); - } - return AEItemStack.create( is ); - } - else - { - if( mode == Actionable.MODULATE ) - { - this.dsu.setStoredItemCount( is.stackSize - (int) request.getStackSize() ); - } - return request.copy(); - } - } - return null; - } + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final BaseActionSource src) { + ItemStack is = this.dsu.getStoredItemType(); + if (request.equals(is)) { + if (request.getStackSize() >= is.stackSize) { + is = is.copy(); + if (mode == Actionable.MODULATE) { + this.dsu.setStoredItemCount(0); + } + return AEItemStack.create(is); + } else { + if (mode == Actionable.MODULATE) { + this.dsu.setStoredItemCount(is.stackSize - (int) request.getStackSize()); + } + return request.copy(); + } + } + return null; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - final ItemStack is = this.dsu.getStoredItemType(); - if( is != null ) - { - out.add( AEItemStack.create( is ) ); - } - return out; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + final ItemStack is = this.dsu.getStoredItemType(); + if (is != null) { + out.add(AEItemStack.create(is)); + } + return out; + } - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } } diff --git a/src/main/java/appeng/integration/modules/helpers/NullRFHandler.java b/src/main/java/appeng/integration/modules/helpers/NullRFHandler.java index 27a90d37454..4dd77525e6d 100644 --- a/src/main/java/appeng/integration/modules/helpers/NullRFHandler.java +++ b/src/main/java/appeng/integration/modules/helpers/NullRFHandler.java @@ -18,35 +18,28 @@ package appeng.integration.modules.helpers; - import cofh.api.energy.IEnergyReceiver; import net.minecraftforge.common.util.ForgeDirection; +public class NullRFHandler implements IEnergyReceiver { -public class NullRFHandler implements IEnergyReceiver -{ - - @Override - public int receiveEnergy( final ForgeDirection from, final int maxReceive, final boolean simulate ) - { - return 0; - } + @Override + public int receiveEnergy(final ForgeDirection from, final int maxReceive, final boolean simulate) { + return 0; + } - @Override - public int getEnergyStored( final ForgeDirection from ) - { - return 0; - } + @Override + public int getEnergyStored(final ForgeDirection from) { + return 0; + } - @Override - public int getMaxEnergyStored( final ForgeDirection from ) - { - return 0; - } + @Override + public int getMaxEnergyStored(final ForgeDirection from) { + return 0; + } - @Override - public boolean canConnectEnergy( final ForgeDirection from ) - { - return true; - } + @Override + public boolean canConnectEnergy(final ForgeDirection from) { + return true; + } } diff --git a/src/main/java/appeng/integration/modules/waila/BaseWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/BaseWailaDataProvider.java index a52181c94d0..92899a9f891 100644 --- a/src/main/java/appeng/integration/modules/waila/BaseWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/BaseWailaDataProvider.java @@ -18,7 +18,7 @@ package appeng.integration.modules.waila; - +import java.util.List; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import mcp.mobius.waila.api.IWailaDataProvider; @@ -28,9 +28,6 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.util.List; - - /** * Base implementation for {@link mcp.mobius.waila.api.IWailaDataProvider} * @@ -38,35 +35,48 @@ * @version rv2 * @since rv2 */ -public abstract class BaseWailaDataProvider implements IWailaDataProvider -{ - @Override - public ItemStack getWailaStack( final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return null; - } +public abstract class BaseWailaDataProvider implements IWailaDataProvider { + @Override + public ItemStack getWailaStack(final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + return null; + } - @Override - public List getWailaHead( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaHead( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + return currentToolTip; + } - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaBody( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + return currentToolTip; + } - @Override - public List getWailaTail( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaTail( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + return currentToolTip; + } - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final TileEntity te, final NBTTagCompound tag, final World world, final int x, final int y, final int z ) - { - return tag; - } + @Override + public NBTTagCompound getNBTData( + final EntityPlayerMP player, + final TileEntity te, + final NBTTagCompound tag, + final World world, + final int x, + final int y, + final int z) { + return tag; + } } diff --git a/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java index 919c761818c..39803adabbc 100644 --- a/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java @@ -18,13 +18,14 @@ package appeng.integration.modules.waila; - -import java.util.List; - +import appeng.api.parts.IPart; import appeng.integration.modules.waila.part.*; import com.google.common.base.Optional; import com.google.common.collect.Lists; - +import java.util.List; +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; +import mcp.mobius.waila.api.IWailaDataProvider; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -32,13 +33,6 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; -import mcp.mobius.waila.api.IWailaDataProvider; - -import appeng.api.parts.IPart; - - /** * Delegation provider for parts through {@link IPartWailaDataProvider} * @@ -46,146 +40,146 @@ * @version rv2 * @since rv2 */ -public final class PartWailaDataProvider implements IWailaDataProvider -{ - /** - * Contains all providers - */ - private final List providers; - - /** - * Can access parts through view-hits - */ - private final PartAccessor accessor = new PartAccessor(); - - /** - * Traces views hit on blocks - */ - private final Tracer tracer = new Tracer(); - - /** - * Initializes the provider list with all wanted providers - */ - public PartWailaDataProvider() - { - final IPartWailaDataProvider channel = new ChannelWailaDataProvider(); - final IPartWailaDataProvider storageMonitor = new StorageMonitorWailaDataProvider(); - final IPartWailaDataProvider powerState = new PowerStateWailaDataProvider(); - final IPartWailaDataProvider p2pState = new P2PStateWailaDataProvider(); - final IPartWailaDataProvider partStack = new BasePartWailaDataProvider(); - - this.providers = Lists.newArrayList( channel, storageMonitor, powerState, p2pState, partStack); - } - - @Override - public ItemStack getWailaStack( final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - final MovingObjectPosition mop = accessor.getPosition(); - - final Optional maybePart = this.accessor.getMaybePart( te, mop ); - - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); - - ItemStack wailaStack = null; - - for( final IPartWailaDataProvider provider : this.providers ) - { - wailaStack = provider.getWailaStack( part, config, wailaStack ); - if (wailaStack != null) - break; - } - return wailaStack; - } - - return null; - } - - @Override - public List getWailaHead( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - final MovingObjectPosition mop = accessor.getPosition(); - - final Optional maybePart = this.accessor.getMaybePart( te, mop ); - - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); - - for( final IPartWailaDataProvider provider : this.providers ) - { - provider.getWailaHead( part, currentToolTip, accessor, config ); - } - } - - return currentToolTip; - } - - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - final MovingObjectPosition mop = accessor.getPosition(); - - final Optional maybePart = this.accessor.getMaybePart( te, mop ); - - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); - - for( final IPartWailaDataProvider provider : this.providers ) - { - provider.getWailaBody( part, currentToolTip, accessor, config ); - } - } - - return currentToolTip; - } - - @Override - public List getWailaTail( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - final MovingObjectPosition mop = accessor.getPosition(); - - final Optional maybePart = this.accessor.getMaybePart( te, mop ); - - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); - - for( final IPartWailaDataProvider provider : this.providers ) - { - provider.getWailaTail( part, currentToolTip, accessor, config ); - } - } - - return currentToolTip; - } - - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final TileEntity te, final NBTTagCompound tag, final World world, final int x, final int y, final int z ) - { - final MovingObjectPosition mop = this.tracer.retraceBlock( world, player, x, y, z ); - - if( mop != null ) - { - final Optional maybePart = this.accessor.getMaybePart( te, mop ); - - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); - - for( final IPartWailaDataProvider provider : this.providers ) - { - provider.getNBTData( player, part, te, tag, world, x, y, z ); - } - } - } - - return tag; - } +public final class PartWailaDataProvider implements IWailaDataProvider { + /** + * Contains all providers + */ + private final List providers; + + /** + * Can access parts through view-hits + */ + private final PartAccessor accessor = new PartAccessor(); + + /** + * Traces views hit on blocks + */ + private final Tracer tracer = new Tracer(); + + /** + * Initializes the provider list with all wanted providers + */ + public PartWailaDataProvider() { + final IPartWailaDataProvider channel = new ChannelWailaDataProvider(); + final IPartWailaDataProvider storageMonitor = new StorageMonitorWailaDataProvider(); + final IPartWailaDataProvider powerState = new PowerStateWailaDataProvider(); + final IPartWailaDataProvider p2pState = new P2PStateWailaDataProvider(); + final IPartWailaDataProvider partStack = new BasePartWailaDataProvider(); + + this.providers = Lists.newArrayList(channel, storageMonitor, powerState, p2pState, partStack); + } + + @Override + public ItemStack getWailaStack(final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + final TileEntity te = accessor.getTileEntity(); + final MovingObjectPosition mop = accessor.getPosition(); + + final Optional maybePart = this.accessor.getMaybePart(te, mop); + + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); + + ItemStack wailaStack = null; + + for (final IPartWailaDataProvider provider : this.providers) { + wailaStack = provider.getWailaStack(part, config, wailaStack); + if (wailaStack != null) break; + } + return wailaStack; + } + + return null; + } + + @Override + public List getWailaHead( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + final TileEntity te = accessor.getTileEntity(); + final MovingObjectPosition mop = accessor.getPosition(); + + final Optional maybePart = this.accessor.getMaybePart(te, mop); + + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); + + for (final IPartWailaDataProvider provider : this.providers) { + provider.getWailaHead(part, currentToolTip, accessor, config); + } + } + + return currentToolTip; + } + + @Override + public List getWailaBody( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + final TileEntity te = accessor.getTileEntity(); + final MovingObjectPosition mop = accessor.getPosition(); + + final Optional maybePart = this.accessor.getMaybePart(te, mop); + + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); + + for (final IPartWailaDataProvider provider : this.providers) { + provider.getWailaBody(part, currentToolTip, accessor, config); + } + } + + return currentToolTip; + } + + @Override + public List getWailaTail( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + final TileEntity te = accessor.getTileEntity(); + final MovingObjectPosition mop = accessor.getPosition(); + + final Optional maybePart = this.accessor.getMaybePart(te, mop); + + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); + + for (final IPartWailaDataProvider provider : this.providers) { + provider.getWailaTail(part, currentToolTip, accessor, config); + } + } + + return currentToolTip; + } + + @Override + public NBTTagCompound getNBTData( + final EntityPlayerMP player, + final TileEntity te, + final NBTTagCompound tag, + final World world, + final int x, + final int y, + final int z) { + final MovingObjectPosition mop = this.tracer.retraceBlock(world, player, x, y, z); + + if (mop != null) { + final Optional maybePart = this.accessor.getMaybePart(te, mop); + + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); + + for (final IPartWailaDataProvider provider : this.providers) { + provider.getNBTData(player, part, te, tag, world, x, y, z); + } + } + } + + return tag; + } } diff --git a/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java index 8b38bf6718a..bd474867794 100644 --- a/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java @@ -18,12 +18,12 @@ package appeng.integration.modules.waila; - import appeng.integration.modules.waila.tile.ChargerWailaDataProvider; import appeng.integration.modules.waila.tile.CraftingMonitorWailaDataProvider; import appeng.integration.modules.waila.tile.PowerStateWailaDataProvider; import appeng.integration.modules.waila.tile.PowerStorageWailaDataProvider; import com.google.common.collect.Lists; +import java.util.List; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import mcp.mobius.waila.api.IWailaDataProvider; @@ -33,9 +33,6 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.util.List; - - /** * Delegation provider for tiles through {@link mcp.mobius.waila.api.IWailaDataProvider} * @@ -43,73 +40,81 @@ * @version rv2 * @since rv2 */ -public final class TileWailaDataProvider implements IWailaDataProvider -{ - /** - * Contains all providers - */ - private final List providers; - - /** - * Initializes the provider list with all wanted providers - */ - public TileWailaDataProvider() - { - final IWailaDataProvider charger = new ChargerWailaDataProvider(); - final IWailaDataProvider energyCell = new PowerStorageWailaDataProvider(); - final IWailaDataProvider craftingBlock = new PowerStateWailaDataProvider(); - final IWailaDataProvider craftingMonitor = new CraftingMonitorWailaDataProvider(); - - this.providers = Lists.newArrayList( charger, energyCell, craftingBlock, craftingMonitor ); - } - - @Override - public ItemStack getWailaStack( final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return null; - } - - @Override - public List getWailaHead( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - for( final IWailaDataProvider provider : this.providers ) - { - provider.getWailaHead( itemStack, currentToolTip, accessor, config ); - } - - return currentToolTip; - } - - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - for( final IWailaDataProvider provider : this.providers ) - { - provider.getWailaBody( itemStack, currentToolTip, accessor, config ); - } - - return currentToolTip; - } - - @Override - public List getWailaTail( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - for( final IWailaDataProvider provider : this.providers ) - { - provider.getWailaTail( itemStack, currentToolTip, accessor, config ); - } - - return currentToolTip; - } - - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final TileEntity te, final NBTTagCompound tag, final World world, final int x, final int y, final int z ) - { - for( final IWailaDataProvider provider : this.providers ) - { - provider.getNBTData( player, te, tag, world, x, y, z ); - } - - return tag; - } +public final class TileWailaDataProvider implements IWailaDataProvider { + /** + * Contains all providers + */ + private final List providers; + + /** + * Initializes the provider list with all wanted providers + */ + public TileWailaDataProvider() { + final IWailaDataProvider charger = new ChargerWailaDataProvider(); + final IWailaDataProvider energyCell = new PowerStorageWailaDataProvider(); + final IWailaDataProvider craftingBlock = new PowerStateWailaDataProvider(); + final IWailaDataProvider craftingMonitor = new CraftingMonitorWailaDataProvider(); + + this.providers = Lists.newArrayList(charger, energyCell, craftingBlock, craftingMonitor); + } + + @Override + public ItemStack getWailaStack(final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + return null; + } + + @Override + public List getWailaHead( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + for (final IWailaDataProvider provider : this.providers) { + provider.getWailaHead(itemStack, currentToolTip, accessor, config); + } + + return currentToolTip; + } + + @Override + public List getWailaBody( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + for (final IWailaDataProvider provider : this.providers) { + provider.getWailaBody(itemStack, currentToolTip, accessor, config); + } + + return currentToolTip; + } + + @Override + public List getWailaTail( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + for (final IWailaDataProvider provider : this.providers) { + provider.getWailaTail(itemStack, currentToolTip, accessor, config); + } + + return currentToolTip; + } + + @Override + public NBTTagCompound getNBTData( + final EntityPlayerMP player, + final TileEntity te, + final NBTTagCompound tag, + final World world, + final int x, + final int y, + final int z) { + for (final IWailaDataProvider provider : this.providers) { + provider.getNBTData(player, te, tag, world, x, y, z); + } + + return tag; + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/BasePartWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/BasePartWailaDataProvider.java index 08647d6044e..587bf943d76 100644 --- a/src/main/java/appeng/integration/modules/waila/part/BasePartWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/BasePartWailaDataProvider.java @@ -18,9 +18,9 @@ package appeng.integration.modules.waila.part; - import appeng.api.parts.IPart; import appeng.api.parts.PartItemStack; +import java.util.List; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.entity.player.EntityPlayerMP; @@ -29,9 +29,6 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.util.List; - - /** * Default implementation of {@link appeng.integration.modules.waila.part.IPartWailaDataProvider} * @@ -39,35 +36,49 @@ * @version rv2 * @since rv2 */ -public class BasePartWailaDataProvider implements IPartWailaDataProvider -{ - @Override - public ItemStack getWailaStack( final IPart part, final IWailaConfigHandler config, final ItemStack partStack ) - { - return part.getItemStack(PartItemStack.World); - } +public class BasePartWailaDataProvider implements IPartWailaDataProvider { + @Override + public ItemStack getWailaStack(final IPart part, final IWailaConfigHandler config, final ItemStack partStack) { + return part.getItemStack(PartItemStack.World); + } - @Override - public List getWailaHead( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaHead( + final IPart part, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + return currentToolTip; + } - @Override - public List getWailaBody( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaBody( + final IPart part, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + return currentToolTip; + } - @Override - public List getWailaTail( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaTail( + final IPart part, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + return currentToolTip; + } - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final IPart part, final TileEntity te, final NBTTagCompound tag, final World world, final int x, final int y, final int z ) - { - return tag; - } + @Override + public NBTTagCompound getNBTData( + final EntityPlayerMP player, + final IPart part, + final TileEntity te, + final NBTTagCompound tag, + final World world, + final int x, + final int y, + final int z) { + return tag; + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/ChannelWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/ChannelWailaDataProvider.java index 362af9762c0..5c310087101 100644 --- a/src/main/java/appeng/integration/modules/waila/part/ChannelWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/ChannelWailaDataProvider.java @@ -18,7 +18,6 @@ package appeng.integration.modules.waila.part; - import appeng.api.parts.IPart; import appeng.core.localization.WailaText; import appeng.parts.networking.PartCableSmart; @@ -26,6 +25,7 @@ import appeng.parts.networking.PartUltraDenseCableSmart; import gnu.trove.map.TObjectShortMap; import gnu.trove.map.hash.TObjectShortHashMap; +import java.util.List; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.entity.player.EntityPlayerMP; @@ -33,9 +33,6 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.util.List; - - /** * Channel-information provider for WAILA * @@ -43,111 +40,112 @@ * @version rv2 * @since rv2 */ -public final class ChannelWailaDataProvider extends BasePartWailaDataProvider -{ - /** - * Channel key used for the transferred {@link net.minecraft.nbt.NBTTagCompound} - */ - private static final String ID_USED_CHANNELS = "usedChannels"; - - /** - * Used cache for channels if the channel was not transmitted through the server. - *

- * This is useful, when a player just started to look at a tile and thus just requested the new information from the - * server. - *

- * The cache will be updated from the server. - */ - private final TObjectShortMap cache = new TObjectShortHashMap<>(); - - /** - * Adds the used and max channel to the tool tip - * - * @param part being looked at part - * @param currentToolTip current tool tip - * @param accessor wrapper for various world information - * @param config config to react to various settings - * @return modified tool tip - */ - @Override - public List getWailaBody( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - if( part instanceof PartCableSmart || part instanceof PartDenseCable) - { - final short usedChannels = this.getUsedChannels(part, accessor.getNBTData()); - final int maxChannels = ((part instanceof PartUltraDenseCableSmart) ? 128 : (( part instanceof PartDenseCable ) ? 32 : 8 )); - - final String formattedToolTip = String.format( WailaText.Channels.getLocal(), usedChannels, maxChannels ); - currentToolTip.add( formattedToolTip ); - } - - return currentToolTip; - } - - /** - * Determines the source of the channel. - *

- * If the client received information of the channels on the server, they are used, else if the cache contains a - * previous stored value, this will be used. Default value is 0. - * - * @param part part to be looked at - * @param tag tag maybe containing the channel information - * @return used channels on the cable - */ - private short getUsedChannels( final IPart part, final NBTTagCompound tag) - { - final short usedChannels; - - if( tag.hasKey( ID_USED_CHANNELS ) ) - { - usedChannels = tag.getShort( ID_USED_CHANNELS ); - this.cache.put( part, usedChannels ); - } - else if( this.cache.containsKey( part ) ) - { - usedChannels = this.cache.get( part ); - } - else - { - usedChannels = 0; - } - - return usedChannels; - } - - /** - * Called on server to transfer information from server to client. - *

- * If the part is a cable, it writes the channel information in the {@code #tag} using the {@code ID_USED_CHANNELS} - * key. - * - * @param player player looking at the part - * @param part part being looked at - * @param te host of the part - * @param tag transferred tag which is send to the client - * @param world world of the part - * @param x x pos of the part - * @param y y pos of the part - * @param z z pos of the part - * @return tag send to the client - */ - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final IPart part, final TileEntity te, final NBTTagCompound tag, final World world, final int x, final int y, final int z ) - { - if( part instanceof PartCableSmart || part instanceof PartDenseCable) - { - final NBTTagCompound tempTag = new NBTTagCompound(); - - part.writeToNBT( tempTag ); - - if( tempTag.hasKey( ID_USED_CHANNELS ) ) - { - final short usedChannels = tempTag.getShort( ID_USED_CHANNELS ); - - tag.setShort( ID_USED_CHANNELS, usedChannels ); - } - } - - return tag; - } +public final class ChannelWailaDataProvider extends BasePartWailaDataProvider { + /** + * Channel key used for the transferred {@link net.minecraft.nbt.NBTTagCompound} + */ + private static final String ID_USED_CHANNELS = "usedChannels"; + + /** + * Used cache for channels if the channel was not transmitted through the server. + *

+ * This is useful, when a player just started to look at a tile and thus just requested the new information from the + * server. + *

+ * The cache will be updated from the server. + */ + private final TObjectShortMap cache = new TObjectShortHashMap<>(); + + /** + * Adds the used and max channel to the tool tip + * + * @param part being looked at part + * @param currentToolTip current tool tip + * @param accessor wrapper for various world information + * @param config config to react to various settings + * @return modified tool tip + */ + @Override + public List getWailaBody( + final IPart part, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + if (part instanceof PartCableSmart || part instanceof PartDenseCable) { + final short usedChannels = this.getUsedChannels(part, accessor.getNBTData()); + final int maxChannels = + ((part instanceof PartUltraDenseCableSmart) ? 128 : ((part instanceof PartDenseCable) ? 32 : 8)); + + final String formattedToolTip = String.format(WailaText.Channels.getLocal(), usedChannels, maxChannels); + currentToolTip.add(formattedToolTip); + } + + return currentToolTip; + } + + /** + * Determines the source of the channel. + *

+ * If the client received information of the channels on the server, they are used, else if the cache contains a + * previous stored value, this will be used. Default value is 0. + * + * @param part part to be looked at + * @param tag tag maybe containing the channel information + * @return used channels on the cable + */ + private short getUsedChannels(final IPart part, final NBTTagCompound tag) { + final short usedChannels; + + if (tag.hasKey(ID_USED_CHANNELS)) { + usedChannels = tag.getShort(ID_USED_CHANNELS); + this.cache.put(part, usedChannels); + } else if (this.cache.containsKey(part)) { + usedChannels = this.cache.get(part); + } else { + usedChannels = 0; + } + + return usedChannels; + } + + /** + * Called on server to transfer information from server to client. + *

+ * If the part is a cable, it writes the channel information in the {@code #tag} using the {@code ID_USED_CHANNELS} + * key. + * + * @param player player looking at the part + * @param part part being looked at + * @param te host of the part + * @param tag transferred tag which is send to the client + * @param world world of the part + * @param x x pos of the part + * @param y y pos of the part + * @param z z pos of the part + * @return tag send to the client + */ + @Override + public NBTTagCompound getNBTData( + final EntityPlayerMP player, + final IPart part, + final TileEntity te, + final NBTTagCompound tag, + final World world, + final int x, + final int y, + final int z) { + if (part instanceof PartCableSmart || part instanceof PartDenseCable) { + final NBTTagCompound tempTag = new NBTTagCompound(); + + part.writeToNBT(tempTag); + + if (tempTag.hasKey(ID_USED_CHANNELS)) { + final short usedChannels = tempTag.getShort(ID_USED_CHANNELS); + + tag.setShort(ID_USED_CHANNELS, usedChannels); + } + } + + return tag; + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/IPartWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/IPartWailaDataProvider.java index 57816d493e6..f9f945735c8 100644 --- a/src/main/java/appeng/integration/modules/waila/part/IPartWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/IPartWailaDataProvider.java @@ -18,8 +18,8 @@ package appeng.integration.modules.waila.part; - import appeng.api.parts.IPart; +import java.util.List; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.entity.player.EntityPlayerMP; @@ -28,9 +28,6 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.util.List; - - /** * An abstraction layer of the {@link appeng.integration.modules.waila.part.IPartWailaDataProvider} for * {@link appeng.api.parts.IPart}. @@ -39,15 +36,18 @@ * @version rv2 * @since rv2 */ -public interface IPartWailaDataProvider -{ - ItemStack getWailaStack( IPart part, IWailaConfigHandler config, ItemStack partStack ); +public interface IPartWailaDataProvider { + ItemStack getWailaStack(IPart part, IWailaConfigHandler config, ItemStack partStack); - List getWailaHead( IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ); + List getWailaHead( + IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config); - List getWailaBody( IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ); + List getWailaBody( + IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config); - List getWailaTail( IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ); + List getWailaTail( + IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config); - NBTTagCompound getNBTData( EntityPlayerMP player, IPart part, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z ); + NBTTagCompound getNBTData( + EntityPlayerMP player, IPart part, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z); } diff --git a/src/main/java/appeng/integration/modules/waila/part/P2PStateWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/P2PStateWailaDataProvider.java index 6d4bc13345e..f2ecbc17554 100644 --- a/src/main/java/appeng/integration/modules/waila/part/P2PStateWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/P2PStateWailaDataProvider.java @@ -18,166 +18,141 @@ package appeng.integration.modules.waila.part; - -import java.text.NumberFormat; -import java.util.List; -import java.util.Locale; - +import appeng.api.parts.IPart; import appeng.core.localization.ButtonToolTips; +import appeng.core.localization.WailaText; +import appeng.me.GridAccessException; +import appeng.parts.p2p.PartP2PTunnel; import com.google.common.collect.Iterators; - +import java.util.List; +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; - -import appeng.api.parts.IPart; -import appeng.core.localization.WailaText; -import appeng.me.GridAccessException; -import appeng.parts.p2p.PartP2PTunnel; -import appeng.util.Platform; - - /** * Provides information about a P2P tunnel to WAILA. */ -public final class P2PStateWailaDataProvider extends BasePartWailaDataProvider -{ - - private static final int STATE_UNLINKED = 0; - private static final int STATE_OUTPUT = 1; - private static final int STATE_INPUT = 2; - public static final String TAG_P2P_STATE = "p2p_state"; - public static final String TAG_P2P_FREQUENCY = "p2p_frequency"; - public static final String TAG_CUSTOMNAME = "custom_name"; - - /** - * Adds state to the tooltip - * - * @param part part with state - * @param currentToolTip to be added to tooltip - * @param accessor wrapper for various information - * @param config config settings - * - * @return modified tooltip - */ - @Override - public List getWailaBody( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - if( part instanceof PartP2PTunnel ) - { - NBTTagCompound nbtData = accessor.getNBTData(); - if( nbtData.hasKey( TAG_P2P_STATE ) ) - { - int[] stateArr = nbtData.getIntArray( TAG_P2P_STATE ); - if( stateArr.length == 2 ) - { - int state = stateArr[0]; - int outputs = stateArr[1]; - - switch( state ) - { - case STATE_UNLINKED: - currentToolTip.add( WailaText.P2PUnlinked.getLocal() ); - break; - case STATE_OUTPUT: - currentToolTip.add( WailaText.P2POutput.getLocal() ); - break; - case STATE_INPUT: - currentToolTip.add( getOutputText( outputs ) ); - break; - } - } - - final long freq = nbtData.getLong( TAG_P2P_FREQUENCY ); - final String freqTooltip = String.format("%X", freq ).replaceAll("(.{4})", "$0 ").trim(); +public final class P2PStateWailaDataProvider extends BasePartWailaDataProvider { + + private static final int STATE_UNLINKED = 0; + private static final int STATE_OUTPUT = 1; + private static final int STATE_INPUT = 2; + public static final String TAG_P2P_STATE = "p2p_state"; + public static final String TAG_P2P_FREQUENCY = "p2p_frequency"; + public static final String TAG_CUSTOMNAME = "custom_name"; + + /** + * Adds state to the tooltip + * + * @param part part with state + * @param currentToolTip to be added to tooltip + * @param accessor wrapper for various information + * @param config config settings + * + * @return modified tooltip + */ + @Override + public List getWailaBody( + final IPart part, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + if (part instanceof PartP2PTunnel) { + NBTTagCompound nbtData = accessor.getNBTData(); + if (nbtData.hasKey(TAG_P2P_STATE)) { + int[] stateArr = nbtData.getIntArray(TAG_P2P_STATE); + if (stateArr.length == 2) { + int state = stateArr[0]; + int outputs = stateArr[1]; + + switch (state) { + case STATE_UNLINKED: + currentToolTip.add(WailaText.P2PUnlinked.getLocal()); + break; + case STATE_OUTPUT: + currentToolTip.add(WailaText.P2POutput.getLocal()); + break; + case STATE_INPUT: + currentToolTip.add(getOutputText(outputs)); + break; + } + } + + final long freq = nbtData.getLong(TAG_P2P_FREQUENCY); + final String freqTooltip = + String.format("%X", freq).replaceAll("(.{4})", "$0 ").trim(); final String local = ButtonToolTips.P2PFrequency.getLocal(); - currentToolTip.add( String.format( local, freqTooltip ) ); - if (nbtData.hasKey(TAG_CUSTOMNAME)) - currentToolTip.add(nbtData.getString(TAG_CUSTOMNAME)); - } - } - - return currentToolTip; - } - - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final IPart part, final TileEntity te, final NBTTagCompound tag, final World world, final int x, final int y, final int z ) - { - if( part instanceof PartP2PTunnel ) - { - final PartP2PTunnel tunnel = (PartP2PTunnel) part; - - if( !tunnel.isPowered() ) - { - return tag; - } - - if (tunnel.hasCustomName()) - tag.setString(TAG_CUSTOMNAME, tunnel.getCustomName()); - - tag.setLong( TAG_P2P_FREQUENCY, tunnel.getFrequency() ); - - // The default state - int state = STATE_UNLINKED; - int outputCount = 0; - - if( !tunnel.isOutput() ) - { - outputCount = getOutputCount( tunnel ); - if( outputCount > 0 ) - { - // Only set it to INPUT if we know there are any outputs - state = STATE_INPUT; - } - } - else - { - PartP2PTunnel input = tunnel.getInput(); - if( input != null ) - { - state = STATE_OUTPUT; - } - } - - tag.setIntArray( TAG_P2P_STATE, new int[] { - state, - outputCount - } ); - - } - - return tag; - } - - private static int getOutputCount( PartP2PTunnel tunnel ) - { - try - { - return Iterators.size( tunnel.getOutputs().iterator() ); - } - catch( GridAccessException e ) - { - // Well... unknown size it is! - return 0; - } - } - - private static String getOutputText( int outputs ) - { - if( outputs <= 1 ) - { - return WailaText.P2PInputOneOutput.getLocal(); - } - else - { - return String.format( WailaText.P2PInputManyOutputs.getLocal(), outputs ); - } - } - + currentToolTip.add(String.format(local, freqTooltip)); + if (nbtData.hasKey(TAG_CUSTOMNAME)) currentToolTip.add(nbtData.getString(TAG_CUSTOMNAME)); + } + } + + return currentToolTip; + } + + @Override + public NBTTagCompound getNBTData( + final EntityPlayerMP player, + final IPart part, + final TileEntity te, + final NBTTagCompound tag, + final World world, + final int x, + final int y, + final int z) { + if (part instanceof PartP2PTunnel) { + final PartP2PTunnel tunnel = (PartP2PTunnel) part; + + if (!tunnel.isPowered()) { + return tag; + } + + if (tunnel.hasCustomName()) tag.setString(TAG_CUSTOMNAME, tunnel.getCustomName()); + + tag.setLong(TAG_P2P_FREQUENCY, tunnel.getFrequency()); + + // The default state + int state = STATE_UNLINKED; + int outputCount = 0; + + if (!tunnel.isOutput()) { + outputCount = getOutputCount(tunnel); + if (outputCount > 0) { + // Only set it to INPUT if we know there are any outputs + state = STATE_INPUT; + } + } else { + PartP2PTunnel input = tunnel.getInput(); + if (input != null) { + state = STATE_OUTPUT; + } + } + + tag.setIntArray(TAG_P2P_STATE, new int[] {state, outputCount}); + } + + return tag; + } + + private static int getOutputCount(PartP2PTunnel tunnel) { + try { + return Iterators.size(tunnel.getOutputs().iterator()); + } catch (GridAccessException e) { + // Well... unknown size it is! + return 0; + } + } + + private static String getOutputText(int outputs) { + if (outputs <= 1) { + return WailaText.P2PInputOneOutput.getLocal(); + } else { + return String.format(WailaText.P2PInputManyOutputs.getLocal(), outputs); + } + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/PartAccessor.java b/src/main/java/appeng/integration/modules/waila/part/PartAccessor.java index 9344aeffb47..621ea8ae7ca 100644 --- a/src/main/java/appeng/integration/modules/waila/part/PartAccessor.java +++ b/src/main/java/appeng/integration/modules/waila/part/PartAccessor.java @@ -18,7 +18,6 @@ package appeng.integration.modules.waila.part; - import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import appeng.api.parts.SelectedPart; @@ -27,7 +26,6 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; - /** * Accessor to access specific parts for WAILA * @@ -35,32 +33,28 @@ * @version rv2 * @since rv2 */ -public final class PartAccessor -{ - /** - * Hits a {@link appeng.api.parts.IPartHost} with {@link net.minecraft.util.MovingObjectPosition}. - *

- * You can derive the looked at {@link appeng.api.parts.IPart} by doing that. If a facade is being looked at, it is - * defined as being absent. - * - * @param te being looked at {@link net.minecraft.tileentity.TileEntity} - * @param mop type of ray-trace - * @return maybe the looked at {@link appeng.api.parts.IPart} - */ - public Optional getMaybePart( final TileEntity te, final MovingObjectPosition mop ) - { - if( te instanceof IPartHost ) - { - final Vec3 position = mop.hitVec.addVector( -mop.blockX, -mop.blockY, -mop.blockZ ); - final IPartHost host = (IPartHost) te; - final SelectedPart sp = host.selectPart( position ); +public final class PartAccessor { + /** + * Hits a {@link appeng.api.parts.IPartHost} with {@link net.minecraft.util.MovingObjectPosition}. + *

+ * You can derive the looked at {@link appeng.api.parts.IPart} by doing that. If a facade is being looked at, it is + * defined as being absent. + * + * @param te being looked at {@link net.minecraft.tileentity.TileEntity} + * @param mop type of ray-trace + * @return maybe the looked at {@link appeng.api.parts.IPart} + */ + public Optional getMaybePart(final TileEntity te, final MovingObjectPosition mop) { + if (te instanceof IPartHost) { + final Vec3 position = mop.hitVec.addVector(-mop.blockX, -mop.blockY, -mop.blockZ); + final IPartHost host = (IPartHost) te; + final SelectedPart sp = host.selectPart(position); - if( sp.part != null ) - { - return Optional.of( sp.part ); - } - } + if (sp.part != null) { + return Optional.of(sp.part); + } + } - return Optional.absent(); - } + return Optional.absent(); + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/PartStackWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/PartStackWailaDataProvider.java index 45f106e1728..8131278b1fc 100644 --- a/src/main/java/appeng/integration/modules/waila/part/PartStackWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/PartStackWailaDataProvider.java @@ -18,13 +18,11 @@ package appeng.integration.modules.waila.part; - import appeng.api.parts.IPart; import appeng.api.parts.PartItemStack; import mcp.mobius.waila.api.IWailaConfigHandler; import net.minecraft.item.ItemStack; - /** * Part ItemStack provider for WAILA * @@ -32,14 +30,11 @@ * @version rv2 * @since rv2 */ -public class PartStackWailaDataProvider extends BasePartWailaDataProvider -{ - - @Override - public ItemStack getWailaStack( final IPart part, final IWailaConfigHandler config, ItemStack partStack ) - { - partStack = part.getItemStack( PartItemStack.Pick ); - return partStack; - } +public class PartStackWailaDataProvider extends BasePartWailaDataProvider { + @Override + public ItemStack getWailaStack(final IPart part, final IWailaConfigHandler config, ItemStack partStack) { + partStack = part.getItemStack(PartItemStack.Pick); + return partStack; + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/PowerStateWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/PowerStateWailaDataProvider.java index 6e960a818fc..683bddb56ff 100644 --- a/src/main/java/appeng/integration/modules/waila/part/PowerStateWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/PowerStateWailaDataProvider.java @@ -18,16 +18,13 @@ package appeng.integration.modules.waila.part; - import appeng.api.implementations.IPowerChannelState; import appeng.api.parts.IPart; import appeng.core.localization.WailaText; +import java.util.List; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; -import java.util.List; - - /** * Power state provider for WAILA * @@ -35,58 +32,51 @@ * @version rv2 * @since rv2 */ -public final class PowerStateWailaDataProvider extends BasePartWailaDataProvider -{ - /** - * Adds state to the tooltip - * - * @param part part with state - * @param currentToolTip to be added to tooltip - * @param accessor wrapper for various information - * @param config config settings - * @return modified tooltip - */ - @Override - public List getWailaBody( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - if( part instanceof IPowerChannelState ) - { - final IPowerChannelState state = (IPowerChannelState) part; +public final class PowerStateWailaDataProvider extends BasePartWailaDataProvider { + /** + * Adds state to the tooltip + * + * @param part part with state + * @param currentToolTip to be added to tooltip + * @param accessor wrapper for various information + * @param config config settings + * @return modified tooltip + */ + @Override + public List getWailaBody( + final IPart part, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + if (part instanceof IPowerChannelState) { + final IPowerChannelState state = (IPowerChannelState) part; - currentToolTip.add( this.getToolTip( state.isActive(), state.isPowered(), state.isBooting() ) ); - } + currentToolTip.add(this.getToolTip(state.isActive(), state.isPowered(), state.isBooting())); + } - return currentToolTip; - } + return currentToolTip; + } - /** - * Gets the corresponding tool tip for different values of {@code #isActive} and {@code #isPowered} - * - * @param isActive if part is active - * @param isPowered if part is powered - * @return tooltip of the state - */ - private String getToolTip( final boolean isActive, final boolean isPowered, final boolean isBooting ) - { - final String result; + /** + * Gets the corresponding tool tip for different values of {@code #isActive} and {@code #isPowered} + * + * @param isActive if part is active + * @param isPowered if part is powered + * @return tooltip of the state + */ + private String getToolTip(final boolean isActive, final boolean isPowered, final boolean isBooting) { + final String result; - if (isBooting) - { - result = WailaText.Booting.getLocal(); - } - else if( isActive && isPowered ) - { - result = WailaText.DeviceOnline.getLocal(); - } - else if( isPowered ) - { - result = WailaText.DeviceMissingChannel.getLocal(); - } - else - { - result = WailaText.DeviceOffline.getLocal(); - } + if (isBooting) { + result = WailaText.Booting.getLocal(); + } else if (isActive && isPowered) { + result = WailaText.DeviceOnline.getLocal(); + } else if (isPowered) { + result = WailaText.DeviceMissingChannel.getLocal(); + } else { + result = WailaText.DeviceOffline.getLocal(); + } - return result; - } + return result; + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/StorageMonitorWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/StorageMonitorWailaDataProvider.java index 937d30ec2fb..86682ec8e5d 100644 --- a/src/main/java/appeng/integration/modules/waila/part/StorageMonitorWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/StorageMonitorWailaDataProvider.java @@ -18,19 +18,16 @@ package appeng.integration.modules.waila.part; - import appeng.api.implementations.parts.IPartStorageMonitor; import appeng.api.parts.IPart; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEStack; import appeng.core.localization.WailaText; +import java.util.List; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; -import java.util.List; - - /** * Storage monitor provider for WAILA * @@ -38,42 +35,42 @@ * @version rv2 * @since rv2 */ -public final class StorageMonitorWailaDataProvider extends BasePartWailaDataProvider -{ - /** - * Displays the stack if present and if the monitor is locked. - * Can handle fluids and items. - * - * @param part maybe storage monitor - * @param currentToolTip to be written to tooltip - * @param accessor information wrapper - * @param config config option - * @return modified tooltip - */ - @Override - public List getWailaBody( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - if( part instanceof IPartStorageMonitor ) - { - final IPartStorageMonitor monitor = (IPartStorageMonitor) part; +public final class StorageMonitorWailaDataProvider extends BasePartWailaDataProvider { + /** + * Displays the stack if present and if the monitor is locked. + * Can handle fluids and items. + * + * @param part maybe storage monitor + * @param currentToolTip to be written to tooltip + * @param accessor information wrapper + * @param config config option + * @return modified tooltip + */ + @Override + public List getWailaBody( + final IPart part, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + if (part instanceof IPartStorageMonitor) { + final IPartStorageMonitor monitor = (IPartStorageMonitor) part; - final IAEStack displayed = monitor.getDisplayed(); - final boolean isLocked = monitor.isLocked(); + final IAEStack displayed = monitor.getDisplayed(); + final boolean isLocked = monitor.isLocked(); - if( displayed instanceof IAEItemStack ) - { - final IAEItemStack ais = (IAEItemStack) displayed; - currentToolTip.add( WailaText.Showing.getLocal() + ": " + ais.getItemStack().getDisplayName() ); - } - else if( displayed instanceof IAEFluidStack ) - { - final IAEFluidStack ais = (IAEFluidStack) displayed; - currentToolTip.add( WailaText.Showing.getLocal() + ": " + ais.getFluid().getLocalizedName( ais.getFluidStack() ) ); - } + if (displayed instanceof IAEItemStack) { + final IAEItemStack ais = (IAEItemStack) displayed; + currentToolTip.add( + WailaText.Showing.getLocal() + ": " + ais.getItemStack().getDisplayName()); + } else if (displayed instanceof IAEFluidStack) { + final IAEFluidStack ais = (IAEFluidStack) displayed; + currentToolTip.add( + WailaText.Showing.getLocal() + ": " + ais.getFluid().getLocalizedName(ais.getFluidStack())); + } - currentToolTip.add( ( isLocked ) ? WailaText.Locked.getLocal() : WailaText.Unlocked.getLocal() ); - } + currentToolTip.add((isLocked) ? WailaText.Locked.getLocal() : WailaText.Unlocked.getLocal()); + } - return currentToolTip; - } + return currentToolTip; + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/Tracer.java b/src/main/java/appeng/integration/modules/waila/part/Tracer.java index e326a1b58e7..e26b0e99c7e 100644 --- a/src/main/java/appeng/integration/modules/waila/part/Tracer.java +++ b/src/main/java/appeng/integration/modules/waila/part/Tracer.java @@ -18,7 +18,6 @@ package appeng.integration.modules.waila.part; - import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; @@ -26,7 +25,6 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; - /** * Tracer for players hitting blocks * @@ -34,62 +32,55 @@ * @version rv2 * @since rv2 */ -public final class Tracer -{ - /** - * Trace view of players to blocks. - * Ignore all which are out of reach. - * - * @param world word of block - * @param player player viewing block - * @param x x pos of block - * @param y y pos of block - * @param z z pos of block - * @return trace movement. Can be null - */ - public MovingObjectPosition retraceBlock( final World world, final EntityPlayerMP player, final int x, final int y, final int z ) - { - final Block block = world.getBlock( x, y, z ); +public final class Tracer { + /** + * Trace view of players to blocks. + * Ignore all which are out of reach. + * + * @param world word of block + * @param player player viewing block + * @param x x pos of block + * @param y y pos of block + * @param z z pos of block + * @return trace movement. Can be null + */ + public MovingObjectPosition retraceBlock( + final World world, final EntityPlayerMP player, final int x, final int y, final int z) { + final Block block = world.getBlock(x, y, z); - final Vec3 headVec = this.getCorrectedHeadVec( player ); - final Vec3 lookVec = player.getLook( 1.0F ); - final double reach = this.getBlockReachDistance_server( player ); - final Vec3 endVec = headVec.addVector( lookVec.xCoord * reach, lookVec.yCoord * reach, lookVec.zCoord * reach ); + final Vec3 headVec = this.getCorrectedHeadVec(player); + final Vec3 lookVec = player.getLook(1.0F); + final double reach = this.getBlockReachDistance_server(player); + final Vec3 endVec = headVec.addVector(lookVec.xCoord * reach, lookVec.yCoord * reach, lookVec.zCoord * reach); - return block.collisionRayTrace( world, x, y, z, headVec, endVec ); - } + return block.collisionRayTrace(world, x, y, z, headVec, endVec); + } - /** - * Gets the view point of a player - * - * @param player player with head - * @return view point of player - */ - private Vec3 getCorrectedHeadVec( final EntityPlayer player ) - { - final Vec3 v = Vec3.createVectorHelper( player.posX, player.posY, player.posZ ); - if( player.worldObj.isRemote ) - { - // compatibility with eye height changing mods - v.yCoord += player.getEyeHeight() - player.getDefaultEyeHeight(); - } - else - { - v.yCoord += player.getEyeHeight(); - if( player instanceof EntityPlayerMP && player.isSneaking() ) - { - v.yCoord -= 0.08; - } - } - return v; - } + /** + * Gets the view point of a player + * + * @param player player with head + * @return view point of player + */ + private Vec3 getCorrectedHeadVec(final EntityPlayer player) { + final Vec3 v = Vec3.createVectorHelper(player.posX, player.posY, player.posZ); + if (player.worldObj.isRemote) { + // compatibility with eye height changing mods + v.yCoord += player.getEyeHeight() - player.getDefaultEyeHeight(); + } else { + v.yCoord += player.getEyeHeight(); + if (player instanceof EntityPlayerMP && player.isSneaking()) { + v.yCoord -= 0.08; + } + } + return v; + } - /** - * @param player multi-player player - * @return block reach distance of player - */ - private double getBlockReachDistance_server( final EntityPlayerMP player ) - { - return player.theItemInWorldManager.getBlockReachDistance(); - } + /** + * @param player multi-player player + * @return block reach distance of player + */ + private double getBlockReachDistance_server(final EntityPlayerMP player) { + return player.theItemInWorldManager.getBlockReachDistance(); + } } diff --git a/src/main/java/appeng/integration/modules/waila/tile/ChargerWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/tile/ChargerWailaDataProvider.java index 03fd06faa66..62ec8578af8 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/ChargerWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/ChargerWailaDataProvider.java @@ -18,10 +18,10 @@ package appeng.integration.modules.waila.tile; - import appeng.core.localization.WailaText; import appeng.integration.modules.waila.BaseWailaDataProvider; import appeng.tile.misc.TileCharger; +import java.util.List; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.entity.player.EntityPlayer; @@ -29,9 +29,6 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -import java.util.List; - - /** * Charger provider for WAILA * @@ -39,37 +36,37 @@ * @version rv2 * @since rv2 */ -public final class ChargerWailaDataProvider extends BaseWailaDataProvider -{ - /** - * Displays the holding item and its tooltip - * - * @param itemStack stack of charger - * @param currentToolTip unmodified tooltip - * @param accessor wrapper information - * @param config config option - * @return modified tooltip - */ - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - if( te instanceof TileCharger ) - { - final TileCharger charger = (TileCharger) te; - final IInventory chargerInventory = charger.getInternalInventory(); - final ItemStack chargingItem = chargerInventory.getStackInSlot( 0 ); +public final class ChargerWailaDataProvider extends BaseWailaDataProvider { + /** + * Displays the holding item and its tooltip + * + * @param itemStack stack of charger + * @param currentToolTip unmodified tooltip + * @param accessor wrapper information + * @param config config option + * @return modified tooltip + */ + @Override + public List getWailaBody( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + final TileEntity te = accessor.getTileEntity(); + if (te instanceof TileCharger) { + final TileCharger charger = (TileCharger) te; + final IInventory chargerInventory = charger.getInternalInventory(); + final ItemStack chargingItem = chargerInventory.getStackInSlot(0); - if( chargingItem != null ) - { - final String currentInventory = chargingItem.getDisplayName(); - final EntityPlayer player = accessor.getPlayer(); + if (chargingItem != null) { + final String currentInventory = chargingItem.getDisplayName(); + final EntityPlayer player = accessor.getPlayer(); - currentToolTip.add( WailaText.Contains + ": " + currentInventory ); - chargingItem.getItem().addInformation( chargingItem, player, currentToolTip, true ); - } - } + currentToolTip.add(WailaText.Contains + ": " + currentInventory); + chargingItem.getItem().addInformation(chargingItem, player, currentToolTip, true); + } + } - return currentToolTip; - } + return currentToolTip; + } } diff --git a/src/main/java/appeng/integration/modules/waila/tile/CraftingMonitorWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/tile/CraftingMonitorWailaDataProvider.java index c30c5c4a10c..487f351b8ff 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/CraftingMonitorWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/CraftingMonitorWailaDataProvider.java @@ -18,19 +18,16 @@ package appeng.integration.modules.waila.tile; - import appeng.api.storage.data.IAEItemStack; import appeng.core.localization.WailaText; import appeng.integration.modules.waila.BaseWailaDataProvider; import appeng.tile.crafting.TileCraftingMonitorTile; +import java.util.List; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -import java.util.List; - - /** * Crafting-monitor provider for WAILA * @@ -38,34 +35,34 @@ * @version rv2 * @since rv2 */ -public final class CraftingMonitorWailaDataProvider extends BaseWailaDataProvider -{ - /** - * Displays the item currently crafted by the CPU cluster - * - * @param itemStack stack of crafting monitor - * @param currentToolTip unmodified tooltip - * @param accessor information wrapper - * @param config config option - * @return modified tooltip - */ - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - if( te instanceof TileCraftingMonitorTile ) - { - final TileCraftingMonitorTile monitor = (TileCraftingMonitorTile) te; - final IAEItemStack displayStack = monitor.getJobProgress(); +public final class CraftingMonitorWailaDataProvider extends BaseWailaDataProvider { + /** + * Displays the item currently crafted by the CPU cluster + * + * @param itemStack stack of crafting monitor + * @param currentToolTip unmodified tooltip + * @param accessor information wrapper + * @param config config option + * @return modified tooltip + */ + @Override + public List getWailaBody( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + final TileEntity te = accessor.getTileEntity(); + if (te instanceof TileCraftingMonitorTile) { + final TileCraftingMonitorTile monitor = (TileCraftingMonitorTile) te; + final IAEItemStack displayStack = monitor.getJobProgress(); - if( displayStack != null ) - { - final String currentCrafting = displayStack.getItemStack().getDisplayName(); + if (displayStack != null) { + final String currentCrafting = displayStack.getItemStack().getDisplayName(); - currentToolTip.add( WailaText.Crafting.getLocal() + ": " + currentCrafting ); - } - } + currentToolTip.add(WailaText.Crafting.getLocal() + ": " + currentCrafting); + } + } - return currentToolTip; - } + return currentToolTip; + } } diff --git a/src/main/java/appeng/integration/modules/waila/tile/PowerStateWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/tile/PowerStateWailaDataProvider.java index 3640b8aef74..e3d31ae9802 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/PowerStateWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/PowerStateWailaDataProvider.java @@ -18,18 +18,15 @@ package appeng.integration.modules.waila.tile; - import appeng.api.implementations.IPowerChannelState; import appeng.core.localization.WailaText; import appeng.integration.modules.waila.BaseWailaDataProvider; +import java.util.List; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -import java.util.List; - - /** * Power state provider for WAILA * @@ -37,48 +34,42 @@ * @version rv2 * @since rv2 */ -public final class PowerStateWailaDataProvider extends BaseWailaDataProvider -{ - /** - * Adds state to the tooltip - * - * @param itemStack stack of power state - * @param currentToolTip to be added to tooltip - * @param accessor wrapper for various information - * @param config config settings - * @return modified tooltip - */ - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); +public final class PowerStateWailaDataProvider extends BaseWailaDataProvider { + /** + * Adds state to the tooltip + * + * @param itemStack stack of power state + * @param currentToolTip to be added to tooltip + * @param accessor wrapper for various information + * @param config config settings + * @return modified tooltip + */ + @Override + public List getWailaBody( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + final TileEntity te = accessor.getTileEntity(); - if( te instanceof IPowerChannelState ) - { - final IPowerChannelState state = (IPowerChannelState) te; + if (te instanceof IPowerChannelState) { + final IPowerChannelState state = (IPowerChannelState) te; - final boolean isActive = state.isActive(); - final boolean isPowered = state.isPowered(); - final boolean isBooting = state.isBooting(); + final boolean isActive = state.isActive(); + final boolean isPowered = state.isPowered(); + final boolean isBooting = state.isBooting(); - if (isBooting) - { - currentToolTip.add( WailaText.Booting.getLocal() ); - } - else if( isActive && isPowered ) - { - currentToolTip.add( WailaText.DeviceOnline.getLocal() ); - } - else if( isPowered ) - { - currentToolTip.add( WailaText.DeviceMissingChannel.getLocal() ); - } - else - { - currentToolTip.add( WailaText.DeviceOffline.getLocal() ); - } - } + if (isBooting) { + currentToolTip.add(WailaText.Booting.getLocal()); + } else if (isActive && isPowered) { + currentToolTip.add(WailaText.DeviceOnline.getLocal()); + } else if (isPowered) { + currentToolTip.add(WailaText.DeviceMissingChannel.getLocal()); + } else { + currentToolTip.add(WailaText.DeviceOffline.getLocal()); + } + } - return currentToolTip; - } -} \ No newline at end of file + return currentToolTip; + } +} diff --git a/src/main/java/appeng/integration/modules/waila/tile/PowerStorageWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/tile/PowerStorageWailaDataProvider.java index 7c7864b0ee9..b2b69940089 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/PowerStorageWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/PowerStorageWailaDataProvider.java @@ -18,13 +18,13 @@ package appeng.integration.modules.waila.tile; - import appeng.api.networking.energy.IAEPowerStorage; import appeng.core.localization.WailaText; import appeng.integration.modules.waila.BaseWailaDataProvider; import appeng.util.Platform; import gnu.trove.map.TObjectLongMap; import gnu.trove.map.hash.TObjectLongHashMap; +import java.util.List; import mcp.mobius.waila.api.ITaggedList; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; @@ -34,9 +34,6 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.util.List; - - /** * Power storage provider for WAILA * @@ -44,123 +41,121 @@ * @version rv2 * @since rv2 */ -public final class PowerStorageWailaDataProvider extends BaseWailaDataProvider -{ - /** - * Power key used for the transferred {@link net.minecraft.nbt.NBTTagCompound} - */ - private static final String ID_CURRENT_POWER = "currentPower"; - - /** - * Used cache for power if the power was not transmitted through the server. - *

- * This is useful, when a player just started to look at a tile and thus just requested the new information from the - * server. - *

- * The cache will be updated from the server. - */ - private final TObjectLongMap cache = new TObjectLongHashMap(); - - /** - * Adds the current and max power to the tool tip - * Will ignore if the tile has an energy buffer ( > 0 ) - * - * @param itemStack stack of power storage - * @param currentToolTip current tool tip - * @param accessor wrapper for various world information - * @param config config to react to various settings - * @return modified tool tip - */ - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - // Removes RF tooltip on WAILA 1.5.9+ - ( (ITaggedList) currentToolTip ).removeEntries( "RFEnergyStorage" ); - - final TileEntity te = accessor.getTileEntity(); - if( te instanceof IAEPowerStorage ) - { - final IAEPowerStorage storage = (IAEPowerStorage) te; - - final double maxPower = storage.getAEMaxPower(); - if( maxPower > 0 ) - { - final NBTTagCompound tag = accessor.getNBTData(); - - final long internalCurrentPower = this.getInternalCurrentPower( tag, te ); - final long internalMaxPower = (long) ( 100 * maxPower ); - - final String formatCurrentPower = Platform.formatPowerLong( internalCurrentPower, false ); - final String formatMaxPower = Platform.formatPowerLong( internalMaxPower, false ); - - currentToolTip.add( WailaText.Contains.getLocal() + ": " + formatCurrentPower + " / " + formatMaxPower ); - } - } - - return currentToolTip; - } - - /** - * Called on server to transfer information from server to client. - *

- * If the {@link net.minecraft.tileentity.TileEntity} is a {@link appeng.api.networking.energy.IAEPowerStorage}, it - * writes the power information to the {@code #tag} using the {@code #ID_CURRENT_POWER} key. - * - * @param player player looking at the power storage - * @param te power storage - * @param tag transferred tag which is send to the client - * @param world world of the power storage - * @param x x pos of the power storage - * @param y y pos of the power storage - * @param z z pos of the power storage - * @return tag send to the client - */ - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final TileEntity te, final NBTTagCompound tag, final World world, final int x, final int y, final int z ) - { - if( te instanceof IAEPowerStorage ) - { - final IAEPowerStorage storage = (IAEPowerStorage) te; - - if( storage.getAEMaxPower() > 0 ) - { - final long internalCurrentPower = (long) ( 100 * storage.getAECurrentPower() ); - - tag.setLong( ID_CURRENT_POWER, internalCurrentPower ); - } - } - - return tag; - } - - /** - * Determines the current power. - *

- * If the client received power information on the server, they are used, else if the cache contains a previous - * stored value, this will be used. Default value is 0. - * - * @param te te to be looked at - * @param tag tag maybe containing the channel information - * @return used channels on the cable - */ - private long getInternalCurrentPower( final NBTTagCompound tag, final TileEntity te ) - { - final long internalCurrentPower; - - if( tag.hasKey( ID_CURRENT_POWER ) ) - { - internalCurrentPower = tag.getLong( ID_CURRENT_POWER ); - this.cache.put( te, internalCurrentPower ); - } - else if( this.cache.containsKey( te ) ) - { - internalCurrentPower = this.cache.get( te ); - } - else - { - internalCurrentPower = 0; - } - - return internalCurrentPower; - } +public final class PowerStorageWailaDataProvider extends BaseWailaDataProvider { + /** + * Power key used for the transferred {@link net.minecraft.nbt.NBTTagCompound} + */ + private static final String ID_CURRENT_POWER = "currentPower"; + + /** + * Used cache for power if the power was not transmitted through the server. + *

+ * This is useful, when a player just started to look at a tile and thus just requested the new information from the + * server. + *

+ * The cache will be updated from the server. + */ + private final TObjectLongMap cache = new TObjectLongHashMap(); + + /** + * Adds the current and max power to the tool tip + * Will ignore if the tile has an energy buffer ( > 0 ) + * + * @param itemStack stack of power storage + * @param currentToolTip current tool tip + * @param accessor wrapper for various world information + * @param config config to react to various settings + * @return modified tool tip + */ + @Override + public List getWailaBody( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + // Removes RF tooltip on WAILA 1.5.9+ + ((ITaggedList) currentToolTip).removeEntries("RFEnergyStorage"); + + final TileEntity te = accessor.getTileEntity(); + if (te instanceof IAEPowerStorage) { + final IAEPowerStorage storage = (IAEPowerStorage) te; + + final double maxPower = storage.getAEMaxPower(); + if (maxPower > 0) { + final NBTTagCompound tag = accessor.getNBTData(); + + final long internalCurrentPower = this.getInternalCurrentPower(tag, te); + final long internalMaxPower = (long) (100 * maxPower); + + final String formatCurrentPower = Platform.formatPowerLong(internalCurrentPower, false); + final String formatMaxPower = Platform.formatPowerLong(internalMaxPower, false); + + currentToolTip.add(WailaText.Contains.getLocal() + ": " + formatCurrentPower + " / " + formatMaxPower); + } + } + + return currentToolTip; + } + + /** + * Called on server to transfer information from server to client. + *

+ * If the {@link net.minecraft.tileentity.TileEntity} is a {@link appeng.api.networking.energy.IAEPowerStorage}, it + * writes the power information to the {@code #tag} using the {@code #ID_CURRENT_POWER} key. + * + * @param player player looking at the power storage + * @param te power storage + * @param tag transferred tag which is send to the client + * @param world world of the power storage + * @param x x pos of the power storage + * @param y y pos of the power storage + * @param z z pos of the power storage + * @return tag send to the client + */ + @Override + public NBTTagCompound getNBTData( + final EntityPlayerMP player, + final TileEntity te, + final NBTTagCompound tag, + final World world, + final int x, + final int y, + final int z) { + if (te instanceof IAEPowerStorage) { + final IAEPowerStorage storage = (IAEPowerStorage) te; + + if (storage.getAEMaxPower() > 0) { + final long internalCurrentPower = (long) (100 * storage.getAECurrentPower()); + + tag.setLong(ID_CURRENT_POWER, internalCurrentPower); + } + } + + return tag; + } + + /** + * Determines the current power. + *

+ * If the client received power information on the server, they are used, else if the cache contains a previous + * stored value, this will be used. Default value is 0. + * + * @param te te to be looked at + * @param tag tag maybe containing the channel information + * @return used channels on the cable + */ + private long getInternalCurrentPower(final NBTTagCompound tag, final TileEntity te) { + final long internalCurrentPower; + + if (tag.hasKey(ID_CURRENT_POWER)) { + internalCurrentPower = tag.getLong(ID_CURRENT_POWER); + this.cache.put(te, internalCurrentPower); + } else if (this.cache.containsKey(te)) { + internalCurrentPower = this.cache.get(te); + } else { + internalCurrentPower = 0; + } + + return internalCurrentPower; + } } diff --git a/src/main/java/appeng/items/AEBaseItem.java b/src/main/java/appeng/items/AEBaseItem.java index 54df88d41de..e1d3da429da 100644 --- a/src/main/java/appeng/items/AEBaseItem.java +++ b/src/main/java/appeng/items/AEBaseItem.java @@ -18,90 +18,78 @@ package appeng.items; - import appeng.core.features.*; import com.google.common.base.Optional; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import java.util.List; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import java.util.EnumSet; -import java.util.List; - - -public abstract class AEBaseItem extends Item implements IAEFeature -{ - private final String fullName; - private final Optional subName; - private IFeatureHandler feature; +public abstract class AEBaseItem extends Item implements IAEFeature { + private final String fullName; + private final Optional subName; + private IFeatureHandler feature; - public AEBaseItem() - { - this( Optional.absent() ); - this.setNoRepair(); - } + public AEBaseItem() { + this(Optional.absent()); + this.setNoRepair(); + } - public AEBaseItem( final Optional subName ) - { - this.subName = subName; - this.fullName = new FeatureNameExtractor( this.getClass(), subName ).get(); - } + public AEBaseItem(final Optional subName) { + this.subName = subName; + this.fullName = new FeatureNameExtractor(this.getClass(), subName).get(); + } - @Override - public String toString() - { - return this.fullName; - } + @Override + public String toString() { + return this.fullName; + } - @Override - public IFeatureHandler handler() - { - return this.feature; - } + @Override + public IFeatureHandler handler() { + return this.feature; + } - @Override - public void postInit() - { - // override! - } + @Override + public void postInit() { + // override! + } - public void setFeature( final EnumSet f ) - { - this.feature = new ItemFeatureHandler( f, this, this, this.subName ); - } + public void setFeature(final EnumSet f) { + this.feature = new ItemFeatureHandler(f, this, this, this.subName); + } @SideOnly(Side.CLIENT) - @Override - @SuppressWarnings( "unchecked" ) - public final void addInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - this.addCheckedInformation( stack, player, lines, displayMoreInfo ); - } - - @Override - @SuppressWarnings( "unchecked" ) - public final void getSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - this.getCheckedSubItems( sameItem, creativeTab, itemStacks ); - } - - @Override - public boolean isBookEnchantable( final ItemStack itemstack1, final ItemStack itemstack2 ) - { - return false; - } + @Override + @SuppressWarnings("unchecked") + public final void addInformation( + final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo) { + this.addCheckedInformation(stack, player, lines, displayMoreInfo); + } + + @Override + @SuppressWarnings("unchecked") + public final void getSubItems(final Item sameItem, final CreativeTabs creativeTab, final List itemStacks) { + this.getCheckedSubItems(sameItem, creativeTab, itemStacks); + } + + @Override + public boolean isBookEnchantable(final ItemStack itemstack1, final ItemStack itemstack2) { + return false; + } @SideOnly(Side.CLIENT) - protected void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - super.addInformation( stack, player, lines, displayMoreInfo ); - } - - protected void getCheckedSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - super.getSubItems( sameItem, creativeTab, itemStacks ); - } + protected void addCheckedInformation( + final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo) { + super.addInformation(stack, player, lines, displayMoreInfo); + } + + protected void getCheckedSubItems( + final Item sameItem, final CreativeTabs creativeTab, final List itemStacks) { + super.getSubItems(sameItem, creativeTab, itemStacks); + } } diff --git a/src/main/java/appeng/items/contents/CellConfig.java b/src/main/java/appeng/items/contents/CellConfig.java index 56eec76c3cc..5982f9ed2de 100644 --- a/src/main/java/appeng/items/contents/CellConfig.java +++ b/src/main/java/appeng/items/contents/CellConfig.java @@ -18,27 +18,22 @@ package appeng.items.contents; - import appeng.tile.inventory.AppEngInternalInventory; import appeng.util.Platform; import net.minecraft.item.ItemStack; +public class CellConfig extends AppEngInternalInventory { -public class CellConfig extends AppEngInternalInventory -{ - - private final ItemStack is; + private final ItemStack is; - public CellConfig( final ItemStack is ) - { - super( null, 63 ); - this.is = is; - this.readFromNBT( Platform.openNbtData( is ), "list" ); - } + public CellConfig(final ItemStack is) { + super(null, 63); + this.is = is; + this.readFromNBT(Platform.openNbtData(is), "list"); + } - @Override - public void markDirty() - { - this.writeToNBT( Platform.openNbtData( this.is ), "list" ); - } -} \ No newline at end of file + @Override + public void markDirty() { + this.writeToNBT(Platform.openNbtData(this.is), "list"); + } +} diff --git a/src/main/java/appeng/items/contents/CellUpgrades.java b/src/main/java/appeng/items/contents/CellUpgrades.java index 59af1688c86..fae9cd76fe8 100644 --- a/src/main/java/appeng/items/contents/CellUpgrades.java +++ b/src/main/java/appeng/items/contents/CellUpgrades.java @@ -18,26 +18,21 @@ package appeng.items.contents; - import appeng.parts.automation.StackUpgradeInventory; import appeng.util.Platform; import net.minecraft.item.ItemStack; +public final class CellUpgrades extends StackUpgradeInventory { + private final ItemStack is; -public final class CellUpgrades extends StackUpgradeInventory -{ - private final ItemStack is; - - public CellUpgrades( final ItemStack is, final int upgrades ) - { - super( is, null, upgrades ); - this.is = is; - this.readFromNBT( Platform.openNbtData( is ), "upgrades" ); - } + public CellUpgrades(final ItemStack is, final int upgrades) { + super(is, null, upgrades); + this.is = is; + this.readFromNBT(Platform.openNbtData(is), "upgrades"); + } - @Override - public void markDirty() - { - this.writeToNBT( Platform.openNbtData( this.is ), "upgrades" ); - } -} \ No newline at end of file + @Override + public void markDirty() { + this.writeToNBT(Platform.openNbtData(this.is), "upgrades"); + } +} diff --git a/src/main/java/appeng/items/contents/NetworkToolViewer.java b/src/main/java/appeng/items/contents/NetworkToolViewer.java index d6f625c9255..85c5c737306 100644 --- a/src/main/java/appeng/items/contents/NetworkToolViewer.java +++ b/src/main/java/appeng/items/contents/NetworkToolViewer.java @@ -18,7 +18,6 @@ package appeng.items.contents; - import appeng.api.implementations.guiobjects.INetworkTool; import appeng.api.implementations.items.IUpgradeModule; import appeng.api.networking.IGridHost; @@ -27,113 +26,97 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; - -public class NetworkToolViewer implements INetworkTool -{ - - private final AppEngInternalInventory inv; - private final ItemStack is; - private final IGridHost gh; - - public NetworkToolViewer( final ItemStack is, final IGridHost gHost ) - { - this.is = is; - this.gh = gHost; - this.inv = new AppEngInternalInventory( null, 9 ); - if( is.hasTagCompound() ) // prevent crash when opening network status screen. - { - this.inv.readFromNBT( Platform.openNbtData( is ), "inv" ); - } - } - - @Override - public int getSizeInventory() - { - return this.inv.getSizeInventory(); - } - - @Override - public ItemStack getStackInSlot( final int i ) - { - return this.inv.getStackInSlot( i ); - } - - @Override - public ItemStack decrStackSize( final int i, final int j ) - { - return this.inv.decrStackSize( i, j ); - } - - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - return this.inv.getStackInSlotOnClosing( i ); - } - - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - this.inv.setInventorySlotContents( i, itemstack ); - } - - @Override - public String getInventoryName() - { - return this.inv.getInventoryName(); - } - - @Override - public boolean hasCustomInventoryName() - { - return this.inv.hasCustomInventoryName(); - } - - @Override - public int getInventoryStackLimit() - { - return this.inv.getInventoryStackLimit(); - } - - @Override - public void markDirty() - { - this.inv.markDirty(); - this.inv.writeToNBT( Platform.openNbtData( this.is ), "inv" ); - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return this.inv.isUseableByPlayer( entityplayer ); - } - - @Override - public void openInventory() - { - this.inv.openInventory(); - } - - @Override - public void closeInventory() - { - this.inv.closeInventory(); - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return this.inv.isItemValidForSlot( i, itemstack ) && itemstack.getItem() instanceof IUpgradeModule && ( (IUpgradeModule) itemstack.getItem() ).getType( itemstack ) != null; - } - - @Override - public ItemStack getItemStack() - { - return this.is; - } - - @Override - public IGridHost getGridHost() - { - return this.gh; - } +public class NetworkToolViewer implements INetworkTool { + + private final AppEngInternalInventory inv; + private final ItemStack is; + private final IGridHost gh; + + public NetworkToolViewer(final ItemStack is, final IGridHost gHost) { + this.is = is; + this.gh = gHost; + this.inv = new AppEngInternalInventory(null, 9); + if (is.hasTagCompound()) // prevent crash when opening network status screen. + { + this.inv.readFromNBT(Platform.openNbtData(is), "inv"); + } + } + + @Override + public int getSizeInventory() { + return this.inv.getSizeInventory(); + } + + @Override + public ItemStack getStackInSlot(final int i) { + return this.inv.getStackInSlot(i); + } + + @Override + public ItemStack decrStackSize(final int i, final int j) { + return this.inv.decrStackSize(i, j); + } + + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + return this.inv.getStackInSlotOnClosing(i); + } + + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + this.inv.setInventorySlotContents(i, itemstack); + } + + @Override + public String getInventoryName() { + return this.inv.getInventoryName(); + } + + @Override + public boolean hasCustomInventoryName() { + return this.inv.hasCustomInventoryName(); + } + + @Override + public int getInventoryStackLimit() { + return this.inv.getInventoryStackLimit(); + } + + @Override + public void markDirty() { + this.inv.markDirty(); + this.inv.writeToNBT(Platform.openNbtData(this.is), "inv"); + } + + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return this.inv.isUseableByPlayer(entityplayer); + } + + @Override + public void openInventory() { + this.inv.openInventory(); + } + + @Override + public void closeInventory() { + this.inv.closeInventory(); + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return this.inv.isItemValidForSlot(i, itemstack) + && itemstack.getItem() instanceof IUpgradeModule + && ((IUpgradeModule) itemstack.getItem()).getType(itemstack) != null; + } + + @Override + public ItemStack getItemStack() { + return this.is; + } + + @Override + public IGridHost getGridHost() { + return this.gh; + } } diff --git a/src/main/java/appeng/items/contents/PortableCellViewer.java b/src/main/java/appeng/items/contents/PortableCellViewer.java index fd8cc0b14c4..07495949043 100644 --- a/src/main/java/appeng/items/contents/PortableCellViewer.java +++ b/src/main/java/appeng/items/contents/PortableCellViewer.java @@ -18,7 +18,6 @@ package appeng.items.contents; - import appeng.api.config.*; import appeng.api.implementations.guiobjects.IPortableCell; import appeng.api.implementations.items.IAEItemPowerStorage; @@ -35,78 +34,66 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; - -public class PortableCellViewer extends MEMonitorHandler implements IPortableCell, IInventorySlotAware -{ - - private final ItemStack target; - private final IAEItemPowerStorage ips; - private final int inventorySlot; - - public PortableCellViewer( final ItemStack is, final int slot ) - { - super( CellInventory.getCell( is, null ) ); - this.ips = (IAEItemPowerStorage) is.getItem(); - this.target = is; - this.inventorySlot = slot; - } - - @Override - public int getInventorySlot() - { - return this.inventorySlot; - } - - @Override - public ItemStack getItemStack() - { - return this.target; - } - - @Override - public double extractAEPower( double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier ) - { - amt = usePowerMultiplier.multiply( amt ); - - if( mode == Actionable.SIMULATE ) - { - return usePowerMultiplier.divide( Math.min( amt, this.ips.getAECurrentPower( this.target ) ) ); - } - - return usePowerMultiplier.divide( this.ips.extractAEPower( this.target, amt ) ); - } - - @Override - public IMEMonitor getItemInventory() - { - return this; - } - - @Override - public IMEMonitor getFluidInventory() - { - return null; - } - - @Override - public IConfigManager getConfigManager() - { - final ConfigManager out = new ConfigManager( new IConfigManagerHost() - { - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - final NBTTagCompound data = Platform.openNbtData( PortableCellViewer.this.target ); - manager.writeToNBT( data ); - } - } ); - - out.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - out.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - out.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); - - out.readFromNBT( (NBTTagCompound) Platform.openNbtData( this.target ).copy() ); - return out; - } +public class PortableCellViewer extends MEMonitorHandler implements IPortableCell, IInventorySlotAware { + + private final ItemStack target; + private final IAEItemPowerStorage ips; + private final int inventorySlot; + + public PortableCellViewer(final ItemStack is, final int slot) { + super(CellInventory.getCell(is, null)); + this.ips = (IAEItemPowerStorage) is.getItem(); + this.target = is; + this.inventorySlot = slot; + } + + @Override + public int getInventorySlot() { + return this.inventorySlot; + } + + @Override + public ItemStack getItemStack() { + return this.target; + } + + @Override + public double extractAEPower(double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier) { + amt = usePowerMultiplier.multiply(amt); + + if (mode == Actionable.SIMULATE) { + return usePowerMultiplier.divide(Math.min(amt, this.ips.getAECurrentPower(this.target))); + } + + return usePowerMultiplier.divide(this.ips.extractAEPower(this.target, amt)); + } + + @Override + public IMEMonitor getItemInventory() { + return this; + } + + @Override + public IMEMonitor getFluidInventory() { + return null; + } + + @Override + public IConfigManager getConfigManager() { + final ConfigManager out = new ConfigManager(new IConfigManagerHost() { + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + final NBTTagCompound data = Platform.openNbtData(PortableCellViewer.this.target); + manager.writeToNBT(data); + } + }); + + out.registerSetting(Settings.SORT_BY, SortOrder.NAME); + out.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + out.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); + + out.readFromNBT((NBTTagCompound) Platform.openNbtData(this.target).copy()); + return out; + } } diff --git a/src/main/java/appeng/items/contents/QuartzKnifeObj.java b/src/main/java/appeng/items/contents/QuartzKnifeObj.java index a3b452880bc..1a2b9e71a76 100644 --- a/src/main/java/appeng/items/contents/QuartzKnifeObj.java +++ b/src/main/java/appeng/items/contents/QuartzKnifeObj.java @@ -18,24 +18,19 @@ package appeng.items.contents; - import appeng.api.implementations.guiobjects.IGuiItemObject; import net.minecraft.item.ItemStack; +public class QuartzKnifeObj implements IGuiItemObject { -public class QuartzKnifeObj implements IGuiItemObject -{ - - private final ItemStack is; + private final ItemStack is; - public QuartzKnifeObj( final ItemStack o ) - { - this.is = o; - } + public QuartzKnifeObj(final ItemStack o) { + this.is = o; + } - @Override - public ItemStack getItemStack() - { - return this.is; - } + @Override + public ItemStack getItemStack() { + return this.is; + } } diff --git a/src/main/java/appeng/items/contents/WirelessTerminalViewCells.java b/src/main/java/appeng/items/contents/WirelessTerminalViewCells.java index b567a090559..3799325832e 100644 --- a/src/main/java/appeng/items/contents/WirelessTerminalViewCells.java +++ b/src/main/java/appeng/items/contents/WirelessTerminalViewCells.java @@ -18,27 +18,22 @@ package appeng.items.contents; - import appeng.tile.inventory.AppEngInternalInventory; import appeng.util.Platform; import net.minecraft.item.ItemStack; +public class WirelessTerminalViewCells extends AppEngInternalInventory { -public class WirelessTerminalViewCells extends AppEngInternalInventory -{ - - private final ItemStack is; + private final ItemStack is; - public WirelessTerminalViewCells( final ItemStack is ) - { - super( null, 5 ); - this.is = is; - this.readFromNBT( Platform.openNbtData( is ), "viewCell" ); - } + public WirelessTerminalViewCells(final ItemStack is) { + super(null, 5); + this.is = is; + this.readFromNBT(Platform.openNbtData(is), "viewCell"); + } - @Override - public void markDirty() - { - this.writeToNBT( Platform.openNbtData( is ), "viewCell" ); - } -} \ No newline at end of file + @Override + public void markDirty() { + this.writeToNBT(Platform.openNbtData(is), "viewCell"); + } +} diff --git a/src/main/java/appeng/items/materials/ItemMultiMaterial.java b/src/main/java/appeng/items/materials/ItemMultiMaterial.java index 83ef1d21caf..9d40a37e004 100644 --- a/src/main/java/appeng/items/materials/ItemMultiMaterial.java +++ b/src/main/java/appeng/items/materials/ItemMultiMaterial.java @@ -18,7 +18,6 @@ package appeng.items.materials; - import appeng.api.config.Upgrades; import appeng.api.implementations.IUpgradeableHost; import appeng.api.implementations.items.IItemGroup; @@ -38,6 +37,10 @@ import appeng.util.Platform; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; +import java.util.*; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; @@ -55,420 +58,352 @@ import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.oredict.OreDictionary; -import java.util.*; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - -public final class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, IUpgradeModule -{ - public static ItemMultiMaterial instance; - - private static final int KILO_SCALAR = 1024; - - private final Map dmgToMaterial = new HashMap(); - private final NameResolver nameResolver; - - public ItemMultiMaterial() - { - this.nameResolver = new NameResolver( this.getClass() ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - this.setHasSubtypes( true ); - instance = this; - } - - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - super.addCheckedInformation( stack, player, lines, displayMoreInfo ); - - final MaterialType mt = this.getTypeByStack( stack ); - if( mt == null ) - { - return; - } - - if( mt == MaterialType.NamePress ) - { - final NBTTagCompound c = Platform.openNbtData( stack ); - lines.add( c.getString( "InscribeName" ) ); - } - - final Upgrades u = this.getType( stack ); - if( u != null ) - { - final List textList = new LinkedList(); - for( final Entry j : u.getSupported().entrySet() ) - { - String name = null; - - final int limit = j.getValue(); - - if( j.getKey().getItem() instanceof IItemGroup ) - { - final IItemGroup ig = (IItemGroup) j.getKey().getItem(); - final String str = ig.getUnlocalizedGroupName( u.getSupported().keySet(), j.getKey() ); - if( str != null ) - { - name = Platform.gui_localize( str ) + ( limit > 1 ? " (" + limit + ')' : "" ); - } - } - - if( name == null ) - { - name = j.getKey().getDisplayName() + ( limit > 1 ? " (" + limit + ')' : "" ); - } - - if( !textList.contains( name ) ) - { - textList.add( name ); - } - } - - final Pattern p = Pattern.compile( "(\\d+)[^\\d]" ); - final SlightlyBetterSort s = new SlightlyBetterSort( p ); - Collections.sort( textList, s ); - lines.addAll( textList ); - } - } - - public MaterialType getTypeByStack( final ItemStack is ) - { - if( this.dmgToMaterial.containsKey( is.getItemDamage() ) ) - { - return this.dmgToMaterial.get( is.getItemDamage() ); - } - return MaterialType.InvalidType; - } - - @Override - public Upgrades getType( final ItemStack itemstack ) - { - switch( this.getTypeByStack( itemstack ) ) - { - case CardOreFilter: - return Upgrades.ORE_FILTER; - case CardPatternCapacity: - return Upgrades.PATTERN_CAPACITY; - case CardCapacity: - return Upgrades.CAPACITY; - case CardFuzzy: - return Upgrades.FUZZY; - case CardRedstone: - return Upgrades.REDSTONE; - case CardSpeed: - return Upgrades.SPEED; - case CardInverter: - return Upgrades.INVERTER; - case CardCrafting: - return Upgrades.CRAFTING; - default: - return null; - } - } - - public IStackSrc createMaterial( final MaterialType mat ) - { - Preconditions.checkState( !mat.isRegistered(), "Cannot create the same material twice." ); - - boolean enabled = true; - - for( final AEFeature f : mat.getFeature() ) - { - enabled = enabled && AEConfig.instance.isFeatureEnabled( f ); - } - - mat.setStackSrc( new MaterialStackSrc( mat ) ); - - if( enabled ) - { - mat.setItemInstance( this ); - mat.markReady(); - final int newMaterialNum = mat.getDamageValue(); - - if( this.dmgToMaterial.get( newMaterialNum ) == null ) - { - this.dmgToMaterial.put( newMaterialNum, mat ); - } - else - - { - throw new IllegalStateException( "Meta Overlap detected." ); - } - } - - return mat.getStackSrc(); - } - - public void makeUnique() - { - for( final MaterialType mt : ImmutableSet.copyOf( this.dmgToMaterial.values() ) ) - { - if( mt.getOreName() != null ) - { - ItemStack replacement = null; - - final String[] names = mt.getOreName().split( "," ); - - for( final String name : names ) - { - if( replacement != null ) - { - break; - } - - final List options = OreDictionary.getOres( name ); - if( options != null && options.size() > 0 ) - { - for( final ItemStack is : options ) - { - if( is != null && is.getItem() != null ) - { - replacement = is.copy(); - break; - } - } - } - } - - if( replacement == null || AEConfig.instance.useAEVersion( mt ) ) - { - // continue using the AE2 item. - for( final String name : names ) - { - OreDictionary.registerOre( name, mt.stack( 1 ) ); - } - } - else - { - if( mt.getItemInstance() == this ) - { - this.dmgToMaterial.remove( mt.getDamageValue() ); - } - - mt.setItemInstance( replacement.getItem() ); - mt.setDamageValue( replacement.getItemDamage() ); - } - } - } - } - - @Override - public IIcon getIconFromDamage( final int dmg ) - { - if( this.dmgToMaterial.containsKey( dmg ) ) - { - return this.dmgToMaterial.get( dmg ).getIIcon(); - } - return new MissingIcon( this ); - } - - @Override - public String getUnlocalizedName( final ItemStack is ) - { - return "item.appliedenergistics2." + this.nameOf( is ); - } - - private String nameOf( final ItemStack is ) - { - if( is == null ) - { - return "null"; - } - - final MaterialType mt = this.getTypeByStack( is ); - if( mt == null ) - { - return "null"; - } - - return this.nameResolver.getName( mt.name() ); - } - - @Override - protected void getCheckedSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - final List types = Arrays.asList( MaterialType.values() ); - Collections.sort( types, new Comparator() - { - - @Override - public int compare( final MaterialType o1, final MaterialType o2 ) - { - return o1.name().compareTo( o2.name() ); - } - } ); - - for( final MaterialType mat : types ) - { - if( mat.getDamageValue() >= 0 && mat.isRegistered() && mat.getItemInstance() == this ) - { - itemStacks.add( new ItemStack( this, 1, mat.getDamageValue() ) ); - } - } - } - - @Override - public void registerIcons( final IIconRegister icoRegister ) - { - for( final MaterialType mat : MaterialType.values() ) - { - if( mat.getDamageValue() != -1 ) - { - final ItemStack what = new ItemStack( this, 1, mat.getDamageValue() ); - if( this.getTypeByStack( what ) != MaterialType.InvalidType ) - { - final String tex = "appliedenergistics2:" + this.nameOf( what ); - mat.setIIcon( icoRegister.registerIcon( tex ) ); - } - } - } - } - - @Override - public boolean onItemUseFirst( final ItemStack is, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, is, 1 ) <= 0 ) - return true; - - if( player.isSneaking() ) - { - final TileEntity te = world.getTileEntity( x, y, z ); - IInventory upgrades = null; - - if( te instanceof IPartHost ) - { - final SelectedPart sp = ( (IPartHost) te ).selectPart( Vec3.createVectorHelper( hitX, hitY, hitZ ) ); - if( sp.part instanceof IUpgradeableHost ) - { - upgrades = ( (ISegmentedInventory) sp.part ).getInventoryByName( "upgrades" ); - } - } - else if( te instanceof IUpgradeableHost ) - { - upgrades = ( (ISegmentedInventory) te ).getInventoryByName( "upgrades" ); - } - - if( upgrades != null && is != null && is.getItem() instanceof IUpgradeModule ) - { - final IUpgradeModule um = (IUpgradeModule) is.getItem(); - final Upgrades u = um.getType( is ); - - if( u != null ) - { - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( upgrades, ForgeDirection.UNKNOWN ); - if( ad != null ) - { - if( player.worldObj.isRemote ) - { - return false; - } - - player.inventory.setInventorySlotContents( player.inventory.currentItem, ad.addItems( is ) ); - return true; - } - } - } - } - - return super.onItemUseFirst( is, player, world, x, y, z, side, hitX, hitY, hitZ ); - } - - @Override - public boolean hasCustomEntity( final ItemStack is ) - { - return this.getTypeByStack( is ).hasCustomEntity(); - } - - @Override - public Entity createEntity( final World w, final Entity location, final ItemStack itemstack ) - { - final Class droppedEntity = this.getTypeByStack( itemstack ).getCustomEntityClass(); - final Entity eqi; - - try - { - eqi = droppedEntity.getConstructor( World.class, double.class, double.class, double.class, ItemStack.class ).newInstance( w, location.posX, location.posY, location.posZ, itemstack ); - } - catch( final Throwable t ) - { - throw new IllegalStateException( t ); - } - - eqi.motionX = location.motionX; - eqi.motionY = location.motionY; - eqi.motionZ = location.motionZ; - - if( location instanceof EntityItem && eqi instanceof EntityItem ) - { - ( (EntityItem) eqi ).delayBeforeCanPickup = ( (EntityItem) location ).delayBeforeCanPickup; - } - - return eqi; - } - - @Override - public int getBytes( final ItemStack is ) - { - switch( this.getTypeByStack( is ) ) - { - case Cell1kPart: - return KILO_SCALAR; - case Cell4kPart: - return KILO_SCALAR * 4; - case Cell16kPart: - return KILO_SCALAR * 16; - case Cell64kPart: - return KILO_SCALAR * 64; - default: - } - return 0; - } - - @Override - public boolean isStorageComponent( final ItemStack is ) - { - switch( this.getTypeByStack( is ) ) - { - case Cell1kPart: - case Cell4kPart: - case Cell16kPart: - case Cell64kPart: - return true; - default: - } - return false; - } - - private static class SlightlyBetterSort implements Comparator - { - private final Pattern pattern; - - public SlightlyBetterSort( final Pattern pattern ) - { - this.pattern = pattern; - } - - @Override - public int compare( final String o1, final String o2 ) - { - try - { - final Matcher a = this.pattern.matcher( o1 ); - final Matcher b = this.pattern.matcher( o2 ); - if( a.find() && b.find() ) - { - final int ia = Integer.parseInt( a.group( 1 ) ); - final int ib = Integer.parseInt( b.group( 1 ) ); - return Integer.compare( ia, ib ); - } - } - catch( final Throwable t ) - { - // ek! - } - return o1.compareTo( o2 ); - } - } +public final class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, IUpgradeModule { + public static ItemMultiMaterial instance; + + private static final int KILO_SCALAR = 1024; + + private final Map dmgToMaterial = new HashMap(); + private final NameResolver nameResolver; + + public ItemMultiMaterial() { + this.nameResolver = new NameResolver(this.getClass()); + this.setFeature(EnumSet.of(AEFeature.Core)); + this.setHasSubtypes(true); + instance = this; + } + + @Override + public void addCheckedInformation( + final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo) { + super.addCheckedInformation(stack, player, lines, displayMoreInfo); + + final MaterialType mt = this.getTypeByStack(stack); + if (mt == null) { + return; + } + + if (mt == MaterialType.NamePress) { + final NBTTagCompound c = Platform.openNbtData(stack); + lines.add(c.getString("InscribeName")); + } + + final Upgrades u = this.getType(stack); + if (u != null) { + final List textList = new LinkedList(); + for (final Entry j : u.getSupported().entrySet()) { + String name = null; + + final int limit = j.getValue(); + + if (j.getKey().getItem() instanceof IItemGroup) { + final IItemGroup ig = (IItemGroup) j.getKey().getItem(); + final String str = + ig.getUnlocalizedGroupName(u.getSupported().keySet(), j.getKey()); + if (str != null) { + name = Platform.gui_localize(str) + (limit > 1 ? " (" + limit + ')' : ""); + } + } + + if (name == null) { + name = j.getKey().getDisplayName() + (limit > 1 ? " (" + limit + ')' : ""); + } + + if (!textList.contains(name)) { + textList.add(name); + } + } + + final Pattern p = Pattern.compile("(\\d+)[^\\d]"); + final SlightlyBetterSort s = new SlightlyBetterSort(p); + Collections.sort(textList, s); + lines.addAll(textList); + } + } + + public MaterialType getTypeByStack(final ItemStack is) { + if (this.dmgToMaterial.containsKey(is.getItemDamage())) { + return this.dmgToMaterial.get(is.getItemDamage()); + } + return MaterialType.InvalidType; + } + + @Override + public Upgrades getType(final ItemStack itemstack) { + switch (this.getTypeByStack(itemstack)) { + case CardOreFilter: + return Upgrades.ORE_FILTER; + case CardPatternCapacity: + return Upgrades.PATTERN_CAPACITY; + case CardCapacity: + return Upgrades.CAPACITY; + case CardFuzzy: + return Upgrades.FUZZY; + case CardRedstone: + return Upgrades.REDSTONE; + case CardSpeed: + return Upgrades.SPEED; + case CardInverter: + return Upgrades.INVERTER; + case CardCrafting: + return Upgrades.CRAFTING; + default: + return null; + } + } + + public IStackSrc createMaterial(final MaterialType mat) { + Preconditions.checkState(!mat.isRegistered(), "Cannot create the same material twice."); + + boolean enabled = true; + + for (final AEFeature f : mat.getFeature()) { + enabled = enabled && AEConfig.instance.isFeatureEnabled(f); + } + + mat.setStackSrc(new MaterialStackSrc(mat)); + + if (enabled) { + mat.setItemInstance(this); + mat.markReady(); + final int newMaterialNum = mat.getDamageValue(); + + if (this.dmgToMaterial.get(newMaterialNum) == null) { + this.dmgToMaterial.put(newMaterialNum, mat); + } else { + throw new IllegalStateException("Meta Overlap detected."); + } + } + + return mat.getStackSrc(); + } + + public void makeUnique() { + for (final MaterialType mt : ImmutableSet.copyOf(this.dmgToMaterial.values())) { + if (mt.getOreName() != null) { + ItemStack replacement = null; + + final String[] names = mt.getOreName().split(","); + + for (final String name : names) { + if (replacement != null) { + break; + } + + final List options = OreDictionary.getOres(name); + if (options != null && options.size() > 0) { + for (final ItemStack is : options) { + if (is != null && is.getItem() != null) { + replacement = is.copy(); + break; + } + } + } + } + + if (replacement == null || AEConfig.instance.useAEVersion(mt)) { + // continue using the AE2 item. + for (final String name : names) { + OreDictionary.registerOre(name, mt.stack(1)); + } + } else { + if (mt.getItemInstance() == this) { + this.dmgToMaterial.remove(mt.getDamageValue()); + } + + mt.setItemInstance(replacement.getItem()); + mt.setDamageValue(replacement.getItemDamage()); + } + } + } + } + + @Override + public IIcon getIconFromDamage(final int dmg) { + if (this.dmgToMaterial.containsKey(dmg)) { + return this.dmgToMaterial.get(dmg).getIIcon(); + } + return new MissingIcon(this); + } + + @Override + public String getUnlocalizedName(final ItemStack is) { + return "item.appliedenergistics2." + this.nameOf(is); + } + + private String nameOf(final ItemStack is) { + if (is == null) { + return "null"; + } + + final MaterialType mt = this.getTypeByStack(is); + if (mt == null) { + return "null"; + } + + return this.nameResolver.getName(mt.name()); + } + + @Override + protected void getCheckedSubItems( + final Item sameItem, final CreativeTabs creativeTab, final List itemStacks) { + final List types = Arrays.asList(MaterialType.values()); + Collections.sort(types, new Comparator() { + + @Override + public int compare(final MaterialType o1, final MaterialType o2) { + return o1.name().compareTo(o2.name()); + } + }); + + for (final MaterialType mat : types) { + if (mat.getDamageValue() >= 0 && mat.isRegistered() && mat.getItemInstance() == this) { + itemStacks.add(new ItemStack(this, 1, mat.getDamageValue())); + } + } + } + + @Override + public void registerIcons(final IIconRegister icoRegister) { + for (final MaterialType mat : MaterialType.values()) { + if (mat.getDamageValue() != -1) { + final ItemStack what = new ItemStack(this, 1, mat.getDamageValue()); + if (this.getTypeByStack(what) != MaterialType.InvalidType) { + final String tex = "appliedenergistics2:" + this.nameOf(what); + mat.setIIcon(icoRegister.registerIcon(tex)); + } + } + } + } + + @Override + public boolean onItemUseFirst( + final ItemStack is, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (ForgeEventFactory.onItemUseStart(player, is, 1) <= 0) return true; + + if (player.isSneaking()) { + final TileEntity te = world.getTileEntity(x, y, z); + IInventory upgrades = null; + + if (te instanceof IPartHost) { + final SelectedPart sp = ((IPartHost) te).selectPart(Vec3.createVectorHelper(hitX, hitY, hitZ)); + if (sp.part instanceof IUpgradeableHost) { + upgrades = ((ISegmentedInventory) sp.part).getInventoryByName("upgrades"); + } + } else if (te instanceof IUpgradeableHost) { + upgrades = ((ISegmentedInventory) te).getInventoryByName("upgrades"); + } + + if (upgrades != null && is != null && is.getItem() instanceof IUpgradeModule) { + final IUpgradeModule um = (IUpgradeModule) is.getItem(); + final Upgrades u = um.getType(is); + + if (u != null) { + final InventoryAdaptor ad = InventoryAdaptor.getAdaptor(upgrades, ForgeDirection.UNKNOWN); + if (ad != null) { + if (player.worldObj.isRemote) { + return false; + } + + player.inventory.setInventorySlotContents(player.inventory.currentItem, ad.addItems(is)); + return true; + } + } + } + } + + return super.onItemUseFirst(is, player, world, x, y, z, side, hitX, hitY, hitZ); + } + + @Override + public boolean hasCustomEntity(final ItemStack is) { + return this.getTypeByStack(is).hasCustomEntity(); + } + + @Override + public Entity createEntity(final World w, final Entity location, final ItemStack itemstack) { + final Class droppedEntity = + this.getTypeByStack(itemstack).getCustomEntityClass(); + final Entity eqi; + + try { + eqi = droppedEntity + .getConstructor(World.class, double.class, double.class, double.class, ItemStack.class) + .newInstance(w, location.posX, location.posY, location.posZ, itemstack); + } catch (final Throwable t) { + throw new IllegalStateException(t); + } + + eqi.motionX = location.motionX; + eqi.motionY = location.motionY; + eqi.motionZ = location.motionZ; + + if (location instanceof EntityItem && eqi instanceof EntityItem) { + ((EntityItem) eqi).delayBeforeCanPickup = ((EntityItem) location).delayBeforeCanPickup; + } + + return eqi; + } + + @Override + public int getBytes(final ItemStack is) { + switch (this.getTypeByStack(is)) { + case Cell1kPart: + return KILO_SCALAR; + case Cell4kPart: + return KILO_SCALAR * 4; + case Cell16kPart: + return KILO_SCALAR * 16; + case Cell64kPart: + return KILO_SCALAR * 64; + default: + } + return 0; + } + + @Override + public boolean isStorageComponent(final ItemStack is) { + switch (this.getTypeByStack(is)) { + case Cell1kPart: + case Cell4kPart: + case Cell16kPart: + case Cell64kPart: + return true; + default: + } + return false; + } + + private static class SlightlyBetterSort implements Comparator { + private final Pattern pattern; + + public SlightlyBetterSort(final Pattern pattern) { + this.pattern = pattern; + } + + @Override + public int compare(final String o1, final String o2) { + try { + final Matcher a = this.pattern.matcher(o1); + final Matcher b = this.pattern.matcher(o2); + if (a.find() && b.find()) { + final int ia = Integer.parseInt(a.group(1)); + final int ib = Integer.parseInt(b.group(1)); + return Integer.compare(ia, ib); + } + } catch (final Throwable t) { + // ek! + } + return o1.compareTo(o2); + } + } } diff --git a/src/main/java/appeng/items/materials/MaterialType.java b/src/main/java/appeng/items/materials/MaterialType.java index 390bfd0fbad..acc24a5f224 100644 --- a/src/main/java/appeng/items/materials/MaterialType.java +++ b/src/main/java/appeng/items/materials/MaterialType.java @@ -18,7 +18,6 @@ package appeng.items.materials; - import appeng.core.AppEng; import appeng.core.features.AEFeature; import appeng.core.features.MaterialStackSrc; @@ -28,217 +27,210 @@ import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.entity.Entity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; -import java.util.EnumSet; - - -public enum MaterialType -{ - InvalidType( -1, AEFeature.Core ), - - CertusQuartzCrystal( 0, AEFeature.Core, "crystalCertusQuartz" ), - CertusQuartzCrystalCharged( 1, AEFeature.Core, EntityChargedQuartz.class ), - - CertusQuartzDust( 2, AEFeature.Core, "dustCertusQuartz" ), - NetherQuartzDust( 3, AEFeature.Core, "dustNetherQuartz" ), - Flour( 4, AEFeature.Flour, "dustWheat" ), - GoldDust( 51, AEFeature.Core, "dustGold" ), - IronDust( 49, AEFeature.Core, "dustIron" ), - IronNugget( 50, AEFeature.Core, "nuggetIron" ), - - Silicon( 5, AEFeature.Core, "itemSilicon" ), - MatterBall( 6 ), - - FluixCrystal( 7, AEFeature.Core, "crystalFluix" ), - FluixDust( 8, AEFeature.Core, "dustFluix" ), - FluixPearl( 9, AEFeature.Core, "pearlFluix" ), - - PurifiedCertusQuartzCrystal( 10 ), - PurifiedNetherQuartzCrystal( 11 ), - PurifiedFluixCrystal( 12 ), - - CalcProcessorPress( 13 ), - EngProcessorPress( 14 ), - LogicProcessorPress( 15 ), - - CalcProcessorPrint( 16 ), - EngProcessorPrint( 17 ), - LogicProcessorPrint( 18 ), - - SiliconPress( 19 ), - SiliconPrint( 20 ), - - NamePress( 21 ), - - LogicProcessor( 22 ), - CalcProcessor( 23 ), - EngProcessor( 24 ), - - // Basic Cards - BasicCard( 25 ), - CardRedstone( 26 ), - CardCapacity( 27 ), - - // Adv Cards - AdvCard( 28 ), - CardFuzzy( 29 ), CardSpeed( 30 ), - CardInverter( 31 ), - - Cell2SpatialPart( 32, AEFeature.SpatialIO ), - Cell16SpatialPart( 33, AEFeature.SpatialIO ), - Cell128SpatialPart( 34, AEFeature.SpatialIO ), - - Cell1kPart( 35, AEFeature.StorageCells ), - Cell4kPart( 36, AEFeature.StorageCells ), - Cell16kPart( 37, AEFeature.StorageCells ), - Cell64kPart( 38, AEFeature.StorageCells ), - EmptyStorageCell( 39, AEFeature.StorageCells ), - - WoodenGear( 40, AEFeature.GrindStone, "gearWood" ), - - Wireless( 41, AEFeature.WirelessAccessTerminal ), - WirelessBooster( 42, AEFeature.WirelessAccessTerminal ), - - FormationCore( 43 ), - AnnihilationCore( 44 ), - - SkyDust( 45, AEFeature.Core ), - - EnderDust( 46, AEFeature.QuantumNetworkBridge, "dustEnder,dustEnderPearl", EntitySingularity.class ), - Singularity( 47, AEFeature.QuantumNetworkBridge, EntitySingularity.class ), - QESingularity( 48, AEFeature.QuantumNetworkBridge, EntitySingularity.class ), - - BlankPattern( 52 ), - CardCrafting( 53 ), - CardPatternCapacity( 54 ), - CardOreFilter( 55 ); - - private final EnumSet features; - // IIcon for the material. - @SideOnly( Side.CLIENT ) - private IIcon IIcon; - private Item itemInstance; - private int damageValue; - // stack! - private MaterialStackSrc stackSrc; - private String oreName; - private Class droppedEntity; - private boolean isRegistered = false; - - MaterialType( final int metaValue ) - { - this.setDamageValue( metaValue ); - this.features = EnumSet.of( AEFeature.Core ); - } - - MaterialType( final int metaValue, final AEFeature part ) - { - this.setDamageValue( metaValue ); - this.features = EnumSet.of( part ); - } - - MaterialType( final int metaValue, final AEFeature part, final Class c ) - { - this.features = EnumSet.of( part ); - this.setDamageValue( metaValue ); - this.droppedEntity = c; - - EntityRegistry.registerModEntity( this.droppedEntity, this.droppedEntity.getSimpleName(), EntityIds.get( this.droppedEntity ), AppEng.instance(), 16, 4, true ); - } - - MaterialType( final int metaValue, final AEFeature part, final String oreDictionary, final Class c ) - { - this.features = EnumSet.of( part ); - this.setDamageValue( metaValue ); - this.oreName = oreDictionary; - this.droppedEntity = c; - EntityRegistry.registerModEntity( this.droppedEntity, this.droppedEntity.getSimpleName(), EntityIds.get( this.droppedEntity ), AppEng.instance(), 16, 4, true ); - } - - MaterialType( final int metaValue, final AEFeature part, final String oreDictionary ) - { - this.features = EnumSet.of( part ); - this.setDamageValue( metaValue ); - this.oreName = oreDictionary; - } - - public ItemStack stack( final int size ) - { - return new ItemStack( this.getItemInstance(), size, this.getDamageValue() ); - } - - EnumSet getFeature() - { - return this.features; - } - - public String getOreName() - { - return this.oreName; - } - - boolean hasCustomEntity() - { - return this.droppedEntity != null; - } - - Class getCustomEntityClass() - { - return this.droppedEntity; - } - - public boolean isRegistered() - { - return this.isRegistered; - } - - void markReady() - { - this.isRegistered = true; - } - - public int getDamageValue() - { - return this.damageValue; - } - - void setDamageValue( final int damageValue ) - { - this.damageValue = damageValue; - } - - public Item getItemInstance() - { - return this.itemInstance; - } - - void setItemInstance( final Item itemInstance ) - { - this.itemInstance = itemInstance; - } - - IIcon getIIcon() - { - return this.IIcon; - } - - void setIIcon( final IIcon iIcon ) - { - this.IIcon = iIcon; - } - - MaterialStackSrc getStackSrc() - { - return this.stackSrc; - } - - void setStackSrc( final MaterialStackSrc stackSrc ) - { - this.stackSrc = stackSrc; - } +public enum MaterialType { + InvalidType(-1, AEFeature.Core), + + CertusQuartzCrystal(0, AEFeature.Core, "crystalCertusQuartz"), + CertusQuartzCrystalCharged(1, AEFeature.Core, EntityChargedQuartz.class), + CertusQuartzDust(2, AEFeature.Core, "dustCertusQuartz"), + NetherQuartzDust(3, AEFeature.Core, "dustNetherQuartz"), + Flour(4, AEFeature.Flour, "dustWheat"), + GoldDust(51, AEFeature.Core, "dustGold"), + IronDust(49, AEFeature.Core, "dustIron"), + IronNugget(50, AEFeature.Core, "nuggetIron"), + + Silicon(5, AEFeature.Core, "itemSilicon"), + MatterBall(6), + + FluixCrystal(7, AEFeature.Core, "crystalFluix"), + FluixDust(8, AEFeature.Core, "dustFluix"), + FluixPearl(9, AEFeature.Core, "pearlFluix"), + + PurifiedCertusQuartzCrystal(10), + PurifiedNetherQuartzCrystal(11), + PurifiedFluixCrystal(12), + + CalcProcessorPress(13), + EngProcessorPress(14), + LogicProcessorPress(15), + + CalcProcessorPrint(16), + EngProcessorPrint(17), + LogicProcessorPrint(18), + + SiliconPress(19), + SiliconPrint(20), + + NamePress(21), + + LogicProcessor(22), + CalcProcessor(23), + EngProcessor(24), + + // Basic Cards + BasicCard(25), + CardRedstone(26), + CardCapacity(27), + + // Adv Cards + AdvCard(28), + CardFuzzy(29), + CardSpeed(30), + CardInverter(31), + + Cell2SpatialPart(32, AEFeature.SpatialIO), + Cell16SpatialPart(33, AEFeature.SpatialIO), + Cell128SpatialPart(34, AEFeature.SpatialIO), + + Cell1kPart(35, AEFeature.StorageCells), + Cell4kPart(36, AEFeature.StorageCells), + Cell16kPart(37, AEFeature.StorageCells), + Cell64kPart(38, AEFeature.StorageCells), + EmptyStorageCell(39, AEFeature.StorageCells), + + WoodenGear(40, AEFeature.GrindStone, "gearWood"), + + Wireless(41, AEFeature.WirelessAccessTerminal), + WirelessBooster(42, AEFeature.WirelessAccessTerminal), + + FormationCore(43), + AnnihilationCore(44), + + SkyDust(45, AEFeature.Core), + + EnderDust(46, AEFeature.QuantumNetworkBridge, "dustEnder,dustEnderPearl", EntitySingularity.class), + Singularity(47, AEFeature.QuantumNetworkBridge, EntitySingularity.class), + QESingularity(48, AEFeature.QuantumNetworkBridge, EntitySingularity.class), + + BlankPattern(52), + CardCrafting(53), + CardPatternCapacity(54), + CardOreFilter(55); + + private final EnumSet features; + // IIcon for the material. + @SideOnly(Side.CLIENT) + private IIcon IIcon; + + private Item itemInstance; + private int damageValue; + // stack! + private MaterialStackSrc stackSrc; + private String oreName; + private Class droppedEntity; + private boolean isRegistered = false; + + MaterialType(final int metaValue) { + this.setDamageValue(metaValue); + this.features = EnumSet.of(AEFeature.Core); + } + + MaterialType(final int metaValue, final AEFeature part) { + this.setDamageValue(metaValue); + this.features = EnumSet.of(part); + } + + MaterialType(final int metaValue, final AEFeature part, final Class c) { + this.features = EnumSet.of(part); + this.setDamageValue(metaValue); + this.droppedEntity = c; + + EntityRegistry.registerModEntity( + this.droppedEntity, + this.droppedEntity.getSimpleName(), + EntityIds.get(this.droppedEntity), + AppEng.instance(), + 16, + 4, + true); + } + + MaterialType( + final int metaValue, final AEFeature part, final String oreDictionary, final Class c) { + this.features = EnumSet.of(part); + this.setDamageValue(metaValue); + this.oreName = oreDictionary; + this.droppedEntity = c; + EntityRegistry.registerModEntity( + this.droppedEntity, + this.droppedEntity.getSimpleName(), + EntityIds.get(this.droppedEntity), + AppEng.instance(), + 16, + 4, + true); + } + + MaterialType(final int metaValue, final AEFeature part, final String oreDictionary) { + this.features = EnumSet.of(part); + this.setDamageValue(metaValue); + this.oreName = oreDictionary; + } + + public ItemStack stack(final int size) { + return new ItemStack(this.getItemInstance(), size, this.getDamageValue()); + } + + EnumSet getFeature() { + return this.features; + } + + public String getOreName() { + return this.oreName; + } + + boolean hasCustomEntity() { + return this.droppedEntity != null; + } + + Class getCustomEntityClass() { + return this.droppedEntity; + } + + public boolean isRegistered() { + return this.isRegistered; + } + + void markReady() { + this.isRegistered = true; + } + + public int getDamageValue() { + return this.damageValue; + } + + void setDamageValue(final int damageValue) { + this.damageValue = damageValue; + } + + public Item getItemInstance() { + return this.itemInstance; + } + + void setItemInstance(final Item itemInstance) { + this.itemInstance = itemInstance; + } + + IIcon getIIcon() { + return this.IIcon; + } + + void setIIcon(final IIcon iIcon) { + this.IIcon = iIcon; + } + + MaterialStackSrc getStackSrc() { + return this.stackSrc; + } + + void setStackSrc(final MaterialStackSrc stackSrc) { + this.stackSrc = stackSrc; + } } diff --git a/src/main/java/appeng/items/misc/ItemCrystalSeed.java b/src/main/java/appeng/items/misc/ItemCrystalSeed.java index 9729c3aac64..f73de91c113 100644 --- a/src/main/java/appeng/items/misc/ItemCrystalSeed.java +++ b/src/main/java/appeng/items/misc/ItemCrystalSeed.java @@ -18,7 +18,6 @@ package appeng.items.misc; - import appeng.api.AEApi; import appeng.api.definitions.IMaterials; import appeng.api.implementations.items.IGrowableCrystal; @@ -33,6 +32,9 @@ import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import java.util.List; +import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; @@ -47,285 +49,252 @@ import net.minecraft.util.IIcon; import net.minecraft.world.World; -import javax.annotation.Nullable; -import java.util.EnumSet; -import java.util.List; - - -public class ItemCrystalSeed extends AEBaseItem implements IGrowableCrystal -{ - - private static final int LEVEL_OFFSET = 200; - private static final int SINGLE_OFFSET = LEVEL_OFFSET * 3; - - public static final int CERTUS = 0; - public static final int NETHER = SINGLE_OFFSET; - public static final int FLUIX = SINGLE_OFFSET * 2; - public static final int FINAL_STAGE = SINGLE_OFFSET * 3; - - private final IIcon[] certus = new IIcon[3]; - private final IIcon[] fluix = new IIcon[3]; - private final IIcon[] nether = new IIcon[3]; - - public ItemCrystalSeed() - { - this.setHasSubtypes( true ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - - EntityRegistry.registerModEntity( EntityGrowingCrystal.class, EntityGrowingCrystal.class.getSimpleName(), EntityIds.get( EntityGrowingCrystal.class ), AppEng.instance(), 16, 4, true ); - } - - @Nullable - public static ResolverResult getResolver( final int certus2 ) - { - ResolverResult resolver = null; - - for( ItemStack crystalSeedStack : AEApi.instance().definitions().items().crystalSeed().maybeStack( 1 ).asSet() ) - { - crystalSeedStack.setItemDamage( certus2 ); - crystalSeedStack = newStyle( crystalSeedStack ); - resolver = new ResolverResult( "ItemCrystalSeed", crystalSeedStack.getItemDamage(), crystalSeedStack.getTagCompound() ); - } - - return resolver; - } - - private static ItemStack newStyle( final ItemStack itemStack ) - { - ( (ItemCrystalSeed) itemStack.getItem() ).getProgress( itemStack ); - return itemStack; - } - - private int getProgress( final ItemStack is ) - { - if( is.hasTagCompound() ) - { - return is.getTagCompound().getInteger( "progress" ); - } - else - { - final int progress; - final NBTTagCompound comp = Platform.openNbtData( is ); - comp.setInteger( "progress", progress = is.getItemDamage() ); - is.setItemDamage( ( is.getItemDamage() / SINGLE_OFFSET ) * SINGLE_OFFSET ); - return progress; - } - } - - @Nullable - @Override - public ItemStack triggerGrowth( final ItemStack is ) - { - final int newDamage = this.getProgress( is ) + 1; - final IMaterials materials = AEApi.instance().definitions().materials(); - final int size = is.stackSize; - - if( newDamage == CERTUS + SINGLE_OFFSET ) - { - for( final ItemStack quartzStack : materials.purifiedCertusQuartzCrystal().maybeStack( size ).asSet() ) - { - return quartzStack; - } - } - if( newDamage == NETHER + SINGLE_OFFSET ) - { - for( final ItemStack quartzStack : materials.purifiedNetherQuartzCrystal().maybeStack( size ).asSet() ) - { - return quartzStack; - } - } - if( newDamage == FLUIX + SINGLE_OFFSET ) - { - for( final ItemStack quartzStack : materials.purifiedFluixCrystal().maybeStack( size ).asSet() ) - { - return quartzStack; - } - } - if( newDamage > FINAL_STAGE ) - { - return null; - } - - this.setProgress( is, newDamage ); - return is; - } - - private void setProgress( final ItemStack is, final int newDamage ) - { - final NBTTagCompound comp = Platform.openNbtData( is ); - comp.setInteger( "progress", newDamage ); - is.setItemDamage( is.getItemDamage() / LEVEL_OFFSET * LEVEL_OFFSET ); - } - - @Override - public float getMultiplier( final Block blk, final Material mat ) - { - return 0.5f; - } +public class ItemCrystalSeed extends AEBaseItem implements IGrowableCrystal { + + private static final int LEVEL_OFFSET = 200; + private static final int SINGLE_OFFSET = LEVEL_OFFSET * 3; + + public static final int CERTUS = 0; + public static final int NETHER = SINGLE_OFFSET; + public static final int FLUIX = SINGLE_OFFSET * 2; + public static final int FINAL_STAGE = SINGLE_OFFSET * 3; + + private final IIcon[] certus = new IIcon[3]; + private final IIcon[] fluix = new IIcon[3]; + private final IIcon[] nether = new IIcon[3]; + + public ItemCrystalSeed() { + this.setHasSubtypes(true); + this.setFeature(EnumSet.of(AEFeature.Core)); + + EntityRegistry.registerModEntity( + EntityGrowingCrystal.class, + EntityGrowingCrystal.class.getSimpleName(), + EntityIds.get(EntityGrowingCrystal.class), + AppEng.instance(), + 16, + 4, + true); + } + + @Nullable + public static ResolverResult getResolver(final int certus2) { + ResolverResult resolver = null; + + for (ItemStack crystalSeedStack : AEApi.instance() + .definitions() + .items() + .crystalSeed() + .maybeStack(1) + .asSet()) { + crystalSeedStack.setItemDamage(certus2); + crystalSeedStack = newStyle(crystalSeedStack); + resolver = new ResolverResult( + "ItemCrystalSeed", crystalSeedStack.getItemDamage(), crystalSeedStack.getTagCompound()); + } + + return resolver; + } + + private static ItemStack newStyle(final ItemStack itemStack) { + ((ItemCrystalSeed) itemStack.getItem()).getProgress(itemStack); + return itemStack; + } + + private int getProgress(final ItemStack is) { + if (is.hasTagCompound()) { + return is.getTagCompound().getInteger("progress"); + } else { + final int progress; + final NBTTagCompound comp = Platform.openNbtData(is); + comp.setInteger("progress", progress = is.getItemDamage()); + is.setItemDamage((is.getItemDamage() / SINGLE_OFFSET) * SINGLE_OFFSET); + return progress; + } + } + + @Nullable + @Override + public ItemStack triggerGrowth(final ItemStack is) { + final int newDamage = this.getProgress(is) + 1; + final IMaterials materials = AEApi.instance().definitions().materials(); + final int size = is.stackSize; + + if (newDamage == CERTUS + SINGLE_OFFSET) { + for (final ItemStack quartzStack : + materials.purifiedCertusQuartzCrystal().maybeStack(size).asSet()) { + return quartzStack; + } + } + if (newDamage == NETHER + SINGLE_OFFSET) { + for (final ItemStack quartzStack : + materials.purifiedNetherQuartzCrystal().maybeStack(size).asSet()) { + return quartzStack; + } + } + if (newDamage == FLUIX + SINGLE_OFFSET) { + for (final ItemStack quartzStack : + materials.purifiedFluixCrystal().maybeStack(size).asSet()) { + return quartzStack; + } + } + if (newDamage > FINAL_STAGE) { + return null; + } + + this.setProgress(is, newDamage); + return is; + } + + private void setProgress(final ItemStack is, final int newDamage) { + final NBTTagCompound comp = Platform.openNbtData(is); + comp.setInteger("progress", newDamage); + is.setItemDamage(is.getItemDamage() / LEVEL_OFFSET * LEVEL_OFFSET); + } + + @Override + public float getMultiplier(final Block blk, final Material mat) { + return 0.5f; + } @SideOnly(Side.CLIENT) - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - lines.add( ButtonToolTips.DoesntDespawn.getLocal() ); - final int progress = this.getProgress( stack ) % SINGLE_OFFSET; - lines.add( Math.floor( (float) progress / (float) ( SINGLE_OFFSET / 100 ) ) + "%" ); - - super.addCheckedInformation( stack, player, lines, displayMoreInfo ); - } - - @Override - public int getEntityLifespan( final ItemStack itemStack, final World world ) - { - return Integer.MAX_VALUE; - } - - @Override - public String getUnlocalizedName( final ItemStack is ) - { - final int damage = this.getProgress( is ); - - if( damage < CERTUS + SINGLE_OFFSET ) - { - return this.getUnlocalizedName() + ".Certus"; - } - - if( damage < NETHER + SINGLE_OFFSET ) - { - return this.getUnlocalizedName() + ".Nether"; - } - - if( damage < FLUIX + SINGLE_OFFSET ) - { - return this.getUnlocalizedName() + ".Fluix"; - } - - return this.getUnlocalizedName(); - } - - @Override - public boolean isDamageable() - { - return false; - } - - @Override - public boolean isDamaged( final ItemStack stack ) - { - return false; - } - - @Override - public int getMaxDamage( final ItemStack stack ) - { - return FINAL_STAGE; - } - - @Override - public IIcon getIcon( final ItemStack stack, final int pass ) - { - return this.getIconIndex( stack ); - } - - @Override - public IIcon getIconIndex( final ItemStack stack ) - { - IIcon[] list = null; - - int damage = this.getProgress( stack ); - - if( damage < CERTUS + SINGLE_OFFSET ) - { - list = this.certus; - } - else if( damage < NETHER + SINGLE_OFFSET ) - { - damage -= NETHER; - list = this.nether; - } - - else if( damage < FLUIX + SINGLE_OFFSET ) - { - damage -= FLUIX; - list = this.fluix; - } - - if( list == null ) - { - return Items.diamond.getIconFromDamage( 0 ); - } - - if( damage < LEVEL_OFFSET ) - { - return list[0]; - } - else if( damage < LEVEL_OFFSET * 2 ) - { - return list[1]; - } - else - { - return list[2]; - } - } - - @Override - public void registerIcons( final IIconRegister ir ) - { - final String preFix = "appliedenergistics2:ItemCrystalSeed."; - - this.certus[0] = ir.registerIcon( preFix + "Certus" ); - this.certus[1] = ir.registerIcon( preFix + "Certus2" ); - this.certus[2] = ir.registerIcon( preFix + "Certus3" ); - - this.nether[0] = ir.registerIcon( preFix + "Nether" ); - this.nether[1] = ir.registerIcon( preFix + "Nether2" ); - this.nether[2] = ir.registerIcon( preFix + "Nether3" ); - - this.fluix[0] = ir.registerIcon( preFix + "Fluix" ); - this.fluix[1] = ir.registerIcon( preFix + "Fluix2" ); - this.fluix[2] = ir.registerIcon( preFix + "Fluix3" ); - } - - @Override - public boolean hasCustomEntity( final ItemStack stack ) - { - return true; - } - - @Override - public Entity createEntity( final World world, final Entity location, final ItemStack itemstack ) - { - final EntityGrowingCrystal egc = new EntityGrowingCrystal( world, location.posX, location.posY, location.posZ, itemstack ); - - egc.motionX = location.motionX; - egc.motionY = location.motionY; - egc.motionZ = location.motionZ; - - if( location instanceof EntityItem ) - { - egc.delayBeforeCanPickup = ( (EntityItem) location ).delayBeforeCanPickup; - } - - return egc; - } - - @Override - protected void getCheckedSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - // lvl 0 - itemStacks.add( newStyle( new ItemStack( this, 1, CERTUS ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, NETHER ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, FLUIX ) ) ); - - // lvl 1 - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET + CERTUS ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET + NETHER ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET + FLUIX ) ) ); - - // lvl 2 - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET * 2 + CERTUS ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET * 2 + NETHER ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET * 2 + FLUIX ) ) ); - } + @Override + public void addCheckedInformation( + final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo) { + lines.add(ButtonToolTips.DoesntDespawn.getLocal()); + final int progress = this.getProgress(stack) % SINGLE_OFFSET; + lines.add(Math.floor((float) progress / (float) (SINGLE_OFFSET / 100)) + "%"); + + super.addCheckedInformation(stack, player, lines, displayMoreInfo); + } + + @Override + public int getEntityLifespan(final ItemStack itemStack, final World world) { + return Integer.MAX_VALUE; + } + + @Override + public String getUnlocalizedName(final ItemStack is) { + final int damage = this.getProgress(is); + + if (damage < CERTUS + SINGLE_OFFSET) { + return this.getUnlocalizedName() + ".Certus"; + } + + if (damage < NETHER + SINGLE_OFFSET) { + return this.getUnlocalizedName() + ".Nether"; + } + + if (damage < FLUIX + SINGLE_OFFSET) { + return this.getUnlocalizedName() + ".Fluix"; + } + + return this.getUnlocalizedName(); + } + + @Override + public boolean isDamageable() { + return false; + } + + @Override + public boolean isDamaged(final ItemStack stack) { + return false; + } + + @Override + public int getMaxDamage(final ItemStack stack) { + return FINAL_STAGE; + } + + @Override + public IIcon getIcon(final ItemStack stack, final int pass) { + return this.getIconIndex(stack); + } + + @Override + public IIcon getIconIndex(final ItemStack stack) { + IIcon[] list = null; + + int damage = this.getProgress(stack); + + if (damage < CERTUS + SINGLE_OFFSET) { + list = this.certus; + } else if (damage < NETHER + SINGLE_OFFSET) { + damage -= NETHER; + list = this.nether; + } else if (damage < FLUIX + SINGLE_OFFSET) { + damage -= FLUIX; + list = this.fluix; + } + + if (list == null) { + return Items.diamond.getIconFromDamage(0); + } + + if (damage < LEVEL_OFFSET) { + return list[0]; + } else if (damage < LEVEL_OFFSET * 2) { + return list[1]; + } else { + return list[2]; + } + } + + @Override + public void registerIcons(final IIconRegister ir) { + final String preFix = "appliedenergistics2:ItemCrystalSeed."; + + this.certus[0] = ir.registerIcon(preFix + "Certus"); + this.certus[1] = ir.registerIcon(preFix + "Certus2"); + this.certus[2] = ir.registerIcon(preFix + "Certus3"); + + this.nether[0] = ir.registerIcon(preFix + "Nether"); + this.nether[1] = ir.registerIcon(preFix + "Nether2"); + this.nether[2] = ir.registerIcon(preFix + "Nether3"); + + this.fluix[0] = ir.registerIcon(preFix + "Fluix"); + this.fluix[1] = ir.registerIcon(preFix + "Fluix2"); + this.fluix[2] = ir.registerIcon(preFix + "Fluix3"); + } + + @Override + public boolean hasCustomEntity(final ItemStack stack) { + return true; + } + + @Override + public Entity createEntity(final World world, final Entity location, final ItemStack itemstack) { + final EntityGrowingCrystal egc = + new EntityGrowingCrystal(world, location.posX, location.posY, location.posZ, itemstack); + + egc.motionX = location.motionX; + egc.motionY = location.motionY; + egc.motionZ = location.motionZ; + + if (location instanceof EntityItem) { + egc.delayBeforeCanPickup = ((EntityItem) location).delayBeforeCanPickup; + } + + return egc; + } + + @Override + protected void getCheckedSubItems( + final Item sameItem, final CreativeTabs creativeTab, final List itemStacks) { + // lvl 0 + itemStacks.add(newStyle(new ItemStack(this, 1, CERTUS))); + itemStacks.add(newStyle(new ItemStack(this, 1, NETHER))); + itemStacks.add(newStyle(new ItemStack(this, 1, FLUIX))); + + // lvl 1 + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET + CERTUS))); + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET + NETHER))); + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET + FLUIX))); + + // lvl 2 + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET * 2 + CERTUS))); + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET * 2 + NETHER))); + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET * 2 + FLUIX))); + } } diff --git a/src/main/java/appeng/items/misc/ItemEncodedPattern.java b/src/main/java/appeng/items/misc/ItemEncodedPattern.java index 11d1e74ba21..ef2165dac89 100644 --- a/src/main/java/appeng/items/misc/ItemEncodedPattern.java +++ b/src/main/java/appeng/items/misc/ItemEncodedPattern.java @@ -18,7 +18,6 @@ package appeng.items.misc; - import appeng.api.AEApi; import appeng.api.implementations.ICraftingPatternItem; import appeng.api.networking.crafting.ICraftingPatternDetails; @@ -30,198 +29,201 @@ import appeng.helpers.PatternHelper; import appeng.items.AEBaseItem; import appeng.util.Platform; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.WeakHashMap; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; import net.minecraft.util.EnumChatFormatting; import net.minecraft.world.World; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.event.ForgeEventFactory; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.WeakHashMap; - - -public class ItemEncodedPattern extends AEBaseItem implements ICraftingPatternItem -{ - // rather simple client side caching. - private static final Map SIMPLE_CACHE = new WeakHashMap(); - - public ItemEncodedPattern() - { - this.setFeature( EnumSet.of( AEFeature.Patterns ) ); - this.setMaxStackSize( 64 ); - if( Platform.isClient() ) - { - MinecraftForgeClient.registerItemRenderer( this, new ItemEncodedPatternRenderer() ); - } - } - - @Override - public ItemStack onItemRightClick( final ItemStack stack, final World w, final EntityPlayer player ) - { - this.clearPattern( stack, player ); - - return stack; - } - - @Override - public boolean onItemUseFirst( final ItemStack stack, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, stack, 1 ) <= 0 ) - return true; - - return this.clearPattern( stack, player ); - } - - private boolean clearPattern( final ItemStack stack, final EntityPlayer player ) - { - if( player.isSneaking() ) - { - if( Platform.isClient() ) - { - return false; - } - - final InventoryPlayer inv = player.inventory; - - for( int s = 0; s < player.inventory.getSizeInventory(); s++ ) - { - if( inv.getStackInSlot( s ) == stack ) - { - for( final ItemStack blankPattern : AEApi.instance().definitions().materials().blankPattern().maybeStack( stack.stackSize ).asSet() ) - { - inv.setInventorySlotContents( s, blankPattern ); - } - - return true; - } - } - } - - return false; - } - - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - final NBTTagCompound encodedValue = stack.getTagCompound(); - - if (encodedValue == null) { - lines.add(EnumChatFormatting.RED + GuiText.InvalidPattern.getLocal()); - return; - } - - final ICraftingPatternDetails details = this.getPatternForItem( stack, player.worldObj ); - final boolean isCrafting = encodedValue.getBoolean("crafting"); - final boolean substitute = encodedValue.getBoolean("substitute"); - IAEItemStack[] inItems; - IAEItemStack[] outItems; - - if (details == null) { - final ItemStack unknownItem = new ItemStack(Blocks.fire); - unknownItem.setStackDisplayName(GuiText.UnknownItem.getLocal()); - - inItems = PatternHelper.convertToCondensedList(PatternHelper.loadIAEItemStackFromNBT(encodedValue.getTagList("in", 10), false, unknownItem)); - outItems = PatternHelper.convertToCondensedList(PatternHelper.loadIAEItemStackFromNBT(encodedValue.getTagList("out", 10), false, unknownItem)); - } else { - inItems = details.getCondensedInputs(); - outItems = details.getCondensedOutputs(); - } - - boolean recipeIsBroken = details == null; - final List in = new ArrayList<>(); - final List out = new ArrayList<>(); - - final String substitutionLabel = GuiText.Substitute.getLocal() + " "; - final String canSubstitute = substitute ? GuiText.Yes.getLocal() : GuiText.No.getLocal(); - final String label = ( isCrafting ? GuiText.Crafts.getLocal() : GuiText.Creates.getLocal() ) + ": "; - final String and = " " + GuiText.And.getLocal() + " "; - final String with = GuiText.With.getLocal() + ": "; - - recipeIsBroken = addInformation(player, inItems, in, with, and, displayMoreInfo) || recipeIsBroken; - recipeIsBroken = addInformation(player, outItems, out, label, and, displayMoreInfo) || recipeIsBroken; - - if (recipeIsBroken) { - lines.add(EnumChatFormatting.RED + GuiText.InvalidPattern.getLocal()); - } - - lines.addAll(out); - lines.addAll(in); - - lines.add(substitutionLabel + canSubstitute); - } - - @Override - public ICraftingPatternDetails getPatternForItem( final ItemStack is, final World w ) - { - try { - return new PatternHelper( is, w ); - } catch(final Throwable t) { - return null; - } - } - - public ItemStack getOutput( final ItemStack item ) - { - ItemStack out = SIMPLE_CACHE.get( item ); - - if (out != null) { - return out; - } - - final World w = CommonHelper.proxy.getWorld(); - - if (w == null) { - return null; - } - - final ICraftingPatternDetails details = this.getPatternForItem( item, w ); - - if (details == null) { - return null; - } - - SIMPLE_CACHE.put( item, out = details.getCondensedOutputs()[0].getItemStack() ); - return out; - } - - private boolean addInformation(final EntityPlayer player, final IAEItemStack[] items, final List lines, final String label, final String and, final boolean displayMoreInfo) - { - final ItemStack unknownItem = new ItemStack(Blocks.fire); - boolean recipeIsBroken = false; - boolean first = true; - - for (final IAEItemStack item: items) { - - if (!recipeIsBroken && item.equals(unknownItem)) { - recipeIsBroken = true; - } - - lines.add((first ? label : and) + item.getStackSize() + " " + Platform.getItemDisplayName(item)); - - if (GuiScreen.isShiftKeyDown()) { - final List l = item.getItemStack().getTooltip(player, displayMoreInfo); - - if (!l.isEmpty()) { - l.remove(0); - } - - lines.addAll(l); - } - - first = false; - } - - return recipeIsBroken; - } +public class ItemEncodedPattern extends AEBaseItem implements ICraftingPatternItem { + // rather simple client side caching. + private static final Map SIMPLE_CACHE = new WeakHashMap(); + + public ItemEncodedPattern() { + this.setFeature(EnumSet.of(AEFeature.Patterns)); + this.setMaxStackSize(64); + if (Platform.isClient()) { + MinecraftForgeClient.registerItemRenderer(this, new ItemEncodedPatternRenderer()); + } + } + + @Override + public ItemStack onItemRightClick(final ItemStack stack, final World w, final EntityPlayer player) { + this.clearPattern(stack, player); + + return stack; + } + + @Override + public boolean onItemUseFirst( + final ItemStack stack, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (ForgeEventFactory.onItemUseStart(player, stack, 1) <= 0) return true; + + return this.clearPattern(stack, player); + } + + private boolean clearPattern(final ItemStack stack, final EntityPlayer player) { + if (player.isSneaking()) { + if (Platform.isClient()) { + return false; + } + + final InventoryPlayer inv = player.inventory; + + for (int s = 0; s < player.inventory.getSizeInventory(); s++) { + if (inv.getStackInSlot(s) == stack) { + for (final ItemStack blankPattern : AEApi.instance() + .definitions() + .materials() + .blankPattern() + .maybeStack(stack.stackSize) + .asSet()) { + inv.setInventorySlotContents(s, blankPattern); + } + + return true; + } + } + } + + return false; + } + + @Override + public void addCheckedInformation( + final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo) { + final NBTTagCompound encodedValue = stack.getTagCompound(); + + if (encodedValue == null) { + lines.add(EnumChatFormatting.RED + GuiText.InvalidPattern.getLocal()); + return; + } + + final ICraftingPatternDetails details = this.getPatternForItem(stack, player.worldObj); + final boolean isCrafting = encodedValue.getBoolean("crafting"); + final boolean substitute = encodedValue.getBoolean("substitute"); + IAEItemStack[] inItems; + IAEItemStack[] outItems; + + if (details == null) { + final ItemStack unknownItem = new ItemStack(Blocks.fire); + unknownItem.setStackDisplayName(GuiText.UnknownItem.getLocal()); + + inItems = PatternHelper.convertToCondensedList( + PatternHelper.loadIAEItemStackFromNBT(encodedValue.getTagList("in", 10), false, unknownItem)); + outItems = PatternHelper.convertToCondensedList( + PatternHelper.loadIAEItemStackFromNBT(encodedValue.getTagList("out", 10), false, unknownItem)); + } else { + inItems = details.getCondensedInputs(); + outItems = details.getCondensedOutputs(); + } + + boolean recipeIsBroken = details == null; + final List in = new ArrayList<>(); + final List out = new ArrayList<>(); + + final String substitutionLabel = GuiText.Substitute.getLocal() + " "; + final String canSubstitute = substitute ? GuiText.Yes.getLocal() : GuiText.No.getLocal(); + final String label = (isCrafting ? GuiText.Crafts.getLocal() : GuiText.Creates.getLocal()) + ": "; + final String and = " " + GuiText.And.getLocal() + " "; + final String with = GuiText.With.getLocal() + ": "; + + recipeIsBroken = addInformation(player, inItems, in, with, and, displayMoreInfo) || recipeIsBroken; + recipeIsBroken = addInformation(player, outItems, out, label, and, displayMoreInfo) || recipeIsBroken; + + if (recipeIsBroken) { + lines.add(EnumChatFormatting.RED + GuiText.InvalidPattern.getLocal()); + } + + lines.addAll(out); + lines.addAll(in); + + lines.add(substitutionLabel + canSubstitute); + } + + @Override + public ICraftingPatternDetails getPatternForItem(final ItemStack is, final World w) { + try { + return new PatternHelper(is, w); + } catch (final Throwable t) { + return null; + } + } + + public ItemStack getOutput(final ItemStack item) { + ItemStack out = SIMPLE_CACHE.get(item); + + if (out != null) { + return out; + } + + final World w = CommonHelper.proxy.getWorld(); + + if (w == null) { + return null; + } + + final ICraftingPatternDetails details = this.getPatternForItem(item, w); + + if (details == null) { + return null; + } + + SIMPLE_CACHE.put(item, out = details.getCondensedOutputs()[0].getItemStack()); + return out; + } + + private boolean addInformation( + final EntityPlayer player, + final IAEItemStack[] items, + final List lines, + final String label, + final String and, + final boolean displayMoreInfo) { + final ItemStack unknownItem = new ItemStack(Blocks.fire); + boolean recipeIsBroken = false; + boolean first = true; + + for (final IAEItemStack item : items) { + + if (!recipeIsBroken && item.equals(unknownItem)) { + recipeIsBroken = true; + } + + lines.add((first ? label : and) + item.getStackSize() + " " + Platform.getItemDisplayName(item)); + + if (GuiScreen.isShiftKeyDown()) { + final List l = item.getItemStack().getTooltip(player, displayMoreInfo); + + if (!l.isEmpty()) { + l.remove(0); + } + + lines.addAll(l); + } + + first = false; + } + return recipeIsBroken; + } } diff --git a/src/main/java/appeng/items/misc/ItemPaintBall.java b/src/main/java/appeng/items/misc/ItemPaintBall.java index 5e82c2239f9..9977928eac0 100644 --- a/src/main/java/appeng/items/misc/ItemPaintBall.java +++ b/src/main/java/appeng/items/misc/ItemPaintBall.java @@ -18,88 +18,72 @@ package appeng.items.misc; - import appeng.api.util.AEColor; import appeng.client.render.items.PaintBallRender; import appeng.core.features.AEFeature; import appeng.core.localization.GuiText; import appeng.items.AEBaseItem; import appeng.util.Platform; +import java.util.EnumSet; +import java.util.List; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.client.MinecraftForgeClient; -import java.util.EnumSet; -import java.util.List; - - -public class ItemPaintBall extends AEBaseItem -{ - - private static final int DAMAGE_THRESHOLD = 20; - - public ItemPaintBall() - { - this.setFeature( EnumSet.of( AEFeature.PaintBalls ) ); - this.setHasSubtypes( true ); - - if( Platform.isClient() ) - { - MinecraftForgeClient.registerItemRenderer( this, new PaintBallRender() ); - } - } - - @Override - public String getItemStackDisplayName( final ItemStack is ) - { - return super.getItemStackDisplayName( is ) + " - " + this.getExtraName( is ); - } - - private String getExtraName( final ItemStack is ) - { - return ( is.getItemDamage() >= DAMAGE_THRESHOLD ? GuiText.Lumen.getLocal() + ' ' : "" ) + this.getColor( is ); - } - - public AEColor getColor( final ItemStack is ) - { - int dmg = is.getItemDamage(); - if( dmg >= DAMAGE_THRESHOLD ) - { - dmg -= DAMAGE_THRESHOLD; - } - - if( dmg >= AEColor.values().length ) - { - return AEColor.Transparent; - } - - return AEColor.values()[dmg]; - } - - @Override - protected void getCheckedSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - for( final AEColor c : AEColor.values() ) - { - if( c != AEColor.Transparent ) - { - itemStacks.add( new ItemStack( this, 1, c.ordinal() ) ); - } - } - - for( final AEColor c : AEColor.values() ) - { - if( c != AEColor.Transparent ) - { - itemStacks.add( new ItemStack( this, 1, DAMAGE_THRESHOLD + c.ordinal() ) ); - } - } - } - - public boolean isLumen( final ItemStack is ) - { - final int dmg = is.getItemDamage(); - return dmg >= DAMAGE_THRESHOLD; - } +public class ItemPaintBall extends AEBaseItem { + + private static final int DAMAGE_THRESHOLD = 20; + + public ItemPaintBall() { + this.setFeature(EnumSet.of(AEFeature.PaintBalls)); + this.setHasSubtypes(true); + + if (Platform.isClient()) { + MinecraftForgeClient.registerItemRenderer(this, new PaintBallRender()); + } + } + + @Override + public String getItemStackDisplayName(final ItemStack is) { + return super.getItemStackDisplayName(is) + " - " + this.getExtraName(is); + } + + private String getExtraName(final ItemStack is) { + return (is.getItemDamage() >= DAMAGE_THRESHOLD ? GuiText.Lumen.getLocal() + ' ' : "") + this.getColor(is); + } + + public AEColor getColor(final ItemStack is) { + int dmg = is.getItemDamage(); + if (dmg >= DAMAGE_THRESHOLD) { + dmg -= DAMAGE_THRESHOLD; + } + + if (dmg >= AEColor.values().length) { + return AEColor.Transparent; + } + + return AEColor.values()[dmg]; + } + + @Override + protected void getCheckedSubItems( + final Item sameItem, final CreativeTabs creativeTab, final List itemStacks) { + for (final AEColor c : AEColor.values()) { + if (c != AEColor.Transparent) { + itemStacks.add(new ItemStack(this, 1, c.ordinal())); + } + } + + for (final AEColor c : AEColor.values()) { + if (c != AEColor.Transparent) { + itemStacks.add(new ItemStack(this, 1, DAMAGE_THRESHOLD + c.ordinal())); + } + } + } + + public boolean isLumen(final ItemStack is) { + final int dmg = is.getItemDamage(); + return dmg >= DAMAGE_THRESHOLD; + } } diff --git a/src/main/java/appeng/items/parts/ItemFacade.java b/src/main/java/appeng/items/parts/ItemFacade.java index 330f8bf52ec..7506054190a 100644 --- a/src/main/java/appeng/items/parts/ItemFacade.java +++ b/src/main/java/appeng/items/parts/ItemFacade.java @@ -18,7 +18,6 @@ package appeng.items.parts; - import appeng.api.AEApi; import appeng.api.exceptions.MissingDefinition; import appeng.api.parts.IAlphaPassItem; @@ -34,6 +33,9 @@ import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.BlockGlass; import net.minecraft.block.BlockStainedGlass; @@ -48,244 +50,206 @@ import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; - - -public class ItemFacade extends AEBaseItem implements IFacadeItem, IAlphaPassItem -{ - - private List subTypes = null; - - public ItemFacade() - { - this.setFeature( EnumSet.of( AEFeature.Facades ) ); - this.setHasSubtypes( true ); - if( Platform.isClient() ) - { - MinecraftForgeClient.registerItemRenderer( this, BusRenderer.INSTANCE ); - } - } - - @Override - @SideOnly( Side.CLIENT ) - public int getSpriteNumber() - { - return 0; - } - - @Override - public boolean onItemUse( final ItemStack is, final EntityPlayer player, final World w, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - return AEApi.instance().partHelper().placeBus( is, x, y, z, side, player, w ); - } - - @Override - public String getItemStackDisplayName( final ItemStack is ) - { - try - { - final ItemStack in = this.getTextureItem( is ); - if( in != null ) - { - return super.getItemStackDisplayName( is ) + " - " + in.getDisplayName(); - } - } - catch( final Throwable ignored ) - { - - } - - return super.getItemStackDisplayName( is ); - } - - @Override - protected void getCheckedSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - this.calculateSubTypes(); - itemStacks.addAll( this.subTypes ); - } - - private void calculateSubTypes() - { - if( this.subTypes == null ) - { - this.subTypes = new ArrayList( 1000 ); - for( final Object blk : Block.blockRegistry ) - { - final Block b = (Block) blk; - try - { - final Item item = Item.getItemFromBlock( b ); - - final List tmpList = new ArrayList( 100 ); - b.getSubBlocks( item, b.getCreativeTabToDisplayOn(), tmpList ); - for( final ItemStack l : tmpList ) - { - final ItemStack facade = this.createFacadeForItem( l, false ); - if( facade != null ) - { - this.subTypes.add( facade ); - } - } - } - catch( final Throwable t ) - { - // just absorb.. - } - } - - if( FacadeConfig.instance.hasChanged() ) - { - FacadeConfig.instance.save(); - } - } - } - - public ItemStack createFacadeForItem( final ItemStack l, final boolean returnItem ) - { - if( l == null ) - { - return null; - } - - final Block b = Block.getBlockFromItem( l.getItem() ); - if( b == null || l.hasTagCompound() ) - { - return null; - } - - final int metadata = l.getItem().getMetadata( l.getItemDamage() ); - - final boolean hasTile = b.hasTileEntity( metadata ); - final boolean enableGlass = b instanceof BlockGlass || b instanceof BlockStainedGlass; - final boolean disableOre = b instanceof OreQuartz; - - final boolean defaultValue = ( b.isOpaqueCube() && !b.getTickRandomly() && !hasTile && !disableOre ) || enableGlass; - if( FacadeConfig.instance.checkEnabled( b, metadata, defaultValue ) ) - { - if( returnItem ) - { - return l; - } - - final ItemStack is = new ItemStack( this ); - final NBTTagCompound data = new NBTTagCompound(); - final int[] ds = new int[2]; - ds[0] = Item.getIdFromItem( l.getItem() ); - ds[1] = metadata; - data.setIntArray( "x", ds ); - final UniqueIdentifier ui = GameRegistry.findUniqueIdentifierFor( l.getItem() ); - data.setString( "modid", ui.modId ); - data.setString( "itemname", ui.name ); - is.setTagCompound( data ); - return is; - } - return null; - } - - @Override - public FacadePart createPartFromItemStack( final ItemStack is, final ForgeDirection side ) - { - final ItemStack in = this.getTextureItem( is ); - if( in != null ) - { - return new FacadePart( is, side ); - } - return null; - } - - @Override - public ItemStack getTextureItem( final ItemStack is ) - { - final Block blk = this.getBlock( is ); - if( blk != null ) - { - return new ItemStack( blk, 1, this.getMeta( is ) ); - } - return null; - } - - @Override - public int getMeta( final ItemStack is ) - { - final NBTTagCompound data = is.getTagCompound(); - if( data != null ) - { - final int[] blk = data.getIntArray( "x" ); - if( blk != null && blk.length == 2 ) - { - return blk[1]; - } - } - return 0; - } - - @Override - public Block getBlock( final ItemStack is ) - { - final NBTTagCompound data = is.getTagCompound(); - if( data != null ) - { - if( data.hasKey( "modid" ) && data.hasKey( "itemname" ) ) - { - return GameRegistry.findBlock( data.getString( "modid" ), data.getString( "itemname" ) ); - } - else - { - final int[] blk = data.getIntArray( "x" ); - if( blk != null && blk.length == 2 ) - { - return Block.getBlockById( blk[0] ); - } - } - } - return Blocks.glass; - } - - public List getFacades() - { - this.calculateSubTypes(); - return this.subTypes; - } - - public ItemStack getCreativeTabIcon() - { - this.calculateSubTypes(); - if( this.subTypes.isEmpty() ) - { - return new ItemStack( Items.cake ); - } - return this.subTypes.get( 0 ); - } - - public ItemStack createFromIDs( final int[] ids ) - { - for( final ItemStack facadeStack : AEApi.instance().definitions().items().facade().maybeStack( 1 ).asSet() ) - { - final NBTTagCompound facadeTag = new NBTTagCompound(); - facadeTag.setIntArray( "x", ids.clone() ); - facadeStack.setTagCompound( facadeTag ); - - return facadeStack; - } - - throw new MissingDefinition( "Tried to create a facade, while facades are being deactivated." ); - } - - @Override - public boolean useAlphaPass( final ItemStack is ) - { - final ItemStack out = this.getTextureItem( is ); - - if( out == null || out.getItem() == null ) - { - return false; - } - - final Block blk = Block.getBlockFromItem( out.getItem() ); - return blk != null && blk.canRenderInPass( 1 ); - - } +public class ItemFacade extends AEBaseItem implements IFacadeItem, IAlphaPassItem { + + private List subTypes = null; + + public ItemFacade() { + this.setFeature(EnumSet.of(AEFeature.Facades)); + this.setHasSubtypes(true); + if (Platform.isClient()) { + MinecraftForgeClient.registerItemRenderer(this, BusRenderer.INSTANCE); + } + } + + @Override + @SideOnly(Side.CLIENT) + public int getSpriteNumber() { + return 0; + } + + @Override + public boolean onItemUse( + final ItemStack is, + final EntityPlayer player, + final World w, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + return AEApi.instance().partHelper().placeBus(is, x, y, z, side, player, w); + } + + @Override + public String getItemStackDisplayName(final ItemStack is) { + try { + final ItemStack in = this.getTextureItem(is); + if (in != null) { + return super.getItemStackDisplayName(is) + " - " + in.getDisplayName(); + } + } catch (final Throwable ignored) { + + } + + return super.getItemStackDisplayName(is); + } + + @Override + protected void getCheckedSubItems( + final Item sameItem, final CreativeTabs creativeTab, final List itemStacks) { + this.calculateSubTypes(); + itemStacks.addAll(this.subTypes); + } + + private void calculateSubTypes() { + if (this.subTypes == null) { + this.subTypes = new ArrayList(1000); + for (final Object blk : Block.blockRegistry) { + final Block b = (Block) blk; + try { + final Item item = Item.getItemFromBlock(b); + + final List tmpList = new ArrayList(100); + b.getSubBlocks(item, b.getCreativeTabToDisplayOn(), tmpList); + for (final ItemStack l : tmpList) { + final ItemStack facade = this.createFacadeForItem(l, false); + if (facade != null) { + this.subTypes.add(facade); + } + } + } catch (final Throwable t) { + // just absorb.. + } + } + + if (FacadeConfig.instance.hasChanged()) { + FacadeConfig.instance.save(); + } + } + } + + public ItemStack createFacadeForItem(final ItemStack l, final boolean returnItem) { + if (l == null) { + return null; + } + + final Block b = Block.getBlockFromItem(l.getItem()); + if (b == null || l.hasTagCompound()) { + return null; + } + + final int metadata = l.getItem().getMetadata(l.getItemDamage()); + + final boolean hasTile = b.hasTileEntity(metadata); + final boolean enableGlass = b instanceof BlockGlass || b instanceof BlockStainedGlass; + final boolean disableOre = b instanceof OreQuartz; + + final boolean defaultValue = + (b.isOpaqueCube() && !b.getTickRandomly() && !hasTile && !disableOre) || enableGlass; + if (FacadeConfig.instance.checkEnabled(b, metadata, defaultValue)) { + if (returnItem) { + return l; + } + + final ItemStack is = new ItemStack(this); + final NBTTagCompound data = new NBTTagCompound(); + final int[] ds = new int[2]; + ds[0] = Item.getIdFromItem(l.getItem()); + ds[1] = metadata; + data.setIntArray("x", ds); + final UniqueIdentifier ui = GameRegistry.findUniqueIdentifierFor(l.getItem()); + data.setString("modid", ui.modId); + data.setString("itemname", ui.name); + is.setTagCompound(data); + return is; + } + return null; + } + + @Override + public FacadePart createPartFromItemStack(final ItemStack is, final ForgeDirection side) { + final ItemStack in = this.getTextureItem(is); + if (in != null) { + return new FacadePart(is, side); + } + return null; + } + + @Override + public ItemStack getTextureItem(final ItemStack is) { + final Block blk = this.getBlock(is); + if (blk != null) { + return new ItemStack(blk, 1, this.getMeta(is)); + } + return null; + } + + @Override + public int getMeta(final ItemStack is) { + final NBTTagCompound data = is.getTagCompound(); + if (data != null) { + final int[] blk = data.getIntArray("x"); + if (blk != null && blk.length == 2) { + return blk[1]; + } + } + return 0; + } + + @Override + public Block getBlock(final ItemStack is) { + final NBTTagCompound data = is.getTagCompound(); + if (data != null) { + if (data.hasKey("modid") && data.hasKey("itemname")) { + return GameRegistry.findBlock(data.getString("modid"), data.getString("itemname")); + } else { + final int[] blk = data.getIntArray("x"); + if (blk != null && blk.length == 2) { + return Block.getBlockById(blk[0]); + } + } + } + return Blocks.glass; + } + + public List getFacades() { + this.calculateSubTypes(); + return this.subTypes; + } + + public ItemStack getCreativeTabIcon() { + this.calculateSubTypes(); + if (this.subTypes.isEmpty()) { + return new ItemStack(Items.cake); + } + return this.subTypes.get(0); + } + + public ItemStack createFromIDs(final int[] ids) { + for (final ItemStack facadeStack : + AEApi.instance().definitions().items().facade().maybeStack(1).asSet()) { + final NBTTagCompound facadeTag = new NBTTagCompound(); + facadeTag.setIntArray("x", ids.clone()); + facadeStack.setTagCompound(facadeTag); + + return facadeStack; + } + + throw new MissingDefinition("Tried to create a facade, while facades are being deactivated."); + } + + @Override + public boolean useAlphaPass(final ItemStack is) { + final ItemStack out = this.getTextureItem(is); + + if (out == null || out.getItem() == null) { + return false; + } + + final Block blk = Block.getBlockFromItem(out.getItem()); + return blk != null && blk.canRenderInPass(1); + } } diff --git a/src/main/java/appeng/items/parts/ItemMultiPart.java b/src/main/java/appeng/items/parts/ItemMultiPart.java index 5315d52559d..893eea0418b 100644 --- a/src/main/java/appeng/items/parts/ItemMultiPart.java +++ b/src/main/java/appeng/items/parts/ItemMultiPart.java @@ -18,7 +18,6 @@ package appeng.items.parts; - import appeng.api.AEApi; import appeng.api.exceptions.MissingDefinition; import appeng.api.implementations.items.IItemGroup; @@ -38,6 +37,11 @@ import com.google.common.base.Preconditions; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.lang.reflect.InvocationTargetException; +import java.util.*; +import java.util.Map.Entry; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; @@ -46,360 +50,322 @@ import net.minecraft.util.IIcon; import net.minecraft.world.World; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.lang.reflect.InvocationTargetException; -import java.util.*; -import java.util.Map.Entry; - +public final class ItemMultiPart extends AEBaseItem implements IPartItem, IItemGroup { + private static final int INITIAL_REGISTERED_CAPACITY = PartType.values().length; + private static final Comparator> REGISTERED_COMPARATOR = + new RegisteredComparator(); -public final class ItemMultiPart extends AEBaseItem implements IPartItem, IItemGroup -{ - private static final int INITIAL_REGISTERED_CAPACITY = PartType.values().length; - private static final Comparator> REGISTERED_COMPARATOR = new RegisteredComparator(); - - public static ItemMultiPart instance; - private final NameResolver nameResolver; - private final Map registered; - - public ItemMultiPart( final IPartHelper partHelper ) - { - Preconditions.checkNotNull( partHelper ); - - this.registered = new HashMap( INITIAL_REGISTERED_CAPACITY ); - - this.nameResolver = new NameResolver( this.getClass() ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - partHelper.setItemBusRenderer( this ); - this.setHasSubtypes( true ); - - instance = this; - } - - @Nonnull - public final ItemStackSrc createPart( final PartType mat ) - { - Preconditions.checkNotNull( mat ); - - return this.createPart( mat, 0 ); - } - - @Nonnull - public ItemStackSrc createPart( final PartType mat, final AEColor color ) - { - Preconditions.checkNotNull( mat ); - Preconditions.checkNotNull( color ); - - final int varID = color.ordinal(); - - return this.createPart( mat, varID ); - } - - @Nonnull - private ItemStackSrc createPart( final PartType mat, final int varID ) - { - assert mat != null; - assert varID >= 0; - - // verify - for( final PartTypeWithVariant p : this.registered.values() ) - { - if( p.part == mat && p.variant == varID ) - { - throw new IllegalStateException( "Cannot create the same material twice..." ); - } - } - - boolean enabled = true; - for( final AEFeature f : mat.getFeature() ) - { - enabled = enabled && AEConfig.instance.isFeatureEnabled( f ); - } - - for( final IntegrationType integrationType : mat.getIntegrations() ) - { - enabled &= IntegrationRegistry.INSTANCE.isEnabled( integrationType ); - } - - final int partDamage = mat.getBaseDamage() + varID; - final ActivityState state = ActivityState.from( enabled ); - final ItemStackSrc output = new ItemStackSrc( this, partDamage, state ); - - final PartTypeWithVariant pti = new PartTypeWithVariant( mat, varID ); - - this.processMetaOverlap( enabled, partDamage, mat, pti ); - - return output; - } - - private void processMetaOverlap( final boolean enabled, final int partDamage, final PartType mat, final PartTypeWithVariant pti ) - { - assert partDamage >= 0; - assert mat != null; - assert pti != null; - - final PartTypeWithVariant registeredPartType = this.registered.get( partDamage ); - if( registeredPartType != null ) - { - throw new IllegalStateException( "Meta Overlap detected with type " + mat + " and damage " + partDamage + ". Found " + registeredPartType + " there already." ); - } - - if( enabled ) - { - this.registered.put( partDamage, pti ); - } - } - - public int getDamageByType( final PartType t ) - { - Preconditions.checkNotNull( t ); - - for( final Entry pt : this.registered.entrySet() ) - { - if( pt.getValue().part == t ) - { - return pt.getKey(); - } - } - return -1; - } - - @Override - @SideOnly( Side.CLIENT ) - public int getSpriteNumber() - { - return 0; - } - - @Override - public IIcon getIconFromDamage( final int dmg ) - { - final PartTypeWithVariant registeredType = this.registered.get( dmg ); - if( registeredType != null ) - { - return registeredType.ico; - } - - final String formattedRegistered = Arrays.toString( this.registered.keySet().toArray() ); - throw new MissingDefinition( "Tried to get the icon from a non-existent part with damage value " + dmg + ". There were registered: " + formattedRegistered + '.' ); - } - - @Override - public boolean onItemUse( final ItemStack is, final EntityPlayer player, final World w, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( this.getTypeByStack( is ) == PartType.InvalidType ) - { - return false; - } - - return AEApi.instance().partHelper().placeBus( is, x, y, z, side, player, w ); - } - - @Override - public String getUnlocalizedName( final ItemStack is ) - { - return "item.appliedenergistics2." + this.getName( is ); - } - - @Override - public String getItemStackDisplayName( final ItemStack is ) - { - final PartType pt = this.getTypeByStack( is ); - - if( pt.isCable() ) - { - final AEColor[] variants = AEColor.values(); - - final int itemDamage = is.getItemDamage(); - final PartTypeWithVariant registeredPartType = this.registered.get( itemDamage ); - if( registeredPartType != null ) - { - return super.getItemStackDisplayName( is ) + " - " + variants[registeredPartType.variant].toString(); - } - } - - if( pt.getExtraName() != null ) - { - return super.getItemStackDisplayName( is ) + " - " + pt.getExtraName().getLocal(); - } - - return super.getItemStackDisplayName( is ); - } - - @Override - public void registerIcons( final IIconRegister iconRegister ) - { - for( final Entry part : this.registered.entrySet() ) - { - final String tex = "appliedenergistics2:" + this.getName( new ItemStack( this, 1, part.getKey() ) ); - part.getValue().ico = iconRegister.registerIcon( tex ); - } - } - - @Override - protected void getCheckedSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - final List> types = new ArrayList>( this.registered.entrySet() ); - Collections.sort( types, REGISTERED_COMPARATOR ); - - for( final Entry part : types ) - { - itemStacks.add( new ItemStack( this, 1, part.getKey() ) ); - } - } - - private String getName( final ItemStack is ) - { - Preconditions.checkNotNull( is ); - - final PartType stackType = this.getTypeByStack( is ); - final String typeName = stackType.name(); - - return this.nameResolver.getName( typeName ); - } - - @Nonnull - public PartType getTypeByStack( final ItemStack is ) - { - Preconditions.checkNotNull( is ); - - final PartTypeWithVariant pt = this.registered.get( is.getItemDamage() ); - if( pt != null ) - { - return pt.part; - } - - return PartType.InvalidType; - } - - @Nullable - @Override - public IPart createPartFromItemStack( final ItemStack is ) - { - final PartType type = this.getTypeByStack( is ); - final Class part = type.getPart(); - if( part == null ) - { - return null; - } - - try - { - if( type.getConstructor() == null ) - { - type.setConstructor( part.getConstructor( ItemStack.class ) ); - } - - return type.getConstructor().newInstance( is ); - } - catch( final InstantiationException e ) - { - throw new IllegalStateException( "Unable to construct IBusPart from IBusItem : " + part.getName() + " ; Possibly didn't have correct constructor( ItemStack )", e ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( "Unable to construct IBusPart from IBusItem : " + part.getName() + " ; Possibly didn't have correct constructor( ItemStack )", e ); - } - catch( final InvocationTargetException e ) - { - throw new IllegalStateException( "Unable to construct IBusPart from IBusItem : " + part.getName() + " ; Possibly didn't have correct constructor( ItemStack )", e ); - } - catch( final NoSuchMethodException e ) - { - throw new IllegalStateException( "Unable to construct IBusPart from IBusItem : " + part.getName() + " ; Possibly didn't have correct constructor( ItemStack )", e ); - } - } - - public int variantOf( final int itemDamage ) - { - final PartTypeWithVariant registeredPartType = this.registered.get( itemDamage ); - if( registeredPartType != null ) - { - return registeredPartType.variant; - } - - return 0; - } - - @Nullable - @Override - public String getUnlocalizedGroupName( final Set others, final ItemStack is ) - { - boolean importBus = false; - boolean exportBus = false; - boolean group = false; - - final PartType u = this.getTypeByStack( is ); - - for( final ItemStack stack : others ) - { - if( stack.getItem() == this ) - { - final PartType pt = this.getTypeByStack( stack ); - switch( pt ) - { - case ImportBus: - importBus = true; - if( u == pt ) - { - group = true; - } - break; - case ExportBus: - exportBus = true; - if( u == pt ) - { - group = true; - } - break; - default: - } - } - } - - if( group && importBus && exportBus ) - { - return GuiText.IOBuses.getUnlocalized(); - } - - return null; - } - - private static final class PartTypeWithVariant - { - private final PartType part; - private final int variant; - - @SideOnly( Side.CLIENT ) - private IIcon ico; - - private PartTypeWithVariant( final PartType part, final int variant ) - { - assert part != null; - assert variant >= 0; - - this.part = part; - this.variant = variant; - } - - @Override - public String toString() - { - return "PartTypeWithVariant{" + - "part=" + this.part + - ", variant=" + this.variant + - ", ico=" + this.ico + - '}'; - } - } - - - private static final class RegisteredComparator implements Comparator> - { - @Override - public int compare( final Entry o1, final Entry o2 ) - { - return o1.getValue().part.name().compareTo( o2.getValue().part.name() ); - } - } + public static ItemMultiPart instance; + private final NameResolver nameResolver; + private final Map registered; + + public ItemMultiPart(final IPartHelper partHelper) { + Preconditions.checkNotNull(partHelper); + + this.registered = new HashMap(INITIAL_REGISTERED_CAPACITY); + + this.nameResolver = new NameResolver(this.getClass()); + this.setFeature(EnumSet.of(AEFeature.Core)); + partHelper.setItemBusRenderer(this); + this.setHasSubtypes(true); + + instance = this; + } + + @Nonnull + public final ItemStackSrc createPart(final PartType mat) { + Preconditions.checkNotNull(mat); + + return this.createPart(mat, 0); + } + + @Nonnull + public ItemStackSrc createPart(final PartType mat, final AEColor color) { + Preconditions.checkNotNull(mat); + Preconditions.checkNotNull(color); + + final int varID = color.ordinal(); + + return this.createPart(mat, varID); + } + + @Nonnull + private ItemStackSrc createPart(final PartType mat, final int varID) { + assert mat != null; + assert varID >= 0; + + // verify + for (final PartTypeWithVariant p : this.registered.values()) { + if (p.part == mat && p.variant == varID) { + throw new IllegalStateException("Cannot create the same material twice..."); + } + } + + boolean enabled = true; + for (final AEFeature f : mat.getFeature()) { + enabled = enabled && AEConfig.instance.isFeatureEnabled(f); + } + + for (final IntegrationType integrationType : mat.getIntegrations()) { + enabled &= IntegrationRegistry.INSTANCE.isEnabled(integrationType); + } + + final int partDamage = mat.getBaseDamage() + varID; + final ActivityState state = ActivityState.from(enabled); + final ItemStackSrc output = new ItemStackSrc(this, partDamage, state); + + final PartTypeWithVariant pti = new PartTypeWithVariant(mat, varID); + + this.processMetaOverlap(enabled, partDamage, mat, pti); + + return output; + } + + private void processMetaOverlap( + final boolean enabled, final int partDamage, final PartType mat, final PartTypeWithVariant pti) { + assert partDamage >= 0; + assert mat != null; + assert pti != null; + + final PartTypeWithVariant registeredPartType = this.registered.get(partDamage); + if (registeredPartType != null) { + throw new IllegalStateException("Meta Overlap detected with type " + mat + " and damage " + partDamage + + ". Found " + registeredPartType + " there already."); + } + + if (enabled) { + this.registered.put(partDamage, pti); + } + } + + public int getDamageByType(final PartType t) { + Preconditions.checkNotNull(t); + + for (final Entry pt : this.registered.entrySet()) { + if (pt.getValue().part == t) { + return pt.getKey(); + } + } + return -1; + } + + @Override + @SideOnly(Side.CLIENT) + public int getSpriteNumber() { + return 0; + } + + @Override + public IIcon getIconFromDamage(final int dmg) { + final PartTypeWithVariant registeredType = this.registered.get(dmg); + if (registeredType != null) { + return registeredType.ico; + } + + final String formattedRegistered = + Arrays.toString(this.registered.keySet().toArray()); + throw new MissingDefinition("Tried to get the icon from a non-existent part with damage value " + dmg + + ". There were registered: " + formattedRegistered + '.'); + } + + @Override + public boolean onItemUse( + final ItemStack is, + final EntityPlayer player, + final World w, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (this.getTypeByStack(is) == PartType.InvalidType) { + return false; + } + + return AEApi.instance().partHelper().placeBus(is, x, y, z, side, player, w); + } + + @Override + public String getUnlocalizedName(final ItemStack is) { + return "item.appliedenergistics2." + this.getName(is); + } + + @Override + public String getItemStackDisplayName(final ItemStack is) { + final PartType pt = this.getTypeByStack(is); + + if (pt.isCable()) { + final AEColor[] variants = AEColor.values(); + + final int itemDamage = is.getItemDamage(); + final PartTypeWithVariant registeredPartType = this.registered.get(itemDamage); + if (registeredPartType != null) { + return super.getItemStackDisplayName(is) + " - " + variants[registeredPartType.variant].toString(); + } + } + + if (pt.getExtraName() != null) { + return super.getItemStackDisplayName(is) + " - " + pt.getExtraName().getLocal(); + } + + return super.getItemStackDisplayName(is); + } + + @Override + public void registerIcons(final IIconRegister iconRegister) { + for (final Entry part : this.registered.entrySet()) { + final String tex = "appliedenergistics2:" + this.getName(new ItemStack(this, 1, part.getKey())); + part.getValue().ico = iconRegister.registerIcon(tex); + } + } + + @Override + protected void getCheckedSubItems( + final Item sameItem, final CreativeTabs creativeTab, final List itemStacks) { + final List> types = + new ArrayList>(this.registered.entrySet()); + Collections.sort(types, REGISTERED_COMPARATOR); + + for (final Entry part : types) { + itemStacks.add(new ItemStack(this, 1, part.getKey())); + } + } + + private String getName(final ItemStack is) { + Preconditions.checkNotNull(is); + + final PartType stackType = this.getTypeByStack(is); + final String typeName = stackType.name(); + + return this.nameResolver.getName(typeName); + } + + @Nonnull + public PartType getTypeByStack(final ItemStack is) { + Preconditions.checkNotNull(is); + + final PartTypeWithVariant pt = this.registered.get(is.getItemDamage()); + if (pt != null) { + return pt.part; + } + + return PartType.InvalidType; + } + + @Nullable + @Override + public IPart createPartFromItemStack(final ItemStack is) { + final PartType type = this.getTypeByStack(is); + final Class part = type.getPart(); + if (part == null) { + return null; + } + + try { + if (type.getConstructor() == null) { + type.setConstructor(part.getConstructor(ItemStack.class)); + } + + return type.getConstructor().newInstance(is); + } catch (final InstantiationException e) { + throw new IllegalStateException( + "Unable to construct IBusPart from IBusItem : " + part.getName() + + " ; Possibly didn't have correct constructor( ItemStack )", + e); + } catch (final IllegalAccessException e) { + throw new IllegalStateException( + "Unable to construct IBusPart from IBusItem : " + part.getName() + + " ; Possibly didn't have correct constructor( ItemStack )", + e); + } catch (final InvocationTargetException e) { + throw new IllegalStateException( + "Unable to construct IBusPart from IBusItem : " + part.getName() + + " ; Possibly didn't have correct constructor( ItemStack )", + e); + } catch (final NoSuchMethodException e) { + throw new IllegalStateException( + "Unable to construct IBusPart from IBusItem : " + part.getName() + + " ; Possibly didn't have correct constructor( ItemStack )", + e); + } + } + + public int variantOf(final int itemDamage) { + final PartTypeWithVariant registeredPartType = this.registered.get(itemDamage); + if (registeredPartType != null) { + return registeredPartType.variant; + } + + return 0; + } + + @Nullable + @Override + public String getUnlocalizedGroupName(final Set others, final ItemStack is) { + boolean importBus = false; + boolean exportBus = false; + boolean group = false; + + final PartType u = this.getTypeByStack(is); + + for (final ItemStack stack : others) { + if (stack.getItem() == this) { + final PartType pt = this.getTypeByStack(stack); + switch (pt) { + case ImportBus: + importBus = true; + if (u == pt) { + group = true; + } + break; + case ExportBus: + exportBus = true; + if (u == pt) { + group = true; + } + break; + default: + } + } + } + + if (group && importBus && exportBus) { + return GuiText.IOBuses.getUnlocalized(); + } + + return null; + } + + private static final class PartTypeWithVariant { + private final PartType part; + private final int variant; + + @SideOnly(Side.CLIENT) + private IIcon ico; + + private PartTypeWithVariant(final PartType part, final int variant) { + assert part != null; + assert variant >= 0; + + this.part = part; + this.variant = variant; + } + + @Override + public String toString() { + return "PartTypeWithVariant{" + "part=" + + this.part + ", variant=" + + this.variant + ", ico=" + + this.ico + '}'; + } + } + + private static final class RegisteredComparator implements Comparator> { + @Override + public int compare(final Entry o1, final Entry o2) { + return o1.getValue().part.name().compareTo(o2.getValue().part.name()); + } + } } diff --git a/src/main/java/appeng/items/parts/PartType.java b/src/main/java/appeng/items/parts/PartType.java index adc06ecaba1..48b98842037 100644 --- a/src/main/java/appeng/items/parts/PartType.java +++ b/src/main/java/appeng/items/parts/PartType.java @@ -18,7 +18,6 @@ package appeng.items.parts; - import appeng.api.parts.IPart; import appeng.core.features.AEFeature; import appeng.core.localization.GuiText; @@ -28,202 +27,268 @@ import appeng.parts.networking.*; import appeng.parts.p2p.*; import appeng.parts.reporting.*; - import java.lang.reflect.Constructor; import java.util.Collections; import java.util.EnumSet; import java.util.Set; - -public enum PartType -{ - InvalidType( -1, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), null ), - - CableGlass( 0, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartCableGlass.class ) - { - @Override - public boolean isCable() - { - return true; - } - }, - - CableCovered( 20, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartCableCovered.class ) - { - @Override - public boolean isCable() - { - return true; - } - }, - - CableSmart( 40, EnumSet.of( AEFeature.Channels ), EnumSet.noneOf( IntegrationType.class ), PartCableSmart.class ) - { - @Override - public boolean isCable() - { - return true; - } - }, - - CableDense( 60, EnumSet.of( AEFeature.Channels ), EnumSet.noneOf( IntegrationType.class ), PartDenseCable.class ) - { - @Override - public boolean isCable() - { - return true; - } - }, - - CableDenseCovered( 520, EnumSet.of( AEFeature.Channels ), EnumSet.noneOf( IntegrationType.class ), PartDenseCableCovered.class ) - { - @Override - public boolean isCable() - { - return true; - } - }, - - CableUltraDenseCovered( 540, EnumSet.of( AEFeature.Channels ), EnumSet.noneOf( IntegrationType.class ), PartUltraDenseCableCovered.class ) - { - @Override - public boolean isCable() - { - return true; - } - }, - CableUltraDenseSmart( 560, EnumSet.of( AEFeature.Channels ), EnumSet.noneOf( IntegrationType.class ), PartUltraDenseCableSmart.class ) - { - @Override - public boolean isCable() - { - return true; - } - }, - - ToggleBus( 80, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartToggleBus.class ), - - InvertedToggleBus( 100, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartInvertedToggleBus.class ), - - CableAnchor( 120, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartCableAnchor.class ), - - QuartzFiber( 140, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartQuartzFiber.class ), - - Monitor( 160, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartPanel.class ), - - SemiDarkMonitor( 180, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartSemiDarkPanel.class ), - - DarkMonitor( 200, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartDarkPanel.class ), - - StorageBus( 220, EnumSet.of( AEFeature.StorageBus ), EnumSet.noneOf( IntegrationType.class ), PartStorageBus.class ), - - ImportBus( 240, EnumSet.of( AEFeature.ImportBus ), EnumSet.noneOf( IntegrationType.class ), PartImportBus.class ), - - ExportBus( 260, EnumSet.of( AEFeature.ExportBus ), EnumSet.noneOf( IntegrationType.class ), PartExportBus.class ), - - LevelEmitter( 280, EnumSet.of( AEFeature.LevelEmitter ), EnumSet.noneOf( IntegrationType.class ), PartLevelEmitter.class ), - - AnnihilationPlane( 300, EnumSet.of( AEFeature.AnnihilationPlane ), EnumSet.noneOf( IntegrationType.class ), PartAnnihilationPlane.class ), - - IdentityAnnihilationPlane( 301, EnumSet.of( AEFeature.AnnihilationPlane, AEFeature.IdentityAnnihilationPlane ), EnumSet.noneOf( IntegrationType.class ), PartIdentityAnnihilationPlane.class ), - - FormationPlane( 320, EnumSet.of( AEFeature.FormationPlane ), EnumSet.noneOf( IntegrationType.class ), PartFormationPlane.class ), - - PatternTerminal( 340, EnumSet.of( AEFeature.Patterns ), EnumSet.noneOf( IntegrationType.class ), PartPatternTerminal.class ), - - CraftingTerminal( 360, EnumSet.of( AEFeature.CraftingTerminal ), EnumSet.noneOf( IntegrationType.class ), PartCraftingTerminal.class ), - - Terminal( 380, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartTerminal.class ), - - StorageMonitor( 400, EnumSet.of( AEFeature.StorageMonitor ), EnumSet.noneOf( IntegrationType.class ), PartStorageMonitor.class ), - - ConversionMonitor( 420, EnumSet.of( AEFeature.PartConversionMonitor ), EnumSet.noneOf( IntegrationType.class ), PartConversionMonitor.class ), - - Interface( 440, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartInterface.class ), - - P2PTunnelME( 460, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelME ), EnumSet.noneOf( IntegrationType.class ), PartP2PTunnelME.class, GuiText.METunnel ), - - P2PTunnelRedstone( 461, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelRedstone ), EnumSet.noneOf( IntegrationType.class ), PartP2PRedstone.class, GuiText.RedstoneTunnel ), - - P2PTunnelItems( 462, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelItems ), EnumSet.noneOf( IntegrationType.class ), PartP2PItems.class, GuiText.ItemTunnel ), - - P2PTunnelLiquids( 463, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelLiquids ), EnumSet.noneOf( IntegrationType.class ), PartP2PLiquids.class, GuiText.FluidTunnel ), - - P2PTunnelEU( 465, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelEU ), EnumSet.of( IntegrationType.IC2 ), PartP2PIC2Power.class, GuiText.EUTunnel ), - - P2PTunnelRF( 466, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelRF ), EnumSet.of( IntegrationType.RF ), PartP2PRFPower.class, GuiText.RFTunnel ), - - P2PTunnelLight( 467, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelLight ), EnumSet.noneOf( IntegrationType.class ), PartP2PLight.class, GuiText.LightTunnel ), - - P2PTunnelOpenComputers( 468, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelOpenComputers ), EnumSet.of( IntegrationType.OpenComputers ), PartP2POpenComputers.class, GuiText.OCTunnel ), - - P2PTunnelPressure( 469, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelPressure ), EnumSet.of( IntegrationType.PneumaticCraft ), PartP2PPressure.class, GuiText.PressureTunnel ), - - P2PTunnelGT( 470, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelGregtech ), EnumSet.of( IntegrationType.GT ), PartP2PGT5Power.class, GuiText.GTTunnel ), - - InterfaceTerminal( 480, EnumSet.of( AEFeature.InterfaceTerminal ), EnumSet.noneOf( IntegrationType.class ), PartInterfaceTerminal.class ), - - PatternTerminalEx( 500, EnumSet.of( AEFeature.Patterns ), EnumSet.noneOf( IntegrationType.class ), PartPatternTerminalEx.class ); - - private final int baseDamage; - private final Set features; - private final Set integrations; - private final Class myPart; - private final GuiText extraName; - private Constructor constructor; - - PartType( final int baseMetaValue, final Set features, final Set integrations, final Class c ) - { - this( baseMetaValue, features, integrations, c, null ); - } - - PartType( final int baseMetaValue, final Set features, final Set integrations, final Class c, final GuiText en ) - { - this.features = Collections.unmodifiableSet( features ); - this.integrations = Collections.unmodifiableSet( integrations ); - this.myPart = c; - this.extraName = en; - this.baseDamage = baseMetaValue; - } - - public boolean isCable() - { - return false; - } - - Set getFeature() - { - return this.features; - } - - Set getIntegrations() - { - return this.integrations; - } - - Class getPart() - { - return this.myPart; - } - - GuiText getExtraName() - { - return this.extraName; - } - - Constructor getConstructor() - { - return this.constructor; - } - - void setConstructor( final Constructor constructor ) - { - this.constructor = constructor; - } - - int getBaseDamage() - { - return this.baseDamage; - } - +public enum PartType { + InvalidType(-1, EnumSet.of(AEFeature.Core), EnumSet.noneOf(IntegrationType.class), null), + + CableGlass(0, EnumSet.of(AEFeature.Core), EnumSet.noneOf(IntegrationType.class), PartCableGlass.class) { + @Override + public boolean isCable() { + return true; + } + }, + + CableCovered(20, EnumSet.of(AEFeature.Core), EnumSet.noneOf(IntegrationType.class), PartCableCovered.class) { + @Override + public boolean isCable() { + return true; + } + }, + + CableSmart(40, EnumSet.of(AEFeature.Channels), EnumSet.noneOf(IntegrationType.class), PartCableSmart.class) { + @Override + public boolean isCable() { + return true; + } + }, + + CableDense(60, EnumSet.of(AEFeature.Channels), EnumSet.noneOf(IntegrationType.class), PartDenseCable.class) { + @Override + public boolean isCable() { + return true; + } + }, + + CableDenseCovered( + 520, EnumSet.of(AEFeature.Channels), EnumSet.noneOf(IntegrationType.class), PartDenseCableCovered.class) { + @Override + public boolean isCable() { + return true; + } + }, + + CableUltraDenseCovered( + 540, + EnumSet.of(AEFeature.Channels), + EnumSet.noneOf(IntegrationType.class), + PartUltraDenseCableCovered.class) { + @Override + public boolean isCable() { + return true; + } + }, + CableUltraDenseSmart( + 560, + EnumSet.of(AEFeature.Channels), + EnumSet.noneOf(IntegrationType.class), + PartUltraDenseCableSmart.class) { + @Override + public boolean isCable() { + return true; + } + }, + + ToggleBus(80, EnumSet.of(AEFeature.Core), EnumSet.noneOf(IntegrationType.class), PartToggleBus.class), + + InvertedToggleBus( + 100, EnumSet.of(AEFeature.Core), EnumSet.noneOf(IntegrationType.class), PartInvertedToggleBus.class), + + CableAnchor(120, EnumSet.of(AEFeature.Core), EnumSet.noneOf(IntegrationType.class), PartCableAnchor.class), + + QuartzFiber(140, EnumSet.of(AEFeature.Core), EnumSet.noneOf(IntegrationType.class), PartQuartzFiber.class), + + Monitor(160, EnumSet.of(AEFeature.Core), EnumSet.noneOf(IntegrationType.class), PartPanel.class), + + SemiDarkMonitor(180, EnumSet.of(AEFeature.Core), EnumSet.noneOf(IntegrationType.class), PartSemiDarkPanel.class), + + DarkMonitor(200, EnumSet.of(AEFeature.Core), EnumSet.noneOf(IntegrationType.class), PartDarkPanel.class), + + StorageBus(220, EnumSet.of(AEFeature.StorageBus), EnumSet.noneOf(IntegrationType.class), PartStorageBus.class), + + ImportBus(240, EnumSet.of(AEFeature.ImportBus), EnumSet.noneOf(IntegrationType.class), PartImportBus.class), + + ExportBus(260, EnumSet.of(AEFeature.ExportBus), EnumSet.noneOf(IntegrationType.class), PartExportBus.class), + + LevelEmitter( + 280, EnumSet.of(AEFeature.LevelEmitter), EnumSet.noneOf(IntegrationType.class), PartLevelEmitter.class), + + AnnihilationPlane( + 300, + EnumSet.of(AEFeature.AnnihilationPlane), + EnumSet.noneOf(IntegrationType.class), + PartAnnihilationPlane.class), + + IdentityAnnihilationPlane( + 301, + EnumSet.of(AEFeature.AnnihilationPlane, AEFeature.IdentityAnnihilationPlane), + EnumSet.noneOf(IntegrationType.class), + PartIdentityAnnihilationPlane.class), + + FormationPlane( + 320, EnumSet.of(AEFeature.FormationPlane), EnumSet.noneOf(IntegrationType.class), PartFormationPlane.class), + + PatternTerminal( + 340, EnumSet.of(AEFeature.Patterns), EnumSet.noneOf(IntegrationType.class), PartPatternTerminal.class), + + CraftingTerminal( + 360, + EnumSet.of(AEFeature.CraftingTerminal), + EnumSet.noneOf(IntegrationType.class), + PartCraftingTerminal.class), + + Terminal(380, EnumSet.of(AEFeature.Core), EnumSet.noneOf(IntegrationType.class), PartTerminal.class), + + StorageMonitor( + 400, EnumSet.of(AEFeature.StorageMonitor), EnumSet.noneOf(IntegrationType.class), PartStorageMonitor.class), + + ConversionMonitor( + 420, + EnumSet.of(AEFeature.PartConversionMonitor), + EnumSet.noneOf(IntegrationType.class), + PartConversionMonitor.class), + + Interface(440, EnumSet.of(AEFeature.Core), EnumSet.noneOf(IntegrationType.class), PartInterface.class), + + P2PTunnelME( + 460, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelME), + EnumSet.noneOf(IntegrationType.class), + PartP2PTunnelME.class, + GuiText.METunnel), + + P2PTunnelRedstone( + 461, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelRedstone), + EnumSet.noneOf(IntegrationType.class), + PartP2PRedstone.class, + GuiText.RedstoneTunnel), + + P2PTunnelItems( + 462, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelItems), + EnumSet.noneOf(IntegrationType.class), + PartP2PItems.class, + GuiText.ItemTunnel), + + P2PTunnelLiquids( + 463, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelLiquids), + EnumSet.noneOf(IntegrationType.class), + PartP2PLiquids.class, + GuiText.FluidTunnel), + + P2PTunnelEU( + 465, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelEU), + EnumSet.of(IntegrationType.IC2), + PartP2PIC2Power.class, + GuiText.EUTunnel), + + P2PTunnelRF( + 466, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelRF), + EnumSet.of(IntegrationType.RF), + PartP2PRFPower.class, + GuiText.RFTunnel), + + P2PTunnelLight( + 467, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelLight), + EnumSet.noneOf(IntegrationType.class), + PartP2PLight.class, + GuiText.LightTunnel), + + P2PTunnelOpenComputers( + 468, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelOpenComputers), + EnumSet.of(IntegrationType.OpenComputers), + PartP2POpenComputers.class, + GuiText.OCTunnel), + + P2PTunnelPressure( + 469, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelPressure), + EnumSet.of(IntegrationType.PneumaticCraft), + PartP2PPressure.class, + GuiText.PressureTunnel), + + P2PTunnelGT( + 470, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelGregtech), + EnumSet.of(IntegrationType.GT), + PartP2PGT5Power.class, + GuiText.GTTunnel), + + InterfaceTerminal( + 480, + EnumSet.of(AEFeature.InterfaceTerminal), + EnumSet.noneOf(IntegrationType.class), + PartInterfaceTerminal.class), + + PatternTerminalEx( + 500, EnumSet.of(AEFeature.Patterns), EnumSet.noneOf(IntegrationType.class), PartPatternTerminalEx.class); + + private final int baseDamage; + private final Set features; + private final Set integrations; + private final Class myPart; + private final GuiText extraName; + private Constructor constructor; + + PartType( + final int baseMetaValue, + final Set features, + final Set integrations, + final Class c) { + this(baseMetaValue, features, integrations, c, null); + } + + PartType( + final int baseMetaValue, + final Set features, + final Set integrations, + final Class c, + final GuiText en) { + this.features = Collections.unmodifiableSet(features); + this.integrations = Collections.unmodifiableSet(integrations); + this.myPart = c; + this.extraName = en; + this.baseDamage = baseMetaValue; + } + + public boolean isCable() { + return false; + } + + Set getFeature() { + return this.features; + } + + Set getIntegrations() { + return this.integrations; + } + + Class getPart() { + return this.myPart; + } + + GuiText getExtraName() { + return this.extraName; + } + + Constructor getConstructor() { + return this.constructor; + } + + void setConstructor(final Constructor constructor) { + this.constructor = constructor; + } + + int getBaseDamage() { + return this.baseDamage; + } } diff --git a/src/main/java/appeng/items/storage/ItemBasicStorageCell.java b/src/main/java/appeng/items/storage/ItemBasicStorageCell.java index b0fb1dc9178..862bd604ba2 100644 --- a/src/main/java/appeng/items/storage/ItemBasicStorageCell.java +++ b/src/main/java/appeng/items/storage/ItemBasicStorageCell.java @@ -18,7 +18,6 @@ package appeng.items.storage; - import appeng.api.AEApi; import appeng.api.config.FuzzyMode; import appeng.api.config.IncludeExclude; @@ -44,7 +43,9 @@ import com.google.common.base.Optional; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import net.java.games.input.Keyboard; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; @@ -54,288 +55,270 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.ForgeEventFactory; -import java.util.EnumSet; -import java.util.List; -import java.util.Set; - - -public final class ItemBasicStorageCell extends AEBaseItem implements IStorageCell, IItemGroup -{ - private final MaterialType component; - private final int totalBytes; - private final int perType; - private final double idleDrain; - - public ItemBasicStorageCell( final MaterialType whichCell, final int kilobytes ) - { - super( Optional.of( kilobytes + "k" ) ); - - this.setFeature( EnumSet.of( AEFeature.StorageCells ) ); - this.setMaxStackSize( 1 ); - this.totalBytes = kilobytes * 1024; - this.component = whichCell; - - switch( this.component ) - { - case Cell1kPart: - this.idleDrain = 0.5; - this.perType = 8; - break; - case Cell4kPart: - this.idleDrain = 1.0; - this.perType = 32; - break; - case Cell16kPart: - this.idleDrain = 1.5; - this.perType = 128; - break; - case Cell64kPart: - this.idleDrain = 2.0; - this.perType = 512; - break; - default: - this.idleDrain = 0.0; - this.perType = 8; - } - } +public final class ItemBasicStorageCell extends AEBaseItem implements IStorageCell, IItemGroup { + private final MaterialType component; + private final int totalBytes; + private final int perType; + private final double idleDrain; + + public ItemBasicStorageCell(final MaterialType whichCell, final int kilobytes) { + super(Optional.of(kilobytes + "k")); + + this.setFeature(EnumSet.of(AEFeature.StorageCells)); + this.setMaxStackSize(1); + this.totalBytes = kilobytes * 1024; + this.component = whichCell; + + switch (this.component) { + case Cell1kPart: + this.idleDrain = 0.5; + this.perType = 8; + break; + case Cell4kPart: + this.idleDrain = 1.0; + this.perType = 32; + break; + case Cell16kPart: + this.idleDrain = 1.5; + this.perType = 128; + break; + case Cell64kPart: + this.idleDrain = 2.0; + this.perType = 512; + break; + default: + this.idleDrain = 0.0; + this.perType = 8; + } + } @SideOnly(Side.CLIENT) - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - final IMEInventoryHandler inventory = AEApi.instance().registries().cell().getCellInventory( stack, null, StorageChannel.ITEMS ); - - if( inventory instanceof ICellInventoryHandler ) - { - final ICellInventoryHandler handler = (ICellInventoryHandler) inventory; - final ICellInventory cellInventory = handler.getCellInv(); - - if( cellInventory != null ) - { - lines.add( cellInventory.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + cellInventory.getTotalBytes() + ' ' + GuiText.BytesUsed.getLocal() ); - - lines.add( cellInventory.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + cellInventory.getTotalItemTypes() + ' ' + GuiText.Types.getLocal() ); - - if( handler.isPreformatted() ) - { - String filter = cellInventory.getOreFilter(); - - if (filter.isEmpty()) { - final String list = (handler.getIncludeExcludeMode() == IncludeExclude.WHITELIST ? GuiText.Included : GuiText.Excluded).getLocal(); - - if (handler.isFuzzy()) { - lines.add(GuiText.Partitioned.getLocal() + " - " + list + ' ' + GuiText.Fuzzy.getLocal()); - } else { - lines.add(GuiText.Partitioned.getLocal() + " - " + list + ' ' + GuiText.Precise.getLocal()); - } + @Override + public void addCheckedInformation( + final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo) { + final IMEInventoryHandler inventory = + AEApi.instance().registries().cell().getCellInventory(stack, null, StorageChannel.ITEMS); + + if (inventory instanceof ICellInventoryHandler) { + final ICellInventoryHandler handler = (ICellInventoryHandler) inventory; + final ICellInventory cellInventory = handler.getCellInv(); + + if (cellInventory != null) { + lines.add(cellInventory.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + + cellInventory.getTotalBytes() + ' ' + GuiText.BytesUsed.getLocal()); + + lines.add(cellInventory.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + + cellInventory.getTotalItemTypes() + ' ' + GuiText.Types.getLocal()); + + if (handler.isPreformatted()) { + String filter = cellInventory.getOreFilter(); + + if (filter.isEmpty()) { + final String list = (handler.getIncludeExcludeMode() == IncludeExclude.WHITELIST + ? GuiText.Included + : GuiText.Excluded) + .getLocal(); + + if (handler.isFuzzy()) { + lines.add(GuiText.Partitioned.getLocal() + " - " + list + ' ' + GuiText.Fuzzy.getLocal()); + } else { + lines.add(GuiText.Partitioned.getLocal() + " - " + list + ' ' + GuiText.Precise.getLocal()); + } if (GuiScreen.isShiftKeyDown()) { lines.add(GuiText.Filter.getLocal() + ": "); - for (int i = 0; i < cellInventory.getConfigInventory().getSizeInventory(); ++i) { + for (int i = 0; + i < cellInventory.getConfigInventory().getSizeInventory(); + ++i) { ItemStack s = cellInventory.getConfigInventory().getStackInSlot(i); - if (s != null) - lines.add(s.getDisplayName()); + if (s != null) lines.add(s.getDisplayName()); } } - } - else { - lines.add(GuiText.PartitionedOre.getLocal() + " : " + filter); - } - } - } - } - } - - @Override - public int getBytes( final ItemStack cellItem ) - { - return this.totalBytes; - } - - @Override - public int BytePerType( final ItemStack cell ) - { - return this.perType; - } - - @Override - public int getBytesPerType( final ItemStack cellItem ) - { - return this.perType; - } - - @Override - public int getTotalTypes( final ItemStack cellItem ) - { - return 63; - } - - @Override - public boolean isBlackListed( final ItemStack cellItem, final IAEItemStack requestedAddition ) - { - return false; - } - - @Override - public boolean storableInStorageCell() - { - return false; - } - - @Override - public boolean isStorageCell( final ItemStack i ) - { - return true; - } - - @Override - public double getIdleDrain() - { - return this.idleDrain; - } - - @Override - public String getUnlocalizedGroupName( final Set others, final ItemStack is ) - { - return GuiText.StorageCells.getUnlocalized(); - } - - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } - - @Override - public IInventory getUpgradesInventory( final ItemStack is ) - { - return new CellUpgrades( is, 2 ); - } - - @Override - public IInventory getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } - - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - final String fz = Platform.openNbtData( is ).getString( "FuzzyMode" ); - try - { - return FuzzyMode.valueOf( fz ); - } - catch( final Throwable t ) - { - return FuzzyMode.IGNORE_ALL; - } - } - - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - Platform.openNbtData( is ).setString( "FuzzyMode", fzMode.name() ); - } - - @Override - public String getOreFilter(ItemStack is) { - return Platform.openNbtData( is ).getString( "OreFilter" ); - } - - @Override - public void setOreFilter(ItemStack is, String filter) { - Platform.openNbtData( is ).setString("OreFilter", filter); - } - - @Override - public ItemStack onItemRightClick( final ItemStack stack, final World world, final EntityPlayer player ) - { - this.disassembleDrive( stack, world, player ); - return stack; - } - - private boolean disassembleDrive( final ItemStack stack, final World world, final EntityPlayer player ) - { - if( player.isSneaking() ) - { - if( Platform.isClient() ) - { - return false; - } - final InventoryPlayer playerInventory = player.inventory; - final IMEInventoryHandler inv = AEApi.instance().registries().cell().getCellInventory( stack, null, StorageChannel.ITEMS ); - if( inv != null && playerInventory.getCurrentItem() == stack ) - { - final InventoryAdaptor ia = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); - final IItemList list = inv.getAvailableItems( StorageChannel.ITEMS.createList() ); - if( list.isEmpty() && ia != null ) - { - playerInventory.setInventorySlotContents( playerInventory.currentItem, null ); - - // drop core - final ItemStack extraB = ia.addItems( this.component.stack( 1 ) ); - if( extraB != null ) - { - player.dropPlayerItemWithRandomChoice( extraB, false ); - } - - // drop upgrades - final IInventory upgradesInventory = this.getUpgradesInventory( stack ); - for( int upgradeIndex = 0; upgradeIndex < upgradesInventory.getSizeInventory(); upgradeIndex++ ) - { - final ItemStack upgradeStack = upgradesInventory.getStackInSlot( upgradeIndex ); - final ItemStack leftStack = ia.addItems( upgradeStack ); - if( leftStack != null && upgradeStack.getItem() instanceof IUpgradeModule ) - { - player.dropPlayerItemWithRandomChoice( upgradeStack, false ); - } - } - - // drop empty storage cell case - for( final ItemStack storageCellStack : AEApi.instance().definitions().materials().emptyStorageCell().maybeStack( 1 ).asSet() ) - { - final ItemStack extraA = ia.addItems( storageCellStack ); - if( extraA != null ) - { - player.dropPlayerItemWithRandomChoice( extraA, false ); - } - } - - if( player.inventoryContainer != null ) - { - player.inventoryContainer.detectAndSendChanges(); - } - - return true; - } - } - } - return false; - } - - @Override - public boolean onItemUseFirst( final ItemStack stack, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, stack, 1 ) <= 0 ) - return true; - - return this.disassembleDrive( stack, world, player ); - } - - @Override - public ItemStack getContainerItem( final ItemStack itemStack ) - { - for( final ItemStack stack : AEApi.instance().definitions().materials().emptyStorageCell().maybeStack( 1 ).asSet() ) - { - return stack; - } - - throw new MissingDefinition( "Tried to use empty storage cells while basic storage cells are defined." ); - } - - @Override - public boolean hasContainerItem( final ItemStack stack ) - { - return AEConfig.instance.isFeatureEnabled( AEFeature.EnableDisassemblyCrafting ); - } + } else { + lines.add(GuiText.PartitionedOre.getLocal() + " : " + filter); + } + } + } + } + } + + @Override + public int getBytes(final ItemStack cellItem) { + return this.totalBytes; + } + + @Override + public int BytePerType(final ItemStack cell) { + return this.perType; + } + + @Override + public int getBytesPerType(final ItemStack cellItem) { + return this.perType; + } + + @Override + public int getTotalTypes(final ItemStack cellItem) { + return 63; + } + + @Override + public boolean isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) { + return false; + } + + @Override + public boolean storableInStorageCell() { + return false; + } + + @Override + public boolean isStorageCell(final ItemStack i) { + return true; + } + + @Override + public double getIdleDrain() { + return this.idleDrain; + } + + @Override + public String getUnlocalizedGroupName(final Set others, final ItemStack is) { + return GuiText.StorageCells.getUnlocalized(); + } + + @Override + public boolean isEditable(final ItemStack is) { + return true; + } + + @Override + public IInventory getUpgradesInventory(final ItemStack is) { + return new CellUpgrades(is, 2); + } + + @Override + public IInventory getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } + + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + final String fz = Platform.openNbtData(is).getString("FuzzyMode"); + try { + return FuzzyMode.valueOf(fz); + } catch (final Throwable t) { + return FuzzyMode.IGNORE_ALL; + } + } + + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { + Platform.openNbtData(is).setString("FuzzyMode", fzMode.name()); + } + + @Override + public String getOreFilter(ItemStack is) { + return Platform.openNbtData(is).getString("OreFilter"); + } + + @Override + public void setOreFilter(ItemStack is, String filter) { + Platform.openNbtData(is).setString("OreFilter", filter); + } + + @Override + public ItemStack onItemRightClick(final ItemStack stack, final World world, final EntityPlayer player) { + this.disassembleDrive(stack, world, player); + return stack; + } + + private boolean disassembleDrive(final ItemStack stack, final World world, final EntityPlayer player) { + if (player.isSneaking()) { + if (Platform.isClient()) { + return false; + } + final InventoryPlayer playerInventory = player.inventory; + final IMEInventoryHandler inv = + AEApi.instance().registries().cell().getCellInventory(stack, null, StorageChannel.ITEMS); + if (inv != null && playerInventory.getCurrentItem() == stack) { + final InventoryAdaptor ia = InventoryAdaptor.getAdaptor(player, ForgeDirection.UNKNOWN); + final IItemList list = inv.getAvailableItems(StorageChannel.ITEMS.createList()); + if (list.isEmpty() && ia != null) { + playerInventory.setInventorySlotContents(playerInventory.currentItem, null); + + // drop core + final ItemStack extraB = ia.addItems(this.component.stack(1)); + if (extraB != null) { + player.dropPlayerItemWithRandomChoice(extraB, false); + } + + // drop upgrades + final IInventory upgradesInventory = this.getUpgradesInventory(stack); + for (int upgradeIndex = 0; upgradeIndex < upgradesInventory.getSizeInventory(); upgradeIndex++) { + final ItemStack upgradeStack = upgradesInventory.getStackInSlot(upgradeIndex); + final ItemStack leftStack = ia.addItems(upgradeStack); + if (leftStack != null && upgradeStack.getItem() instanceof IUpgradeModule) { + player.dropPlayerItemWithRandomChoice(upgradeStack, false); + } + } + + // drop empty storage cell case + for (final ItemStack storageCellStack : AEApi.instance() + .definitions() + .materials() + .emptyStorageCell() + .maybeStack(1) + .asSet()) { + final ItemStack extraA = ia.addItems(storageCellStack); + if (extraA != null) { + player.dropPlayerItemWithRandomChoice(extraA, false); + } + } + + if (player.inventoryContainer != null) { + player.inventoryContainer.detectAndSendChanges(); + } + + return true; + } + } + } + return false; + } + + @Override + public boolean onItemUseFirst( + final ItemStack stack, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (ForgeEventFactory.onItemUseStart(player, stack, 1) <= 0) return true; + + return this.disassembleDrive(stack, world, player); + } + + @Override + public ItemStack getContainerItem(final ItemStack itemStack) { + for (final ItemStack stack : AEApi.instance() + .definitions() + .materials() + .emptyStorageCell() + .maybeStack(1) + .asSet()) { + return stack; + } + + throw new MissingDefinition("Tried to use empty storage cells while basic storage cells are defined."); + } + + @Override + public boolean hasContainerItem(final ItemStack stack) { + return AEConfig.instance.isFeatureEnabled(AEFeature.EnableDisassemblyCrafting); + } } diff --git a/src/main/java/appeng/items/storage/ItemCreativeStorageCell.java b/src/main/java/appeng/items/storage/ItemCreativeStorageCell.java index 573684b7554..a1e98cc214b 100644 --- a/src/main/java/appeng/items/storage/ItemCreativeStorageCell.java +++ b/src/main/java/appeng/items/storage/ItemCreativeStorageCell.java @@ -18,63 +18,50 @@ package appeng.items.storage; - import appeng.api.config.FuzzyMode; import appeng.api.storage.ICellWorkbenchItem; import appeng.core.features.AEFeature; import appeng.items.AEBaseItem; import appeng.items.contents.CellConfig; +import java.util.EnumSet; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.util.EnumSet; - - -public class ItemCreativeStorageCell extends AEBaseItem implements ICellWorkbenchItem -{ - - public ItemCreativeStorageCell() - { - this.setFeature( EnumSet.of( AEFeature.StorageCells, AEFeature.Creative ) ); - this.setMaxStackSize( 1 ); - } +public class ItemCreativeStorageCell extends AEBaseItem implements ICellWorkbenchItem { - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } + public ItemCreativeStorageCell() { + this.setFeature(EnumSet.of(AEFeature.StorageCells, AEFeature.Creative)); + this.setMaxStackSize(1); + } - @Override - public IInventory getUpgradesInventory( final ItemStack is ) - { - return null; - } + @Override + public boolean isEditable(final ItemStack is) { + return true; + } - @Override - public IInventory getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } + @Override + public IInventory getUpgradesInventory(final ItemStack is) { + return null; + } - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - return FuzzyMode.IGNORE_ALL; - } + @Override + public IInventory getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + return FuzzyMode.IGNORE_ALL; + } - } + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) {} - @Override - public String getOreFilter(ItemStack is) { - return ""; - } + @Override + public String getOreFilter(ItemStack is) { + return ""; + } - @Override - public void setOreFilter(ItemStack is, String filter) { - } + @Override + public void setOreFilter(ItemStack is, String filter) {} } diff --git a/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java b/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java index f17102b702a..1f299885139 100644 --- a/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java +++ b/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java @@ -18,7 +18,6 @@ package appeng.items.storage; - import appeng.api.implementations.TransitionResult; import appeng.api.implementations.items.ISpatialStorageCell; import appeng.api.util.WorldCoord; @@ -30,176 +29,160 @@ import appeng.spatial.StorageWorldProvider; import appeng.util.Platform; import com.google.common.base.Optional; +import java.util.EnumSet; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; -import java.util.EnumSet; -import java.util.List; - - -public class ItemSpatialStorageCell extends AEBaseItem implements ISpatialStorageCell -{ - private final int maxRegion; - - public ItemSpatialStorageCell( final int spatialScale ) - { - super( Optional.of( spatialScale + "Cubed" ) ); - this.setFeature( EnumSet.of( AEFeature.SpatialIO ) ); - this.setMaxStackSize( 1 ); - this.maxRegion = spatialScale; - } - - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - final WorldCoord wc = this.getStoredSize( stack ); - if( wc.x > 0 ) - { - lines.add( GuiText.StoredSize.getLocal() + ": " + wc.x + " x " + wc.y + " x " + wc.z ); - } - } - - @Override - public boolean isSpatialStorage( final ItemStack is ) - { - return true; - } - - @Override - public int getMaxStoredDim( final ItemStack is ) - { - return this.maxRegion; - } - - @Override - public World getWorld( final ItemStack is ) - { - if( is.hasTagCompound() ) - { - final NBTTagCompound c = is.getTagCompound(); - final int dim = c.getInteger( "StorageDim" ); - World w = DimensionManager.getWorld( dim ); - if( w == null ) - { - DimensionManager.initDimension( dim ); - w = DimensionManager.getWorld( dim ); - } - - if( w != null ) - { - if( w.provider instanceof StorageWorldProvider ) - { - return w; - } - } - } - return null; - } - - @Override - public WorldCoord getStoredSize( final ItemStack is ) - { - if( is.hasTagCompound() ) - { - final NBTTagCompound c = is.getTagCompound(); - if( Platform.isServer() ) - { - final int dim = c.getInteger( "StorageDim" ); - return WorldData.instance().dimensionData().getStoredSize( dim ); - } - else - { - return new WorldCoord( c.getInteger( "sizeX" ), c.getInteger( "sizeY" ), c.getInteger( "sizeZ" ) ); - } - } - return new WorldCoord( 0, 0, 0 ); - } - - @Override - public WorldCoord getMin( final ItemStack is ) - { - final World w = this.getWorld( is ); - if( w != null ) - { - final NBTTagCompound info = (NBTTagCompound) w.getWorldInfo().getAdditionalProperty( "storageCell" ); - if( info != null ) - { - return new WorldCoord( info.getInteger( "minX" ), info.getInteger( "minY" ), info.getInteger( "minZ" ) ); - } - } - return new WorldCoord( 0, 0, 0 ); - } - - @Override - public WorldCoord getMax( final ItemStack is ) - { - final World w = this.getWorld( is ); - if( w != null ) - { - final NBTTagCompound info = (NBTTagCompound) w.getWorldInfo().getAdditionalProperty( "storageCell" ); - if( info != null ) - { - return new WorldCoord( info.getInteger( "maxX" ), info.getInteger( "maxY" ), info.getInteger( "maxZ" ) ); - } - } - return new WorldCoord( 0, 0, 0 ); - } - - @Override - public TransitionResult doSpatialTransition( final ItemStack is, final World w, final WorldCoord min, final WorldCoord max, final boolean doTransition ) - { - final WorldCoord scale = this.getStoredSize( is ); - - final int targetX = max.x - min.x - 1; - final int targetY = max.y - min.y - 1; - final int targetZ = max.z - min.z - 1; - final int maxSize = this.getMaxStoredDim( is ); - - World destination = this.getWorld( is ); - - if( ( scale.x == 0 && scale.y == 0 && scale.z == 0 ) || ( scale.x == targetX && scale.y == targetY && scale.z == targetZ ) ) - { - if( targetX <= maxSize && targetY <= maxSize && targetZ <= maxSize ) - { - if( destination == null ) - { - destination = this.createNewWorld( is ); - } - - final int floorBuffer = 64; - StorageHelper.getInstance().swapRegions( w, destination, min.x + 1, min.y + 1, min.z + 1, 1, floorBuffer + 1, 1, targetX - 1, targetY - 1, targetZ - 1 ); - this.setStoredSize( is, targetX, targetY, targetZ ); - - return new TransitionResult( true, 0 ); - } - } - - return new TransitionResult( false, 0 ); - } - - private World createNewWorld( final ItemStack is ) - { - final NBTTagCompound c = Platform.openNbtData( is ); - final int newDim = DimensionManager.getNextFreeDimId(); - c.setInteger( "StorageDim", newDim ); - WorldData.instance().dimensionData().addStorageCell( newDim ); - DimensionManager.initDimension( newDim ); - return DimensionManager.getWorld( newDim ); - } - - private void setStoredSize( final ItemStack is, final int targetX, final int targetY, final int targetZ ) - { - if( is.hasTagCompound() ) - { - final NBTTagCompound c = is.getTagCompound(); - final int dim = c.getInteger( "StorageDim" ); - c.setInteger( "sizeX", targetX ); - c.setInteger( "sizeY", targetY ); - c.setInteger( "sizeZ", targetZ ); - WorldData.instance().dimensionData().setStoredSize( dim, targetX, targetY, targetZ ); - } - } +public class ItemSpatialStorageCell extends AEBaseItem implements ISpatialStorageCell { + private final int maxRegion; + + public ItemSpatialStorageCell(final int spatialScale) { + super(Optional.of(spatialScale + "Cubed")); + this.setFeature(EnumSet.of(AEFeature.SpatialIO)); + this.setMaxStackSize(1); + this.maxRegion = spatialScale; + } + + @Override + public void addCheckedInformation( + final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo) { + final WorldCoord wc = this.getStoredSize(stack); + if (wc.x > 0) { + lines.add(GuiText.StoredSize.getLocal() + ": " + wc.x + " x " + wc.y + " x " + wc.z); + } + } + + @Override + public boolean isSpatialStorage(final ItemStack is) { + return true; + } + + @Override + public int getMaxStoredDim(final ItemStack is) { + return this.maxRegion; + } + + @Override + public World getWorld(final ItemStack is) { + if (is.hasTagCompound()) { + final NBTTagCompound c = is.getTagCompound(); + final int dim = c.getInteger("StorageDim"); + World w = DimensionManager.getWorld(dim); + if (w == null) { + DimensionManager.initDimension(dim); + w = DimensionManager.getWorld(dim); + } + + if (w != null) { + if (w.provider instanceof StorageWorldProvider) { + return w; + } + } + } + return null; + } + + @Override + public WorldCoord getStoredSize(final ItemStack is) { + if (is.hasTagCompound()) { + final NBTTagCompound c = is.getTagCompound(); + if (Platform.isServer()) { + final int dim = c.getInteger("StorageDim"); + return WorldData.instance().dimensionData().getStoredSize(dim); + } else { + return new WorldCoord(c.getInteger("sizeX"), c.getInteger("sizeY"), c.getInteger("sizeZ")); + } + } + return new WorldCoord(0, 0, 0); + } + + @Override + public WorldCoord getMin(final ItemStack is) { + final World w = this.getWorld(is); + if (w != null) { + final NBTTagCompound info = (NBTTagCompound) w.getWorldInfo().getAdditionalProperty("storageCell"); + if (info != null) { + return new WorldCoord(info.getInteger("minX"), info.getInteger("minY"), info.getInteger("minZ")); + } + } + return new WorldCoord(0, 0, 0); + } + + @Override + public WorldCoord getMax(final ItemStack is) { + final World w = this.getWorld(is); + if (w != null) { + final NBTTagCompound info = (NBTTagCompound) w.getWorldInfo().getAdditionalProperty("storageCell"); + if (info != null) { + return new WorldCoord(info.getInteger("maxX"), info.getInteger("maxY"), info.getInteger("maxZ")); + } + } + return new WorldCoord(0, 0, 0); + } + + @Override + public TransitionResult doSpatialTransition( + final ItemStack is, final World w, final WorldCoord min, final WorldCoord max, final boolean doTransition) { + final WorldCoord scale = this.getStoredSize(is); + + final int targetX = max.x - min.x - 1; + final int targetY = max.y - min.y - 1; + final int targetZ = max.z - min.z - 1; + final int maxSize = this.getMaxStoredDim(is); + + World destination = this.getWorld(is); + + if ((scale.x == 0 && scale.y == 0 && scale.z == 0) + || (scale.x == targetX && scale.y == targetY && scale.z == targetZ)) { + if (targetX <= maxSize && targetY <= maxSize && targetZ <= maxSize) { + if (destination == null) { + destination = this.createNewWorld(is); + } + + final int floorBuffer = 64; + StorageHelper.getInstance() + .swapRegions( + w, + destination, + min.x + 1, + min.y + 1, + min.z + 1, + 1, + floorBuffer + 1, + 1, + targetX - 1, + targetY - 1, + targetZ - 1); + this.setStoredSize(is, targetX, targetY, targetZ); + + return new TransitionResult(true, 0); + } + } + + return new TransitionResult(false, 0); + } + + private World createNewWorld(final ItemStack is) { + final NBTTagCompound c = Platform.openNbtData(is); + final int newDim = DimensionManager.getNextFreeDimId(); + c.setInteger("StorageDim", newDim); + WorldData.instance().dimensionData().addStorageCell(newDim); + DimensionManager.initDimension(newDim); + return DimensionManager.getWorld(newDim); + } + + private void setStoredSize(final ItemStack is, final int targetX, final int targetY, final int targetZ) { + if (is.hasTagCompound()) { + final NBTTagCompound c = is.getTagCompound(); + final int dim = c.getInteger("StorageDim"); + c.setInteger("sizeX", targetX); + c.setInteger("sizeY", targetY); + c.setInteger("sizeZ", targetZ); + WorldData.instance().dimensionData().setStoredSize(dim, targetX, targetY, targetZ); + } + } } diff --git a/src/main/java/appeng/items/storage/ItemViewCell.java b/src/main/java/appeng/items/storage/ItemViewCell.java index 1c6e10b9bc5..6738859a296 100644 --- a/src/main/java/appeng/items/storage/ItemViewCell.java +++ b/src/main/java/appeng/items/storage/ItemViewCell.java @@ -18,7 +18,6 @@ package appeng.items.storage; - import appeng.api.AEApi; import appeng.api.config.FuzzyMode; import appeng.api.config.Upgrades; @@ -34,147 +33,132 @@ import appeng.util.Platform; import appeng.util.item.AEItemStack; import appeng.util.prioitylist.*; +import java.util.EnumSet; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.util.EnumSet; -import java.util.List; - - -public class ItemViewCell extends AEBaseItem implements ICellWorkbenchItem -{ - public ItemViewCell() - { - this.setFeature( EnumSet.of( AEFeature.Core ) ); - this.setMaxStackSize( 1 ); - } - - public static IPartitionList createFilter( final ItemStack[] list ) - { - IPartitionList myPartitionList = null; - - final MergedPriorityList myMergedList = new MergedPriorityList(); - - for( final ItemStack currentViewCell : list ) - { - if( currentViewCell == null ) - { - continue; - } - - if( ( currentViewCell.getItem() instanceof ItemViewCell ) ) - { - final ICellWorkbenchItem vc = (ICellWorkbenchItem) currentViewCell.getItem(); - final IInventory upgrades = vc.getUpgradesInventory( currentViewCell ); - final IInventory config = vc.getConfigInventory( currentViewCell ); - final FuzzyMode fzMode = vc.getFuzzyMode( currentViewCell ); - final String filter = vc.getOreFilter(currentViewCell); - - boolean hasInverter = false; - boolean hasFuzzy = false; - boolean hasOreFilter = false; - for (int x = 0; x < upgrades.getSizeInventory(); x++) { - final ItemStack is = upgrades.getStackInSlot(x); - if (is != null && is.getItem() instanceof IUpgradeModule) { - final Upgrades u = ((IUpgradeModule) is.getItem()).getType(is); - if (u != null) { - switch (u) { - case FUZZY: - hasFuzzy = true; - break; - case INVERTER: - hasInverter = true; - break; - case ORE_FILTER: - hasOreFilter = true; - break; - default: - } - } - } - } - - if (hasOreFilter && !filter.isEmpty()) { - myMergedList.addNewList(new OreFilteredList(filter), !hasInverter); - } - else { - final IItemList priorityList = AEApi.instance().storage().createItemList(); - - for (int x = 0; x < config.getSizeInventory(); x++) { - final ItemStack is = config.getStackInSlot(x); - if (is != null) { - priorityList.add(AEItemStack.create(is)); - } - } - - if (!priorityList.isEmpty()) { - if (hasFuzzy) { - myMergedList.addNewList(new FuzzyPriorityList(priorityList, fzMode), !hasInverter); - } else { - myMergedList.addNewList(new PrecisePriorityList(priorityList), !hasInverter); - } - } - } - myPartitionList = myMergedList; - } - } - - return myPartitionList; - } - - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } - - @Override - public IInventory getUpgradesInventory( final ItemStack is ) - { - return new CellUpgrades( is, 2 ); - } - - @Override - public IInventory getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } - - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - final String fz = Platform.openNbtData( is ).getString( "FuzzyMode" ); - try - { - return FuzzyMode.valueOf( fz ); - } - catch( final Throwable t ) - { - return FuzzyMode.IGNORE_ALL; - } - } - - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - Platform.openNbtData( is ).setString( "FuzzyMode", fzMode.name() ); - } - - @Override - public String getOreFilter(ItemStack is) { - return Platform.openNbtData( is ).getString( "OreFilter" ); - } - - @Override - public void setOreFilter(ItemStack is, String filter) { - Platform.openNbtData( is ).setString("OreFilter", filter); - } - @Override - public void addCheckedInformation(final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - String filter = getOreFilter(stack); - if (!filter.isEmpty()) - lines.add(GuiText.PartitionedOre.getLocal() + " : " + filter); - } +public class ItemViewCell extends AEBaseItem implements ICellWorkbenchItem { + public ItemViewCell() { + this.setFeature(EnumSet.of(AEFeature.Core)); + this.setMaxStackSize(1); + } + + public static IPartitionList createFilter(final ItemStack[] list) { + IPartitionList myPartitionList = null; + + final MergedPriorityList myMergedList = new MergedPriorityList(); + + for (final ItemStack currentViewCell : list) { + if (currentViewCell == null) { + continue; + } + + if ((currentViewCell.getItem() instanceof ItemViewCell)) { + final ICellWorkbenchItem vc = (ICellWorkbenchItem) currentViewCell.getItem(); + final IInventory upgrades = vc.getUpgradesInventory(currentViewCell); + final IInventory config = vc.getConfigInventory(currentViewCell); + final FuzzyMode fzMode = vc.getFuzzyMode(currentViewCell); + final String filter = vc.getOreFilter(currentViewCell); + + boolean hasInverter = false; + boolean hasFuzzy = false; + boolean hasOreFilter = false; + for (int x = 0; x < upgrades.getSizeInventory(); x++) { + final ItemStack is = upgrades.getStackInSlot(x); + if (is != null && is.getItem() instanceof IUpgradeModule) { + final Upgrades u = ((IUpgradeModule) is.getItem()).getType(is); + if (u != null) { + switch (u) { + case FUZZY: + hasFuzzy = true; + break; + case INVERTER: + hasInverter = true; + break; + case ORE_FILTER: + hasOreFilter = true; + break; + default: + } + } + } + } + + if (hasOreFilter && !filter.isEmpty()) { + myMergedList.addNewList(new OreFilteredList(filter), !hasInverter); + } else { + final IItemList priorityList = + AEApi.instance().storage().createItemList(); + + for (int x = 0; x < config.getSizeInventory(); x++) { + final ItemStack is = config.getStackInSlot(x); + if (is != null) { + priorityList.add(AEItemStack.create(is)); + } + } + + if (!priorityList.isEmpty()) { + if (hasFuzzy) { + myMergedList.addNewList( + new FuzzyPriorityList(priorityList, fzMode), !hasInverter); + } else { + myMergedList.addNewList(new PrecisePriorityList(priorityList), !hasInverter); + } + } + } + myPartitionList = myMergedList; + } + } + + return myPartitionList; + } + + @Override + public boolean isEditable(final ItemStack is) { + return true; + } + + @Override + public IInventory getUpgradesInventory(final ItemStack is) { + return new CellUpgrades(is, 2); + } + + @Override + public IInventory getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } + + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + final String fz = Platform.openNbtData(is).getString("FuzzyMode"); + try { + return FuzzyMode.valueOf(fz); + } catch (final Throwable t) { + return FuzzyMode.IGNORE_ALL; + } + } + + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { + Platform.openNbtData(is).setString("FuzzyMode", fzMode.name()); + } + + @Override + public String getOreFilter(ItemStack is) { + return Platform.openNbtData(is).getString("OreFilter"); + } + + @Override + public void setOreFilter(ItemStack is, String filter) { + Platform.openNbtData(is).setString("OreFilter", filter); + } + + @Override + public void addCheckedInformation( + final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo) { + String filter = getOreFilter(stack); + if (!filter.isEmpty()) lines.add(GuiText.PartitionedOre.getLocal() + " : " + filter); + } } diff --git a/src/main/java/appeng/items/tools/ToolBiometricCard.java b/src/main/java/appeng/items/tools/ToolBiometricCard.java index 1cd86812b52..026192e05b8 100644 --- a/src/main/java/appeng/items/tools/ToolBiometricCard.java +++ b/src/main/java/appeng/items/tools/ToolBiometricCard.java @@ -18,7 +18,6 @@ package appeng.items.tools; - import appeng.api.config.SecurityPermissions; import appeng.api.features.IPlayerRegistry; import appeng.api.implementations.items.IBiometricCard; @@ -29,6 +28,8 @@ import appeng.items.AEBaseItem; import appeng.util.Platform; import com.mojang.authlib.GameProfile; +import java.util.EnumSet; +import java.util.List; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -38,172 +39,137 @@ import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.event.ForgeEventFactory; -import java.util.EnumSet; -import java.util.List; - - -public class ToolBiometricCard extends AEBaseItem implements IBiometricCard -{ - public ToolBiometricCard() - { - this.setFeature( EnumSet.of( AEFeature.Security ) ); - this.setMaxStackSize( 1 ); - - if( Platform.isClient() ) - { - MinecraftForgeClient.registerItemRenderer( this, new ToolBiometricCardRender() ); - } - } - - @Override - public ItemStack onItemRightClick( final ItemStack is, final World w, final EntityPlayer p ) - { - if( ForgeEventFactory.onItemUseStart( p, is, 1 ) > 0 && p.isSneaking() ) - { - this.encode( is, p ); - p.swingItem(); - return is; - } - - return is; - } - - @Override - public boolean itemInteractionForEntity( ItemStack is, final EntityPlayer par2EntityPlayer, final EntityLivingBase target ) - { - if( target instanceof EntityPlayer && !par2EntityPlayer.isSneaking() ) - { - if( par2EntityPlayer.capabilities.isCreativeMode ) - { - is = par2EntityPlayer.getCurrentEquippedItem(); - } - this.encode( is, (EntityPlayer) target ); - par2EntityPlayer.swingItem(); - return true; - } - return false; - } - - @Override - public String getItemStackDisplayName( final ItemStack is ) - { - final GameProfile username = this.getProfile( is ); - return username != null ? super.getItemStackDisplayName( is ) + " - " + username.getName() : super.getItemStackDisplayName( is ); - } - - private void encode( final ItemStack is, final EntityPlayer p ) - { - final GameProfile username = this.getProfile( is ); - - if( username != null && username.equals( p.getGameProfile() ) ) - { - this.setProfile( is, null ); - } - else - { - this.setProfile( is, p.getGameProfile() ); - } - } - - @Override - public void setProfile( final ItemStack itemStack, final GameProfile profile ) - { - final NBTTagCompound tag = Platform.openNbtData( itemStack ); - - if( profile != null ) - { - final NBTTagCompound pNBT = new NBTTagCompound(); - NBTUtil.func_152460_a( pNBT, profile ); - tag.setTag( "profile", pNBT ); - } - else - { - tag.removeTag( "profile" ); - } - } - - @Override - public GameProfile getProfile( final ItemStack is ) - { - final NBTTagCompound tag = Platform.openNbtData( is ); - if( tag.hasKey( "profile" ) ) - { - return NBTUtil.func_152459_a( tag.getCompoundTag( "profile" ) ); - } - return null; - } - - @Override - public EnumSet getPermissions( final ItemStack is ) - { - final NBTTagCompound tag = Platform.openNbtData( is ); - final EnumSet result = EnumSet.noneOf( SecurityPermissions.class ); - - for( final SecurityPermissions sp : SecurityPermissions.values() ) - { - if( tag.getBoolean( sp.name() ) ) - { - result.add( sp ); - } - } - - return result; - } - - @Override - public boolean hasPermission( final ItemStack is, final SecurityPermissions permission ) - { - final NBTTagCompound tag = Platform.openNbtData( is ); - return tag.getBoolean( permission.name() ); - } - - @Override - public void removePermission( final ItemStack itemStack, final SecurityPermissions permission ) - { - final NBTTagCompound tag = Platform.openNbtData( itemStack ); - if( tag.hasKey( permission.name() ) ) - { - tag.removeTag( permission.name() ); - } - } - - @Override - public void addPermission( final ItemStack itemStack, final SecurityPermissions permission ) - { - final NBTTagCompound tag = Platform.openNbtData( itemStack ); - tag.setBoolean( permission.name(), true ); - } - - @Override - public void registerPermissions( final ISecurityRegistry register, final IPlayerRegistry pr, final ItemStack is ) - { - register.addPlayer( pr.getID( this.getProfile( is ) ), this.getPermissions( is ) ); - } - - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - final EnumSet perms = this.getPermissions( stack ); - if( perms.isEmpty() ) - { - lines.add( GuiText.NoPermissions.getLocal() ); - } - else - { - String msg = null; - - for( final SecurityPermissions sp : perms ) - { - if( msg == null ) - { - msg = Platform.gui_localize( sp.getUnlocalizedName() ); - } - else - { - msg = msg + ", " + Platform.gui_localize( sp.getUnlocalizedName() ); - } - } - lines.add( msg ); - } - } +public class ToolBiometricCard extends AEBaseItem implements IBiometricCard { + public ToolBiometricCard() { + this.setFeature(EnumSet.of(AEFeature.Security)); + this.setMaxStackSize(1); + + if (Platform.isClient()) { + MinecraftForgeClient.registerItemRenderer(this, new ToolBiometricCardRender()); + } + } + + @Override + public ItemStack onItemRightClick(final ItemStack is, final World w, final EntityPlayer p) { + if (ForgeEventFactory.onItemUseStart(p, is, 1) > 0 && p.isSneaking()) { + this.encode(is, p); + p.swingItem(); + return is; + } + + return is; + } + + @Override + public boolean itemInteractionForEntity( + ItemStack is, final EntityPlayer par2EntityPlayer, final EntityLivingBase target) { + if (target instanceof EntityPlayer && !par2EntityPlayer.isSneaking()) { + if (par2EntityPlayer.capabilities.isCreativeMode) { + is = par2EntityPlayer.getCurrentEquippedItem(); + } + this.encode(is, (EntityPlayer) target); + par2EntityPlayer.swingItem(); + return true; + } + return false; + } + + @Override + public String getItemStackDisplayName(final ItemStack is) { + final GameProfile username = this.getProfile(is); + return username != null + ? super.getItemStackDisplayName(is) + " - " + username.getName() + : super.getItemStackDisplayName(is); + } + + private void encode(final ItemStack is, final EntityPlayer p) { + final GameProfile username = this.getProfile(is); + + if (username != null && username.equals(p.getGameProfile())) { + this.setProfile(is, null); + } else { + this.setProfile(is, p.getGameProfile()); + } + } + + @Override + public void setProfile(final ItemStack itemStack, final GameProfile profile) { + final NBTTagCompound tag = Platform.openNbtData(itemStack); + + if (profile != null) { + final NBTTagCompound pNBT = new NBTTagCompound(); + NBTUtil.func_152460_a(pNBT, profile); + tag.setTag("profile", pNBT); + } else { + tag.removeTag("profile"); + } + } + + @Override + public GameProfile getProfile(final ItemStack is) { + final NBTTagCompound tag = Platform.openNbtData(is); + if (tag.hasKey("profile")) { + return NBTUtil.func_152459_a(tag.getCompoundTag("profile")); + } + return null; + } + + @Override + public EnumSet getPermissions(final ItemStack is) { + final NBTTagCompound tag = Platform.openNbtData(is); + final EnumSet result = EnumSet.noneOf(SecurityPermissions.class); + + for (final SecurityPermissions sp : SecurityPermissions.values()) { + if (tag.getBoolean(sp.name())) { + result.add(sp); + } + } + + return result; + } + + @Override + public boolean hasPermission(final ItemStack is, final SecurityPermissions permission) { + final NBTTagCompound tag = Platform.openNbtData(is); + return tag.getBoolean(permission.name()); + } + + @Override + public void removePermission(final ItemStack itemStack, final SecurityPermissions permission) { + final NBTTagCompound tag = Platform.openNbtData(itemStack); + if (tag.hasKey(permission.name())) { + tag.removeTag(permission.name()); + } + } + + @Override + public void addPermission(final ItemStack itemStack, final SecurityPermissions permission) { + final NBTTagCompound tag = Platform.openNbtData(itemStack); + tag.setBoolean(permission.name(), true); + } + + @Override + public void registerPermissions(final ISecurityRegistry register, final IPlayerRegistry pr, final ItemStack is) { + register.addPlayer(pr.getID(this.getProfile(is)), this.getPermissions(is)); + } + + @Override + public void addCheckedInformation( + final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo) { + final EnumSet perms = this.getPermissions(stack); + if (perms.isEmpty()) { + lines.add(GuiText.NoPermissions.getLocal()); + } else { + String msg = null; + + for (final SecurityPermissions sp : perms) { + if (msg == null) { + msg = Platform.gui_localize(sp.getUnlocalizedName()); + } else { + msg = msg + ", " + Platform.gui_localize(sp.getUnlocalizedName()); + } + } + lines.add(msg); + } + } } diff --git a/src/main/java/appeng/items/tools/ToolMemoryCard.java b/src/main/java/appeng/items/tools/ToolMemoryCard.java index 29293395f4f..ef1fa115711 100644 --- a/src/main/java/appeng/items/tools/ToolMemoryCard.java +++ b/src/main/java/appeng/items/tools/ToolMemoryCard.java @@ -18,17 +18,16 @@ package appeng.items.tools; - import appeng.api.implementations.items.IMemoryCard; import appeng.api.implementations.items.MemoryCardMessages; -import appeng.api.util.AEColor; import appeng.core.features.AEFeature; import appeng.core.localization.ButtonToolTips; import appeng.core.localization.GuiText; import appeng.core.localization.PlayerMessages; import appeng.items.AEBaseItem; import appeng.util.Platform; - +import java.util.EnumSet; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -36,145 +35,130 @@ import net.minecraft.world.World; import net.minecraftforge.event.ForgeEventFactory; -import java.text.NumberFormat; -import java.util.EnumSet; -import java.util.List; -import java.util.Locale; - - -public class ToolMemoryCard extends AEBaseItem implements IMemoryCard -{ - - public ToolMemoryCard() - { - this.setFeature( EnumSet.of( AEFeature.Core ) ); - this.setMaxStackSize( 1 ); - } - - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - lines.add( this.getLocalizedName( this.getSettingsName( stack ) + ".name", this.getSettingsName( stack ) ) ); - - final NBTTagCompound data = this.getData( stack ); - if( data.hasKey( "tooltip" ) ) - { - lines.add( StatCollector.translateToLocal( this.getLocalizedName( data.getString( "tooltip" ) + ".name", data.getString( "tooltip" ) ) ) ); - } - - if( data.hasKey( "freq" ) ) - { - final long freq = data.getLong( "freq" ); - final String freqTooltip = String.format("%X", freq ).replaceAll("(.{4})", "$0 ").trim(); - - final String local = ButtonToolTips.P2PFrequency.getLocal(); - - lines.add( String.format( local, freqTooltip ) ); - } - if (data.hasKey( "custom_name" )) - lines.add(data.getString("custom_name")); - } - - /** - * Find the localized string... - * - * @param name possible names for the localized string - * @return localized name - */ - private String getLocalizedName( final String... name ) - { - for( final String n : name ) - { - final String l = StatCollector.translateToLocal( n ); - if( !l.equals( n ) ) - { - return l; - } - } - - for( final String n : name ) - { - return n; - } - - return ""; - } - - @Override - public void setMemoryCardContents( final ItemStack is, final String settingsName, final NBTTagCompound data ) - { - final NBTTagCompound c = Platform.openNbtData( is ); - c.setString( "Config", settingsName ); - c.setTag( "Data", data ); - } - - @Override - public String getSettingsName( final ItemStack is ) - { - final NBTTagCompound c = Platform.openNbtData( is ); - final String name = c.getString( "Config" ); - return name == null || name.isEmpty() ? GuiText.Blank.getUnlocalized() : name; - } - - @Override - public NBTTagCompound getData( final ItemStack is ) - { - final NBTTagCompound c = Platform.openNbtData( is ); - NBTTagCompound o = c.getCompoundTag( "Data" ); - if( o == null ) - { - o = new NBTTagCompound(); - } - return (NBTTagCompound) o.copy(); - } - - @Override - public void notifyUser( final EntityPlayer player, final MemoryCardMessages msg ) - { - if( Platform.isClient() ) - { - return; - } - - switch( msg ) - { - case SETTINGS_CLEARED: - player.addChatMessage( PlayerMessages.SettingCleared.get() ); - break; - case INVALID_MACHINE: - player.addChatMessage( PlayerMessages.InvalidMachine.get() ); - break; - case SETTINGS_LOADED: - player.addChatMessage( PlayerMessages.LoadedSettings.get() ); - break; - case SETTINGS_SAVED: - player.addChatMessage( PlayerMessages.SavedSettings.get() ); - break; - default: - } - } - - @Override - public boolean onItemUse( final ItemStack is, final EntityPlayer player, final World w, final int x, final int y, final int z, final int side, final float hx, final float hy, final float hz ) - { - if( player.isSneaking() && !w.isRemote ) - { - if( ForgeEventFactory.onItemUseStart( player, is, 1 ) <= 0 ) - return false; - final IMemoryCard mem = (IMemoryCard) is.getItem(); - mem.notifyUser( player, MemoryCardMessages.SETTINGS_CLEARED ); - is.setTagCompound( null ); - return true; - } - else - { - return super.onItemUse( is, player, w, x, y, z, side, hx, hy, hz ); - } - } - - @Override - public boolean doesSneakBypassUse( final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - return true; - } +public class ToolMemoryCard extends AEBaseItem implements IMemoryCard { + + public ToolMemoryCard() { + this.setFeature(EnumSet.of(AEFeature.Core)); + this.setMaxStackSize(1); + } + + @Override + public void addCheckedInformation( + final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo) { + lines.add(this.getLocalizedName(this.getSettingsName(stack) + ".name", this.getSettingsName(stack))); + + final NBTTagCompound data = this.getData(stack); + if (data.hasKey("tooltip")) { + lines.add(StatCollector.translateToLocal( + this.getLocalizedName(data.getString("tooltip") + ".name", data.getString("tooltip")))); + } + + if (data.hasKey("freq")) { + final long freq = data.getLong("freq"); + final String freqTooltip = + String.format("%X", freq).replaceAll("(.{4})", "$0 ").trim(); + + final String local = ButtonToolTips.P2PFrequency.getLocal(); + + lines.add(String.format(local, freqTooltip)); + } + if (data.hasKey("custom_name")) lines.add(data.getString("custom_name")); + } + + /** + * Find the localized string... + * + * @param name possible names for the localized string + * @return localized name + */ + private String getLocalizedName(final String... name) { + for (final String n : name) { + final String l = StatCollector.translateToLocal(n); + if (!l.equals(n)) { + return l; + } + } + + for (final String n : name) { + return n; + } + + return ""; + } + + @Override + public void setMemoryCardContents(final ItemStack is, final String settingsName, final NBTTagCompound data) { + final NBTTagCompound c = Platform.openNbtData(is); + c.setString("Config", settingsName); + c.setTag("Data", data); + } + + @Override + public String getSettingsName(final ItemStack is) { + final NBTTagCompound c = Platform.openNbtData(is); + final String name = c.getString("Config"); + return name == null || name.isEmpty() ? GuiText.Blank.getUnlocalized() : name; + } + + @Override + public NBTTagCompound getData(final ItemStack is) { + final NBTTagCompound c = Platform.openNbtData(is); + NBTTagCompound o = c.getCompoundTag("Data"); + if (o == null) { + o = new NBTTagCompound(); + } + return (NBTTagCompound) o.copy(); + } + + @Override + public void notifyUser(final EntityPlayer player, final MemoryCardMessages msg) { + if (Platform.isClient()) { + return; + } + + switch (msg) { + case SETTINGS_CLEARED: + player.addChatMessage(PlayerMessages.SettingCleared.get()); + break; + case INVALID_MACHINE: + player.addChatMessage(PlayerMessages.InvalidMachine.get()); + break; + case SETTINGS_LOADED: + player.addChatMessage(PlayerMessages.LoadedSettings.get()); + break; + case SETTINGS_SAVED: + player.addChatMessage(PlayerMessages.SavedSettings.get()); + break; + default: + } + } + + @Override + public boolean onItemUse( + final ItemStack is, + final EntityPlayer player, + final World w, + final int x, + final int y, + final int z, + final int side, + final float hx, + final float hy, + final float hz) { + if (player.isSneaking() && !w.isRemote) { + if (ForgeEventFactory.onItemUseStart(player, is, 1) <= 0) return false; + final IMemoryCard mem = (IMemoryCard) is.getItem(); + mem.notifyUser(player, MemoryCardMessages.SETTINGS_CLEARED); + is.setTagCompound(null); + return true; + } else { + return super.onItemUse(is, player, w, x, y, z, side, hx, hy, hz); + } + } + + @Override + public boolean doesSneakBypassUse( + final World world, final int x, final int y, final int z, final EntityPlayer player) { + return true; + } } diff --git a/src/main/java/appeng/items/tools/ToolNetworkTool.java b/src/main/java/appeng/items/tools/ToolNetworkTool.java index 28637cf8f62..ac9f16aff51 100644 --- a/src/main/java/appeng/items/tools/ToolNetworkTool.java +++ b/src/main/java/appeng/items/tools/ToolNetworkTool.java @@ -18,7 +18,6 @@ package appeng.items.tools; - import appeng.api.implementations.guiobjects.IGuiItem; import appeng.api.implementations.guiobjects.IGuiItemObject; import appeng.api.implementations.items.IAEWrench; @@ -40,6 +39,7 @@ import appeng.util.Platform; import buildcraft.api.tools.IToolWrench; import com.google.common.base.Optional; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -51,180 +51,177 @@ import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import java.util.EnumSet; - - -@Interface( iface = "buildcraft.api.tools.IToolWrench", iname = IntegrationType.BuildCraftCore ) -public class ToolNetworkTool extends AEBaseItem implements IGuiItem, IAEWrench, IToolWrench -{ - - public ToolNetworkTool() - { - super( Optional.absent() ); - - this.setFeature( EnumSet.of( AEFeature.NetworkTool ) ); - this.setMaxStackSize( 1 ); - this.setHarvestLevel( "wrench", 0 ); - } - - @Override - public IGuiItemObject getGuiObject( final ItemStack is, final World world, final int x, final int y, final int z ) - { - final TileEntity te = world.getTileEntity( x, y, z ); - return new NetworkToolViewer( is, (IGridHost) ( te instanceof IGridHost ? te : null ) ); - } - - @Override - public ItemStack onItemRightClick( final ItemStack it, final World w, final EntityPlayer p ) - { - if( Platform.isClient() ) - { - final MovingObjectPosition mop = ClientHelper.proxy.getMOP(); - - if( mop == null ) - { - this.onItemUseFirst( it, p, w, 0, 0, 0, -1, 0, 0, 0 ); - } - else - { - final int i = mop.blockX; - final int j = mop.blockY; - final int k = mop.blockZ; - - if( w.getBlock( i, j, k ).isAir( w, i, j, k ) ) - { - this.onItemUseFirst( it, p, w, 0, 0, 0, -1, 0, 0, 0 ); - } - } - } - - return it; - } - - @Override - public boolean onItemUseFirst( final ItemStack is, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, is, 1 ) <= 0 ) - return true; - - Block blk = world.getBlock( x, y, z ); - if( blk != null ) - if( ForgeEventFactory.onPlayerInteract( player, - blk.isAir( world, x, y, z ) ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, - x, y, z, side, world ).isCanceled() ) - return true; - - final MovingObjectPosition mop = new MovingObjectPosition( x, y, z, side, Vec3.createVectorHelper( hitX, hitY, hitZ ) ); - final TileEntity te = world.getTileEntity( x, y, z ); - if( te instanceof IPartHost ) - { - final SelectedPart part = ( (IPartHost) te ).selectPart( mop.hitVec ); - - if( part.part != null || part.facade != null ) - { - if( part.part instanceof INetworkToolAgent && !( (INetworkToolAgent) part.part ).showNetworkInfo( mop ) ) - { - return false; - } - } - } - else if( te instanceof INetworkToolAgent && !( (INetworkToolAgent) te ).showNetworkInfo( mop ) ) - { - return false; - } - - if( Platform.isClient() ) - { - NetworkHandler.instance.sendToServer( new PacketClick( x, y, z, side, hitX, hitY, hitZ ) ); - } - return true; - } - - @Override - public boolean doesSneakBypassUse( final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - return true; - } - - public boolean serverSideToolLogic( final ItemStack is, final EntityPlayer p, final World w, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( side >= 0 ) - { - if( !Platform.hasPermissions( new DimensionalCoord( w, x, y, z ), p ) ) - { - return false; - } - - final Block b = w.getBlock( x, y, z ); - - if( b != null ) - if( ForgeEventFactory.onPlayerInteract( p, - b.isAir( w, x, y, z ) ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, - x, y, z, side, w ).isCanceled() ) - return false; - - if( b != null && !p.isSneaking() ) - { - final TileEntity te = w.getTileEntity( x, y, z ); - if( !( te instanceof IGridHost ) ) - { - if( b.rotateBlock( w, x, y, z, ForgeDirection.getOrientation( side ) ) ) - { - b.onNeighborBlockChange( w, x, y, z, Platform.AIR_BLOCK ); - p.swingItem(); - return !w.isRemote; - } - } - } - - if( !p.isSneaking() ) - { - if( p.openContainer instanceof AEBaseContainer ) - { - return true; - } - - final TileEntity te = w.getTileEntity( x, y, z ); - - if( te instanceof IGridHost ) - { - Platform.openGUI( p, te, ForgeDirection.getOrientation( side ), GuiBridge.GUI_NETWORK_STATUS ); - } - else - { - Platform.openGUI( p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_NETWORK_TOOL ); - } - - return true; - } - else - { - b.onBlockActivated( w, x, y, z, p, side, hitX, hitY, hitZ ); - } - } - else - { - Platform.openGUI( p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_NETWORK_TOOL ); - } - - return false; - } - - @Override - public boolean canWrench( final ItemStack is, final EntityPlayer player, final int x, final int y, final int z ) - { - return true; - } - - @Override - public boolean canWrench( final EntityPlayer player, final int x, final int y, final int z ) - { - return true; - } - - @Override - public void wrenchUsed( final EntityPlayer player, final int x, final int y, final int z ) - { - player.swingItem(); - } +@Interface(iface = "buildcraft.api.tools.IToolWrench", iname = IntegrationType.BuildCraftCore) +public class ToolNetworkTool extends AEBaseItem implements IGuiItem, IAEWrench, IToolWrench { + + public ToolNetworkTool() { + super(Optional.absent()); + + this.setFeature(EnumSet.of(AEFeature.NetworkTool)); + this.setMaxStackSize(1); + this.setHarvestLevel("wrench", 0); + } + + @Override + public IGuiItemObject getGuiObject(final ItemStack is, final World world, final int x, final int y, final int z) { + final TileEntity te = world.getTileEntity(x, y, z); + return new NetworkToolViewer(is, (IGridHost) (te instanceof IGridHost ? te : null)); + } + + @Override + public ItemStack onItemRightClick(final ItemStack it, final World w, final EntityPlayer p) { + if (Platform.isClient()) { + final MovingObjectPosition mop = ClientHelper.proxy.getMOP(); + + if (mop == null) { + this.onItemUseFirst(it, p, w, 0, 0, 0, -1, 0, 0, 0); + } else { + final int i = mop.blockX; + final int j = mop.blockY; + final int k = mop.blockZ; + + if (w.getBlock(i, j, k).isAir(w, i, j, k)) { + this.onItemUseFirst(it, p, w, 0, 0, 0, -1, 0, 0, 0); + } + } + } + + return it; + } + + @Override + public boolean onItemUseFirst( + final ItemStack is, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (ForgeEventFactory.onItemUseStart(player, is, 1) <= 0) return true; + + Block blk = world.getBlock(x, y, z); + if (blk != null) + if (ForgeEventFactory.onPlayerInteract( + player, + blk.isAir(world, x, y, z) + ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR + : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, + x, + y, + z, + side, + world) + .isCanceled()) return true; + + final MovingObjectPosition mop = + new MovingObjectPosition(x, y, z, side, Vec3.createVectorHelper(hitX, hitY, hitZ)); + final TileEntity te = world.getTileEntity(x, y, z); + if (te instanceof IPartHost) { + final SelectedPart part = ((IPartHost) te).selectPart(mop.hitVec); + + if (part.part != null || part.facade != null) { + if (part.part instanceof INetworkToolAgent && !((INetworkToolAgent) part.part).showNetworkInfo(mop)) { + return false; + } + } + } else if (te instanceof INetworkToolAgent && !((INetworkToolAgent) te).showNetworkInfo(mop)) { + return false; + } + + if (Platform.isClient()) { + NetworkHandler.instance.sendToServer(new PacketClick(x, y, z, side, hitX, hitY, hitZ)); + } + return true; + } + + @Override + public boolean doesSneakBypassUse( + final World world, final int x, final int y, final int z, final EntityPlayer player) { + return true; + } + + public boolean serverSideToolLogic( + final ItemStack is, + final EntityPlayer p, + final World w, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (side >= 0) { + if (!Platform.hasPermissions(new DimensionalCoord(w, x, y, z), p)) { + return false; + } + + final Block b = w.getBlock(x, y, z); + + if (b != null) + if (ForgeEventFactory.onPlayerInteract( + p, + b.isAir(w, x, y, z) + ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR + : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, + x, + y, + z, + side, + w) + .isCanceled()) return false; + + if (b != null && !p.isSneaking()) { + final TileEntity te = w.getTileEntity(x, y, z); + if (!(te instanceof IGridHost)) { + if (b.rotateBlock(w, x, y, z, ForgeDirection.getOrientation(side))) { + b.onNeighborBlockChange(w, x, y, z, Platform.AIR_BLOCK); + p.swingItem(); + return !w.isRemote; + } + } + } + + if (!p.isSneaking()) { + if (p.openContainer instanceof AEBaseContainer) { + return true; + } + + final TileEntity te = w.getTileEntity(x, y, z); + + if (te instanceof IGridHost) { + Platform.openGUI(p, te, ForgeDirection.getOrientation(side), GuiBridge.GUI_NETWORK_STATUS); + } else { + Platform.openGUI(p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_NETWORK_TOOL); + } + + return true; + } else { + b.onBlockActivated(w, x, y, z, p, side, hitX, hitY, hitZ); + } + } else { + Platform.openGUI(p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_NETWORK_TOOL); + } + + return false; + } + + @Override + public boolean canWrench(final ItemStack is, final EntityPlayer player, final int x, final int y, final int z) { + return true; + } + + @Override + public boolean canWrench(final EntityPlayer player, final int x, final int y, final int z) { + return true; + } + + @Override + public void wrenchUsed(final EntityPlayer player, final int x, final int y, final int z) { + player.swingItem(); + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolChargedStaff.java b/src/main/java/appeng/items/tools/powered/ToolChargedStaff.java index 65c2e54d2a3..4ea830fec64 100644 --- a/src/main/java/appeng/items/tools/powered/ToolChargedStaff.java +++ b/src/main/java/appeng/items/tools/powered/ToolChargedStaff.java @@ -18,7 +18,6 @@ package appeng.items.tools.powered; - import appeng.core.AEConfig; import appeng.core.features.AEFeature; import appeng.core.sync.packets.PacketLightning; @@ -26,47 +25,40 @@ import appeng.server.ServerHelper; import appeng.util.Platform; import com.google.common.base.Optional; +import java.util.EnumSet; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraftforge.event.ForgeEventFactory; -import java.util.EnumSet; - - -public class ToolChargedStaff extends AEBasePoweredItem -{ +public class ToolChargedStaff extends AEBasePoweredItem { - public ToolChargedStaff() - { - super( AEConfig.instance.chargedStaffBattery, Optional.absent() ); - this.setFeature( EnumSet.of( AEFeature.ChargedStaff, AEFeature.PoweredTools ) ); - } + public ToolChargedStaff() { + super(AEConfig.instance.chargedStaffBattery, Optional.absent()); + this.setFeature(EnumSet.of(AEFeature.ChargedStaff, AEFeature.PoweredTools)); + } - @Override - public boolean hitEntity( final ItemStack item, final EntityLivingBase target, final EntityLivingBase hitter ) - { - if( hitter instanceof EntityPlayer && ForgeEventFactory.onItemUseStart( (EntityPlayer) hitter, item, 1 ) <= 0 ) - return false; + @Override + public boolean hitEntity(final ItemStack item, final EntityLivingBase target, final EntityLivingBase hitter) { + if (hitter instanceof EntityPlayer && ForgeEventFactory.onItemUseStart((EntityPlayer) hitter, item, 1) <= 0) + return false; - if( this.getAECurrentPower( item ) > 300 ) - { - this.extractAEPower( item, 300 ); - if( Platform.isServer() ) - { - for( int x = 0; x < 2; x++ ) - { - final float dx = (float) ( Platform.getRandomFloat() * target.width + target.boundingBox.minX ); - final float dy = (float) ( Platform.getRandomFloat() * target.height + target.boundingBox.minY ); - final float dz = (float) ( Platform.getRandomFloat() * target.width + target.boundingBox.minZ ); - ServerHelper.proxy.sendToAllNearExcept( null, dx, dy, dz, 32.0, target.worldObj, new PacketLightning( dx, dy, dz ) ); - } - } - target.attackEntityFrom( DamageSource.magic, 6 ); - return true; - } + if (this.getAECurrentPower(item) > 300) { + this.extractAEPower(item, 300); + if (Platform.isServer()) { + for (int x = 0; x < 2; x++) { + final float dx = (float) (Platform.getRandomFloat() * target.width + target.boundingBox.minX); + final float dy = (float) (Platform.getRandomFloat() * target.height + target.boundingBox.minY); + final float dz = (float) (Platform.getRandomFloat() * target.width + target.boundingBox.minZ); + ServerHelper.proxy.sendToAllNearExcept( + null, dx, dy, dz, 32.0, target.worldObj, new PacketLightning(dx, dy, dz)); + } + } + target.attackEntityFrom(DamageSource.magic, 6); + return true; + } - return false; - } + return false; + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java b/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java index 042db68525b..7f9ddc2b047 100644 --- a/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java +++ b/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java @@ -18,7 +18,6 @@ package appeng.items.tools.powered; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.FuzzyMode; @@ -55,6 +54,7 @@ import com.google.common.base.Optional; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.*; import net.minecraft.block.Block; import net.minecraft.block.BlockDispenser; import net.minecraft.entity.player.EntityPlayer; @@ -69,502 +69,445 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.oredict.OreDictionary; -import java.util.*; - - -public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCell, IItemGroup, IBlockTool, IMouseWheelItem -{ - - private static final Map ORE_TO_COLOR = new HashMap(); - - static - { - - for( final AEColor col : AEColor.values() ) - { - if( col == AEColor.Transparent ) - { - continue; - } - - ORE_TO_COLOR.put( OreDictionary.getOreID( "dye" + col.name() ), col ); - } - } - - public ToolColorApplicator() - { - super( AEConfig.instance.colorApplicatorBattery, Optional.absent() ); - this.setFeature( EnumSet.of( AEFeature.ColorApplicator, AEFeature.PoweredTools ) ); - if( Platform.isClient() ) - { - MinecraftForgeClient.registerItemRenderer( this, new ToolColorApplicatorRender() ); - } - } - - @Override - public void postInit() - { - super.postInit(); - BlockDispenser.dispenseBehaviorRegistry.putObject( this, new DispenserBlockTool() ); - } - - @Override - public boolean onItemUse( final ItemStack is, final EntityPlayer p, final World w, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - final Block blk = w.getBlock( x, y, z ); - - ItemStack paintBall = this.getColor( is ); - - final IMEInventory inv = AEApi.instance().registries().cell().getCellInventory( is, null, StorageChannel.ITEMS ); - if( inv != null ) - { - final IAEItemStack option = inv.extractItems( AEItemStack.create( paintBall ), Actionable.SIMULATE, new BaseActionSource() ); - - if( option != null ) - { - paintBall = option.getItemStack(); - paintBall.stackSize = 1; - } - else - { - paintBall = null; - } - - if( !Platform.hasPermissions( new DimensionalCoord( w, x, y, z ), p ) ) - { - return false; - } - - final double powerPerUse = 100; - if( paintBall != null && paintBall.getItem() instanceof ItemSnowball ) - { - final ForgeDirection orientation = ForgeDirection.getOrientation( side ); - final TileEntity te = w.getTileEntity( x, y, z ); - // clean cables. - if( te instanceof IColorableTile ) - { - if( this.getAECurrentPower( is ) > powerPerUse && ( (IColorableTile) te ).getColor() != AEColor.Transparent ) - { - if( ( (IColorableTile) te ).recolourBlock( orientation, AEColor.Transparent, p ) ) - { - inv.extractItems( AEItemStack.create( paintBall ), Actionable.MODULATE, new BaseActionSource() ); - this.extractAEPower( is, powerPerUse ); - return true; - } - } - } - - // clean paint balls.. - final Block testBlk = w.getBlock( x + orientation.offsetX, y + orientation.offsetY, z + orientation.offsetZ ); - final TileEntity painted = w.getTileEntity( x + orientation.offsetX, y + orientation.offsetY, z + orientation.offsetZ ); - if( this.getAECurrentPower( is ) > powerPerUse && testBlk instanceof BlockPaint && painted instanceof TilePaint ) - { - inv.extractItems( AEItemStack.create( paintBall ), Actionable.MODULATE, new BaseActionSource() ); - this.extractAEPower( is, powerPerUse ); - ( (TilePaint) painted ).cleanSide( orientation.getOpposite() ); - return true; - } - } - else if( paintBall != null ) - { - final AEColor color = this.getColorFromItem( paintBall ); - - if( color != null && this.getAECurrentPower( is ) > powerPerUse ) - { - if( color != AEColor.Transparent && this.recolourBlock( blk, ForgeDirection.getOrientation( side ), w, x, y, z, ForgeDirection.getOrientation( side ), color, p ) ) - { - inv.extractItems( AEItemStack.create( paintBall ), Actionable.MODULATE, new BaseActionSource() ); - this.extractAEPower( is, powerPerUse ); - return true; - } - } - } - } - - if( p.isSneaking() ) - { - this.cycleColors( is, paintBall, 1 ); - } - - return false; - } - - @Override - public String getItemStackDisplayName( final ItemStack par1ItemStack ) - { - String extra = GuiText.Empty.getLocal(); - - final AEColor selected = this.getActiveColor( par1ItemStack ); - - if( selected != null && Platform.isClient() ) - { - extra = Platform.gui_localize( selected.unlocalizedName ); - } - - return super.getItemStackDisplayName( par1ItemStack ) + " - " + extra; - } - - public AEColor getActiveColor( final ItemStack tol ) - { - return this.getColorFromItem( this.getColor( tol ) ); - } - - private AEColor getColorFromItem( final ItemStack paintBall ) - { - if( paintBall == null ) - { - return null; - } - - if( paintBall.getItem() instanceof ItemSnowball ) - { - return AEColor.Transparent; - } - - if( paintBall.getItem() instanceof ItemPaintBall ) - { - final ItemPaintBall ipb = (ItemPaintBall) paintBall.getItem(); - return ipb.getColor( paintBall ); - } - else - { - final int[] id = OreDictionary.getOreIDs( paintBall ); - - for( final int oreID : id ) - { - if( ORE_TO_COLOR.containsKey( oreID ) ) - { - return ORE_TO_COLOR.get( oreID ); - } - } - } - - return null; - } - - public ItemStack getColor( final ItemStack is ) - { - final NBTTagCompound c = is.getTagCompound(); - if( c != null && c.hasKey( "color" ) ) - { - final NBTTagCompound color = c.getCompoundTag( "color" ); - final ItemStack oldColor = ItemStack.loadItemStackFromNBT( color ); - if( oldColor != null ) - { - return oldColor; - } - } - - return this.findNextColor( is, null, 0 ); - } - - private ItemStack findNextColor( final ItemStack is, final ItemStack anchor, final int scrollOffset ) - { - ItemStack newColor = null; - - final IMEInventory inv = AEApi.instance().registries().cell().getCellInventory( is, null, StorageChannel.ITEMS ); - if( inv != null ) - { - final IItemList itemList = inv.getAvailableItems( AEApi.instance().storage().createItemList() ); - if( anchor == null ) - { - final IAEItemStack firstItem = itemList.getFirstItem(); - if( firstItem != null ) - { - newColor = firstItem.getItemStack(); - } - } - else - { - final LinkedList list = new LinkedList(); - - for( final IAEItemStack i : itemList ) - { - list.add( i ); - } - - Collections.sort( list, new Comparator() - { - - @Override - public int compare( final IAEItemStack a, final IAEItemStack b ) - { - return ItemSorters.compareInt( a.getItemDamage(), b.getItemDamage() ); - } - } ); - - if( list.size() <= 0 ) - { - return null; - } - - IAEItemStack where = list.getFirst(); - int cycles = 1 + list.size(); - - while( cycles > 0 && !where.equals( anchor ) ) - { - list.addLast( list.removeFirst() ); - cycles--; - where = list.getFirst(); - } - - if( scrollOffset > 0 ) - { - list.addLast( list.removeFirst() ); - } - - if( scrollOffset < 0 ) - { - list.addFirst( list.removeLast() ); - } - - return list.get( 0 ).getItemStack(); - } - } - - if( newColor != null ) - { - this.setColor( is, newColor ); - } - - return newColor; - } - - private void setColor( final ItemStack is, final ItemStack newColor ) - { - final NBTTagCompound data = Platform.openNbtData( is ); - if( newColor == null ) - { - data.removeTag( "color" ); - } - else - { - final NBTTagCompound color = new NBTTagCompound(); - newColor.writeToNBT( color ); - data.setTag( "color", color ); - } - } - - private boolean recolourBlock( final Block blk, final ForgeDirection side, final World w, final int x, final int y, final int z, final ForgeDirection orientation, final AEColor newColor, final EntityPlayer p ) - { - if( blk == Blocks.carpet ) - { - final int meta = w.getBlockMetadata( x, y, z ); - if( newColor.ordinal() == meta ) - { - return false; - } - return w.setBlock( x, y, z, Blocks.carpet, newColor.ordinal(), 3 ); - } - - if( blk == Blocks.glass ) - { - return w.setBlock( x, y, z, Blocks.stained_glass, newColor.ordinal(), 3 ); - } - - if( blk == Blocks.stained_glass ) - { - final int meta = w.getBlockMetadata( x, y, z ); - if( newColor.ordinal() == meta ) - { - return false; - } - return w.setBlock( x, y, z, Blocks.stained_glass, newColor.ordinal(), 3 ); - } - - if( blk == Blocks.glass_pane ) - { - return w.setBlock( x, y, z, Blocks.stained_glass_pane, newColor.ordinal(), 3 ); - } - - if( blk == Blocks.stained_glass_pane ) - { - final int meta = w.getBlockMetadata( x, y, z ); - if( newColor.ordinal() == meta ) - { - return false; - } - return w.setBlock( x, y, z, Blocks.stained_glass_pane, newColor.ordinal(), 3 ); - } - - if( blk == Blocks.hardened_clay ) - { - return w.setBlock( x, y, z, Blocks.stained_hardened_clay, newColor.ordinal(), 3 ); - } - - if( blk == Blocks.stained_hardened_clay ) - { - final int meta = w.getBlockMetadata( x, y, z ); - if( newColor.ordinal() == meta ) - { - return false; - } - return w.setBlock( x, y, z, Blocks.stained_hardened_clay, newColor.ordinal(), 3 ); - } - - if( blk instanceof BlockCableBus ) - { - return ( (BlockCableBus) blk ).recolourBlock( w, x, y, z, side, newColor.ordinal(), p ); - } - - return blk.recolourBlock( w, x, y, z, side, newColor.ordinal() ); - } - - public void cycleColors( final ItemStack is, final ItemStack paintBall, final int i ) - { - if( paintBall == null ) - { - this.setColor( is, this.getColor( is ) ); - } - else - { - this.setColor( is, this.findNextColor( is, paintBall, i ) ); - } - } +public class ToolColorApplicator extends AEBasePoweredItem + implements IStorageCell, IItemGroup, IBlockTool, IMouseWheelItem { + + private static final Map ORE_TO_COLOR = new HashMap(); + + static { + for (final AEColor col : AEColor.values()) { + if (col == AEColor.Transparent) { + continue; + } + + ORE_TO_COLOR.put(OreDictionary.getOreID("dye" + col.name()), col); + } + } + + public ToolColorApplicator() { + super(AEConfig.instance.colorApplicatorBattery, Optional.absent()); + this.setFeature(EnumSet.of(AEFeature.ColorApplicator, AEFeature.PoweredTools)); + if (Platform.isClient()) { + MinecraftForgeClient.registerItemRenderer(this, new ToolColorApplicatorRender()); + } + } + + @Override + public void postInit() { + super.postInit(); + BlockDispenser.dispenseBehaviorRegistry.putObject(this, new DispenserBlockTool()); + } + + @Override + public boolean onItemUse( + final ItemStack is, + final EntityPlayer p, + final World w, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + final Block blk = w.getBlock(x, y, z); + + ItemStack paintBall = this.getColor(is); + + final IMEInventory inv = + AEApi.instance().registries().cell().getCellInventory(is, null, StorageChannel.ITEMS); + if (inv != null) { + final IAEItemStack option = + inv.extractItems(AEItemStack.create(paintBall), Actionable.SIMULATE, new BaseActionSource()); + + if (option != null) { + paintBall = option.getItemStack(); + paintBall.stackSize = 1; + } else { + paintBall = null; + } + + if (!Platform.hasPermissions(new DimensionalCoord(w, x, y, z), p)) { + return false; + } + + final double powerPerUse = 100; + if (paintBall != null && paintBall.getItem() instanceof ItemSnowball) { + final ForgeDirection orientation = ForgeDirection.getOrientation(side); + final TileEntity te = w.getTileEntity(x, y, z); + // clean cables. + if (te instanceof IColorableTile) { + if (this.getAECurrentPower(is) > powerPerUse + && ((IColorableTile) te).getColor() != AEColor.Transparent) { + if (((IColorableTile) te).recolourBlock(orientation, AEColor.Transparent, p)) { + inv.extractItems( + AEItemStack.create(paintBall), Actionable.MODULATE, new BaseActionSource()); + this.extractAEPower(is, powerPerUse); + return true; + } + } + } + + // clean paint balls.. + final Block testBlk = + w.getBlock(x + orientation.offsetX, y + orientation.offsetY, z + orientation.offsetZ); + final TileEntity painted = + w.getTileEntity(x + orientation.offsetX, y + orientation.offsetY, z + orientation.offsetZ); + if (this.getAECurrentPower(is) > powerPerUse + && testBlk instanceof BlockPaint + && painted instanceof TilePaint) { + inv.extractItems(AEItemStack.create(paintBall), Actionable.MODULATE, new BaseActionSource()); + this.extractAEPower(is, powerPerUse); + ((TilePaint) painted).cleanSide(orientation.getOpposite()); + return true; + } + } else if (paintBall != null) { + final AEColor color = this.getColorFromItem(paintBall); + + if (color != null && this.getAECurrentPower(is) > powerPerUse) { + if (color != AEColor.Transparent + && this.recolourBlock( + blk, + ForgeDirection.getOrientation(side), + w, + x, + y, + z, + ForgeDirection.getOrientation(side), + color, + p)) { + inv.extractItems(AEItemStack.create(paintBall), Actionable.MODULATE, new BaseActionSource()); + this.extractAEPower(is, powerPerUse); + return true; + } + } + } + } + + if (p.isSneaking()) { + this.cycleColors(is, paintBall, 1); + } + + return false; + } + + @Override + public String getItemStackDisplayName(final ItemStack par1ItemStack) { + String extra = GuiText.Empty.getLocal(); + + final AEColor selected = this.getActiveColor(par1ItemStack); + + if (selected != null && Platform.isClient()) { + extra = Platform.gui_localize(selected.unlocalizedName); + } + + return super.getItemStackDisplayName(par1ItemStack) + " - " + extra; + } + + public AEColor getActiveColor(final ItemStack tol) { + return this.getColorFromItem(this.getColor(tol)); + } + + private AEColor getColorFromItem(final ItemStack paintBall) { + if (paintBall == null) { + return null; + } + + if (paintBall.getItem() instanceof ItemSnowball) { + return AEColor.Transparent; + } + + if (paintBall.getItem() instanceof ItemPaintBall) { + final ItemPaintBall ipb = (ItemPaintBall) paintBall.getItem(); + return ipb.getColor(paintBall); + } else { + final int[] id = OreDictionary.getOreIDs(paintBall); + + for (final int oreID : id) { + if (ORE_TO_COLOR.containsKey(oreID)) { + return ORE_TO_COLOR.get(oreID); + } + } + } + + return null; + } + + public ItemStack getColor(final ItemStack is) { + final NBTTagCompound c = is.getTagCompound(); + if (c != null && c.hasKey("color")) { + final NBTTagCompound color = c.getCompoundTag("color"); + final ItemStack oldColor = ItemStack.loadItemStackFromNBT(color); + if (oldColor != null) { + return oldColor; + } + } + + return this.findNextColor(is, null, 0); + } + + private ItemStack findNextColor(final ItemStack is, final ItemStack anchor, final int scrollOffset) { + ItemStack newColor = null; + + final IMEInventory inv = + AEApi.instance().registries().cell().getCellInventory(is, null, StorageChannel.ITEMS); + if (inv != null) { + final IItemList itemList = + inv.getAvailableItems(AEApi.instance().storage().createItemList()); + if (anchor == null) { + final IAEItemStack firstItem = itemList.getFirstItem(); + if (firstItem != null) { + newColor = firstItem.getItemStack(); + } + } else { + final LinkedList list = new LinkedList(); + + for (final IAEItemStack i : itemList) { + list.add(i); + } + + Collections.sort(list, new Comparator() { + + @Override + public int compare(final IAEItemStack a, final IAEItemStack b) { + return ItemSorters.compareInt(a.getItemDamage(), b.getItemDamage()); + } + }); + + if (list.size() <= 0) { + return null; + } + + IAEItemStack where = list.getFirst(); + int cycles = 1 + list.size(); + + while (cycles > 0 && !where.equals(anchor)) { + list.addLast(list.removeFirst()); + cycles--; + where = list.getFirst(); + } + + if (scrollOffset > 0) { + list.addLast(list.removeFirst()); + } + + if (scrollOffset < 0) { + list.addFirst(list.removeLast()); + } + + return list.get(0).getItemStack(); + } + } + + if (newColor != null) { + this.setColor(is, newColor); + } + + return newColor; + } + + private void setColor(final ItemStack is, final ItemStack newColor) { + final NBTTagCompound data = Platform.openNbtData(is); + if (newColor == null) { + data.removeTag("color"); + } else { + final NBTTagCompound color = new NBTTagCompound(); + newColor.writeToNBT(color); + data.setTag("color", color); + } + } + + private boolean recolourBlock( + final Block blk, + final ForgeDirection side, + final World w, + final int x, + final int y, + final int z, + final ForgeDirection orientation, + final AEColor newColor, + final EntityPlayer p) { + if (blk == Blocks.carpet) { + final int meta = w.getBlockMetadata(x, y, z); + if (newColor.ordinal() == meta) { + return false; + } + return w.setBlock(x, y, z, Blocks.carpet, newColor.ordinal(), 3); + } + + if (blk == Blocks.glass) { + return w.setBlock(x, y, z, Blocks.stained_glass, newColor.ordinal(), 3); + } + + if (blk == Blocks.stained_glass) { + final int meta = w.getBlockMetadata(x, y, z); + if (newColor.ordinal() == meta) { + return false; + } + return w.setBlock(x, y, z, Blocks.stained_glass, newColor.ordinal(), 3); + } + + if (blk == Blocks.glass_pane) { + return w.setBlock(x, y, z, Blocks.stained_glass_pane, newColor.ordinal(), 3); + } + + if (blk == Blocks.stained_glass_pane) { + final int meta = w.getBlockMetadata(x, y, z); + if (newColor.ordinal() == meta) { + return false; + } + return w.setBlock(x, y, z, Blocks.stained_glass_pane, newColor.ordinal(), 3); + } + + if (blk == Blocks.hardened_clay) { + return w.setBlock(x, y, z, Blocks.stained_hardened_clay, newColor.ordinal(), 3); + } + + if (blk == Blocks.stained_hardened_clay) { + final int meta = w.getBlockMetadata(x, y, z); + if (newColor.ordinal() == meta) { + return false; + } + return w.setBlock(x, y, z, Blocks.stained_hardened_clay, newColor.ordinal(), 3); + } + + if (blk instanceof BlockCableBus) { + return ((BlockCableBus) blk).recolourBlock(w, x, y, z, side, newColor.ordinal(), p); + } + + return blk.recolourBlock(w, x, y, z, side, newColor.ordinal()); + } + + public void cycleColors(final ItemStack is, final ItemStack paintBall, final int i) { + if (paintBall == null) { + this.setColor(is, this.getColor(is)); + } else { + this.setColor(is, this.findNextColor(is, paintBall, i)); + } + } @SideOnly(Side.CLIENT) - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - super.addCheckedInformation( stack, player, lines, displayMoreInfo ); - - final IMEInventory cdi = AEApi.instance().registries().cell().getCellInventory( stack, null, StorageChannel.ITEMS ); - - if( cdi instanceof CellInventoryHandler ) - { - final ICellInventory cd = ( (ICellInventoryHandler) cdi ).getCellInv(); - if( cd != null ) - { - lines.add( cd.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalBytes() + ' ' + GuiText.BytesUsed.getLocal() ); - lines.add( cd.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalItemTypes() + ' ' + GuiText.Types.getLocal() ); - } - } - } - - @Override - public int getBytes( final ItemStack cellItem ) - { - return 512; - } - - @Override - public int BytePerType( final ItemStack cell ) - { - return 8; - } - - @Override - public int getBytesPerType( final ItemStack cellItem ) - { - return 8; - } - - @Override - public int getTotalTypes( final ItemStack cellItem ) - { - return 27; - } - - @Override - public boolean isBlackListed( final ItemStack cellItem, final IAEItemStack requestedAddition ) - { - if( requestedAddition != null ) - { - final int[] id = OreDictionary.getOreIDs( requestedAddition.getItemStack() ); - - for( final int x : id ) - { - if( ORE_TO_COLOR.containsKey( x ) ) - { - return false; - } - } - - if( requestedAddition.getItem() instanceof ItemSnowball ) - { - return false; - } - - return !( requestedAddition.getItem() instanceof ItemPaintBall && requestedAddition.getItemDamage() < 20 ); - } - return true; - } - - @Override - public boolean storableInStorageCell() - { - return true; - } - - @Override - public boolean isStorageCell( final ItemStack i ) - { - return true; - } - - @Override - public double getIdleDrain() - { - return 0.5; - } - - @Override - public String getUnlocalizedGroupName( final Set others, final ItemStack is ) - { - return GuiText.StorageCells.getUnlocalized(); - } - - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } - - @Override - public IInventory getUpgradesInventory( final ItemStack is ) - { - return new CellUpgrades( is, 2 ); - } - - @Override - public IInventory getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } - - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - final String fz = Platform.openNbtData( is ).getString( "FuzzyMode" ); - try - { - return FuzzyMode.valueOf( fz ); - } - catch( final Throwable t ) - { - return FuzzyMode.IGNORE_ALL; - } - } - - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - Platform.openNbtData( is ).setString( "FuzzyMode", fzMode.name() ); - } - - @Override - public void onWheel( final ItemStack is, final boolean up ) - { - this.cycleColors( is, this.getColor( is ), up ? 1 : -1 ); - } - - @Override - public String getOreFilter(ItemStack is) { - return Platform.openNbtData( is ).getString( "OreFilter" ); - } - - @Override - public void setOreFilter(ItemStack is, String filter) { - Platform.openNbtData( is ).setString("OreFilter", filter); - } + @Override + public void addCheckedInformation( + final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo) { + super.addCheckedInformation(stack, player, lines, displayMoreInfo); + + final IMEInventory cdi = + AEApi.instance().registries().cell().getCellInventory(stack, null, StorageChannel.ITEMS); + + if (cdi instanceof CellInventoryHandler) { + final ICellInventory cd = ((ICellInventoryHandler) cdi).getCellInv(); + if (cd != null) { + lines.add(cd.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalBytes() + ' ' + + GuiText.BytesUsed.getLocal()); + lines.add(cd.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalItemTypes() + ' ' + + GuiText.Types.getLocal()); + } + } + } + + @Override + public int getBytes(final ItemStack cellItem) { + return 512; + } + + @Override + public int BytePerType(final ItemStack cell) { + return 8; + } + + @Override + public int getBytesPerType(final ItemStack cellItem) { + return 8; + } + + @Override + public int getTotalTypes(final ItemStack cellItem) { + return 27; + } + + @Override + public boolean isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) { + if (requestedAddition != null) { + final int[] id = OreDictionary.getOreIDs(requestedAddition.getItemStack()); + + for (final int x : id) { + if (ORE_TO_COLOR.containsKey(x)) { + return false; + } + } + + if (requestedAddition.getItem() instanceof ItemSnowball) { + return false; + } + + return !(requestedAddition.getItem() instanceof ItemPaintBall && requestedAddition.getItemDamage() < 20); + } + return true; + } + + @Override + public boolean storableInStorageCell() { + return true; + } + + @Override + public boolean isStorageCell(final ItemStack i) { + return true; + } + + @Override + public double getIdleDrain() { + return 0.5; + } + + @Override + public String getUnlocalizedGroupName(final Set others, final ItemStack is) { + return GuiText.StorageCells.getUnlocalized(); + } + + @Override + public boolean isEditable(final ItemStack is) { + return true; + } + + @Override + public IInventory getUpgradesInventory(final ItemStack is) { + return new CellUpgrades(is, 2); + } + + @Override + public IInventory getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } + + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + final String fz = Platform.openNbtData(is).getString("FuzzyMode"); + try { + return FuzzyMode.valueOf(fz); + } catch (final Throwable t) { + return FuzzyMode.IGNORE_ALL; + } + } + + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { + Platform.openNbtData(is).setString("FuzzyMode", fzMode.name()); + } + + @Override + public void onWheel(final ItemStack is, final boolean up) { + this.cycleColors(is, this.getColor(is), up ? 1 : -1); + } + + @Override + public String getOreFilter(ItemStack is) { + return Platform.openNbtData(is).getString("OreFilter"); + } + + @Override + public void setOreFilter(ItemStack is, String filter) { + Platform.openNbtData(is).setString("OreFilter", filter); + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolEntropyManipulator.java b/src/main/java/appeng/items/tools/powered/ToolEntropyManipulator.java index 40ac625c195..6e8fa4ee6c2 100644 --- a/src/main/java/appeng/items/tools/powered/ToolEntropyManipulator.java +++ b/src/main/java/appeng/items/tools/powered/ToolEntropyManipulator.java @@ -18,7 +18,6 @@ package appeng.items.tools.powered; - import appeng.api.util.DimensionalCoord; import appeng.block.misc.BlockTinyTNT; import appeng.core.AEConfig; @@ -29,6 +28,7 @@ import appeng.util.InWorldToolOperationResult; import appeng.util.Platform; import com.google.common.base.Optional; +import java.util.*; import net.minecraft.block.Block; import net.minecraft.block.BlockDispenser; import net.minecraft.block.BlockTNT; @@ -50,336 +50,349 @@ import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.oredict.OreDictionary; -import java.util.*; - - -public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockTool -{ - private final Map heatUp; - private final Map coolDown; - - public ToolEntropyManipulator() - { - super( AEConfig.instance.entropyManipulatorBattery, Optional.absent() ); - - this.setFeature( EnumSet.of( AEFeature.EntropyManipulator, AEFeature.PoweredTools ) ); - - this.heatUp = new HashMap(); - this.coolDown = new HashMap(); - - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.stone, 0 ), new InWorldToolOperationResult( new ItemStack( Blocks.cobblestone ) ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.stonebrick, 0 ), new InWorldToolOperationResult( new ItemStack( Blocks.stonebrick, 1, 2 ) ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.lava, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult( new ItemStack( Blocks.obsidian ) ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.flowing_lava, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult( new ItemStack( Blocks.obsidian ) ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.grass, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult( new ItemStack( Blocks.dirt ) ) ); - - final List snowBalls = new ArrayList(); - snowBalls.add( new ItemStack( Items.snowball ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.flowing_water, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult( null, snowBalls ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.water, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult( new ItemStack( Blocks.ice ) ) ); - - this.heatUp.put( new InWorldToolOperationIngredient( Blocks.ice, 0 ), new InWorldToolOperationResult( new ItemStack( Blocks.water ) ) ); - this.heatUp.put( new InWorldToolOperationIngredient( Blocks.flowing_water, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult() ); - this.heatUp.put( new InWorldToolOperationIngredient( Blocks.water, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult() ); - this.heatUp.put( new InWorldToolOperationIngredient( Blocks.snow, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult( new ItemStack( Blocks.flowing_water ) ) ); - } - - private static final boolean breakBlockWithCheck( final World w, final EntityPlayer p, final int x, final int y, final int z ) - { - BlockEvent.BreakEvent event = new BlockEvent.BreakEvent( x, y, z, w, w.getBlock( x, y, z ), w.getBlockMetadata( x, y, z ), p ); - MinecraftForge.EVENT_BUS.post( event ); - return !event.isCanceled() && w.setBlockToAir( x, y, z ); - } - - @Override - public void postInit() - { - super.postInit(); - BlockDispenser.dispenseBehaviorRegistry.putObject( this, new DispenserBlockTool() ); - } - - private boolean heat( final Block blockID, final EntityPlayer p, final int metadata, final World w, final int x, final int y, final int z ) - { - if( !breakBlockWithCheck( w, p, x, y, z ) ) - return false; - - InWorldToolOperationResult r = this.heatUp.get( new InWorldToolOperationIngredient( blockID, metadata ) ); - - - if( r == null ) - { - r = this.heatUp.get( new InWorldToolOperationIngredient( blockID, OreDictionary.WILDCARD_VALUE ) ); - } - - if( r.getBlockItem() != null ) - { - w.setBlock( x, y, z, Block.getBlockFromItem( r.getBlockItem().getItem() ), r.getBlockItem().getItemDamage(), 3 ); - } - - if( r.getDrops() != null ) - { - Platform.spawnDrops( w, x, y, z, r.getDrops() ); - } - - return true; - } - - private boolean canHeat( final Block blockID, final int metadata ) - { - InWorldToolOperationResult r = this.heatUp.get( new InWorldToolOperationIngredient( blockID, metadata ) ); - - if( r == null ) - { - r = this.heatUp.get( new InWorldToolOperationIngredient( blockID, OreDictionary.WILDCARD_VALUE ) ); - } - - return r != null; - } - - private boolean cool( final Block blockID, final EntityPlayer p, final int metadata, final World w, final int x, final int y, final int z ) - { - if( !breakBlockWithCheck( w, p, x, y, z ) ) - return false; - - InWorldToolOperationResult r = this.coolDown.get( new InWorldToolOperationIngredient( blockID, metadata ) ); - - if( r == null ) - { - r = this.coolDown.get( new InWorldToolOperationIngredient( blockID, OreDictionary.WILDCARD_VALUE ) ); - } - - if( r.getBlockItem() != null ) - { - w.setBlock( x, y, z, Block.getBlockFromItem( r.getBlockItem().getItem() ), r.getBlockItem().getItemDamage(), 3 ); - } - - if( r.getDrops() != null ) - { - Platform.spawnDrops( w, x, y, z, r.getDrops() ); - } - - return true; - } - - private boolean canCool( final Block blockID, final int metadata ) - { - InWorldToolOperationResult r = this.coolDown.get( new InWorldToolOperationIngredient( blockID, metadata ) ); - - if( r == null ) - { - r = this.coolDown.get( new InWorldToolOperationIngredient( blockID, OreDictionary.WILDCARD_VALUE ) ); - } - - return r != null; - } - - @Override - public boolean hitEntity( final ItemStack item, final EntityLivingBase target, final EntityLivingBase hitter ) - { - if( this.getAECurrentPower( item ) > 1600 ) - { - this.extractAEPower( item, 1600 ); - target.setFire( 8 ); - } - - return false; - } - - @Override - public ItemStack onItemRightClick( final ItemStack item, final World w, final EntityPlayer p ) - { - final MovingObjectPosition target = this.getMovingObjectPositionFromPlayer( w, p, true ); - - if( target == null ) - { - return item; - } - else - { - if( target.typeOfHit == MovingObjectType.BLOCK ) - { - final int x = target.blockX; - final int y = target.blockY; - final int z = target.blockZ; - - if( w.getBlock( x, y, z ).getMaterial() == Material.lava || w.getBlock( x, y, z ).getMaterial() == Material.water ) - { - if( Platform.hasPermissions( new DimensionalCoord( w, x, y, z ), p ) ) - { - this.onItemUse( item, p, w, x, y, z, 0, 0.0F, 0.0F, 0.0F ); - } - } - } - } - - return item; - } - - @Override - public boolean onItemUse( final ItemStack item, final EntityPlayer p, final World w, int x, int y, int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( this.getAECurrentPower( item ) > 1600 ) - { - if( !p.canPlayerEdit( x, y, z, side, item ) ) - { - return false; - } - - final Block blockID = w.getBlock( x, y, z ); - final int metadata = w.getBlockMetadata( x, y, z ); - - if( blockID == null || ForgeEventFactory.onPlayerInteract( p, - blockID.isAir( w, x, y, z ) ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, - x, y, z, side, w ).isCanceled() ) - return false; - - if( p.isSneaking() ) - { - if( this.canCool( blockID, metadata ) ) - { - if( this.cool( blockID, p, metadata, w, x, y, z ) ) - { - this.extractAEPower( item, 1600 ); - return true; - } - return false; - } - } - else - { - if( blockID instanceof BlockTNT ) - { - if( !breakBlockWithCheck( w, p, x, y, z ) ) - return false; - ( (BlockTNT) blockID ).func_150114_a( w, x, y, z, 1, p ); - return true; - } - - if( blockID instanceof BlockTinyTNT ) - { - if( !breakBlockWithCheck( w, p, x, y, z ) ) - return false; - ( (BlockTinyTNT) blockID ).startFuse( w, x, y, z, p ); - return true; - } - - if( this.canHeat( blockID, metadata ) ) - { - if( this.heat( blockID, p, metadata, w, x, y, z ) ) - { - this.extractAEPower( item, 1600 ); - return true; - } - return false; - } - - final ItemStack[] stack = Platform.getBlockDrops( w, x, y, z ); - final List out = new ArrayList(); - boolean hasFurnaceable = false; - boolean canFurnaceable = true; - - for( final ItemStack i : stack ) - { - final ItemStack result = FurnaceRecipes.smelting().getSmeltingResult( i ); - - if( result != null ) - { - if( result.getItem() instanceof ItemBlock ) - { - if( Block.getBlockFromItem( result.getItem() ) == blockID && result.getItem().getDamage( result ) == metadata ) - { - canFurnaceable = false; - } - } - hasFurnaceable = true; - out.add( result ); - } - else - { - canFurnaceable = false; - out.add( i ); - } - } - - if( hasFurnaceable && canFurnaceable ) - { - if( !breakBlockWithCheck( w, p, x, y, z ) ) - return false; - - this.extractAEPower( item, 1600 ); - final InWorldToolOperationResult or = InWorldToolOperationResult.getBlockOperationResult( out.toArray( new ItemStack[out.size()] ) ); - w.playSoundEffect( x + 0.5D, y + 0.5D, z + 0.5D, "fire.ignite", 1.0F, itemRand.nextFloat() * 0.4F + 0.8F ); - - if( or.getBlockItem() != null ) - { - w.setBlock( x, y, z, Block.getBlockFromItem( or.getBlockItem().getItem() ), or.getBlockItem().getItemDamage(), 3 ); - } - - if( or.getDrops() != null ) - { - Platform.spawnDrops( w, x, y, z, or.getDrops() ); - } - - return true; - } - else - { - final ForgeDirection dir = ForgeDirection.getOrientation( side ); - x += dir.offsetX; - y += dir.offsetY; - z += dir.offsetZ; - - if( !p.canPlayerEdit( x, y, z, side, item ) ) - { - return false; - } - - if( w.isAirBlock( x, y, z ) ) - { - this.extractAEPower( item, 1600 ); - w.playSoundEffect( x + 0.5D, y + 0.5D, z + 0.5D, "fire.ignite", 1.0F, itemRand.nextFloat() * 0.4F + 0.8F ); - w.setBlock( x, y, z, Blocks.fire ); - } - - return true; - } - } - } - - return false; - } - - private static class InWorldToolOperationIngredient - { - private final Block blockID; - private final int metadata; - - public InWorldToolOperationIngredient( final Block blockID, final int metadata ) - { - this.blockID = blockID; - this.metadata = metadata; - } - - @Override - public int hashCode() - { - return this.blockID.hashCode() ^ this.metadata; - } - - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - final InWorldToolOperationIngredient other = (InWorldToolOperationIngredient) obj; - return this.blockID == other.blockID && this.metadata == other.metadata; - } - } - +public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockTool { + private final Map heatUp; + private final Map coolDown; + + public ToolEntropyManipulator() { + super(AEConfig.instance.entropyManipulatorBattery, Optional.absent()); + + this.setFeature(EnumSet.of(AEFeature.EntropyManipulator, AEFeature.PoweredTools)); + + this.heatUp = new HashMap(); + this.coolDown = new HashMap(); + + this.coolDown.put( + new InWorldToolOperationIngredient(Blocks.stone, 0), + new InWorldToolOperationResult(new ItemStack(Blocks.cobblestone))); + this.coolDown.put( + new InWorldToolOperationIngredient(Blocks.stonebrick, 0), + new InWorldToolOperationResult(new ItemStack(Blocks.stonebrick, 1, 2))); + this.coolDown.put( + new InWorldToolOperationIngredient(Blocks.lava, OreDictionary.WILDCARD_VALUE), + new InWorldToolOperationResult(new ItemStack(Blocks.obsidian))); + this.coolDown.put( + new InWorldToolOperationIngredient(Blocks.flowing_lava, OreDictionary.WILDCARD_VALUE), + new InWorldToolOperationResult(new ItemStack(Blocks.obsidian))); + this.coolDown.put( + new InWorldToolOperationIngredient(Blocks.grass, OreDictionary.WILDCARD_VALUE), + new InWorldToolOperationResult(new ItemStack(Blocks.dirt))); + + final List snowBalls = new ArrayList(); + snowBalls.add(new ItemStack(Items.snowball)); + this.coolDown.put( + new InWorldToolOperationIngredient(Blocks.flowing_water, OreDictionary.WILDCARD_VALUE), + new InWorldToolOperationResult(null, snowBalls)); + this.coolDown.put( + new InWorldToolOperationIngredient(Blocks.water, OreDictionary.WILDCARD_VALUE), + new InWorldToolOperationResult(new ItemStack(Blocks.ice))); + + this.heatUp.put( + new InWorldToolOperationIngredient(Blocks.ice, 0), + new InWorldToolOperationResult(new ItemStack(Blocks.water))); + this.heatUp.put( + new InWorldToolOperationIngredient(Blocks.flowing_water, OreDictionary.WILDCARD_VALUE), + new InWorldToolOperationResult()); + this.heatUp.put( + new InWorldToolOperationIngredient(Blocks.water, OreDictionary.WILDCARD_VALUE), + new InWorldToolOperationResult()); + this.heatUp.put( + new InWorldToolOperationIngredient(Blocks.snow, OreDictionary.WILDCARD_VALUE), + new InWorldToolOperationResult(new ItemStack(Blocks.flowing_water))); + } + + private static final boolean breakBlockWithCheck( + final World w, final EntityPlayer p, final int x, final int y, final int z) { + BlockEvent.BreakEvent event = + new BlockEvent.BreakEvent(x, y, z, w, w.getBlock(x, y, z), w.getBlockMetadata(x, y, z), p); + MinecraftForge.EVENT_BUS.post(event); + return !event.isCanceled() && w.setBlockToAir(x, y, z); + } + + @Override + public void postInit() { + super.postInit(); + BlockDispenser.dispenseBehaviorRegistry.putObject(this, new DispenserBlockTool()); + } + + private boolean heat( + final Block blockID, + final EntityPlayer p, + final int metadata, + final World w, + final int x, + final int y, + final int z) { + if (!breakBlockWithCheck(w, p, x, y, z)) return false; + + InWorldToolOperationResult r = this.heatUp.get(new InWorldToolOperationIngredient(blockID, metadata)); + + if (r == null) { + r = this.heatUp.get(new InWorldToolOperationIngredient(blockID, OreDictionary.WILDCARD_VALUE)); + } + + if (r.getBlockItem() != null) { + w.setBlock( + x, + y, + z, + Block.getBlockFromItem(r.getBlockItem().getItem()), + r.getBlockItem().getItemDamage(), + 3); + } + + if (r.getDrops() != null) { + Platform.spawnDrops(w, x, y, z, r.getDrops()); + } + + return true; + } + + private boolean canHeat(final Block blockID, final int metadata) { + InWorldToolOperationResult r = this.heatUp.get(new InWorldToolOperationIngredient(blockID, metadata)); + + if (r == null) { + r = this.heatUp.get(new InWorldToolOperationIngredient(blockID, OreDictionary.WILDCARD_VALUE)); + } + + return r != null; + } + + private boolean cool( + final Block blockID, + final EntityPlayer p, + final int metadata, + final World w, + final int x, + final int y, + final int z) { + if (!breakBlockWithCheck(w, p, x, y, z)) return false; + + InWorldToolOperationResult r = this.coolDown.get(new InWorldToolOperationIngredient(blockID, metadata)); + + if (r == null) { + r = this.coolDown.get(new InWorldToolOperationIngredient(blockID, OreDictionary.WILDCARD_VALUE)); + } + + if (r.getBlockItem() != null) { + w.setBlock( + x, + y, + z, + Block.getBlockFromItem(r.getBlockItem().getItem()), + r.getBlockItem().getItemDamage(), + 3); + } + + if (r.getDrops() != null) { + Platform.spawnDrops(w, x, y, z, r.getDrops()); + } + + return true; + } + + private boolean canCool(final Block blockID, final int metadata) { + InWorldToolOperationResult r = this.coolDown.get(new InWorldToolOperationIngredient(blockID, metadata)); + + if (r == null) { + r = this.coolDown.get(new InWorldToolOperationIngredient(blockID, OreDictionary.WILDCARD_VALUE)); + } + + return r != null; + } + + @Override + public boolean hitEntity(final ItemStack item, final EntityLivingBase target, final EntityLivingBase hitter) { + if (this.getAECurrentPower(item) > 1600) { + this.extractAEPower(item, 1600); + target.setFire(8); + } + + return false; + } + + @Override + public ItemStack onItemRightClick(final ItemStack item, final World w, final EntityPlayer p) { + final MovingObjectPosition target = this.getMovingObjectPositionFromPlayer(w, p, true); + + if (target == null) { + return item; + } else { + if (target.typeOfHit == MovingObjectType.BLOCK) { + final int x = target.blockX; + final int y = target.blockY; + final int z = target.blockZ; + + if (w.getBlock(x, y, z).getMaterial() == Material.lava + || w.getBlock(x, y, z).getMaterial() == Material.water) { + if (Platform.hasPermissions(new DimensionalCoord(w, x, y, z), p)) { + this.onItemUse(item, p, w, x, y, z, 0, 0.0F, 0.0F, 0.0F); + } + } + } + } + + return item; + } + + @Override + public boolean onItemUse( + final ItemStack item, + final EntityPlayer p, + final World w, + int x, + int y, + int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (this.getAECurrentPower(item) > 1600) { + if (!p.canPlayerEdit(x, y, z, side, item)) { + return false; + } + + final Block blockID = w.getBlock(x, y, z); + final int metadata = w.getBlockMetadata(x, y, z); + + if (blockID == null + || ForgeEventFactory.onPlayerInteract( + p, + blockID.isAir(w, x, y, z) + ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR + : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, + x, + y, + z, + side, + w) + .isCanceled()) return false; + + if (p.isSneaking()) { + if (this.canCool(blockID, metadata)) { + if (this.cool(blockID, p, metadata, w, x, y, z)) { + this.extractAEPower(item, 1600); + return true; + } + return false; + } + } else { + if (blockID instanceof BlockTNT) { + if (!breakBlockWithCheck(w, p, x, y, z)) return false; + ((BlockTNT) blockID).func_150114_a(w, x, y, z, 1, p); + return true; + } + + if (blockID instanceof BlockTinyTNT) { + if (!breakBlockWithCheck(w, p, x, y, z)) return false; + ((BlockTinyTNT) blockID).startFuse(w, x, y, z, p); + return true; + } + + if (this.canHeat(blockID, metadata)) { + if (this.heat(blockID, p, metadata, w, x, y, z)) { + this.extractAEPower(item, 1600); + return true; + } + return false; + } + + final ItemStack[] stack = Platform.getBlockDrops(w, x, y, z); + final List out = new ArrayList(); + boolean hasFurnaceable = false; + boolean canFurnaceable = true; + + for (final ItemStack i : stack) { + final ItemStack result = FurnaceRecipes.smelting().getSmeltingResult(i); + + if (result != null) { + if (result.getItem() instanceof ItemBlock) { + if (Block.getBlockFromItem(result.getItem()) == blockID + && result.getItem().getDamage(result) == metadata) { + canFurnaceable = false; + } + } + hasFurnaceable = true; + out.add(result); + } else { + canFurnaceable = false; + out.add(i); + } + } + + if (hasFurnaceable && canFurnaceable) { + if (!breakBlockWithCheck(w, p, x, y, z)) return false; + + this.extractAEPower(item, 1600); + final InWorldToolOperationResult or = + InWorldToolOperationResult.getBlockOperationResult(out.toArray(new ItemStack[out.size()])); + w.playSoundEffect( + x + 0.5D, y + 0.5D, z + 0.5D, "fire.ignite", 1.0F, itemRand.nextFloat() * 0.4F + 0.8F); + + if (or.getBlockItem() != null) { + w.setBlock( + x, + y, + z, + Block.getBlockFromItem(or.getBlockItem().getItem()), + or.getBlockItem().getItemDamage(), + 3); + } + + if (or.getDrops() != null) { + Platform.spawnDrops(w, x, y, z, or.getDrops()); + } + + return true; + } else { + final ForgeDirection dir = ForgeDirection.getOrientation(side); + x += dir.offsetX; + y += dir.offsetY; + z += dir.offsetZ; + + if (!p.canPlayerEdit(x, y, z, side, item)) { + return false; + } + + if (w.isAirBlock(x, y, z)) { + this.extractAEPower(item, 1600); + w.playSoundEffect( + x + 0.5D, y + 0.5D, z + 0.5D, "fire.ignite", 1.0F, itemRand.nextFloat() * 0.4F + 0.8F); + w.setBlock(x, y, z, Blocks.fire); + } + + return true; + } + } + } + + return false; + } + + private static class InWorldToolOperationIngredient { + private final Block blockID; + private final int metadata; + + public InWorldToolOperationIngredient(final Block blockID, final int metadata) { + this.blockID = blockID; + this.metadata = metadata; + } + + @Override + public int hashCode() { + return this.blockID.hashCode() ^ this.metadata; + } + + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final InWorldToolOperationIngredient other = (InWorldToolOperationIngredient) obj; + return this.blockID == other.blockID && this.metadata == other.metadata; + } + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolMassCannon.java b/src/main/java/appeng/items/tools/powered/ToolMassCannon.java index 68181cfaa45..faa7779fed8 100644 --- a/src/main/java/appeng/items/tools/powered/ToolMassCannon.java +++ b/src/main/java/appeng/items/tools/powered/ToolMassCannon.java @@ -18,7 +18,6 @@ package appeng.items.tools.powered; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.FuzzyMode; @@ -55,6 +54,8 @@ import com.google.common.base.Optional; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.BlockDispenser; import net.minecraft.entity.Entity; @@ -71,481 +72,461 @@ import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.List; - - -public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell -{ +public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell { - public ToolMassCannon() - { - super( AEConfig.instance.matterCannonBattery, Optional.absent() ); - this.setFeature( EnumSet.of( AEFeature.MatterCannon, AEFeature.PoweredTools ) ); - } + public ToolMassCannon() { + super(AEConfig.instance.matterCannonBattery, Optional.absent()); + this.setFeature(EnumSet.of(AEFeature.MatterCannon, AEFeature.PoweredTools)); + } - @Override - public void postInit() - { - super.postInit(); - BlockDispenser.dispenseBehaviorRegistry.putObject( this, new DispenserMatterCannon() ); - } + @Override + public void postInit() { + super.postInit(); + BlockDispenser.dispenseBehaviorRegistry.putObject(this, new DispenserMatterCannon()); + } @SideOnly(Side.CLIENT) - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - super.addCheckedInformation( stack, player, lines, displayMoreInfo ); - - final IMEInventory cdi = AEApi.instance().registries().cell().getCellInventory( stack, null, StorageChannel.ITEMS ); - - if( cdi instanceof CellInventoryHandler ) - { - final ICellInventory cd = ( (ICellInventoryHandler) cdi ).getCellInv(); - if( cd != null ) - { - lines.add( cd.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalBytes() + ' ' + GuiText.BytesUsed.getLocal() ); - lines.add( cd.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalItemTypes() + ' ' + GuiText.Types.getLocal() ); - } - } - } - - @Override - public ItemStack onItemRightClick( final ItemStack item, final World w, final EntityPlayer p ) - { - if( this.getAECurrentPower( item ) > 1600 ) - { - int shots = 1; - - final CellUpgrades cu = (CellUpgrades) this.getUpgradesInventory( item ); - if( cu != null ) - { - shots += cu.getInstalledUpgrades( Upgrades.SPEED ); - } - - final IMEInventory inv = AEApi.instance().registries().cell().getCellInventory( item, null, StorageChannel.ITEMS ); - if( inv != null ) - { - final IItemList itemList = inv.getAvailableItems( AEApi.instance().storage().createItemList() ); - IAEStack aeAmmo = itemList.getFirstItem(); - if( aeAmmo instanceof IAEItemStack ) - { - shots = Math.min( shots, (int) aeAmmo.getStackSize() ); - for( int sh = 0; sh < shots; sh++ ) - { - this.extractAEPower( item, 1600 ); - - if( Platform.isClient() ) - { - return item; - } - - aeAmmo.setStackSize( 1 ); - final ItemStack ammo = ( (IAEItemStack) aeAmmo ).getItemStack(); - if( ammo == null ) - { - return item; - } - - ammo.stackSize = 1; - aeAmmo = inv.extractItems( aeAmmo, Actionable.MODULATE, new PlayerSource( p, null ) ); - if( aeAmmo == null ) - { - return item; - } - - final float f = 1.0F; - final float f1 = p.prevRotationPitch + ( p.rotationPitch - p.prevRotationPitch ) * f; - final float f2 = p.prevRotationYaw + ( p.rotationYaw - p.prevRotationYaw ) * f; - final double d0 = p.prevPosX + ( p.posX - p.prevPosX ) * f; - final double d1 = p.prevPosY + ( p.posY - p.prevPosY ) * f + 1.62D - p.yOffset; - final double d2 = p.prevPosZ + ( p.posZ - p.prevPosZ ) * f; - final Vec3 vec3 = Vec3.createVectorHelper( d0, d1, d2 ); - final float f3 = MathHelper.cos( -f2 * 0.017453292F - (float) Math.PI ); - final float f4 = MathHelper.sin( -f2 * 0.017453292F - (float) Math.PI ); - final float f5 = -MathHelper.cos( -f1 * 0.017453292F ); - final float f6 = MathHelper.sin( -f1 * 0.017453292F ); - final float f7 = f4 * f5; - final float f8 = f3 * f5; - final double d3 = 32.0D; - - final Vec3 vec31 = vec3.addVector( f7 * d3, f6 * d3, f8 * d3 ); - final Vec3 direction = Vec3.createVectorHelper( f7 * d3, f6 * d3, f8 * d3 ); - direction.normalize(); - - final float penetration = AEApi.instance().registries().matterCannon().getPenetration( ammo ); // 196.96655f; - if( penetration <= 0 ) - { - final ItemStack type = ( (IAEItemStack) aeAmmo ).getItemStack(); - if( type.getItem() instanceof ItemPaintBall ) - { - this.shootPaintBalls( type, w, p, vec3, vec31, direction, d0, d1, d2 ); - } - return item; - } - else - { - this.standardAmmo( penetration, w, p, vec3, vec31, direction, d0, d1, d2 ); - } - } - } - else - { - if( Platform.isServer() && !(p instanceof FakePlayer) ) - { - p.addChatMessage( PlayerMessages.AmmoDepleted.get() ); - } - return item; - } - } - } - return item; - } - - private void shootPaintBalls( final ItemStack type, final World w, final EntityPlayer p, final Vec3 vec3, final Vec3 vec31, final Vec3 direction, final double d0, final double d1, final double d2 ) - { - final AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( Math.min( vec3.xCoord, vec31.xCoord ), Math.min( vec3.yCoord, vec31.yCoord ), Math.min( vec3.zCoord, vec31.zCoord ), Math.max( vec3.xCoord, vec31.xCoord ), Math.max( vec3.yCoord, vec31.yCoord ), Math.max( vec3.zCoord, vec31.zCoord ) ).expand( 16, 16, 16 ); - - Entity entity = null; - final List list = w.getEntitiesWithinAABBExcludingEntity( p, bb ); - double closest = 9999999.0D; - - for( int l = 0; l < list.size(); ++l ) - { - final Entity entity1 = (Entity) list.get( l ); - - if( !entity1.isDead && entity1 != p && !( entity1 instanceof EntityItem ) ) - { - if( entity1.isEntityAlive() ) - { - // prevent killing / flying of mounts. - if( entity1.riddenByEntity == p ) - { - continue; - } - - final float f1 = 0.3F; - - final AxisAlignedBB boundingBox = entity1.boundingBox.expand( f1, f1, f1 ); - final MovingObjectPosition movingObjectPosition = boundingBox.calculateIntercept( vec3, vec31 ); - - if( movingObjectPosition != null ) - { - final double nd = vec3.squareDistanceTo( movingObjectPosition.hitVec ); - - if( nd < closest ) - { - entity = entity1; - closest = nd; - } - } - } - } - } - - MovingObjectPosition pos = w.rayTraceBlocks( vec3, vec31, false ); - - final Vec3 vec = Vec3.createVectorHelper( d0, d1, d2 ); - if( entity != null && pos != null && pos.hitVec.squareDistanceTo( vec ) > closest ) - { - pos = new MovingObjectPosition( entity ); - } - else if( entity != null && pos == null ) - { - pos = new MovingObjectPosition( entity ); - } - - try - { - CommonHelper.proxy.sendToAllNearExcept( null, d0, d1, d2, 128, w, new PacketMatterCannon( d0, d1, d2, (float) direction.xCoord, (float) direction.yCoord, (float) direction.zCoord, (byte) ( pos == null ? 32 : pos.hitVec.squareDistanceTo( vec ) + 1 ) ) ); - } - catch( final Exception err ) - { - AELog.debug( err ); - } - - if( pos != null && type != null && type.getItem() instanceof ItemPaintBall ) - { - final ItemPaintBall ipb = (ItemPaintBall) type.getItem(); - - final AEColor col = ipb.getColor( type ); - // boolean lit = ipb.isLumen( type ); - - if( pos.typeOfHit == MovingObjectType.ENTITY ) - { - final int id = pos.entityHit.getEntityId(); - final PlayerColor marker = new PlayerColor( id, col, 20 * 30 ); - TickHandler.INSTANCE.getPlayerColors().put( id, marker ); - - if( pos.entityHit instanceof EntitySheep ) - { - final EntitySheep sh = (EntitySheep) pos.entityHit; - sh.setFleeceColor( col.ordinal() ); - } - - pos.entityHit.attackEntityFrom( DamageSource.causePlayerDamage( p ), 0 ); - NetworkHandler.instance.sendToAll( marker.getPacket() ); - } - else if( pos.typeOfHit == MovingObjectType.BLOCK ) - { - final ForgeDirection side = ForgeDirection.getOrientation( pos.sideHit ); - - final int x = pos.blockX + side.offsetX; - final int y = pos.blockY + side.offsetY; - final int z = pos.blockZ + side.offsetZ; - - if( !Platform.hasPermissions( new DimensionalCoord( w, x, y, z ), p ) ) - { - return; - } - - final Block whatsThere = w.getBlock( x, y, z ); - if( whatsThere.isReplaceable( w, x, y, z ) && w.isAirBlock( x, y, z ) ) - { - for( final Block paintBlock : AEApi.instance().definitions().blocks().paint().maybeBlock().asSet() ) - { - w.setBlock( x, y, z, paintBlock, 0, 3 ); - } - } - - final TileEntity te = w.getTileEntity( x, y, z ); - if( te instanceof TilePaint ) - { - pos.hitVec.xCoord -= x; - pos.hitVec.yCoord -= y; - pos.hitVec.zCoord -= z; - ( (TilePaint) te ).addBlot( type, side.getOpposite(), pos.hitVec ); - } - } - } - } - - private void standardAmmo( float penetration, final World w, final EntityPlayer p, final Vec3 vec3, final Vec3 vec31, final Vec3 direction, final double d0, final double d1, final double d2 ) - { - boolean hasDestroyed = true; - while( penetration > 0 && hasDestroyed ) - { - hasDestroyed = false; - - final AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( Math.min( vec3.xCoord, vec31.xCoord ), Math.min( vec3.yCoord, vec31.yCoord ), Math.min( vec3.zCoord, vec31.zCoord ), Math.max( vec3.xCoord, vec31.xCoord ), Math.max( vec3.yCoord, vec31.yCoord ), Math.max( vec3.zCoord, vec31.zCoord ) ).expand( 16, 16, 16 ); - - Entity entity = null; - final List list = w.getEntitiesWithinAABBExcludingEntity( p, bb ); - double closest = 9999999.0D; - - for( int l = 0; l < list.size(); ++l ) - { - final Entity entity1 = (Entity) list.get( l ); - - if( !entity1.isDead && entity1 != p && !( entity1 instanceof EntityItem ) ) - { - if( entity1.isEntityAlive() ) - { - // prevent killing / flying of mounts. - if( entity1.riddenByEntity == p ) - { - continue; - } - - final float f1 = 0.3F; - - final AxisAlignedBB boundingBox = entity1.boundingBox.expand( f1, f1, f1 ); - final MovingObjectPosition movingObjectPosition = boundingBox.calculateIntercept( vec3, vec31 ); - - if( movingObjectPosition != null ) - { - final double nd = vec3.squareDistanceTo( movingObjectPosition.hitVec ); - - if( nd < closest ) - { - entity = entity1; - closest = nd; - } - } - } - } - } - - final Vec3 vec = Vec3.createVectorHelper( d0, d1, d2 ); - MovingObjectPosition pos = w.rayTraceBlocks( vec3, vec31, true ); - if( entity != null && pos != null && pos.hitVec.squareDistanceTo( vec ) > closest ) - { - pos = new MovingObjectPosition( entity ); - } - else if( entity != null && pos == null ) - { - pos = new MovingObjectPosition( entity ); - } - - try - { - CommonHelper.proxy.sendToAllNearExcept( null, d0, d1, d2, 128, w, new PacketMatterCannon( d0, d1, d2, (float) direction.xCoord, (float) direction.yCoord, (float) direction.zCoord, (byte) ( pos == null ? 32 : pos.hitVec.squareDistanceTo( vec ) + 1 ) ) ); - } - catch( final Exception err ) - { - AELog.debug( err ); - } - - if( pos != null ) - { - final DamageSource dmgSrc = DamageSource.causePlayerDamage( p ); - dmgSrc.damageType = "masscannon"; - - if( pos.typeOfHit == MovingObjectType.ENTITY ) - { - final int dmg = (int) Math.ceil( penetration / 20.0f ); - if( pos.entityHit instanceof EntityLivingBase ) - { - final EntityLivingBase el = (EntityLivingBase) pos.entityHit; - penetration -= dmg; - el.knockBack( p, 0, -direction.xCoord, -direction.zCoord ); - // el.knockBack( p, 0, vec3.xCoord, - // vec3.zCoord ); - el.attackEntityFrom( dmgSrc, dmg ); - if( !el.isEntityAlive() ) - { - hasDestroyed = true; - } - } - else if( pos.entityHit instanceof EntityItem ) - { - hasDestroyed = true; - pos.entityHit.setDead(); - } - else if( pos.entityHit.attackEntityFrom( dmgSrc, dmg ) ) - { - hasDestroyed = true; - } - } - else if( pos.typeOfHit == MovingObjectType.BLOCK ) - { - if( !AEConfig.instance.isFeatureEnabled( AEFeature.MassCannonBlockDamage ) ) - { - penetration = 0; - } - else - { - final Block b = w.getBlock( pos.blockX, pos.blockY, pos.blockZ ); - // int meta = w.getBlockMetadata( - // pos.blockX, pos.blockY, pos.blockZ ); - - final float hardness = b.getBlockHardness( w, pos.blockX, pos.blockY, pos.blockZ ) * 9.0f; - if( hardness >= 0.0 ) - { - if( penetration > hardness && Platform.hasPermissions( new DimensionalCoord( w, pos.blockX, pos.blockY, pos.blockZ ), p ) ) - { - hasDestroyed = true; - penetration -= hardness; - penetration *= 0.60; - w.func_147480_a( pos.blockX, pos.blockY, pos.blockZ, true ); - // w.destroyBlock( pos.blockX, pos.blockY, pos.blockZ, true ); - } - } - } - } - } - } - } - - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } - - @Override - public IInventory getUpgradesInventory( final ItemStack is ) - { - return new CellUpgrades( is, 4 ); - } - - @Override - public IInventory getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } - - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - final String fz = Platform.openNbtData( is ).getString( "FuzzyMode" ); - try - { - return FuzzyMode.valueOf( fz ); - } - catch( final Throwable t ) - { - return FuzzyMode.IGNORE_ALL; - } - } - - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - Platform.openNbtData( is ).setString( "FuzzyMode", fzMode.name() ); - } - - @Override - public int getBytes( final ItemStack cellItem ) - { - return 512; - } - - @Override - public int BytePerType( final ItemStack cell ) - { - return 8; - } - - @Override - public int getBytesPerType( final ItemStack cellItem ) - { - return 8; - } - - @Override - public int getTotalTypes( final ItemStack cellItem ) - { - return 1; - } - - @Override - public boolean isBlackListed( final ItemStack cellItem, final IAEItemStack requestedAddition ) - { - final float pen = AEApi.instance().registries().matterCannon().getPenetration( requestedAddition.getItemStack() ); - if( pen > 0 ) - { - return false; - } - - return !( requestedAddition.getItem() instanceof ItemPaintBall ); - } - - @Override - public boolean storableInStorageCell() - { - return true; - } - - @Override - public boolean isStorageCell( final ItemStack i ) - { - return true; - } - - @Override - public double getIdleDrain() - { - return 0.5; - } - - @Override - public String getOreFilter(ItemStack is) { - return Platform.openNbtData( is ).getString( "OreFilter" ); - } - - @Override - public void setOreFilter(ItemStack is, String filter) { - Platform.openNbtData( is ).setString("OreFilter", filter); - } + @Override + public void addCheckedInformation( + final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo) { + super.addCheckedInformation(stack, player, lines, displayMoreInfo); + + final IMEInventory cdi = + AEApi.instance().registries().cell().getCellInventory(stack, null, StorageChannel.ITEMS); + + if (cdi instanceof CellInventoryHandler) { + final ICellInventory cd = ((ICellInventoryHandler) cdi).getCellInv(); + if (cd != null) { + lines.add(cd.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalBytes() + ' ' + + GuiText.BytesUsed.getLocal()); + lines.add(cd.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalItemTypes() + ' ' + + GuiText.Types.getLocal()); + } + } + } + + @Override + public ItemStack onItemRightClick(final ItemStack item, final World w, final EntityPlayer p) { + if (this.getAECurrentPower(item) > 1600) { + int shots = 1; + + final CellUpgrades cu = (CellUpgrades) this.getUpgradesInventory(item); + if (cu != null) { + shots += cu.getInstalledUpgrades(Upgrades.SPEED); + } + + final IMEInventory inv = + AEApi.instance().registries().cell().getCellInventory(item, null, StorageChannel.ITEMS); + if (inv != null) { + final IItemList itemList = + inv.getAvailableItems(AEApi.instance().storage().createItemList()); + IAEStack aeAmmo = itemList.getFirstItem(); + if (aeAmmo instanceof IAEItemStack) { + shots = Math.min(shots, (int) aeAmmo.getStackSize()); + for (int sh = 0; sh < shots; sh++) { + this.extractAEPower(item, 1600); + + if (Platform.isClient()) { + return item; + } + + aeAmmo.setStackSize(1); + final ItemStack ammo = ((IAEItemStack) aeAmmo).getItemStack(); + if (ammo == null) { + return item; + } + + ammo.stackSize = 1; + aeAmmo = inv.extractItems(aeAmmo, Actionable.MODULATE, new PlayerSource(p, null)); + if (aeAmmo == null) { + return item; + } + + final float f = 1.0F; + final float f1 = p.prevRotationPitch + (p.rotationPitch - p.prevRotationPitch) * f; + final float f2 = p.prevRotationYaw + (p.rotationYaw - p.prevRotationYaw) * f; + final double d0 = p.prevPosX + (p.posX - p.prevPosX) * f; + final double d1 = p.prevPosY + (p.posY - p.prevPosY) * f + 1.62D - p.yOffset; + final double d2 = p.prevPosZ + (p.posZ - p.prevPosZ) * f; + final Vec3 vec3 = Vec3.createVectorHelper(d0, d1, d2); + final float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI); + final float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI); + final float f5 = -MathHelper.cos(-f1 * 0.017453292F); + final float f6 = MathHelper.sin(-f1 * 0.017453292F); + final float f7 = f4 * f5; + final float f8 = f3 * f5; + final double d3 = 32.0D; + + final Vec3 vec31 = vec3.addVector(f7 * d3, f6 * d3, f8 * d3); + final Vec3 direction = Vec3.createVectorHelper(f7 * d3, f6 * d3, f8 * d3); + direction.normalize(); + + final float penetration = + AEApi.instance().registries().matterCannon().getPenetration(ammo); // 196.96655f; + if (penetration <= 0) { + final ItemStack type = ((IAEItemStack) aeAmmo).getItemStack(); + if (type.getItem() instanceof ItemPaintBall) { + this.shootPaintBalls(type, w, p, vec3, vec31, direction, d0, d1, d2); + } + return item; + } else { + this.standardAmmo(penetration, w, p, vec3, vec31, direction, d0, d1, d2); + } + } + } else { + if (Platform.isServer() && !(p instanceof FakePlayer)) { + p.addChatMessage(PlayerMessages.AmmoDepleted.get()); + } + return item; + } + } + } + return item; + } + + private void shootPaintBalls( + final ItemStack type, + final World w, + final EntityPlayer p, + final Vec3 vec3, + final Vec3 vec31, + final Vec3 direction, + final double d0, + final double d1, + final double d2) { + final AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( + Math.min(vec3.xCoord, vec31.xCoord), + Math.min(vec3.yCoord, vec31.yCoord), + Math.min(vec3.zCoord, vec31.zCoord), + Math.max(vec3.xCoord, vec31.xCoord), + Math.max(vec3.yCoord, vec31.yCoord), + Math.max(vec3.zCoord, vec31.zCoord)) + .expand(16, 16, 16); + + Entity entity = null; + final List list = w.getEntitiesWithinAABBExcludingEntity(p, bb); + double closest = 9999999.0D; + + for (int l = 0; l < list.size(); ++l) { + final Entity entity1 = (Entity) list.get(l); + + if (!entity1.isDead && entity1 != p && !(entity1 instanceof EntityItem)) { + if (entity1.isEntityAlive()) { + // prevent killing / flying of mounts. + if (entity1.riddenByEntity == p) { + continue; + } + + final float f1 = 0.3F; + + final AxisAlignedBB boundingBox = entity1.boundingBox.expand(f1, f1, f1); + final MovingObjectPosition movingObjectPosition = boundingBox.calculateIntercept(vec3, vec31); + + if (movingObjectPosition != null) { + final double nd = vec3.squareDistanceTo(movingObjectPosition.hitVec); + + if (nd < closest) { + entity = entity1; + closest = nd; + } + } + } + } + } + + MovingObjectPosition pos = w.rayTraceBlocks(vec3, vec31, false); + + final Vec3 vec = Vec3.createVectorHelper(d0, d1, d2); + if (entity != null && pos != null && pos.hitVec.squareDistanceTo(vec) > closest) { + pos = new MovingObjectPosition(entity); + } else if (entity != null && pos == null) { + pos = new MovingObjectPosition(entity); + } + + try { + CommonHelper.proxy.sendToAllNearExcept( + null, + d0, + d1, + d2, + 128, + w, + new PacketMatterCannon( + d0, + d1, + d2, + (float) direction.xCoord, + (float) direction.yCoord, + (float) direction.zCoord, + (byte) (pos == null ? 32 : pos.hitVec.squareDistanceTo(vec) + 1))); + } catch (final Exception err) { + AELog.debug(err); + } + + if (pos != null && type != null && type.getItem() instanceof ItemPaintBall) { + final ItemPaintBall ipb = (ItemPaintBall) type.getItem(); + + final AEColor col = ipb.getColor(type); + // boolean lit = ipb.isLumen( type ); + + if (pos.typeOfHit == MovingObjectType.ENTITY) { + final int id = pos.entityHit.getEntityId(); + final PlayerColor marker = new PlayerColor(id, col, 20 * 30); + TickHandler.INSTANCE.getPlayerColors().put(id, marker); + + if (pos.entityHit instanceof EntitySheep) { + final EntitySheep sh = (EntitySheep) pos.entityHit; + sh.setFleeceColor(col.ordinal()); + } + + pos.entityHit.attackEntityFrom(DamageSource.causePlayerDamage(p), 0); + NetworkHandler.instance.sendToAll(marker.getPacket()); + } else if (pos.typeOfHit == MovingObjectType.BLOCK) { + final ForgeDirection side = ForgeDirection.getOrientation(pos.sideHit); + + final int x = pos.blockX + side.offsetX; + final int y = pos.blockY + side.offsetY; + final int z = pos.blockZ + side.offsetZ; + + if (!Platform.hasPermissions(new DimensionalCoord(w, x, y, z), p)) { + return; + } + + final Block whatsThere = w.getBlock(x, y, z); + if (whatsThere.isReplaceable(w, x, y, z) && w.isAirBlock(x, y, z)) { + for (final Block paintBlock : AEApi.instance() + .definitions() + .blocks() + .paint() + .maybeBlock() + .asSet()) { + w.setBlock(x, y, z, paintBlock, 0, 3); + } + } + + final TileEntity te = w.getTileEntity(x, y, z); + if (te instanceof TilePaint) { + pos.hitVec.xCoord -= x; + pos.hitVec.yCoord -= y; + pos.hitVec.zCoord -= z; + ((TilePaint) te).addBlot(type, side.getOpposite(), pos.hitVec); + } + } + } + } + + private void standardAmmo( + float penetration, + final World w, + final EntityPlayer p, + final Vec3 vec3, + final Vec3 vec31, + final Vec3 direction, + final double d0, + final double d1, + final double d2) { + boolean hasDestroyed = true; + while (penetration > 0 && hasDestroyed) { + hasDestroyed = false; + + final AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( + Math.min(vec3.xCoord, vec31.xCoord), + Math.min(vec3.yCoord, vec31.yCoord), + Math.min(vec3.zCoord, vec31.zCoord), + Math.max(vec3.xCoord, vec31.xCoord), + Math.max(vec3.yCoord, vec31.yCoord), + Math.max(vec3.zCoord, vec31.zCoord)) + .expand(16, 16, 16); + + Entity entity = null; + final List list = w.getEntitiesWithinAABBExcludingEntity(p, bb); + double closest = 9999999.0D; + + for (int l = 0; l < list.size(); ++l) { + final Entity entity1 = (Entity) list.get(l); + + if (!entity1.isDead && entity1 != p && !(entity1 instanceof EntityItem)) { + if (entity1.isEntityAlive()) { + // prevent killing / flying of mounts. + if (entity1.riddenByEntity == p) { + continue; + } + + final float f1 = 0.3F; + + final AxisAlignedBB boundingBox = entity1.boundingBox.expand(f1, f1, f1); + final MovingObjectPosition movingObjectPosition = boundingBox.calculateIntercept(vec3, vec31); + + if (movingObjectPosition != null) { + final double nd = vec3.squareDistanceTo(movingObjectPosition.hitVec); + + if (nd < closest) { + entity = entity1; + closest = nd; + } + } + } + } + } + + final Vec3 vec = Vec3.createVectorHelper(d0, d1, d2); + MovingObjectPosition pos = w.rayTraceBlocks(vec3, vec31, true); + if (entity != null && pos != null && pos.hitVec.squareDistanceTo(vec) > closest) { + pos = new MovingObjectPosition(entity); + } else if (entity != null && pos == null) { + pos = new MovingObjectPosition(entity); + } + + try { + CommonHelper.proxy.sendToAllNearExcept( + null, + d0, + d1, + d2, + 128, + w, + new PacketMatterCannon( + d0, + d1, + d2, + (float) direction.xCoord, + (float) direction.yCoord, + (float) direction.zCoord, + (byte) (pos == null ? 32 : pos.hitVec.squareDistanceTo(vec) + 1))); + } catch (final Exception err) { + AELog.debug(err); + } + + if (pos != null) { + final DamageSource dmgSrc = DamageSource.causePlayerDamage(p); + dmgSrc.damageType = "masscannon"; + + if (pos.typeOfHit == MovingObjectType.ENTITY) { + final int dmg = (int) Math.ceil(penetration / 20.0f); + if (pos.entityHit instanceof EntityLivingBase) { + final EntityLivingBase el = (EntityLivingBase) pos.entityHit; + penetration -= dmg; + el.knockBack(p, 0, -direction.xCoord, -direction.zCoord); + // el.knockBack( p, 0, vec3.xCoord, + // vec3.zCoord ); + el.attackEntityFrom(dmgSrc, dmg); + if (!el.isEntityAlive()) { + hasDestroyed = true; + } + } else if (pos.entityHit instanceof EntityItem) { + hasDestroyed = true; + pos.entityHit.setDead(); + } else if (pos.entityHit.attackEntityFrom(dmgSrc, dmg)) { + hasDestroyed = true; + } + } else if (pos.typeOfHit == MovingObjectType.BLOCK) { + if (!AEConfig.instance.isFeatureEnabled(AEFeature.MassCannonBlockDamage)) { + penetration = 0; + } else { + final Block b = w.getBlock(pos.blockX, pos.blockY, pos.blockZ); + // int meta = w.getBlockMetadata( + // pos.blockX, pos.blockY, pos.blockZ ); + + final float hardness = b.getBlockHardness(w, pos.blockX, pos.blockY, pos.blockZ) * 9.0f; + if (hardness >= 0.0) { + if (penetration > hardness + && Platform.hasPermissions( + new DimensionalCoord(w, pos.blockX, pos.blockY, pos.blockZ), p)) { + hasDestroyed = true; + penetration -= hardness; + penetration *= 0.60; + w.func_147480_a(pos.blockX, pos.blockY, pos.blockZ, true); + // w.destroyBlock( pos.blockX, pos.blockY, pos.blockZ, true ); + } + } + } + } + } + } + } + + @Override + public boolean isEditable(final ItemStack is) { + return true; + } + + @Override + public IInventory getUpgradesInventory(final ItemStack is) { + return new CellUpgrades(is, 4); + } + + @Override + public IInventory getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } + + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + final String fz = Platform.openNbtData(is).getString("FuzzyMode"); + try { + return FuzzyMode.valueOf(fz); + } catch (final Throwable t) { + return FuzzyMode.IGNORE_ALL; + } + } + + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { + Platform.openNbtData(is).setString("FuzzyMode", fzMode.name()); + } + + @Override + public int getBytes(final ItemStack cellItem) { + return 512; + } + + @Override + public int BytePerType(final ItemStack cell) { + return 8; + } + + @Override + public int getBytesPerType(final ItemStack cellItem) { + return 8; + } + + @Override + public int getTotalTypes(final ItemStack cellItem) { + return 1; + } + + @Override + public boolean isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) { + final float pen = AEApi.instance().registries().matterCannon().getPenetration(requestedAddition.getItemStack()); + if (pen > 0) { + return false; + } + + return !(requestedAddition.getItem() instanceof ItemPaintBall); + } + + @Override + public boolean storableInStorageCell() { + return true; + } + + @Override + public boolean isStorageCell(final ItemStack i) { + return true; + } + + @Override + public double getIdleDrain() { + return 0.5; + } + + @Override + public String getOreFilter(ItemStack is) { + return Platform.openNbtData(is).getString("OreFilter"); + } + + @Override + public void setOreFilter(ItemStack is, String filter) { + Platform.openNbtData(is).setString("OreFilter", filter); + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolPortableCell.java b/src/main/java/appeng/items/tools/powered/ToolPortableCell.java index a6d2bc00d56..fd84f54f706 100644 --- a/src/main/java/appeng/items/tools/powered/ToolPortableCell.java +++ b/src/main/java/appeng/items/tools/powered/ToolPortableCell.java @@ -18,7 +18,6 @@ package appeng.items.tools.powered; - import appeng.api.AEApi; import appeng.api.config.FuzzyMode; import appeng.api.implementations.guiobjects.IGuiItem; @@ -43,163 +42,140 @@ import com.google.common.base.Optional; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.List; -import java.util.Set; +public class ToolPortableCell extends AEBasePoweredItem implements IStorageCell, IGuiItem, IItemGroup { + public ToolPortableCell() { + super(AEConfig.instance.portableCellBattery, Optional.absent()); + this.setFeature(EnumSet.of(AEFeature.PortableCell, AEFeature.StorageCells, AEFeature.PoweredTools)); + } + @Override + public ItemStack onItemRightClick(final ItemStack item, final World w, final EntityPlayer player) { + Platform.openGUI(player, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_PORTABLE_CELL); + return item; + } -public class ToolPortableCell extends AEBasePoweredItem implements IStorageCell, IGuiItem, IItemGroup -{ - public ToolPortableCell() - { - super( AEConfig.instance.portableCellBattery, Optional.absent() ); - this.setFeature( EnumSet.of( AEFeature.PortableCell, AEFeature.StorageCells, AEFeature.PoweredTools ) ); - } - - @Override - public ItemStack onItemRightClick( final ItemStack item, final World w, final EntityPlayer player ) - { - Platform.openGUI( player, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_PORTABLE_CELL ); - return item; - } - - @SideOnly( Side.CLIENT ) - @Override - public boolean isFull3D() - { - return false; - } + @SideOnly(Side.CLIENT) + @Override + public boolean isFull3D() { + return false; + } @SideOnly(Side.CLIENT) - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - super.addCheckedInformation( stack, player, lines, displayMoreInfo ); - - final IMEInventory cdi = AEApi.instance().registries().cell().getCellInventory( stack, null, StorageChannel.ITEMS ); - - if( cdi instanceof CellInventoryHandler ) - { - final ICellInventory cd = ( (ICellInventoryHandler) cdi ).getCellInv(); - if( cd != null ) - { - lines.add( cd.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalBytes() + ' ' + GuiText.BytesUsed.getLocal() ); - lines.add( cd.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalItemTypes() + ' ' + GuiText.Types.getLocal() ); - } - } - } - - @Override - public int getBytes( final ItemStack cellItem ) - { - return 512; - } - - @Override - public int BytePerType( final ItemStack cell ) - { - return 8; - } - - @Override - public int getBytesPerType( final ItemStack cellItem ) - { - return 8; - } - - @Override - public int getTotalTypes( final ItemStack cellItem ) - { - return 27; - } - - @Override - public boolean isBlackListed( final ItemStack cellItem, final IAEItemStack requestedAddition ) - { - return false; - } - - @Override - public boolean storableInStorageCell() - { - return false; - } - - @Override - public boolean isStorageCell( final ItemStack i ) - { - return true; - } - - @Override - public double getIdleDrain() - { - return 0.5; - } - - @Override - public String getUnlocalizedGroupName( final Set others, final ItemStack is ) - { - return GuiText.StorageCells.getUnlocalized(); - } - - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } - - @Override - public IInventory getUpgradesInventory( final ItemStack is ) - { - return new CellUpgrades( is, 2 ); - } - - @Override - public IInventory getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } - - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - final String fz = Platform.openNbtData( is ).getString( "FuzzyMode" ); - try - { - return FuzzyMode.valueOf( fz ); - } - catch( final Throwable t ) - { - return FuzzyMode.IGNORE_ALL; - } - } - - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - Platform.openNbtData( is ).setString( "FuzzyMode", fzMode.name() ); - } - - @Override - public IGuiItemObject getGuiObject( final ItemStack is, final World w, final int x, final int y, final int z ) - { - return new PortableCellViewer( is, x ); - } - - @Override - public String getOreFilter(ItemStack is) { - return Platform.openNbtData( is ).getString( "OreFilter" ); - } - - @Override - public void setOreFilter(ItemStack is, String filter) { - Platform.openNbtData( is ).setString("OreFilter", filter); - } + @Override + public void addCheckedInformation( + final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo) { + super.addCheckedInformation(stack, player, lines, displayMoreInfo); + + final IMEInventory cdi = + AEApi.instance().registries().cell().getCellInventory(stack, null, StorageChannel.ITEMS); + + if (cdi instanceof CellInventoryHandler) { + final ICellInventory cd = ((ICellInventoryHandler) cdi).getCellInv(); + if (cd != null) { + lines.add(cd.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalBytes() + ' ' + + GuiText.BytesUsed.getLocal()); + lines.add(cd.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + cd.getTotalItemTypes() + ' ' + + GuiText.Types.getLocal()); + } + } + } + + @Override + public int getBytes(final ItemStack cellItem) { + return 512; + } + + @Override + public int BytePerType(final ItemStack cell) { + return 8; + } + + @Override + public int getBytesPerType(final ItemStack cellItem) { + return 8; + } + + @Override + public int getTotalTypes(final ItemStack cellItem) { + return 27; + } + + @Override + public boolean isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) { + return false; + } + + @Override + public boolean storableInStorageCell() { + return false; + } + + @Override + public boolean isStorageCell(final ItemStack i) { + return true; + } + + @Override + public double getIdleDrain() { + return 0.5; + } + + @Override + public String getUnlocalizedGroupName(final Set others, final ItemStack is) { + return GuiText.StorageCells.getUnlocalized(); + } + + @Override + public boolean isEditable(final ItemStack is) { + return true; + } + + @Override + public IInventory getUpgradesInventory(final ItemStack is) { + return new CellUpgrades(is, 2); + } + + @Override + public IInventory getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } + + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + final String fz = Platform.openNbtData(is).getString("FuzzyMode"); + try { + return FuzzyMode.valueOf(fz); + } catch (final Throwable t) { + return FuzzyMode.IGNORE_ALL; + } + } + + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { + Platform.openNbtData(is).setString("FuzzyMode", fzMode.name()); + } + + @Override + public IGuiItemObject getGuiObject(final ItemStack is, final World w, final int x, final int y, final int z) { + return new PortableCellViewer(is, x); + } + + @Override + public String getOreFilter(ItemStack is) { + return Platform.openNbtData(is).getString("OreFilter"); + } + + @Override + public void setOreFilter(ItemStack is, String filter) { + Platform.openNbtData(is).setString("OreFilter", filter); + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java b/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java index 4027216e834..f0371bed9b4 100644 --- a/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java +++ b/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java @@ -18,7 +18,6 @@ package appeng.items.tools.powered; - import appeng.api.AEApi; import appeng.api.config.Settings; import appeng.api.config.SortDir; @@ -36,6 +35,8 @@ import com.google.common.base.Optional; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -43,115 +44,92 @@ import net.minecraft.world.World; import net.minecraftforge.event.ForgeEventFactory; -import java.util.EnumSet; -import java.util.List; - +public class ToolWirelessTerminal extends AEBasePoweredItem implements IWirelessTermHandler { -public class ToolWirelessTerminal extends AEBasePoweredItem implements IWirelessTermHandler -{ + public ToolWirelessTerminal() { + super(AEConfig.instance.wirelessTerminalBattery, Optional.absent()); + this.setFeature(EnumSet.of(AEFeature.WirelessAccessTerminal, AEFeature.PoweredTools)); + } - public ToolWirelessTerminal() - { - super( AEConfig.instance.wirelessTerminalBattery, Optional.absent() ); - this.setFeature( EnumSet.of( AEFeature.WirelessAccessTerminal, AEFeature.PoweredTools ) ); - } + @Override + public ItemStack onItemRightClick(final ItemStack item, final World w, final EntityPlayer player) { + if (ForgeEventFactory.onItemUseStart(player, item, 1) > 0) + AEApi.instance().registries().wireless().openWirelessTerminalGui(item, w, player); + return item; + } - @Override - public ItemStack onItemRightClick( final ItemStack item, final World w, final EntityPlayer player ) - { - if( ForgeEventFactory.onItemUseStart( player, item, 1 ) > 0 ) - AEApi.instance().registries().wireless().openWirelessTerminalGui( item, w, player ); - return item; - } - - @SideOnly( Side.CLIENT ) - @Override - public boolean isFull3D() - { - return false; - } + @SideOnly(Side.CLIENT) + @Override + public boolean isFull3D() { + return false; + } @SideOnly(Side.CLIENT) - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - super.addCheckedInformation( stack, player, lines, displayMoreInfo ); - - if( stack.hasTagCompound() ) - { - final NBTTagCompound tag = Platform.openNbtData( stack ); - if( tag != null ) - { - final String encKey = tag.getString( "encryptionKey" ); - - if( encKey == null || encKey.isEmpty() ) - { - lines.add( GuiText.Unlinked.getLocal() ); - } - else - { - lines.add( GuiText.Linked.getLocal() ); - } - } - } - else - { - lines.add( StatCollector.translateToLocal( "AppEng.GuiITooltip.Unlinked" ) ); - } - } - - @Override - public boolean canHandle( final ItemStack is ) - { - return AEApi.instance().definitions().items().wirelessTerminal().isSameAs( is ); - } - - @Override - public boolean usePower( final EntityPlayer player, final double amount, final ItemStack is ) - { - return this.extractAEPower( is, amount ) >= amount - 0.5; - } - - @Override - public boolean hasPower( final EntityPlayer player, final double amt, final ItemStack is ) - { - return this.getAECurrentPower( is ) >= amt; - } - - @Override - public IConfigManager getConfigManager( final ItemStack target ) - { - final ConfigManager out = new ConfigManager( new IConfigManagerHost() - { - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - final NBTTagCompound data = Platform.openNbtData( target ); - manager.writeToNBT( data ); - } - } ); - - out.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - out.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - out.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); - - out.readFromNBT( (NBTTagCompound) Platform.openNbtData( target ).copy() ); - return out; - } - - @Override - public String getEncryptionKey( final ItemStack item ) - { - final NBTTagCompound tag = Platform.openNbtData( item ); - return tag.getString( "encryptionKey" ); - } - - @Override - public void setEncryptionKey( final ItemStack item, final String encKey, final String name ) - { - final NBTTagCompound tag = Platform.openNbtData( item ); - tag.setString( "encryptionKey", encKey ); - tag.setString( "name", name ); - } + @Override + public void addCheckedInformation( + final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo) { + super.addCheckedInformation(stack, player, lines, displayMoreInfo); + + if (stack.hasTagCompound()) { + final NBTTagCompound tag = Platform.openNbtData(stack); + if (tag != null) { + final String encKey = tag.getString("encryptionKey"); + + if (encKey == null || encKey.isEmpty()) { + lines.add(GuiText.Unlinked.getLocal()); + } else { + lines.add(GuiText.Linked.getLocal()); + } + } + } else { + lines.add(StatCollector.translateToLocal("AppEng.GuiITooltip.Unlinked")); + } + } + + @Override + public boolean canHandle(final ItemStack is) { + return AEApi.instance().definitions().items().wirelessTerminal().isSameAs(is); + } + + @Override + public boolean usePower(final EntityPlayer player, final double amount, final ItemStack is) { + return this.extractAEPower(is, amount) >= amount - 0.5; + } + + @Override + public boolean hasPower(final EntityPlayer player, final double amt, final ItemStack is) { + return this.getAECurrentPower(is) >= amt; + } + + @Override + public IConfigManager getConfigManager(final ItemStack target) { + final ConfigManager out = new ConfigManager(new IConfigManagerHost() { + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + final NBTTagCompound data = Platform.openNbtData(target); + manager.writeToNBT(data); + } + }); + + out.registerSetting(Settings.SORT_BY, SortOrder.NAME); + out.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + out.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); + + out.readFromNBT((NBTTagCompound) Platform.openNbtData(target).copy()); + return out; + } + + @Override + public String getEncryptionKey(final ItemStack item) { + final NBTTagCompound tag = Platform.openNbtData(item); + return tag.getString("encryptionKey"); + } + + @Override + public void setEncryptionKey(final ItemStack item, final String encKey, final String name) { + final NBTTagCompound tag = Platform.openNbtData(item); + tag.setString("encryptionKey", encKey); + tag.setString("name", name); + } } diff --git a/src/main/java/appeng/items/tools/powered/powersink/AEBasePoweredItem.java b/src/main/java/appeng/items/tools/powered/powersink/AEBasePoweredItem.java index 9cd1dedb30a..a1add405587 100644 --- a/src/main/java/appeng/items/tools/powered/powersink/AEBasePoweredItem.java +++ b/src/main/java/appeng/items/tools/powered/powersink/AEBasePoweredItem.java @@ -18,16 +18,12 @@ package appeng.items.tools.powered.powersink; - import com.google.common.base.Optional; +public abstract class AEBasePoweredItem extends RedstoneFlux { + public AEBasePoweredItem(final double powerCapacity, final Optional subName) { + super(powerCapacity, subName); -public abstract class AEBasePoweredItem extends RedstoneFlux -{ - public AEBasePoweredItem( final double powerCapacity, final Optional subName ) - { - super( powerCapacity, subName ); - - this.setMaxStackSize( 1 ); - } + this.setMaxStackSize(1); + } } diff --git a/src/main/java/appeng/items/tools/powered/powersink/AERootPoweredItem.java b/src/main/java/appeng/items/tools/powered/powersink/AERootPoweredItem.java index 4b782645207..e35eda5fea1 100644 --- a/src/main/java/appeng/items/tools/powered/powersink/AERootPoweredItem.java +++ b/src/main/java/appeng/items/tools/powered/powersink/AERootPoweredItem.java @@ -18,7 +18,6 @@ package appeng.items.tools.powered.powersink; - import appeng.api.config.AccessRestriction; import appeng.api.config.PowerUnits; import appeng.api.implementations.items.IAEItemPowerStorage; @@ -26,179 +25,158 @@ import appeng.items.AEBaseItem; import appeng.util.Platform; import com.google.common.base.Optional; +import java.text.MessageFormat; +import java.util.List; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.text.MessageFormat; -import java.util.List; - - -public abstract class AERootPoweredItem extends AEBaseItem implements IAEItemPowerStorage -{ - private static final String POWER_NBT_KEY = "internalCurrentPower"; - private final double powerCapacity; - - public AERootPoweredItem( final double powerCapacity, final Optional subName ) - { - super( subName ); - this.setMaxDamage( 32 ); - this.hasSubtypes = false; - this.setFull3D(); - - this.powerCapacity = powerCapacity; - } - - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - final NBTTagCompound tag = stack.getTagCompound(); - double internalCurrentPower = 0; - final double internalMaxPower = this.getAEMaxPower( stack ); - - if( tag != null ) - { - internalCurrentPower = tag.getDouble( "internalCurrentPower" ); - } - - final double percent = internalCurrentPower / internalMaxPower; - - lines.add( GuiText.StoredEnergy.getLocal() + ':' + MessageFormat.format( " {0,number,#} ", internalCurrentPower ) + Platform.gui_localize( PowerUnits.AE.unlocalizedName ) + " - " + MessageFormat.format( " {0,number,#.##%} ", percent ) ); - } - - @Override - public boolean isDamageable() - { - return true; - } - - @Override - protected void getCheckedSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - super.getCheckedSubItems( sameItem, creativeTab, itemStacks ); - - final ItemStack charged = new ItemStack( this, 1 ); - final NBTTagCompound tag = Platform.openNbtData( charged ); - tag.setDouble( "internalCurrentPower", this.getAEMaxPower( charged ) ); - tag.setDouble( "internalMaxPower", this.getAEMaxPower( charged ) ); - - itemStacks.add( charged ); - } - - @Override - public boolean isRepairable() - { - return false; - } - - @Override - public double getDurabilityForDisplay( final ItemStack is ) - { - return 1 - this.getAECurrentPower( is ) / this.getAEMaxPower( is ); - } - - @Override - public boolean isDamaged( final ItemStack stack ) - { - return true; - } - - @Override - public void setDamage( final ItemStack stack, final int damage ) - { - - } - - private double getInternalBattery( final ItemStack is, final batteryOperation op, final double adjustment ) - { - final NBTTagCompound data = Platform.openNbtData( is ); - - double currentStorage = data.getDouble( POWER_NBT_KEY ); - final double maxStorage = this.getAEMaxPower( is ); - - switch( op ) - { - case INJECT: - currentStorage += adjustment; - if( currentStorage > maxStorage ) - { - final double diff = currentStorage - maxStorage; - data.setDouble( POWER_NBT_KEY, maxStorage ); - return diff; - } - data.setDouble( POWER_NBT_KEY, currentStorage ); - return 0; - case EXTRACT: - if( currentStorage > adjustment ) - { - currentStorage -= adjustment; - data.setDouble( POWER_NBT_KEY, currentStorage ); - return adjustment; - } - data.setDouble( POWER_NBT_KEY, 0 ); - return currentStorage; - default: - break; - } - - return currentStorage; - } - - /** - * inject external - */ - double injectExternalPower( final PowerUnits input, final ItemStack is, final double amount, final boolean simulate ) - { - if( simulate ) - { - final int requiredEU = (int) PowerUnits.AE.convertTo( PowerUnits.EU, this.getAEMaxPower( is ) - this.getAECurrentPower( is ) ); - if( amount < requiredEU ) - { - return 0; - } - return amount - requiredEU; - } - else - { - final double powerRemainder = this.injectAEPower( is, PowerUnits.EU.convertTo( PowerUnits.AE, amount ) ); - return PowerUnits.AE.convertTo( PowerUnits.EU, powerRemainder ); - } - } - - @Override - public double injectAEPower( final ItemStack is, final double amt ) - { - return this.getInternalBattery( is, batteryOperation.INJECT, amt ); - } - - @Override - public double extractAEPower( final ItemStack is, final double amt ) - { - return this.getInternalBattery( is, batteryOperation.EXTRACT, amt ); - } - - @Override - public double getAEMaxPower( final ItemStack is ) - { - return this.powerCapacity; - } - - @Override - public double getAECurrentPower( final ItemStack is ) - { - return this.getInternalBattery( is, batteryOperation.STORAGE, 0 ); - } - - @Override - public AccessRestriction getPowerFlow( final ItemStack is ) - { - return AccessRestriction.WRITE; - } - - private enum batteryOperation - { - STORAGE, INJECT, EXTRACT - } +public abstract class AERootPoweredItem extends AEBaseItem implements IAEItemPowerStorage { + private static final String POWER_NBT_KEY = "internalCurrentPower"; + private final double powerCapacity; + + public AERootPoweredItem(final double powerCapacity, final Optional subName) { + super(subName); + this.setMaxDamage(32); + this.hasSubtypes = false; + this.setFull3D(); + + this.powerCapacity = powerCapacity; + } + + @Override + public void addCheckedInformation( + final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo) { + final NBTTagCompound tag = stack.getTagCompound(); + double internalCurrentPower = 0; + final double internalMaxPower = this.getAEMaxPower(stack); + + if (tag != null) { + internalCurrentPower = tag.getDouble("internalCurrentPower"); + } + + final double percent = internalCurrentPower / internalMaxPower; + + lines.add(GuiText.StoredEnergy.getLocal() + ':' + MessageFormat.format(" {0,number,#} ", internalCurrentPower) + + Platform.gui_localize(PowerUnits.AE.unlocalizedName) + " - " + + MessageFormat.format(" {0,number,#.##%} ", percent)); + } + + @Override + public boolean isDamageable() { + return true; + } + + @Override + protected void getCheckedSubItems( + final Item sameItem, final CreativeTabs creativeTab, final List itemStacks) { + super.getCheckedSubItems(sameItem, creativeTab, itemStacks); + + final ItemStack charged = new ItemStack(this, 1); + final NBTTagCompound tag = Platform.openNbtData(charged); + tag.setDouble("internalCurrentPower", this.getAEMaxPower(charged)); + tag.setDouble("internalMaxPower", this.getAEMaxPower(charged)); + + itemStacks.add(charged); + } + + @Override + public boolean isRepairable() { + return false; + } + + @Override + public double getDurabilityForDisplay(final ItemStack is) { + return 1 - this.getAECurrentPower(is) / this.getAEMaxPower(is); + } + + @Override + public boolean isDamaged(final ItemStack stack) { + return true; + } + + @Override + public void setDamage(final ItemStack stack, final int damage) {} + + private double getInternalBattery(final ItemStack is, final batteryOperation op, final double adjustment) { + final NBTTagCompound data = Platform.openNbtData(is); + + double currentStorage = data.getDouble(POWER_NBT_KEY); + final double maxStorage = this.getAEMaxPower(is); + + switch (op) { + case INJECT: + currentStorage += adjustment; + if (currentStorage > maxStorage) { + final double diff = currentStorage - maxStorage; + data.setDouble(POWER_NBT_KEY, maxStorage); + return diff; + } + data.setDouble(POWER_NBT_KEY, currentStorage); + return 0; + case EXTRACT: + if (currentStorage > adjustment) { + currentStorage -= adjustment; + data.setDouble(POWER_NBT_KEY, currentStorage); + return adjustment; + } + data.setDouble(POWER_NBT_KEY, 0); + return currentStorage; + default: + break; + } + + return currentStorage; + } + + /** + * inject external + */ + double injectExternalPower( + final PowerUnits input, final ItemStack is, final double amount, final boolean simulate) { + if (simulate) { + final int requiredEU = + (int) PowerUnits.AE.convertTo(PowerUnits.EU, this.getAEMaxPower(is) - this.getAECurrentPower(is)); + if (amount < requiredEU) { + return 0; + } + return amount - requiredEU; + } else { + final double powerRemainder = this.injectAEPower(is, PowerUnits.EU.convertTo(PowerUnits.AE, amount)); + return PowerUnits.AE.convertTo(PowerUnits.EU, powerRemainder); + } + } + + @Override + public double injectAEPower(final ItemStack is, final double amt) { + return this.getInternalBattery(is, batteryOperation.INJECT, amt); + } + + @Override + public double extractAEPower(final ItemStack is, final double amt) { + return this.getInternalBattery(is, batteryOperation.EXTRACT, amt); + } + + @Override + public double getAEMaxPower(final ItemStack is) { + return this.powerCapacity; + } + + @Override + public double getAECurrentPower(final ItemStack is) { + return this.getInternalBattery(is, batteryOperation.STORAGE, 0); + } + + @Override + public AccessRestriction getPowerFlow(final ItemStack is) { + return AccessRestriction.WRITE; + } + + private enum batteryOperation { + STORAGE, + INJECT, + EXTRACT + } } diff --git a/src/main/java/appeng/items/tools/powered/powersink/IC2.java b/src/main/java/appeng/items/tools/powered/powersink/IC2.java index f7949353426..b75a585e4d1 100644 --- a/src/main/java/appeng/items/tools/powered/powersink/IC2.java +++ b/src/main/java/appeng/items/tools/powered/powersink/IC2.java @@ -18,7 +18,6 @@ package appeng.items.tools.powered.powersink; - import appeng.api.config.PowerUnits; import appeng.integration.IntegrationType; import appeng.transformer.annotations.Integration.Interface; @@ -31,111 +30,107 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; - -@InterfaceList( value = { @Interface( iface = "ic2.api.item.ISpecialElectricItem", iname = IntegrationType.IC2 ), @Interface( iface = "ic2.api.item.IElectricItemManager", iname = IntegrationType.IC2 ) } ) -public abstract class IC2 extends AERootPoweredItem implements IElectricItemManager, ISpecialElectricItem -{ - public IC2( final double powerCapacity, final Optional subName ) - { - super( powerCapacity, subName ); - } - - @Override - public double charge( final ItemStack is, final double amount, final int tier, final boolean ignoreTransferLimit, final boolean simulate ) - { - double addedAmt = amount; - final double limit = this.getTransferLimit( is ); - - if( !ignoreTransferLimit && amount > limit ) - { - addedAmt = limit; - } - - return addedAmt - ( (int) this.injectExternalPower( PowerUnits.EU, is, addedAmt, simulate ) ); - } - - @Override - public double discharge( final ItemStack itemStack, final double amount, final int tier, final boolean ignoreTransferLimit, final boolean externally, final boolean simulate ) - { - return 0; - } - - @Override - public double getCharge( final ItemStack is ) - { - return (int) PowerUnits.AE.convertTo( PowerUnits.EU, this.getAECurrentPower( is ) ); - } - - @Override - public boolean canUse( final ItemStack is, final double amount ) - { - return this.getCharge( is ) > amount; - } - - @Override - public boolean use( final ItemStack is, final double amount, final EntityLivingBase entity ) - { - if( this.canUse( is, amount ) ) - { - // use the power.. - this.extractAEPower( is, PowerUnits.EU.convertTo( PowerUnits.AE, amount ) ); - return true; - } - return false; - } - - @Override - public void chargeFromArmor( final ItemStack itemStack, final EntityLivingBase entity ) - { - // wtf? - } - - @Override - public String getToolTip( final ItemStack itemStack ) - { - return null; - } - - @Override - public boolean canProvideEnergy( final ItemStack itemStack ) - { - return false; - } - - @Override - public Item getChargedItem( final ItemStack itemStack ) - { - return itemStack.getItem(); - } - - @Override - public Item getEmptyItem( final ItemStack itemStack ) - { - return itemStack.getItem(); - } - - @Override - public double getMaxCharge( final ItemStack itemStack ) - { - return PowerUnits.AE.convertTo( PowerUnits.EU, this.getAEMaxPower( itemStack ) ); - } - - @Override - public int getTier( final ItemStack itemStack ) - { - return 1; - } - - @Override - public double getTransferLimit( final ItemStack itemStack ) - { - return Math.max( 32, this.getMaxCharge( itemStack ) / 200 ); - } - - @Override - @Method( iname = IntegrationType.IC2 ) - public IElectricItemManager getManager( final ItemStack itemStack ) - { - return this; - } +@InterfaceList( + value = { + @Interface(iface = "ic2.api.item.ISpecialElectricItem", iname = IntegrationType.IC2), + @Interface(iface = "ic2.api.item.IElectricItemManager", iname = IntegrationType.IC2) + }) +public abstract class IC2 extends AERootPoweredItem implements IElectricItemManager, ISpecialElectricItem { + public IC2(final double powerCapacity, final Optional subName) { + super(powerCapacity, subName); + } + + @Override + public double charge( + final ItemStack is, + final double amount, + final int tier, + final boolean ignoreTransferLimit, + final boolean simulate) { + double addedAmt = amount; + final double limit = this.getTransferLimit(is); + + if (!ignoreTransferLimit && amount > limit) { + addedAmt = limit; + } + + return addedAmt - ((int) this.injectExternalPower(PowerUnits.EU, is, addedAmt, simulate)); + } + + @Override + public double discharge( + final ItemStack itemStack, + final double amount, + final int tier, + final boolean ignoreTransferLimit, + final boolean externally, + final boolean simulate) { + return 0; + } + + @Override + public double getCharge(final ItemStack is) { + return (int) PowerUnits.AE.convertTo(PowerUnits.EU, this.getAECurrentPower(is)); + } + + @Override + public boolean canUse(final ItemStack is, final double amount) { + return this.getCharge(is) > amount; + } + + @Override + public boolean use(final ItemStack is, final double amount, final EntityLivingBase entity) { + if (this.canUse(is, amount)) { + // use the power.. + this.extractAEPower(is, PowerUnits.EU.convertTo(PowerUnits.AE, amount)); + return true; + } + return false; + } + + @Override + public void chargeFromArmor(final ItemStack itemStack, final EntityLivingBase entity) { + // wtf? + } + + @Override + public String getToolTip(final ItemStack itemStack) { + return null; + } + + @Override + public boolean canProvideEnergy(final ItemStack itemStack) { + return false; + } + + @Override + public Item getChargedItem(final ItemStack itemStack) { + return itemStack.getItem(); + } + + @Override + public Item getEmptyItem(final ItemStack itemStack) { + return itemStack.getItem(); + } + + @Override + public double getMaxCharge(final ItemStack itemStack) { + return PowerUnits.AE.convertTo(PowerUnits.EU, this.getAEMaxPower(itemStack)); + } + + @Override + public int getTier(final ItemStack itemStack) { + return 1; + } + + @Override + public double getTransferLimit(final ItemStack itemStack) { + return Math.max(32, this.getMaxCharge(itemStack) / 200); + } + + @Override + @Method(iname = IntegrationType.IC2) + public IElectricItemManager getManager(final ItemStack itemStack) { + return this; + } } diff --git a/src/main/java/appeng/items/tools/powered/powersink/RedstoneFlux.java b/src/main/java/appeng/items/tools/powered/powersink/RedstoneFlux.java index 455e30f520d..85ead77bab1 100644 --- a/src/main/java/appeng/items/tools/powered/powersink/RedstoneFlux.java +++ b/src/main/java/appeng/items/tools/powered/powersink/RedstoneFlux.java @@ -18,7 +18,6 @@ package appeng.items.tools.powered.powersink; - import appeng.api.config.PowerUnits; import appeng.integration.IntegrationType; import appeng.transformer.annotations.Integration.Interface; @@ -26,36 +25,29 @@ import com.google.common.base.Optional; import net.minecraft.item.ItemStack; - -@Interface( iface = "cofh.api.energy.IEnergyContainerItem", iname = IntegrationType.RFItem ) -public abstract class RedstoneFlux extends IC2 implements IEnergyContainerItem -{ - public RedstoneFlux( final double powerCapacity, final Optional subName ) - { - super( powerCapacity, subName ); - } - - @Override - public int receiveEnergy( final ItemStack is, final int maxReceive, final boolean simulate ) - { - return maxReceive - (int) this.injectExternalPower( PowerUnits.RF, is, maxReceive, simulate ); - } - - @Override - public int extractEnergy( final ItemStack container, final int maxExtract, final boolean simulate ) - { - return 0; - } - - @Override - public int getEnergyStored( final ItemStack is ) - { - return (int) PowerUnits.AE.convertTo( PowerUnits.RF, this.getAECurrentPower( is ) ); - } - - @Override - public int getMaxEnergyStored( final ItemStack is ) - { - return (int) PowerUnits.AE.convertTo( PowerUnits.RF, this.getAEMaxPower( is ) ); - } +@Interface(iface = "cofh.api.energy.IEnergyContainerItem", iname = IntegrationType.RFItem) +public abstract class RedstoneFlux extends IC2 implements IEnergyContainerItem { + public RedstoneFlux(final double powerCapacity, final Optional subName) { + super(powerCapacity, subName); + } + + @Override + public int receiveEnergy(final ItemStack is, final int maxReceive, final boolean simulate) { + return maxReceive - (int) this.injectExternalPower(PowerUnits.RF, is, maxReceive, simulate); + } + + @Override + public int extractEnergy(final ItemStack container, final int maxExtract, final boolean simulate) { + return 0; + } + + @Override + public int getEnergyStored(final ItemStack is) { + return (int) PowerUnits.AE.convertTo(PowerUnits.RF, this.getAECurrentPower(is)); + } + + @Override + public int getMaxEnergyStored(final ItemStack is) { + return (int) PowerUnits.AE.convertTo(PowerUnits.RF, this.getAEMaxPower(is)); + } } diff --git a/src/main/java/appeng/items/tools/powered/powersink/UniversalElectricity.java b/src/main/java/appeng/items/tools/powered/powersink/UniversalElectricity.java index 53e4b3371c8..4c5c625f9ed 100644 --- a/src/main/java/appeng/items/tools/powered/powersink/UniversalElectricity.java +++ b/src/main/java/appeng/items/tools/powered/powersink/UniversalElectricity.java @@ -18,39 +18,37 @@ package appeng.items.tools.powered.powersink; - /* - @Interface(iface = "universalelectricity.core.item.IItemElectric", modid = "IC2") - public class UniversalElectricity extends ThermalExpansion implements IItemElectric - { - * - * public UniversalElectricity(Class c, String subName) { super( c, subName ); } - * - * @Override public float recharge(ItemStack is, float energy, boolean - * doRecharge) { return (float) (energy - injectExternalPower( PowerUnits.KJ, - * is, energy, !doRecharge )); } - * - * @Override public float discharge(ItemStack is, float energy, boolean - * doDischarge) { return 0; } - * - * @Override public float getElectricityStored(ItemStack is) { return (int) - * PowerUnits.AE.convertTo( PowerUnits.KJ, getAECurrentPower( is ) ); } - * - * @Override public float getMaxElectricityStored(ItemStack is) { return (int) - * PowerUnits.AE.convertTo( PowerUnits.KJ, getAEMaxPower( is ) ); } - * - * @Override public void setElectricity(ItemStack is, float joules) { double - * currentPower = getAECurrentPower( is ); double targetPower = - * PowerUnits.KJ.convertTo( PowerUnits.AE, joules ); if ( targetPower > - * currentPower ) injectAEPower( is, targetPower - currentPower ); else - * extractAEPower( is, currentPower - targetPower ); } - * - * @Override public float getTransfer(ItemStack is) { return (float) - * PowerUnits.AE.convertTo( PowerUnits.KJ, getAEMaxPower( is ) - - * getAECurrentPower( is ) ); } - * - * @Override public float getVoltage(ItemStack itemStack) { return 120; } - - } - */ +@Interface(iface = "universalelectricity.core.item.IItemElectric", modid = "IC2") +public class UniversalElectricity extends ThermalExpansion implements IItemElectric +{ +* +* public UniversalElectricity(Class c, String subName) { super( c, subName ); } +* +* @Override public float recharge(ItemStack is, float energy, boolean +* doRecharge) { return (float) (energy - injectExternalPower( PowerUnits.KJ, +* is, energy, !doRecharge )); } +* +* @Override public float discharge(ItemStack is, float energy, boolean +* doDischarge) { return 0; } +* +* @Override public float getElectricityStored(ItemStack is) { return (int) +* PowerUnits.AE.convertTo( PowerUnits.KJ, getAECurrentPower( is ) ); } +* +* @Override public float getMaxElectricityStored(ItemStack is) { return (int) +* PowerUnits.AE.convertTo( PowerUnits.KJ, getAEMaxPower( is ) ); } +* +* @Override public void setElectricity(ItemStack is, float joules) { double +* currentPower = getAECurrentPower( is ); double targetPower = +* PowerUnits.KJ.convertTo( PowerUnits.AE, joules ); if ( targetPower > +* currentPower ) injectAEPower( is, targetPower - currentPower ); else +* extractAEPower( is, currentPower - targetPower ); } +* +* @Override public float getTransfer(ItemStack is) { return (float) +* PowerUnits.AE.convertTo( PowerUnits.KJ, getAEMaxPower( is ) - +* getAECurrentPower( is ) ); } +* +* @Override public float getVoltage(ItemStack itemStack) { return 120; } +} +*/ diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java index 3016c0d02ef..fd5c79c5d3b 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java @@ -18,45 +18,38 @@ package appeng.items.tools.quartz; - import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; import appeng.core.features.IFeatureHandler; import appeng.core.features.ItemFeatureHandler; import appeng.util.Platform; import com.google.common.base.Optional; +import java.util.EnumSet; import net.minecraft.item.ItemAxe; import net.minecraft.item.ItemStack; -import java.util.EnumSet; - - -public class ToolQuartzAxe extends ItemAxe implements IAEFeature -{ - private final AEFeature type; - private final IFeatureHandler feature; - - public ToolQuartzAxe( final AEFeature type ) - { - super( ToolMaterial.IRON ); - this.feature = new ItemFeatureHandler( EnumSet.of( this.type = type, AEFeature.QuartzAxe ), this, this, Optional.of( type.name() ) ); - } - - @Override - public IFeatureHandler handler() - { - return this.feature; - } - - @Override - public void postInit() - { - // override! - } - - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } +public class ToolQuartzAxe extends ItemAxe implements IAEFeature { + private final AEFeature type; + private final IFeatureHandler feature; + + public ToolQuartzAxe(final AEFeature type) { + super(ToolMaterial.IRON); + this.feature = new ItemFeatureHandler( + EnumSet.of(this.type = type, AEFeature.QuartzAxe), this, this, Optional.of(type.name())); + } + + @Override + public IFeatureHandler handler() { + return this.feature; + } + + @Override + public void postInit() { + // override! + } + + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java index bd759901da2..12b93e3fb1a 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java @@ -18,7 +18,6 @@ package appeng.items.tools.quartz; - import appeng.api.implementations.guiobjects.IGuiItem; import appeng.api.implementations.guiobjects.IGuiItemObject; import appeng.core.features.AEFeature; @@ -29,88 +28,83 @@ import appeng.tile.networking.TileCableBus; import appeng.util.Platform; import com.google.common.base.Optional; +import java.util.EnumSet; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class ToolQuartzCuttingKnife extends AEBaseItem implements IGuiItem -{ - private final AEFeature type; - - public ToolQuartzCuttingKnife( final AEFeature type ) - { - super( Optional.of( type.name() ) ); - - this.type = type; - this.setFeature( EnumSet.of( type, AEFeature.QuartzKnife ) ); - this.setMaxDamage( 50 ); - this.setMaxStackSize( 1 ); - } - - @Override - public boolean onItemUse( final ItemStack is, final EntityPlayer p, final World w, final int x, final int y, final int z, final int s, final float hitX, final float hitY, final float hitZ ) - { - if( Platform.isServer() ) - { - TileEntity te = w.getTileEntity(x,y, z); - if (te instanceof AEBaseTile && !(te instanceof TileCableBus)) - Platform.openGUI( p, te, ForgeDirection.getOrientation( s ), GuiBridge.GUI_RENAMER ); - else - Platform.openGUI( p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_QUARTZ_KNIFE ); - } - return true; - } - - @Override - public ItemStack onItemRightClick( final ItemStack it, final World w, final EntityPlayer p ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_QUARTZ_KNIFE ); - } - p.swingItem(); - return it; - } - - @Override - public boolean doesContainerItemLeaveCraftingGrid( final ItemStack par1ItemStack ) - { - return false; - } - - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } - - @Override - public boolean isRepairable() - { - return false; - } - - @Override - public ItemStack getContainerItem( final ItemStack itemStack ) - { - itemStack.setItemDamage( itemStack.getItemDamage() + 1 ); - return itemStack; - } - - @Override - public boolean hasContainerItem( final ItemStack stack ) - { - return true; - } - - @Override - public IGuiItemObject getGuiObject( final ItemStack is, final World world, final int x, final int y, final int z ) - { - return new QuartzKnifeObj( is ); - } +public class ToolQuartzCuttingKnife extends AEBaseItem implements IGuiItem { + private final AEFeature type; + + public ToolQuartzCuttingKnife(final AEFeature type) { + super(Optional.of(type.name())); + + this.type = type; + this.setFeature(EnumSet.of(type, AEFeature.QuartzKnife)); + this.setMaxDamage(50); + this.setMaxStackSize(1); + } + + @Override + public boolean onItemUse( + final ItemStack is, + final EntityPlayer p, + final World w, + final int x, + final int y, + final int z, + final int s, + final float hitX, + final float hitY, + final float hitZ) { + if (Platform.isServer()) { + TileEntity te = w.getTileEntity(x, y, z); + if (te instanceof AEBaseTile && !(te instanceof TileCableBus)) + Platform.openGUI(p, te, ForgeDirection.getOrientation(s), GuiBridge.GUI_RENAMER); + else Platform.openGUI(p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_QUARTZ_KNIFE); + } + return true; + } + + @Override + public ItemStack onItemRightClick(final ItemStack it, final World w, final EntityPlayer p) { + if (Platform.isServer()) { + Platform.openGUI(p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_QUARTZ_KNIFE); + } + p.swingItem(); + return it; + } + + @Override + public boolean doesContainerItemLeaveCraftingGrid(final ItemStack par1ItemStack) { + return false; + } + + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } + + @Override + public boolean isRepairable() { + return false; + } + + @Override + public ItemStack getContainerItem(final ItemStack itemStack) { + itemStack.setItemDamage(itemStack.getItemDamage() + 1); + return itemStack; + } + + @Override + public boolean hasContainerItem(final ItemStack stack) { + return true; + } + + @Override + public IGuiItemObject getGuiObject(final ItemStack is, final World world, final int x, final int y, final int z) { + return new QuartzKnifeObj(is); + } } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzHoe.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzHoe.java index ea9b5a6b5d6..01abfe1a0bd 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzHoe.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzHoe.java @@ -18,47 +18,40 @@ package appeng.items.tools.quartz; - import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; import appeng.core.features.IFeatureHandler; import appeng.core.features.ItemFeatureHandler; import appeng.util.Platform; import com.google.common.base.Optional; +import java.util.EnumSet; import net.minecraft.item.ItemHoe; import net.minecraft.item.ItemStack; -import java.util.EnumSet; - - -public class ToolQuartzHoe extends ItemHoe implements IAEFeature -{ - private final AEFeature feature; - private final IFeatureHandler handler; - - public ToolQuartzHoe( final AEFeature feature ) - { - super( ToolMaterial.IRON ); - - this.feature = feature; - this.handler = new ItemFeatureHandler( EnumSet.of( feature, AEFeature.QuartzHoe ), this, this, Optional.of( feature.name() ) ); - } - - @Override - public IFeatureHandler handler() - { - return this.handler; - } - - @Override - public void postInit() - { - // override! - } - - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.feature, a, b ); - } -} \ No newline at end of file +public class ToolQuartzHoe extends ItemHoe implements IAEFeature { + private final AEFeature feature; + private final IFeatureHandler handler; + + public ToolQuartzHoe(final AEFeature feature) { + super(ToolMaterial.IRON); + + this.feature = feature; + this.handler = new ItemFeatureHandler( + EnumSet.of(feature, AEFeature.QuartzHoe), this, this, Optional.of(feature.name())); + } + + @Override + public IFeatureHandler handler() { + return this.handler; + } + + @Override + public void postInit() { + // override! + } + + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.feature, a, b); + } +} diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java index 505ebc2b3f6..9bcccee70b4 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java @@ -18,47 +18,40 @@ package appeng.items.tools.quartz; - import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; import appeng.core.features.IFeatureHandler; import appeng.core.features.ItemFeatureHandler; import appeng.util.Platform; import com.google.common.base.Optional; +import java.util.EnumSet; import net.minecraft.item.ItemPickaxe; import net.minecraft.item.ItemStack; -import java.util.EnumSet; - - -public class ToolQuartzPickaxe extends ItemPickaxe implements IAEFeature -{ - private final AEFeature type; - private final IFeatureHandler feature; +public class ToolQuartzPickaxe extends ItemPickaxe implements IAEFeature { + private final AEFeature type; + private final IFeatureHandler feature; - public ToolQuartzPickaxe( final AEFeature type ) - { - super( ToolMaterial.IRON ); + public ToolQuartzPickaxe(final AEFeature type) { + super(ToolMaterial.IRON); - this.type = type; - this.feature = new ItemFeatureHandler( EnumSet.of( type, AEFeature.QuartzPickaxe ), this, this, Optional.of( type.name() ) ); - } + this.type = type; + this.feature = + new ItemFeatureHandler(EnumSet.of(type, AEFeature.QuartzPickaxe), this, this, Optional.of(type.name())); + } - @Override - public IFeatureHandler handler() - { - return this.feature; - } + @Override + public IFeatureHandler handler() { + return this.feature; + } - @Override - public void postInit() - { - // override! - } + @Override + public void postInit() { + // override! + } - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java index b5488012294..03067d6f7cb 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java @@ -18,46 +18,39 @@ package appeng.items.tools.quartz; - import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; import appeng.core.features.IFeatureHandler; import appeng.core.features.ItemFeatureHandler; import appeng.util.Platform; import com.google.common.base.Optional; +import java.util.EnumSet; import net.minecraft.item.ItemSpade; import net.minecraft.item.ItemStack; -import java.util.EnumSet; - - -public class ToolQuartzSpade extends ItemSpade implements IAEFeature -{ - private final AEFeature type; - private final IFeatureHandler handler; +public class ToolQuartzSpade extends ItemSpade implements IAEFeature { + private final AEFeature type; + private final IFeatureHandler handler; - public ToolQuartzSpade( final AEFeature type ) - { - super( ToolMaterial.IRON ); + public ToolQuartzSpade(final AEFeature type) { + super(ToolMaterial.IRON); - this.handler = new ItemFeatureHandler( EnumSet.of( this.type = type, AEFeature.QuartzSpade ), this, this, Optional.of( type.name() ) ); - } + this.handler = new ItemFeatureHandler( + EnumSet.of(this.type = type, AEFeature.QuartzSpade), this, this, Optional.of(type.name())); + } - @Override - public IFeatureHandler handler() - { - return this.handler; - } + @Override + public IFeatureHandler handler() { + return this.handler; + } - @Override - public void postInit() - { - // override! - } + @Override + public void postInit() { + // override! + } - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java index ccc3cbe2f21..dde30cbdaf8 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java @@ -18,45 +18,38 @@ package appeng.items.tools.quartz; - import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; import appeng.core.features.IFeatureHandler; import appeng.core.features.ItemFeatureHandler; import appeng.util.Platform; import com.google.common.base.Optional; +import java.util.EnumSet; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; -import java.util.EnumSet; - - -public class ToolQuartzSword extends ItemSword implements IAEFeature -{ - private final AEFeature type; - private final IFeatureHandler feature; - - public ToolQuartzSword( final AEFeature type ) - { - super( ToolMaterial.IRON ); - this.feature = new ItemFeatureHandler( EnumSet.of( this.type = type, AEFeature.QuartzSword ), this, this, Optional.of( type.name() ) ); - } - - @Override - public IFeatureHandler handler() - { - return this.feature; - } - - @Override - public void postInit() - { - // override! - } - - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } +public class ToolQuartzSword extends ItemSword implements IAEFeature { + private final AEFeature type; + private final IFeatureHandler feature; + + public ToolQuartzSword(final AEFeature type) { + super(ToolMaterial.IRON); + this.feature = new ItemFeatureHandler( + EnumSet.of(this.type = type, AEFeature.QuartzSword), this, this, Optional.of(type.name())); + } + + @Override + public IFeatureHandler handler() { + return this.feature; + } + + @Override + public void postInit() { + // override! + } + + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java index 50db358fb87..dacba524ea8 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java @@ -18,7 +18,6 @@ package appeng.items.tools.quartz; - import appeng.api.implementations.items.IAEWrench; import appeng.api.util.DimensionalCoord; import appeng.core.features.AEFeature; @@ -28,6 +27,7 @@ import appeng.util.Platform; import buildcraft.api.tools.IToolWrench; import com.google.common.base.Optional; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -36,75 +36,82 @@ import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import java.util.EnumSet; - - -@Interface( iface = "buildcraft.api.tools.IToolWrench", iname = IntegrationType.BuildCraftCore ) -public class ToolQuartzWrench extends AEBaseItem implements IAEWrench, IToolWrench -{ - - public ToolQuartzWrench( final AEFeature type ) - { - super( Optional.of( type.name() ) ); - - this.setFeature( EnumSet.of( type, AEFeature.QuartzWrench ) ); - this.setMaxStackSize( 1 ); - this.setHarvestLevel( "wrench", 0 ); - } - - @Override - public boolean onItemUseFirst( final ItemStack is, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, is, 1 ) <= 0 ) - return true; - - final Block b = world.getBlock( x, y, z ); - - if( b != null && ForgeEventFactory.onPlayerInteract( player, - b.isAir( world, x, y, z ) ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, - x, y, z, side, world ).isCanceled() ) - return true; - - if( b != null && !player.isSneaking() && Platform.hasPermissions( new DimensionalCoord( world, x, y, z ), player ) ) - { - if( Platform.isClient() ) - { - return !world.isRemote; - } - - final ForgeDirection mySide = ForgeDirection.getOrientation( side ); - if( b.rotateBlock( world, x, y, z, mySide ) ) - { - b.onNeighborBlockChange( world, x, y, z, Platform.AIR_BLOCK ); - player.swingItem(); - return !world.isRemote; - } - } - return false; - } - - @Override - // public boolean shouldPassSneakingClickToBlock(World w, int x, int y, int z) - public boolean doesSneakBypassUse( final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - return true; - } - - @Override - public boolean canWrench( final ItemStack is, final EntityPlayer player, final int x, final int y, final int z ) - { - return true; - } - - @Override - public boolean canWrench( final EntityPlayer player, final int x, final int y, final int z ) - { - return true; - } - - @Override - public void wrenchUsed( final EntityPlayer player, final int x, final int y, final int z ) - { - player.swingItem(); - } +@Interface(iface = "buildcraft.api.tools.IToolWrench", iname = IntegrationType.BuildCraftCore) +public class ToolQuartzWrench extends AEBaseItem implements IAEWrench, IToolWrench { + + public ToolQuartzWrench(final AEFeature type) { + super(Optional.of(type.name())); + + this.setFeature(EnumSet.of(type, AEFeature.QuartzWrench)); + this.setMaxStackSize(1); + this.setHarvestLevel("wrench", 0); + } + + @Override + public boolean onItemUseFirst( + final ItemStack is, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + if (ForgeEventFactory.onItemUseStart(player, is, 1) <= 0) return true; + + final Block b = world.getBlock(x, y, z); + + if (b != null + && ForgeEventFactory.onPlayerInteract( + player, + b.isAir(world, x, y, z) + ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR + : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, + x, + y, + z, + side, + world) + .isCanceled()) return true; + + if (b != null + && !player.isSneaking() + && Platform.hasPermissions(new DimensionalCoord(world, x, y, z), player)) { + if (Platform.isClient()) { + return !world.isRemote; + } + + final ForgeDirection mySide = ForgeDirection.getOrientation(side); + if (b.rotateBlock(world, x, y, z, mySide)) { + b.onNeighborBlockChange(world, x, y, z, Platform.AIR_BLOCK); + player.swingItem(); + return !world.isRemote; + } + } + return false; + } + + @Override + // public boolean shouldPassSneakingClickToBlock(World w, int x, int y, int z) + public boolean doesSneakBypassUse( + final World world, final int x, final int y, final int z, final EntityPlayer player) { + return true; + } + + @Override + public boolean canWrench(final ItemStack is, final EntityPlayer player, final int x, final int y, final int z) { + return true; + } + + @Override + public boolean canWrench(final EntityPlayer player, final int x, final int y, final int z) { + return true; + } + + @Override + public void wrenchUsed(final EntityPlayer player, final int x, final int y, final int z) { + player.swingItem(); + } } diff --git a/src/main/java/appeng/me/Grid.java b/src/main/java/appeng/me/Grid.java index 870f38068c6..454790d71cd 100644 --- a/src/main/java/appeng/me/Grid.java +++ b/src/main/java/appeng/me/Grid.java @@ -18,7 +18,6 @@ package appeng.me; - import appeng.api.AEApi; import appeng.api.networking.*; import appeng.api.networking.events.MENetworkEvent; @@ -27,302 +26,250 @@ import appeng.core.worlddata.WorldData; import appeng.hooks.TickHandler; import appeng.util.ReadOnlyCollection; - import java.util.*; import java.util.Map.Entry; - -public class Grid implements IGrid -{ - private final NetworkEventBus eventBus = new NetworkEventBus(); - private final Map, MachineSet> machines = new HashMap, MachineSet>(); - private final Map, GridCacheWrapper> caches = new HashMap, GridCacheWrapper>(); - private GridNode pivot; - private int priority; // how import is this network? - private GridStorage myStorage; - private int[] timeStatistics = null; - private static final int PROFILING_SAMPLE_COUNT = 200; - private int timeStatisticsIndex = 0; - private boolean profilingPassedFullCycle = false; - - public Grid( final GridNode center ) - { - this.pivot = center; - - final Map, IGridCache> myCaches = AEApi.instance().registries().gridCache().createCacheInstance( this ); - for( final Entry, IGridCache> c : myCaches.entrySet() ) - { - final Class key = c.getKey(); - final IGridCache value = c.getValue(); - final Class valueClass = value.getClass(); - - this.eventBus.readClass( key, valueClass ); - this.caches.put( key, new GridCacheWrapper( value ) ); - } - - this.postEvent( new MENetworkPostCacheConstruction() ); - - TickHandler.INSTANCE.addNetwork( this ); - center.setGrid( this ); - } - - int getPriority() - { - return this.priority; - } - - IGridStorage getMyStorage() - { - return this.myStorage; - } - - Map, GridCacheWrapper> getCaches() - { - return this.caches; - } - - public Iterable> getMachineClasses() - { - return this.machines.keySet(); - } - - int size() - { - int out = 0; - for( final Collection x : this.machines.values() ) - { - out += x.size(); - } - return out; - } - - void remove( final GridNode gridNode ) - { - for( final IGridCache c : this.caches.values() ) - { - final IGridHost machine = gridNode.getMachine(); - c.removeNode( gridNode, machine ); - } - - final Class machineClass = gridNode.getMachineClass(); - final Set nodes = this.machines.get( machineClass ); - if( nodes != null ) - { - nodes.remove( gridNode ); - } - - gridNode.setGridStorage( null ); - - if( this.pivot == gridNode ) - { - final Iterator n = this.getNodes().iterator(); - if( n.hasNext() ) - { - this.pivot = (GridNode) n.next(); - } - else - { - this.pivot = null; - TickHandler.INSTANCE.removeNetwork( this ); - this.myStorage.remove(); - } - } - } - - void add( final GridNode gridNode ) - { - final Class mClass = gridNode.getMachineClass(); - - MachineSet nodes = this.machines.get( mClass ); - if( nodes == null ) - { - nodes = new MachineSet( mClass ); - this.machines.put( mClass, nodes ); - this.eventBus.readClass( mClass, mClass ); - } - - // handle loading grid storages. - if( gridNode.getGridStorage() != null ) - { - final GridStorage gs = gridNode.getGridStorage(); - final IGrid grid = gs.getGrid(); - - if( grid == null ) - { - this.myStorage = gs; - this.myStorage.setGrid( this ); - - for( final IGridCache gc : this.caches.values() ) - { - gc.onJoin( this.myStorage ); - } - } - else if( grid != this ) - { - if( this.myStorage == null ) - { - this.myStorage = WorldData.instance().storageData().getNewGridStorage(); - this.myStorage.setGrid( this ); - } - - final IGridStorage tmp = new GridStorage(); - if( !gs.hasDivided( this.myStorage ) ) - { - gs.addDivided( this.myStorage ); - - for( final IGridCache gc : ( (Grid) grid ).caches.values() ) - { - gc.onSplit( tmp ); - } - - for( final IGridCache gc : this.caches.values() ) - { - gc.onJoin( tmp ); - } - } - } - } - else if( this.myStorage == null ) - { - this.myStorage = WorldData.instance().storageData().getNewGridStorage(); - this.myStorage.setGrid( this ); - } - - // update grid node... - gridNode.setGridStorage( this.myStorage ); - - // track node. - nodes.add( gridNode ); - - for( final IGridCache cache : this.caches.values() ) - { - final IGridHost machine = gridNode.getMachine(); - cache.addNode( gridNode, machine ); - } - - gridNode.getGridProxy().gridChanged(); - // postEventTo( gridNode, networkChanged ); - } - - @Override - @SuppressWarnings( "unchecked" ) - public C getCache( final Class iface ) - { - return (C) this.caches.get( iface ).getCache(); - } - - @Override - public MENetworkEvent postEvent( final MENetworkEvent ev ) - { - return this.eventBus.postEvent( this, ev ); - } - - @Override - public MENetworkEvent postEventTo( final IGridNode node, final MENetworkEvent ev ) - { - return this.eventBus.postEventTo( this, (GridNode) node, ev ); - } - - @Override - public IReadOnlyCollection> getMachinesClasses() - { - final Set> machineKeys = this.machines.keySet(); - - return new ReadOnlyCollection>( machineKeys ); - } - - @Override - public IMachineSet getMachines( final Class c ) - { - final MachineSet s = this.machines.get( c ); - if( s == null ) - { - return new MachineSet( c ); - } - return s; - } - - @Override - public IReadOnlyCollection getNodes() - { - return new GridNodeCollection( this.machines ); - } - - @Override - public boolean isEmpty() - { - return this.pivot == null; - } - - @Override - public IGridNode getPivot() - { - return this.pivot; - } - - void setPivot( final GridNode pivot ) - { - this.pivot = pivot; - } - - public void startProfiling() - { - timeStatistics = new int[PROFILING_SAMPLE_COUNT]; - profilingPassedFullCycle = false; - } - - public int stopProfiling() - { - if( timeStatistics == null ) - return 0; - long sum = 0; - int N = profilingPassedFullCycle ? PROFILING_SAMPLE_COUNT : timeStatisticsIndex; - for (int i = 0; i < N; ++i) - sum += timeStatistics[i]; - timeStatistics = null; - return (int)(sum / N); - } - - public boolean isProfiling() - { - return timeStatistics != null; - } - - public void update() - { - long time = 0; - if( isProfiling() ) - time = System.nanoTime(); - for( final IGridCache gc : this.caches.values() ) - { - // are there any nodes left? - if( this.pivot != null ) - { - gc.onUpdateTick(); - } - } - if( isProfiling() ) - { - ++timeStatisticsIndex; - if (timeStatisticsIndex == PROFILING_SAMPLE_COUNT) { - profilingPassedFullCycle = true; - timeStatisticsIndex = 0; - } - timeStatistics[timeStatisticsIndex] = (int) (System.nanoTime() - time); - } - } - - void saveState() - { - for( final IGridCache c : this.caches.values() ) - { - c.populateGridStorage( this.myStorage ); - } - } - - public void setImportantFlag( final int i, final boolean publicHasPower ) - { - final int flag = 1 << i; - this.priority = ( this.priority & ~flag ) | ( publicHasPower ? flag : 0 ); - } +public class Grid implements IGrid { + private final NetworkEventBus eventBus = new NetworkEventBus(); + private final Map, MachineSet> machines = + new HashMap, MachineSet>(); + private final Map, GridCacheWrapper> caches = + new HashMap, GridCacheWrapper>(); + private GridNode pivot; + private int priority; // how import is this network? + private GridStorage myStorage; + private int[] timeStatistics = null; + private static final int PROFILING_SAMPLE_COUNT = 200; + private int timeStatisticsIndex = 0; + private boolean profilingPassedFullCycle = false; + + public Grid(final GridNode center) { + this.pivot = center; + + final Map, IGridCache> myCaches = + AEApi.instance().registries().gridCache().createCacheInstance(this); + for (final Entry, IGridCache> c : myCaches.entrySet()) { + final Class key = c.getKey(); + final IGridCache value = c.getValue(); + final Class valueClass = value.getClass(); + + this.eventBus.readClass(key, valueClass); + this.caches.put(key, new GridCacheWrapper(value)); + } + + this.postEvent(new MENetworkPostCacheConstruction()); + + TickHandler.INSTANCE.addNetwork(this); + center.setGrid(this); + } + + int getPriority() { + return this.priority; + } + + IGridStorage getMyStorage() { + return this.myStorage; + } + + Map, GridCacheWrapper> getCaches() { + return this.caches; + } + + public Iterable> getMachineClasses() { + return this.machines.keySet(); + } + + int size() { + int out = 0; + for (final Collection x : this.machines.values()) { + out += x.size(); + } + return out; + } + + void remove(final GridNode gridNode) { + for (final IGridCache c : this.caches.values()) { + final IGridHost machine = gridNode.getMachine(); + c.removeNode(gridNode, machine); + } + + final Class machineClass = gridNode.getMachineClass(); + final Set nodes = this.machines.get(machineClass); + if (nodes != null) { + nodes.remove(gridNode); + } + + gridNode.setGridStorage(null); + + if (this.pivot == gridNode) { + final Iterator n = this.getNodes().iterator(); + if (n.hasNext()) { + this.pivot = (GridNode) n.next(); + } else { + this.pivot = null; + TickHandler.INSTANCE.removeNetwork(this); + this.myStorage.remove(); + } + } + } + + void add(final GridNode gridNode) { + final Class mClass = gridNode.getMachineClass(); + + MachineSet nodes = this.machines.get(mClass); + if (nodes == null) { + nodes = new MachineSet(mClass); + this.machines.put(mClass, nodes); + this.eventBus.readClass(mClass, mClass); + } + + // handle loading grid storages. + if (gridNode.getGridStorage() != null) { + final GridStorage gs = gridNode.getGridStorage(); + final IGrid grid = gs.getGrid(); + + if (grid == null) { + this.myStorage = gs; + this.myStorage.setGrid(this); + + for (final IGridCache gc : this.caches.values()) { + gc.onJoin(this.myStorage); + } + } else if (grid != this) { + if (this.myStorage == null) { + this.myStorage = WorldData.instance().storageData().getNewGridStorage(); + this.myStorage.setGrid(this); + } + + final IGridStorage tmp = new GridStorage(); + if (!gs.hasDivided(this.myStorage)) { + gs.addDivided(this.myStorage); + + for (final IGridCache gc : ((Grid) grid).caches.values()) { + gc.onSplit(tmp); + } + + for (final IGridCache gc : this.caches.values()) { + gc.onJoin(tmp); + } + } + } + } else if (this.myStorage == null) { + this.myStorage = WorldData.instance().storageData().getNewGridStorage(); + this.myStorage.setGrid(this); + } + + // update grid node... + gridNode.setGridStorage(this.myStorage); + + // track node. + nodes.add(gridNode); + + for (final IGridCache cache : this.caches.values()) { + final IGridHost machine = gridNode.getMachine(); + cache.addNode(gridNode, machine); + } + + gridNode.getGridProxy().gridChanged(); + // postEventTo( gridNode, networkChanged ); + } + + @Override + @SuppressWarnings("unchecked") + public C getCache(final Class iface) { + return (C) this.caches.get(iface).getCache(); + } + + @Override + public MENetworkEvent postEvent(final MENetworkEvent ev) { + return this.eventBus.postEvent(this, ev); + } + + @Override + public MENetworkEvent postEventTo(final IGridNode node, final MENetworkEvent ev) { + return this.eventBus.postEventTo(this, (GridNode) node, ev); + } + + @Override + public IReadOnlyCollection> getMachinesClasses() { + final Set> machineKeys = this.machines.keySet(); + + return new ReadOnlyCollection>(machineKeys); + } + + @Override + public IMachineSet getMachines(final Class c) { + final MachineSet s = this.machines.get(c); + if (s == null) { + return new MachineSet(c); + } + return s; + } + + @Override + public IReadOnlyCollection getNodes() { + return new GridNodeCollection(this.machines); + } + + @Override + public boolean isEmpty() { + return this.pivot == null; + } + + @Override + public IGridNode getPivot() { + return this.pivot; + } + + void setPivot(final GridNode pivot) { + this.pivot = pivot; + } + + public void startProfiling() { + timeStatistics = new int[PROFILING_SAMPLE_COUNT]; + profilingPassedFullCycle = false; + } + + public int stopProfiling() { + if (timeStatistics == null) return 0; + long sum = 0; + int N = profilingPassedFullCycle ? PROFILING_SAMPLE_COUNT : timeStatisticsIndex; + for (int i = 0; i < N; ++i) sum += timeStatistics[i]; + timeStatistics = null; + return (int) (sum / N); + } + + public boolean isProfiling() { + return timeStatistics != null; + } + + public void update() { + long time = 0; + if (isProfiling()) time = System.nanoTime(); + for (final IGridCache gc : this.caches.values()) { + // are there any nodes left? + if (this.pivot != null) { + gc.onUpdateTick(); + } + } + if (isProfiling()) { + ++timeStatisticsIndex; + if (timeStatisticsIndex == PROFILING_SAMPLE_COUNT) { + profilingPassedFullCycle = true; + timeStatisticsIndex = 0; + } + timeStatistics[timeStatisticsIndex] = (int) (System.nanoTime() - time); + } + } + + void saveState() { + for (final IGridCache c : this.caches.values()) { + c.populateGridStorage(this.myStorage); + } + } + + public void setImportantFlag(final int i, final boolean publicHasPower) { + final int flag = 1 << i; + this.priority = (this.priority & ~flag) | (publicHasPower ? flag : 0); + } } diff --git a/src/main/java/appeng/me/GridAccessException.java b/src/main/java/appeng/me/GridAccessException.java index 6877e217697..1442d9202c3 100644 --- a/src/main/java/appeng/me/GridAccessException.java +++ b/src/main/java/appeng/me/GridAccessException.java @@ -18,9 +18,7 @@ package appeng.me; +public class GridAccessException extends Exception { -public class GridAccessException extends Exception -{ - - private static final long serialVersionUID = 3914554394866375300L; + private static final long serialVersionUID = 3914554394866375300L; } diff --git a/src/main/java/appeng/me/GridCacheWrapper.java b/src/main/java/appeng/me/GridCacheWrapper.java index 2825faa45c8..d3bf5cd07e9 100644 --- a/src/main/java/appeng/me/GridCacheWrapper.java +++ b/src/main/java/appeng/me/GridCacheWrapper.java @@ -18,68 +18,56 @@ package appeng.me; - import appeng.api.networking.IGridCache; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.networking.IGridStorage; +public class GridCacheWrapper implements IGridCache { -public class GridCacheWrapper implements IGridCache -{ - - private final IGridCache myCache; - private final String name; + private final IGridCache myCache; + private final String name; - public GridCacheWrapper( final IGridCache gc ) - { - this.myCache = gc; - this.name = this.getCache().getClass().getName(); - } + public GridCacheWrapper(final IGridCache gc) { + this.myCache = gc; + this.name = this.getCache().getClass().getName(); + } - @Override - public void onUpdateTick() - { - this.getCache().onUpdateTick(); - } + @Override + public void onUpdateTick() { + this.getCache().onUpdateTick(); + } - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - this.getCache().removeNode( gridNode, machine ); - } + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + this.getCache().removeNode(gridNode, machine); + } - @Override - public void addNode( final IGridNode gridNode, final IGridHost machine ) - { - this.getCache().addNode( gridNode, machine ); - } + @Override + public void addNode(final IGridNode gridNode, final IGridHost machine) { + this.getCache().addNode(gridNode, machine); + } - @Override - public void onSplit( final IGridStorage storageB ) - { - this.getCache().onSplit( storageB ); - } + @Override + public void onSplit(final IGridStorage storageB) { + this.getCache().onSplit(storageB); + } - @Override - public void onJoin( final IGridStorage storageB ) - { - this.getCache().onJoin( storageB ); - } + @Override + public void onJoin(final IGridStorage storageB) { + this.getCache().onJoin(storageB); + } - @Override - public void populateGridStorage( final IGridStorage storage ) - { - this.getCache().populateGridStorage( storage ); - } + @Override + public void populateGridStorage(final IGridStorage storage) { + this.getCache().populateGridStorage(storage); + } - public String getName() - { - return this.name; - } + public String getName() { + return this.name; + } - IGridCache getCache() - { - return this.myCache; - } + IGridCache getCache() { + return this.myCache; + } } diff --git a/src/main/java/appeng/me/GridConnection.java b/src/main/java/appeng/me/GridConnection.java index 89602a2dcf8..ff650ba84b4 100644 --- a/src/main/java/appeng/me/GridConnection.java +++ b/src/main/java/appeng/me/GridConnection.java @@ -18,7 +18,6 @@ package appeng.me; - import appeng.api.exceptions.ExistingConnectionException; import appeng.api.exceptions.FailedConnection; import appeng.api.exceptions.NullNodeConnectionException; @@ -36,274 +35,234 @@ import appeng.me.pathfinding.IPathItem; import appeng.util.Platform; import appeng.util.ReadOnlyCollection; +import java.util.Arrays; +import java.util.EnumSet; import net.minecraftforge.common.util.ForgeDirection; import org.apache.logging.log4j.Level; -import java.util.Arrays; -import java.util.EnumSet; +public class GridConnection implements IGridConnection, IPathItem { + + private static final String EXISTING_CONNECTION_MESSAGE = + "Connection between node [machine=%s, %s] and [machine=%s, %s] on [%s] already exists."; + + private static final MENetworkChannelsChanged EVENT = new MENetworkChannelsChanged(); + private int channelData = 0; + private Object visitorIterationNumber = null; + private GridNode sideA; + private ForgeDirection fromAtoB; + private GridNode sideB; + + public GridConnection(final IGridNode aNode, final IGridNode bNode, final ForgeDirection fromAtoB) + throws FailedConnection { + + final GridNode a = (GridNode) aNode; + final GridNode b = (GridNode) bNode; + + if (Platform.securityCheck(a, b)) { + if (AEConfig.instance.isFeatureEnabled(AEFeature.LogSecurityAudits)) { + final DimensionalCoord aCoordinates = a.getGridBlock().getLocation(); + final DimensionalCoord bCoordinates = b.getGridBlock().getLocation(); + + AELog.info( + "Security audit 1 failed at [%s] belonging to player [id=%d]", + aCoordinates.toString(), a.getPlayerID()); + AELog.info( + "Security audit 2 failed at [%s] belonging to player [id=%d]", + bCoordinates.toString(), b.getPlayerID()); + } + throw new SecurityConnectionException(); + } + + if (a == null || b == null) { + throw new NullNodeConnectionException(); + } + + if (a.hasConnection(b) || b.hasConnection(a)) { + final String aMachineClass = + a.getGridBlock().getMachine().getClass().getSimpleName(); + final String bMachineClass = + b.getGridBlock().getMachine().getClass().getSimpleName(); + final String aCoordinates = a.getGridBlock().getLocation().toString(); + final String bCoordinates = b.getGridBlock().getLocation().toString(); + + throw new ExistingConnectionException(String.format( + EXISTING_CONNECTION_MESSAGE, aMachineClass, aCoordinates, bMachineClass, bCoordinates, fromAtoB)); + } + + this.sideA = a; + this.fromAtoB = fromAtoB; + this.sideB = b; + + if (b.getMyGrid() == null) { + b.setGrid(a.getInternalGrid()); + } else { + if (a.getMyGrid() == null) { + final GridPropagator gp = new GridPropagator(b.getInternalGrid()); + a.beginVisit(gp); + } else if (b.getMyGrid() == null) { + final GridPropagator gp = new GridPropagator(a.getInternalGrid()); + b.beginVisit(gp); + } else if (this.isNetworkABetter(a, b)) { + final GridPropagator gp = new GridPropagator(a.getInternalGrid()); + b.beginVisit(gp); + } else { + final GridPropagator gp = new GridPropagator(b.getInternalGrid()); + a.beginVisit(gp); + } + } -public class GridConnection implements IGridConnection, IPathItem -{ - - private static final String EXISTING_CONNECTION_MESSAGE = "Connection between node [machine=%s, %s] and [machine=%s, %s] on [%s] already exists."; - - private static final MENetworkChannelsChanged EVENT = new MENetworkChannelsChanged(); - private int channelData = 0; - private Object visitorIterationNumber = null; - private GridNode sideA; - private ForgeDirection fromAtoB; - private GridNode sideB; - - public GridConnection( final IGridNode aNode, final IGridNode bNode, final ForgeDirection fromAtoB ) throws FailedConnection - { - - final GridNode a = (GridNode) aNode; - final GridNode b = (GridNode) bNode; - - if( Platform.securityCheck( a, b ) ) - { - if( AEConfig.instance.isFeatureEnabled( AEFeature.LogSecurityAudits ) ) - { - final DimensionalCoord aCoordinates = a.getGridBlock().getLocation(); - final DimensionalCoord bCoordinates = b.getGridBlock().getLocation(); - - AELog.info( "Security audit 1 failed at [%s] belonging to player [id=%d]", aCoordinates.toString(), a.getPlayerID() ); - AELog.info( "Security audit 2 failed at [%s] belonging to player [id=%d]", bCoordinates.toString(), b.getPlayerID() ); - } - - throw new SecurityConnectionException(); - } - - if( a == null || b == null ) - { - throw new NullNodeConnectionException(); - } - - if( a.hasConnection( b ) || b.hasConnection( a ) ) - { - final String aMachineClass = a.getGridBlock().getMachine().getClass().getSimpleName(); - final String bMachineClass = b.getGridBlock().getMachine().getClass().getSimpleName(); - final String aCoordinates = a.getGridBlock().getLocation().toString(); - final String bCoordinates = b.getGridBlock().getLocation().toString(); - - throw new ExistingConnectionException( String.format( EXISTING_CONNECTION_MESSAGE, aMachineClass, aCoordinates, bMachineClass, bCoordinates, fromAtoB ) ); - } - - this.sideA = a; - this.fromAtoB = fromAtoB; - this.sideB = b; - - if( b.getMyGrid() == null ) - { - b.setGrid( a.getInternalGrid() ); - } - else - { - if( a.getMyGrid() == null ) - { - final GridPropagator gp = new GridPropagator( b.getInternalGrid() ); - a.beginVisit( gp ); - } - else if( b.getMyGrid() == null ) - { - final GridPropagator gp = new GridPropagator( a.getInternalGrid() ); - b.beginVisit( gp ); - } - else if( this.isNetworkABetter( a, b ) ) - { - final GridPropagator gp = new GridPropagator( a.getInternalGrid() ); - b.beginVisit( gp ); - } - else - { - final GridPropagator gp = new GridPropagator( b.getInternalGrid() ); - a.beginVisit( gp ); - } - } - - // a connection was destroyed RE-PATH!! - final IPathingGrid p = this.sideA.getInternalGrid().getCache( IPathingGrid.class ); - if (AEConfig.instance.debugPathFinding) - { + // a connection was destroyed RE-PATH!! + final IPathingGrid p = this.sideA.getInternalGrid().getCache(IPathingGrid.class); + if (AEConfig.instance.debugPathFinding) { final String aCoordinates = a.getGridBlock().getLocation().toString(); final String bCoordinates = b.getGridBlock().getLocation().toString(); - AELog.info( "Repath is triggered by adding connection from [%s] to [%s]", aCoordinates, bCoordinates ); - AELog.printStackTrace( Level.INFO ); + AELog.info("Repath is triggered by adding connection from [%s] to [%s]", aCoordinates, bCoordinates); + AELog.printStackTrace(Level.INFO); } - p.repath(); - - this.sideA.addConnection( this ); - this.sideB.addConnection( this ); - } - - private boolean isNetworkABetter( final GridNode a, final GridNode b ) - { - return a.getMyGrid().getPriority() > b.getMyGrid().getPriority() || a.getMyGrid().size() > b.getMyGrid().size(); - } - - @Override - public IGridNode getOtherSide( final IGridNode gridNode ) - { - if( gridNode == this.sideA ) - { - return this.sideB; - } - if( gridNode == this.sideB ) - { - return this.sideA; - } - - throw new GridException( "Invalid Side of Connection" ); - } - - @Override - public ForgeDirection getDirection( final IGridNode side ) - { - if( this.fromAtoB == ForgeDirection.UNKNOWN ) - { - return this.fromAtoB; - } - - if( this.sideA == side ) - { - return this.fromAtoB; - } - else - { - return this.fromAtoB.getOpposite(); - } - } - - @Override - public void destroy() - { - if (AEConfig.instance.debugPathFinding) - { + p.repath(); + + this.sideA.addConnection(this); + this.sideB.addConnection(this); + } + + private boolean isNetworkABetter(final GridNode a, final GridNode b) { + return a.getMyGrid().getPriority() > b.getMyGrid().getPriority() + || a.getMyGrid().size() > b.getMyGrid().size(); + } + + @Override + public IGridNode getOtherSide(final IGridNode gridNode) { + if (gridNode == this.sideA) { + return this.sideB; + } + if (gridNode == this.sideB) { + return this.sideA; + } + + throw new GridException("Invalid Side of Connection"); + } + + @Override + public ForgeDirection getDirection(final IGridNode side) { + if (this.fromAtoB == ForgeDirection.UNKNOWN) { + return this.fromAtoB; + } + + if (this.sideA == side) { + return this.fromAtoB; + } else { + return this.fromAtoB.getOpposite(); + } + } + + @Override + public void destroy() { + if (AEConfig.instance.debugPathFinding) { final String aCoordinates = sideA.getGridBlock().getLocation().toString(); final String bCoordinates = sideB.getGridBlock().getLocation().toString(); - AELog.info( "Repath is triggered by destroying connection from [%s] to [%s]", aCoordinates, bCoordinates ); - AELog.printStackTrace( Level.INFO ); + AELog.info("Repath is triggered by destroying connection from [%s] to [%s]", aCoordinates, bCoordinates); + AELog.printStackTrace(Level.INFO); + } + + // a connection was destroyed RE-PATH!! + final IPathingGrid p = this.sideA.getInternalGrid().getCache(IPathingGrid.class); + p.repath(); + + this.sideA.removeConnection(this); + this.sideB.removeConnection(this); + + this.sideA.validateGrid(); + this.sideB.validateGrid(); + } + + @Override + public IGridNode a() { + return this.sideA; + } + + @Override + public IGridNode b() { + return this.sideB; + } + + @Override + public boolean hasDirection() { + return this.fromAtoB != ForgeDirection.UNKNOWN; + } + + @Override + public int getUsedChannels() { + return (this.channelData >> 8) & 0xff; + } + + @Override + public IPathItem getControllerRoute() { + if (this.sideA.getFlags().contains(GridFlags.CANNOT_CARRY)) { + return null; + } + return this.sideA; + } + + @Override + public void setControllerRoute(final IPathItem fast, final boolean zeroOut) { + if (zeroOut) { + this.channelData &= ~0xff; } - // a connection was destroyed RE-PATH!! - final IPathingGrid p = this.sideA.getInternalGrid().getCache( IPathingGrid.class ); - p.repath(); - - this.sideA.removeConnection( this ); - this.sideB.removeConnection( this ); - - this.sideA.validateGrid(); - this.sideB.validateGrid(); - } - - @Override - public IGridNode a() - { - return this.sideA; - } - - @Override - public IGridNode b() - { - return this.sideB; - } - - @Override - public boolean hasDirection() - { - return this.fromAtoB != ForgeDirection.UNKNOWN; - } - - @Override - public int getUsedChannels() - { - return ( this.channelData >> 8 ) & 0xff; - } - - @Override - public IPathItem getControllerRoute() - { - if( this.sideA.getFlags().contains( GridFlags.CANNOT_CARRY ) ) - { - return null; - } - return this.sideA; - } - - @Override - public void setControllerRoute( final IPathItem fast, final boolean zeroOut ) - { - if( zeroOut ) - { - this.channelData &= ~0xff; - } - - if( this.sideB == fast ) - { - final GridNode tmp = this.sideA; - this.sideA = this.sideB; - this.sideB = tmp; - this.fromAtoB = this.fromAtoB.getOpposite(); - } - } - - @Override - public boolean canSupportMoreChannels() - { - return this.getLastUsedChannels() < 128; // max, PERIOD. - } - - @Override - public IReadOnlyCollection getPossibleOptions() - { - return new ReadOnlyCollection( Arrays.asList( (IPathItem) this.a(), (IPathItem) this.b() ) ); - } - - @Override - public void incrementChannelCount( final int usedChannels ) - { - this.channelData += usedChannels; - } - - @Override - public EnumSet getFlags() - { - return EnumSet.noneOf( GridFlags.class ); - } - - @Override - public void finalizeChannels() - { - if( this.getUsedChannels() != this.getLastUsedChannels() ) - { - this.channelData &= 0xff; - this.channelData |= this.channelData << 8; - - if( this.sideA.getInternalGrid() != null ) - { - this.sideA.getInternalGrid().postEventTo( this.sideA, EVENT ); - } - - if( this.sideB.getInternalGrid() != null ) - { - this.sideB.getInternalGrid().postEventTo( this.sideB, EVENT ); - } - } - } - - private int getLastUsedChannels() - { - return this.channelData & 0xff; - } - - Object getVisitorIterationNumber() - { - return this.visitorIterationNumber; - } - - void setVisitorIterationNumber( final Object visitorIterationNumber ) - { - this.visitorIterationNumber = visitorIterationNumber; - } + if (this.sideB == fast) { + final GridNode tmp = this.sideA; + this.sideA = this.sideB; + this.sideB = tmp; + this.fromAtoB = this.fromAtoB.getOpposite(); + } + } + + @Override + public boolean canSupportMoreChannels() { + return this.getLastUsedChannels() < 128; // max, PERIOD. + } + + @Override + public IReadOnlyCollection getPossibleOptions() { + return new ReadOnlyCollection(Arrays.asList((IPathItem) this.a(), (IPathItem) this.b())); + } + + @Override + public void incrementChannelCount(final int usedChannels) { + this.channelData += usedChannels; + } + + @Override + public EnumSet getFlags() { + return EnumSet.noneOf(GridFlags.class); + } + + @Override + public void finalizeChannels() { + if (this.getUsedChannels() != this.getLastUsedChannels()) { + this.channelData &= 0xff; + this.channelData |= this.channelData << 8; + + if (this.sideA.getInternalGrid() != null) { + this.sideA.getInternalGrid().postEventTo(this.sideA, EVENT); + } + + if (this.sideB.getInternalGrid() != null) { + this.sideB.getInternalGrid().postEventTo(this.sideB, EVENT); + } + } + } + + private int getLastUsedChannels() { + return this.channelData & 0xff; + } + + Object getVisitorIterationNumber() { + return this.visitorIterationNumber; + } + + void setVisitorIterationNumber(final Object visitorIterationNumber) { + this.visitorIterationNumber = visitorIterationNumber; + } } diff --git a/src/main/java/appeng/me/GridException.java b/src/main/java/appeng/me/GridException.java index 5a3f418b775..590868b0e0b 100644 --- a/src/main/java/appeng/me/GridException.java +++ b/src/main/java/appeng/me/GridException.java @@ -18,15 +18,12 @@ package appeng.me; +public class GridException extends RuntimeException { -public class GridException extends RuntimeException -{ + private static final long serialVersionUID = -8110077032108243076L; - private static final long serialVersionUID = -8110077032108243076L; + public GridException(final String s) { - public GridException( final String s ) - { - - super( s ); - } + super(s); + } } diff --git a/src/main/java/appeng/me/GridNode.java b/src/main/java/appeng/me/GridNode.java index 5a9dab3deba..aba5b6325c8 100644 --- a/src/main/java/appeng/me/GridNode.java +++ b/src/main/java/appeng/me/GridNode.java @@ -18,7 +18,6 @@ package appeng.me; - import appeng.api.exceptions.FailedConnection; import appeng.api.networking.*; import appeng.api.networking.energy.IEnergyGrid; @@ -32,692 +31,563 @@ import appeng.me.pathfinding.IPathItem; import appeng.util.IWorldCallable; import appeng.util.ReadOnlyCollection; +import java.util.*; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.*; - - -public class GridNode implements IGridNode, IPathItem -{ - private static final MENetworkChannelsChanged EVENT = new MENetworkChannelsChanged(); - private static final int[] CHANNEL_COUNT = { 0, 8, 32, 128 }; - - private final List connections = new LinkedList<>(); - private final IGridBlock gridProxy; - // old power draw, used to diff - private double previousDraw = 0.0; - private long lastSecurityKey = -1; - private int playerID = -1; - private GridStorage myStorage = null; - private Grid myGrid; - private Object visitorIterationNumber = null; - // connection criteria - private int compressedData = 0; - private int usedChannels = 0; - private int lastUsedChannels = 0; - - public GridNode( final IGridBlock what ) - { - this.gridProxy = what; - } - - IGridBlock getGridProxy() - { - return this.gridProxy; - } - - Grid getMyGrid() - { - return this.myGrid; - } - - public int usedChannels() - { - return this.lastUsedChannels; - } - - Class getMachineClass() - { - return this.getMachine().getClass(); - } - - void addConnection( final IGridConnection gridConnection ) - { - this.connections.add( gridConnection ); - if( gridConnection.hasDirection() ) - { - this.gridProxy.onGridNotification( GridNotification.ConnectionsChanged ); - } - - final IGridNode gn = this; - - Collections.sort( this.connections, new ConnectionComparator( gn ) ); - } - - void removeConnection( final IGridConnection gridConnection ) - { - this.connections.remove( gridConnection ); - if( gridConnection.hasDirection() ) - { - this.gridProxy.onGridNotification( GridNotification.ConnectionsChanged ); - } - } - - boolean hasConnection( final IGridNode otherSide ) - { - for( final IGridConnection gc : this.connections ) - { - if( gc.a() == otherSide || gc.b() == otherSide ) - { - return true; - } - } - return false; - } - - void validateGrid() - { - final GridSplitDetector gsd = new GridSplitDetector( this.getInternalGrid().getPivot() ); - this.beginVisit( gsd ); - if( !gsd.isPivotFound() ) - { - final IGridVisitor gp = new GridPropagator( new Grid( this ) ); - this.beginVisit( gp ); - } - } - - public Grid getInternalGrid() - { - if( this.myGrid == null ) - { - this.myGrid = new Grid( this ); - } - - return this.myGrid; - } - - @Override - public void beginVisit( final IGridVisitor g ) - { - final Object tracker = new Object(); - - LinkedList nextRun = new LinkedList(); - nextRun.add( this ); - - this.visitorIterationNumber = tracker; - - if( g instanceof IGridConnectionVisitor ) - { - final LinkedList nextConn = new LinkedList(); - final IGridConnectionVisitor gcv = (IGridConnectionVisitor) g; - - while( !nextRun.isEmpty() ) - { - while( !nextConn.isEmpty() ) - { - gcv.visitConnection( nextConn.poll() ); - } - - final Iterable thisRun = nextRun; - nextRun = new LinkedList(); - - for( final GridNode n : thisRun ) - { - n.visitorConnection( tracker, g, nextRun, nextConn ); - } - } - } - else - { - while( !nextRun.isEmpty() ) - { - final Iterable thisRun = nextRun; - nextRun = new LinkedList(); - - for( final GridNode n : thisRun ) - { - n.visitorNode( tracker, g, nextRun ); - } - } - } - } - - @Override - public void updateState() - { - this.compressedData = getCompressedChannelsIndex(this.gridProxy.getFlags()); - - this.compressedData |= ( this.gridProxy.getGridColor().ordinal() << 3 ); - - for( final ForgeDirection dir : this.gridProxy.getConnectableSides() ) - { - this.compressedData |= ( 1 << ( dir.ordinal() + 8 ) ); - } - - this.FindConnections(); - this.getInternalGrid(); - } - - private int getCompressedChannelsIndex(final EnumSet set) { - if (set.contains(GridFlags.CANNOT_CARRY)) - return 0; - else if (set.contains(GridFlags.ULTRA_DENSE_CAPACITY)) - return 3; - else if (set.contains(GridFlags.DENSE_CAPACITY)) - return 2; - return 1; - } - - @Override - public IGridHost getMachine() - { - return this.gridProxy.getMachine(); - } - - @Override - public IGrid getGrid() - { - return this.myGrid; - } - - void setGrid( final Grid grid ) - { - if( this.myGrid == grid ) - { - return; - } - - if( this.myGrid != null ) - { - this.myGrid.remove( this ); - - if( this.myGrid.isEmpty() ) - { - this.myGrid.saveState(); - - for( final IGridCache c : grid.getCaches().values() ) - { - c.onJoin( this.myGrid.getMyStorage() ); - } - } - } - - this.myGrid = grid; - this.myGrid.add( this ); - } - - @Override - public void destroy() - { - while( !this.connections.isEmpty() ) - { - // not part of this network for real anymore. - if( this.connections.size() == 1 ) - { - this.setGridStorage( null ); - } - - final IGridConnection c = this.connections.listIterator().next(); - final GridNode otherSide = (GridNode) c.getOtherSide( this ); - otherSide.getInternalGrid().setPivot( otherSide ); - c.destroy(); - } - - if( this.myGrid != null ) - { - this.myGrid.remove( this ); - } - } - - @Override - public World getWorld() - { - return this.gridProxy.getLocation().getWorld(); - } - - @Override - public EnumSet getConnectedSides() - { - final EnumSet set = EnumSet.noneOf( ForgeDirection.class ); - for( final IGridConnection gc : this.connections ) - { - set.add( gc.getDirection( this ) ); - } - return set; - } - - @Override - public IReadOnlyCollection getConnections() - { - return new ReadOnlyCollection( this.connections ); - } - - @Override - public IGridBlock getGridBlock() - { - return this.gridProxy; - } - - @Override - public boolean isActive() - { - final IGrid g = this.getGrid(); - if( g != null ) - { - final IPathingGrid pg = g.getCache( IPathingGrid.class ); - final IEnergyGrid eg = g.getCache( IEnergyGrid.class ); - return this.meetsChannelRequirements() && eg.isNetworkPowered() && !pg.isNetworkBooting(); - } - return false; - } - - @Override - public void loadFromNBT( final String name, final NBTTagCompound nodeData ) - { - if( this.myGrid == null ) - { - final NBTTagCompound node = nodeData.getCompoundTag( name ); - this.playerID = node.getInteger( "p" ); - this.setLastSecurityKey( node.getLong( "k" ) ); - - final long storageID = node.getLong( "g" ); - final GridStorage gridStorage = WorldData.instance().storageData().getGridStorage( storageID ); - this.setGridStorage( gridStorage ); - } - else - { - throw new IllegalStateException( "Loading data after part of a grid, this is invalid." ); - } - } - - @Override - public void saveToNBT( final String name, final NBTTagCompound nodeData ) - { - if( this.myStorage != null ) - { - final NBTTagCompound node = new NBTTagCompound(); - - node.setInteger( "p", this.playerID ); - node.setLong( "k", this.getLastSecurityKey() ); - node.setLong( "g", this.myStorage.getID() ); - - nodeData.setTag( name, node ); - } - else - { - nodeData.removeTag( name ); - } - } - - @Override - public boolean meetsChannelRequirements() - { - return ( !this.gridProxy.getFlags().contains( GridFlags.REQUIRE_CHANNEL ) || this.getUsedChannels() > 0 ); - } - - @Override - public boolean hasFlag( final GridFlags flag ) - { - return this.gridProxy.getFlags().contains( flag ); - } - - @Override - public int getPlayerID() - { - return this.playerID; - } - - @Override - public void setPlayerID( final int playerID ) - { - if( playerID >= 0 ) - { - this.playerID = playerID; - } - } - - private int getUsedChannels() - { - return this.usedChannels; - } - - private void FindConnections() - { - if( !this.gridProxy.isWorldAccessible() ) - { - return; - } - - final EnumSet newSecurityConnections = EnumSet.noneOf( ForgeDirection.class ); - - final DimensionalCoord dc = this.gridProxy.getLocation(); - for( final ForgeDirection f : ForgeDirection.VALID_DIRECTIONS ) - { - final IGridHost te = this.findGridHost( dc.getWorld(), dc.x + f.offsetX, dc.y + f.offsetY, dc.z + f.offsetZ ); - if( te != null ) - { - final GridNode node = (GridNode) te.getGridNode( f.getOpposite() ); - if( node == null ) - { - continue; - } - - final boolean isValidConnection = this.canConnect( node, f ) && node.canConnect( this, f.getOpposite() ); - - IGridConnection con = null; // find the connection for this - // direction.. - for( final IGridConnection c : this.getConnections() ) - { - if( c.getDirection( this ) == f ) - { - con = c; - break; - } - } - - if( con != null ) - { - final IGridNode os = con.getOtherSide( this ); - if( os == node ) - { - // if this connection is no longer valid, destroy it. - if( !isValidConnection ) - { - con.destroy(); - } - } - else - { - con.destroy(); - // throw new GridException( "invalid state found, encountered connection to phantom block." ); - } - } - else if( isValidConnection ) - { - if( node.getLastSecurityKey() != -1 ) - { - newSecurityConnections.add( f ); - } - else - { - // construct a new connection between these two nodes. - try - { - new GridConnection( node, this, f.getOpposite() ); - } - catch( final FailedConnection e ) - { - TickHandler.INSTANCE.addCallable( node.getWorld(), new MachineSecurityBreak( this ) ); - - return; - } - } - } - } - } - - for( final ForgeDirection f : newSecurityConnections ) - { - final IGridHost te = this.findGridHost( dc.getWorld(), dc.x + f.offsetX, dc.y + f.offsetY, dc.z + f.offsetZ ); - if( te != null ) - { - final GridNode node = (GridNode) te.getGridNode( f.getOpposite() ); - if( node == null ) - { - continue; - } - - // construct a new connection between these two nodes. - try - { - new GridConnection( node, this, f.getOpposite() ); - } - catch( final FailedConnection e ) - { - TickHandler.INSTANCE.addCallable( node.getWorld(), new MachineSecurityBreak( this ) ); - - return; - } - } - } - } - - private IGridHost findGridHost( final World world, final int x, final int y, final int z ) - { - if( world.blockExists( x, y, z ) ) - { - final TileEntity te = world.getTileEntity( x, y, z ); - if( te instanceof IGridHost ) - { - return (IGridHost) te; - } - } - return null; - } - - private boolean canConnect( final GridNode from, final ForgeDirection dir ) - { - if( !this.isValidDirection( dir ) ) - { - return false; - } - - // only connect ultra dense cable to dense cables - if (hasFlag(GridFlags.ULTRA_DENSE_CAPACITY) && !hasFlag(GridFlags.DENSE_CAPACITY) && - !(from.hasFlag(GridFlags.ULTRA_DENSE_CAPACITY) || - (from.hasFlag(GridFlags.DENSE_CAPACITY) && !from.hasFlag(GridFlags.CANNOT_CARRY)))) - return false; - - return from.getColor().matches( this.getColor() ); - } - - private boolean isValidDirection( final ForgeDirection dir ) - { - return ( this.compressedData & ( 1 << ( 8 + dir.ordinal() ) ) ) > 0; - } - - private AEColor getColor() - { - return AEColor.values()[( this.compressedData >> 3 ) & 0x1F]; - } - - private void visitorConnection( final Object tracker, final IGridVisitor g, final Deque nextRun, final Deque nextConnections ) - { - if( g.visitNode( this ) ) - { - for( final IGridConnection gc : this.getConnections() ) - { - final GridNode gn = (GridNode) gc.getOtherSide( this ); - final GridConnection gcc = (GridConnection) gc; - - if( gcc.getVisitorIterationNumber() != tracker ) - { - gcc.setVisitorIterationNumber( tracker ); - nextConnections.add( gc ); - } - - if( tracker == gn.visitorIterationNumber ) - { - continue; - } - - gn.visitorIterationNumber = tracker; - - nextRun.add( gn ); - } - } - } - - private void visitorNode( final Object tracker, final IGridVisitor g, final Deque nextRun ) - { - if( g.visitNode( this ) ) - { - for( final IGridConnection gc : this.getConnections() ) - { - final GridNode gn = (GridNode) gc.getOtherSide( this ); - - if( tracker == gn.visitorIterationNumber ) - { - continue; - } - - gn.visitorIterationNumber = tracker; - - nextRun.add( gn ); - } - } - } - - GridStorage getGridStorage() - { - return this.myStorage; - } - - void setGridStorage( final GridStorage s ) - { - this.myStorage = s; - this.usedChannels = 0; - this.lastUsedChannels = 0; - } - - @Override - public IPathItem getControllerRoute() - { - if( this.connections.isEmpty() || this.getFlags().contains( GridFlags.CANNOT_CARRY ) ) - { - return null; - } - - return (IPathItem) this.connections.get( 0 ); - } - - @Override - public void setControllerRoute( final IPathItem fast, final boolean zeroOut ) - { - if( zeroOut ) - { - this.usedChannels = 0; - } - - final int idx = this.connections.indexOf( fast ); - if( idx > 0 ) - { - this.connections.remove( fast ); - this.connections.add( 0, (IGridConnection) fast ); - } - } - - @Override - public boolean canSupportMoreChannels() - { - return this.getUsedChannels() < this.getMaxChannels(); - } - - private int getMaxChannels() - { - return CHANNEL_COUNT[this.compressedData & 0x3]; - } - - @Override - public IReadOnlyCollection getPossibleOptions() - { - return (IReadOnlyCollection) this.getConnections(); - } - - @Override - public void incrementChannelCount( final int usedChannels ) - { - this.usedChannels += usedChannels; - } - - @Override - public EnumSet getFlags() - { - return this.gridProxy.getFlags(); - } - - @Override - public void finalizeChannels() - { - if( this.getFlags().contains( GridFlags.CANNOT_CARRY ) ) - { - return; - } - - if( this.getLastUsedChannels() != this.getUsedChannels() ) - { - this.lastUsedChannels = this.usedChannels; - - if( this.getInternalGrid() != null ) - { - this.getInternalGrid().postEventTo( this, EVENT ); - } - } - } - - private int getLastUsedChannels() - { - return this.lastUsedChannels; - } - - public long getLastSecurityKey() - { - return this.lastSecurityKey; - } - - public void setLastSecurityKey( final long lastSecurityKey ) - { - this.lastSecurityKey = lastSecurityKey; - } - - public double getPreviousDraw() - { - return this.previousDraw; - } - - public void setPreviousDraw( final double previousDraw ) - { - this.previousDraw = previousDraw; - } - - private static class MachineSecurityBreak implements IWorldCallable - { - private final GridNode node; - - public MachineSecurityBreak( final GridNode node ) - { - this.node = node; - } - - @Override - public Void call( final World world ) throws Exception - { - this.node.getMachine().securityBreak(); - - return null; - } - } - - - private static class ConnectionComparator implements Comparator - { - private final IGridNode gn; - - public ConnectionComparator( final IGridNode gn ) - { - this.gn = gn; - } - - @Override - public int compare( final IGridConnection o1, final IGridConnection o2 ) - { - final boolean preferredA = o1.getOtherSide( this.gn ).hasFlag( GridFlags.PREFERRED ); - final boolean preferredB = o2.getOtherSide( this.gn ).hasFlag( GridFlags.PREFERRED ); - - return preferredA == preferredB ? 0 : ( preferredA ? -1 : 1 ); - } - } +public class GridNode implements IGridNode, IPathItem { + private static final MENetworkChannelsChanged EVENT = new MENetworkChannelsChanged(); + private static final int[] CHANNEL_COUNT = {0, 8, 32, 128}; + + private final List connections = new LinkedList<>(); + private final IGridBlock gridProxy; + // old power draw, used to diff + private double previousDraw = 0.0; + private long lastSecurityKey = -1; + private int playerID = -1; + private GridStorage myStorage = null; + private Grid myGrid; + private Object visitorIterationNumber = null; + // connection criteria + private int compressedData = 0; + private int usedChannels = 0; + private int lastUsedChannels = 0; + + public GridNode(final IGridBlock what) { + this.gridProxy = what; + } + + IGridBlock getGridProxy() { + return this.gridProxy; + } + + Grid getMyGrid() { + return this.myGrid; + } + + public int usedChannels() { + return this.lastUsedChannels; + } + + Class getMachineClass() { + return this.getMachine().getClass(); + } + + void addConnection(final IGridConnection gridConnection) { + this.connections.add(gridConnection); + if (gridConnection.hasDirection()) { + this.gridProxy.onGridNotification(GridNotification.ConnectionsChanged); + } + + final IGridNode gn = this; + + Collections.sort(this.connections, new ConnectionComparator(gn)); + } + + void removeConnection(final IGridConnection gridConnection) { + this.connections.remove(gridConnection); + if (gridConnection.hasDirection()) { + this.gridProxy.onGridNotification(GridNotification.ConnectionsChanged); + } + } + + boolean hasConnection(final IGridNode otherSide) { + for (final IGridConnection gc : this.connections) { + if (gc.a() == otherSide || gc.b() == otherSide) { + return true; + } + } + return false; + } + + void validateGrid() { + final GridSplitDetector gsd = + new GridSplitDetector(this.getInternalGrid().getPivot()); + this.beginVisit(gsd); + if (!gsd.isPivotFound()) { + final IGridVisitor gp = new GridPropagator(new Grid(this)); + this.beginVisit(gp); + } + } + + public Grid getInternalGrid() { + if (this.myGrid == null) { + this.myGrid = new Grid(this); + } + + return this.myGrid; + } + + @Override + public void beginVisit(final IGridVisitor g) { + final Object tracker = new Object(); + + LinkedList nextRun = new LinkedList(); + nextRun.add(this); + + this.visitorIterationNumber = tracker; + + if (g instanceof IGridConnectionVisitor) { + final LinkedList nextConn = new LinkedList(); + final IGridConnectionVisitor gcv = (IGridConnectionVisitor) g; + + while (!nextRun.isEmpty()) { + while (!nextConn.isEmpty()) { + gcv.visitConnection(nextConn.poll()); + } + + final Iterable thisRun = nextRun; + nextRun = new LinkedList(); + + for (final GridNode n : thisRun) { + n.visitorConnection(tracker, g, nextRun, nextConn); + } + } + } else { + while (!nextRun.isEmpty()) { + final Iterable thisRun = nextRun; + nextRun = new LinkedList(); + + for (final GridNode n : thisRun) { + n.visitorNode(tracker, g, nextRun); + } + } + } + } + + @Override + public void updateState() { + this.compressedData = getCompressedChannelsIndex(this.gridProxy.getFlags()); + + this.compressedData |= (this.gridProxy.getGridColor().ordinal() << 3); + + for (final ForgeDirection dir : this.gridProxy.getConnectableSides()) { + this.compressedData |= (1 << (dir.ordinal() + 8)); + } + + this.FindConnections(); + this.getInternalGrid(); + } + + private int getCompressedChannelsIndex(final EnumSet set) { + if (set.contains(GridFlags.CANNOT_CARRY)) return 0; + else if (set.contains(GridFlags.ULTRA_DENSE_CAPACITY)) return 3; + else if (set.contains(GridFlags.DENSE_CAPACITY)) return 2; + return 1; + } + + @Override + public IGridHost getMachine() { + return this.gridProxy.getMachine(); + } + + @Override + public IGrid getGrid() { + return this.myGrid; + } + + void setGrid(final Grid grid) { + if (this.myGrid == grid) { + return; + } + + if (this.myGrid != null) { + this.myGrid.remove(this); + + if (this.myGrid.isEmpty()) { + this.myGrid.saveState(); + + for (final IGridCache c : grid.getCaches().values()) { + c.onJoin(this.myGrid.getMyStorage()); + } + } + } + + this.myGrid = grid; + this.myGrid.add(this); + } + + @Override + public void destroy() { + while (!this.connections.isEmpty()) { + // not part of this network for real anymore. + if (this.connections.size() == 1) { + this.setGridStorage(null); + } + + final IGridConnection c = this.connections.listIterator().next(); + final GridNode otherSide = (GridNode) c.getOtherSide(this); + otherSide.getInternalGrid().setPivot(otherSide); + c.destroy(); + } + + if (this.myGrid != null) { + this.myGrid.remove(this); + } + } + + @Override + public World getWorld() { + return this.gridProxy.getLocation().getWorld(); + } + + @Override + public EnumSet getConnectedSides() { + final EnumSet set = EnumSet.noneOf(ForgeDirection.class); + for (final IGridConnection gc : this.connections) { + set.add(gc.getDirection(this)); + } + return set; + } + + @Override + public IReadOnlyCollection getConnections() { + return new ReadOnlyCollection(this.connections); + } + + @Override + public IGridBlock getGridBlock() { + return this.gridProxy; + } + + @Override + public boolean isActive() { + final IGrid g = this.getGrid(); + if (g != null) { + final IPathingGrid pg = g.getCache(IPathingGrid.class); + final IEnergyGrid eg = g.getCache(IEnergyGrid.class); + return this.meetsChannelRequirements() && eg.isNetworkPowered() && !pg.isNetworkBooting(); + } + return false; + } + + @Override + public void loadFromNBT(final String name, final NBTTagCompound nodeData) { + if (this.myGrid == null) { + final NBTTagCompound node = nodeData.getCompoundTag(name); + this.playerID = node.getInteger("p"); + this.setLastSecurityKey(node.getLong("k")); + + final long storageID = node.getLong("g"); + final GridStorage gridStorage = WorldData.instance().storageData().getGridStorage(storageID); + this.setGridStorage(gridStorage); + } else { + throw new IllegalStateException("Loading data after part of a grid, this is invalid."); + } + } + + @Override + public void saveToNBT(final String name, final NBTTagCompound nodeData) { + if (this.myStorage != null) { + final NBTTagCompound node = new NBTTagCompound(); + + node.setInteger("p", this.playerID); + node.setLong("k", this.getLastSecurityKey()); + node.setLong("g", this.myStorage.getID()); + + nodeData.setTag(name, node); + } else { + nodeData.removeTag(name); + } + } + + @Override + public boolean meetsChannelRequirements() { + return (!this.gridProxy.getFlags().contains(GridFlags.REQUIRE_CHANNEL) || this.getUsedChannels() > 0); + } + + @Override + public boolean hasFlag(final GridFlags flag) { + return this.gridProxy.getFlags().contains(flag); + } + + @Override + public int getPlayerID() { + return this.playerID; + } + + @Override + public void setPlayerID(final int playerID) { + if (playerID >= 0) { + this.playerID = playerID; + } + } + + private int getUsedChannels() { + return this.usedChannels; + } + + private void FindConnections() { + if (!this.gridProxy.isWorldAccessible()) { + return; + } + + final EnumSet newSecurityConnections = EnumSet.noneOf(ForgeDirection.class); + + final DimensionalCoord dc = this.gridProxy.getLocation(); + for (final ForgeDirection f : ForgeDirection.VALID_DIRECTIONS) { + final IGridHost te = this.findGridHost(dc.getWorld(), dc.x + f.offsetX, dc.y + f.offsetY, dc.z + f.offsetZ); + if (te != null) { + final GridNode node = (GridNode) te.getGridNode(f.getOpposite()); + if (node == null) { + continue; + } + + final boolean isValidConnection = this.canConnect(node, f) && node.canConnect(this, f.getOpposite()); + + IGridConnection con = null; // find the connection for this + // direction.. + for (final IGridConnection c : this.getConnections()) { + if (c.getDirection(this) == f) { + con = c; + break; + } + } + + if (con != null) { + final IGridNode os = con.getOtherSide(this); + if (os == node) { + // if this connection is no longer valid, destroy it. + if (!isValidConnection) { + con.destroy(); + } + } else { + con.destroy(); + // throw new GridException( "invalid state found, encountered connection to phantom block." ); + } + } else if (isValidConnection) { + if (node.getLastSecurityKey() != -1) { + newSecurityConnections.add(f); + } else { + // construct a new connection between these two nodes. + try { + new GridConnection(node, this, f.getOpposite()); + } catch (final FailedConnection e) { + TickHandler.INSTANCE.addCallable(node.getWorld(), new MachineSecurityBreak(this)); + + return; + } + } + } + } + } + + for (final ForgeDirection f : newSecurityConnections) { + final IGridHost te = this.findGridHost(dc.getWorld(), dc.x + f.offsetX, dc.y + f.offsetY, dc.z + f.offsetZ); + if (te != null) { + final GridNode node = (GridNode) te.getGridNode(f.getOpposite()); + if (node == null) { + continue; + } + + // construct a new connection between these two nodes. + try { + new GridConnection(node, this, f.getOpposite()); + } catch (final FailedConnection e) { + TickHandler.INSTANCE.addCallable(node.getWorld(), new MachineSecurityBreak(this)); + + return; + } + } + } + } + + private IGridHost findGridHost(final World world, final int x, final int y, final int z) { + if (world.blockExists(x, y, z)) { + final TileEntity te = world.getTileEntity(x, y, z); + if (te instanceof IGridHost) { + return (IGridHost) te; + } + } + return null; + } + + private boolean canConnect(final GridNode from, final ForgeDirection dir) { + if (!this.isValidDirection(dir)) { + return false; + } + + // only connect ultra dense cable to dense cables + if (hasFlag(GridFlags.ULTRA_DENSE_CAPACITY) + && !hasFlag(GridFlags.DENSE_CAPACITY) + && !(from.hasFlag(GridFlags.ULTRA_DENSE_CAPACITY) + || (from.hasFlag(GridFlags.DENSE_CAPACITY) && !from.hasFlag(GridFlags.CANNOT_CARRY)))) + return false; + + return from.getColor().matches(this.getColor()); + } + + private boolean isValidDirection(final ForgeDirection dir) { + return (this.compressedData & (1 << (8 + dir.ordinal()))) > 0; + } + + private AEColor getColor() { + return AEColor.values()[(this.compressedData >> 3) & 0x1F]; + } + + private void visitorConnection( + final Object tracker, + final IGridVisitor g, + final Deque nextRun, + final Deque nextConnections) { + if (g.visitNode(this)) { + for (final IGridConnection gc : this.getConnections()) { + final GridNode gn = (GridNode) gc.getOtherSide(this); + final GridConnection gcc = (GridConnection) gc; + + if (gcc.getVisitorIterationNumber() != tracker) { + gcc.setVisitorIterationNumber(tracker); + nextConnections.add(gc); + } + + if (tracker == gn.visitorIterationNumber) { + continue; + } + + gn.visitorIterationNumber = tracker; + + nextRun.add(gn); + } + } + } + + private void visitorNode(final Object tracker, final IGridVisitor g, final Deque nextRun) { + if (g.visitNode(this)) { + for (final IGridConnection gc : this.getConnections()) { + final GridNode gn = (GridNode) gc.getOtherSide(this); + + if (tracker == gn.visitorIterationNumber) { + continue; + } + + gn.visitorIterationNumber = tracker; + + nextRun.add(gn); + } + } + } + + GridStorage getGridStorage() { + return this.myStorage; + } + + void setGridStorage(final GridStorage s) { + this.myStorage = s; + this.usedChannels = 0; + this.lastUsedChannels = 0; + } + + @Override + public IPathItem getControllerRoute() { + if (this.connections.isEmpty() || this.getFlags().contains(GridFlags.CANNOT_CARRY)) { + return null; + } + + return (IPathItem) this.connections.get(0); + } + + @Override + public void setControllerRoute(final IPathItem fast, final boolean zeroOut) { + if (zeroOut) { + this.usedChannels = 0; + } + + final int idx = this.connections.indexOf(fast); + if (idx > 0) { + this.connections.remove(fast); + this.connections.add(0, (IGridConnection) fast); + } + } + + @Override + public boolean canSupportMoreChannels() { + return this.getUsedChannels() < this.getMaxChannels(); + } + + private int getMaxChannels() { + return CHANNEL_COUNT[this.compressedData & 0x3]; + } + + @Override + public IReadOnlyCollection getPossibleOptions() { + return (IReadOnlyCollection) this.getConnections(); + } + + @Override + public void incrementChannelCount(final int usedChannels) { + this.usedChannels += usedChannels; + } + + @Override + public EnumSet getFlags() { + return this.gridProxy.getFlags(); + } + + @Override + public void finalizeChannels() { + if (this.getFlags().contains(GridFlags.CANNOT_CARRY)) { + return; + } + + if (this.getLastUsedChannels() != this.getUsedChannels()) { + this.lastUsedChannels = this.usedChannels; + + if (this.getInternalGrid() != null) { + this.getInternalGrid().postEventTo(this, EVENT); + } + } + } + + private int getLastUsedChannels() { + return this.lastUsedChannels; + } + + public long getLastSecurityKey() { + return this.lastSecurityKey; + } + + public void setLastSecurityKey(final long lastSecurityKey) { + this.lastSecurityKey = lastSecurityKey; + } + + public double getPreviousDraw() { + return this.previousDraw; + } + + public void setPreviousDraw(final double previousDraw) { + this.previousDraw = previousDraw; + } + + private static class MachineSecurityBreak implements IWorldCallable { + private final GridNode node; + + public MachineSecurityBreak(final GridNode node) { + this.node = node; + } + + @Override + public Void call(final World world) throws Exception { + this.node.getMachine().securityBreak(); + + return null; + } + } + + private static class ConnectionComparator implements Comparator { + private final IGridNode gn; + + public ConnectionComparator(final IGridNode gn) { + this.gn = gn; + } + + @Override + public int compare(final IGridConnection o1, final IGridConnection o2) { + final boolean preferredA = o1.getOtherSide(this.gn).hasFlag(GridFlags.PREFERRED); + final boolean preferredB = o2.getOtherSide(this.gn).hasFlag(GridFlags.PREFERRED); + + return preferredA == preferredB ? 0 : (preferredA ? -1 : 1); + } + } } diff --git a/src/main/java/appeng/me/GridNodeCollection.java b/src/main/java/appeng/me/GridNodeCollection.java index 64d39def098..12ffa5497c7 100644 --- a/src/main/java/appeng/me/GridNodeCollection.java +++ b/src/main/java/appeng/me/GridNodeCollection.java @@ -18,78 +18,63 @@ package appeng.me; - import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.util.IReadOnlyCollection; - import java.util.Iterator; import java.util.Map; import java.util.Set; +public class GridNodeCollection implements IReadOnlyCollection { + private final Map, MachineSet> machines; -public class GridNodeCollection implements IReadOnlyCollection -{ - private final Map, MachineSet> machines; - - public GridNodeCollection( final Map, MachineSet> machines ) - { - this.machines = machines; - } + public GridNodeCollection(final Map, MachineSet> machines) { + this.machines = machines; + } - @Override - public Iterator iterator() - { - return new GridNodeIterator( this.machines ); - } + @Override + public Iterator iterator() { + return new GridNodeIterator(this.machines); + } - @Override - public int size() - { - int size = 0; + @Override + public int size() { + int size = 0; - for( final Set o : this.machines.values() ) - { - size += o.size(); - } + for (final Set o : this.machines.values()) { + size += o.size(); + } - return size; - } + return size; + } - @Override - public boolean isEmpty() - { - for( final Set o : this.machines.values() ) - { - if( !o.isEmpty() ) - { - return false; - } - } + @Override + public boolean isEmpty() { + for (final Set o : this.machines.values()) { + if (!o.isEmpty()) { + return false; + } + } - return true; - } + return true; + } - @Override - public boolean contains( final Object maybeGridNode ) - { - final boolean doesContainNode; + @Override + public boolean contains(final Object maybeGridNode) { + final boolean doesContainNode; - if( maybeGridNode instanceof IGridNode ) - { - final IGridNode node = (IGridNode) maybeGridNode; - final IGridHost machine = node.getMachine(); - final Class machineClass = machine.getClass(); + if (maybeGridNode instanceof IGridNode) { + final IGridNode node = (IGridNode) maybeGridNode; + final IGridHost machine = node.getMachine(); + final Class machineClass = machine.getClass(); - final MachineSet machineSet = this.machines.get( machineClass ); + final MachineSet machineSet = this.machines.get(machineClass); - doesContainNode = machineSet != null && machineSet.contains( maybeGridNode ); - } - else - { - doesContainNode = false; - } + doesContainNode = machineSet != null && machineSet.contains(maybeGridNode); + } else { + doesContainNode = false; + } - return doesContainNode; - } + return doesContainNode; + } } diff --git a/src/main/java/appeng/me/GridNodeIterator.java b/src/main/java/appeng/me/GridNodeIterator.java index 219ea58857e..9d3828c827f 100644 --- a/src/main/java/appeng/me/GridNodeIterator.java +++ b/src/main/java/appeng/me/GridNodeIterator.java @@ -18,69 +18,55 @@ package appeng.me; - import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; - import java.util.Iterator; import java.util.Map; - /** * Nested iterator for {@link appeng.me.MachineSet} *

* Traverses first over the {@link appeng.me.MachineSet} and then over every containing * {@link appeng.api.networking.IGridNode} */ -public class GridNodeIterator implements Iterator -{ - private final Iterator outerIterator; - private Iterator innerIterator; +public class GridNodeIterator implements Iterator { + private final Iterator outerIterator; + private Iterator innerIterator; - public GridNodeIterator( final Map, MachineSet> machines ) - { - this.outerIterator = machines.values().iterator(); - this.innerHasNext(); - } + public GridNodeIterator(final Map, MachineSet> machines) { + this.outerIterator = machines.values().iterator(); + this.innerHasNext(); + } - private boolean innerHasNext() - { - final boolean hasNext = this.outerIterator.hasNext(); + private boolean innerHasNext() { + final boolean hasNext = this.outerIterator.hasNext(); - if( hasNext ) - { - final MachineSet nextElem = this.outerIterator.next(); - this.innerIterator = nextElem.iterator(); - } + if (hasNext) { + final MachineSet nextElem = this.outerIterator.next(); + this.innerIterator = nextElem.iterator(); + } - return hasNext; - } + return hasNext; + } - @Override - public boolean hasNext() - { - while( true ) - { - if( this.innerIterator.hasNext() ) - { - return true; - } - else if( !this.innerHasNext() ) - { - return false; - } - } - } + @Override + public boolean hasNext() { + while (true) { + if (this.innerIterator.hasNext()) { + return true; + } else if (!this.innerHasNext()) { + return false; + } + } + } - @Override - public IGridNode next() - { - return this.innerIterator.next(); - } + @Override + public IGridNode next() { + return this.innerIterator.next(); + } - @Override - public void remove() - { - this.innerIterator.remove(); - } + @Override + public void remove() { + this.innerIterator.remove(); + } } diff --git a/src/main/java/appeng/me/GridPropagator.java b/src/main/java/appeng/me/GridPropagator.java index 4bc6c99fbc6..2e12292e8cd 100644 --- a/src/main/java/appeng/me/GridPropagator.java +++ b/src/main/java/appeng/me/GridPropagator.java @@ -18,30 +18,24 @@ package appeng.me; - import appeng.api.networking.IGridNode; import appeng.api.networking.IGridVisitor; +public class GridPropagator implements IGridVisitor { + private final Grid g; -public class GridPropagator implements IGridVisitor -{ - private final Grid g; - - public GridPropagator( final Grid g ) - { - this.g = g; - } + public GridPropagator(final Grid g) { + this.g = g; + } - @Override - public boolean visitNode( final IGridNode n ) - { - final GridNode gn = (GridNode) n; - if( gn.getMyGrid() != this.g || this.g.getPivot() == n ) - { - gn.setGrid( this.g ); + @Override + public boolean visitNode(final IGridNode n) { + final GridNode gn = (GridNode) n; + if (gn.getMyGrid() != this.g || this.g.getPivot() == n) { + gn.setGrid(this.g); - return true; - } - return false; - } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/me/GridSplitDetector.java b/src/main/java/appeng/me/GridSplitDetector.java index ac0b98c7ac7..6bc747b8c26 100644 --- a/src/main/java/appeng/me/GridSplitDetector.java +++ b/src/main/java/appeng/me/GridSplitDetector.java @@ -18,40 +18,32 @@ package appeng.me; - import appeng.api.networking.IGridNode; import appeng.api.networking.IGridVisitor; +class GridSplitDetector implements IGridVisitor { -class GridSplitDetector implements IGridVisitor -{ - - private final IGridNode pivot; - private boolean pivotFound; + private final IGridNode pivot; + private boolean pivotFound; - public GridSplitDetector( final IGridNode pivot ) - { - this.pivot = pivot; - } + public GridSplitDetector(final IGridNode pivot) { + this.pivot = pivot; + } - @Override - public boolean visitNode( final IGridNode n ) - { - if( n == this.pivot ) - { - this.setPivotFound( true ); - } + @Override + public boolean visitNode(final IGridNode n) { + if (n == this.pivot) { + this.setPivotFound(true); + } - return !this.isPivotFound(); - } + return !this.isPivotFound(); + } - public boolean isPivotFound() - { - return this.pivotFound; - } + public boolean isPivotFound() { + return this.pivotFound; + } - private void setPivotFound( final boolean pivotFound ) - { - this.pivotFound = pivotFound; - } + private void setPivotFound(final boolean pivotFound) { + this.pivotFound = pivotFound; + } } diff --git a/src/main/java/appeng/me/GridStorage.java b/src/main/java/appeng/me/GridStorage.java index cf9cfc581b0..29fe72dcd6b 100644 --- a/src/main/java/appeng/me/GridStorage.java +++ b/src/main/java/appeng/me/GridStorage.java @@ -18,137 +18,115 @@ package appeng.me; - import appeng.api.networking.IGrid; import appeng.api.networking.IGridStorage; import appeng.core.AELog; import appeng.core.worlddata.WorldData; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.WeakHashMap; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; - -public class GridStorage implements IGridStorage -{ - - private final long myID; - private final NBTTagCompound data; - private final GridStorageSearch mySearchEntry; // keep myself in the list until I'm - private final WeakHashMap divided = new WeakHashMap(); - private WeakReference internalGrid = null; - - // lost... - - /** - * for use with world settings - * - * @param id ID of grid storage - * @param gss grid storage search - */ - public GridStorage( final long id, final GridStorageSearch gss ) - { - this.myID = id; - this.mySearchEntry = gss; - this.data = new NBTTagCompound(); - } - - /** - * for use with world settings - * - * @param input array of bytes string - * @param id ID of grid storage - * @param gss grid storage search - */ - public GridStorage( final String input, final long id, final GridStorageSearch gss ) - { - this.myID = id; - this.mySearchEntry = gss; - NBTTagCompound myTag = null; - - try - { - final byte[] byteData = javax.xml.bind.DatatypeConverter.parseBase64Binary( input ); - myTag = CompressedStreamTools.readCompressed( new ByteArrayInputStream( byteData ) ); - } - catch( final Throwable t ) - { - myTag = new NBTTagCompound(); - } - - this.data = myTag; - } - - /** - * fake storage. - */ - public GridStorage() - { - this.myID = 0; - this.mySearchEntry = null; - this.data = new NBTTagCompound(); - } - - public String getValue() - { - final Grid currentGrid = (Grid) this.getGrid(); - if( currentGrid != null ) - { - currentGrid.saveState(); - } - - try - { - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - CompressedStreamTools.writeCompressed( this.data, out ); - return javax.xml.bind.DatatypeConverter.printBase64Binary( out.toByteArray() ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - - return ""; - } - - public IGrid getGrid() - { - return this.internalGrid == null ? null : this.internalGrid.get(); - } - - void setGrid( final Grid grid ) - { - this.internalGrid = new WeakReference( grid ); - } - - @Override - public NBTTagCompound dataObject() - { - return this.data; - } - - @Override - public long getID() - { - return this.myID; - } - - void addDivided( final GridStorage gs ) - { - this.divided.put( gs, true ); - } - - boolean hasDivided( final GridStorage myStorage ) - { - return this.divided.containsKey( myStorage ); - } - - void remove() - { - WorldData.instance().storageData().destroyGridStorage( this.myID ); - } +public class GridStorage implements IGridStorage { + + private final long myID; + private final NBTTagCompound data; + private final GridStorageSearch mySearchEntry; // keep myself in the list until I'm + private final WeakHashMap divided = new WeakHashMap(); + private WeakReference internalGrid = null; + + // lost... + + /** + * for use with world settings + * + * @param id ID of grid storage + * @param gss grid storage search + */ + public GridStorage(final long id, final GridStorageSearch gss) { + this.myID = id; + this.mySearchEntry = gss; + this.data = new NBTTagCompound(); + } + + /** + * for use with world settings + * + * @param input array of bytes string + * @param id ID of grid storage + * @param gss grid storage search + */ + public GridStorage(final String input, final long id, final GridStorageSearch gss) { + this.myID = id; + this.mySearchEntry = gss; + NBTTagCompound myTag = null; + + try { + final byte[] byteData = javax.xml.bind.DatatypeConverter.parseBase64Binary(input); + myTag = CompressedStreamTools.readCompressed(new ByteArrayInputStream(byteData)); + } catch (final Throwable t) { + myTag = new NBTTagCompound(); + } + + this.data = myTag; + } + + /** + * fake storage. + */ + public GridStorage() { + this.myID = 0; + this.mySearchEntry = null; + this.data = new NBTTagCompound(); + } + + public String getValue() { + final Grid currentGrid = (Grid) this.getGrid(); + if (currentGrid != null) { + currentGrid.saveState(); + } + + try { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + CompressedStreamTools.writeCompressed(this.data, out); + return javax.xml.bind.DatatypeConverter.printBase64Binary(out.toByteArray()); + } catch (final IOException e) { + AELog.debug(e); + } + + return ""; + } + + public IGrid getGrid() { + return this.internalGrid == null ? null : this.internalGrid.get(); + } + + void setGrid(final Grid grid) { + this.internalGrid = new WeakReference(grid); + } + + @Override + public NBTTagCompound dataObject() { + return this.data; + } + + @Override + public long getID() { + return this.myID; + } + + void addDivided(final GridStorage gs) { + this.divided.put(gs, true); + } + + boolean hasDivided(final GridStorage myStorage) { + return this.divided.containsKey(myStorage); + } + + void remove() { + WorldData.instance().storageData().destroyGridStorage(this.myID); + } } diff --git a/src/main/java/appeng/me/GridStorageSearch.java b/src/main/java/appeng/me/GridStorageSearch.java index c410720552c..153efc77752 100644 --- a/src/main/java/appeng/me/GridStorageSearch.java +++ b/src/main/java/appeng/me/GridStorageSearch.java @@ -18,56 +18,45 @@ package appeng.me; - import java.lang.ref.WeakReference; - -public class GridStorageSearch -{ - - private final long id; - private WeakReference gridStorage; - - /** - * for use with the world settings - * - * @param id ID of grid storage search - */ - public GridStorageSearch( final long id ) - { - this.id = id; - } - - @Override - public int hashCode() - { - return ( (Long) this.id ).hashCode(); - } - - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - - final GridStorageSearch other = (GridStorageSearch) obj; - return this.id == other.id; - - } - - public WeakReference getGridStorage() - { - return this.gridStorage; - } - - public void setGridStorage( final WeakReference gridStorage ) - { - this.gridStorage = gridStorage; - } +public class GridStorageSearch { + + private final long id; + private WeakReference gridStorage; + + /** + * for use with the world settings + * + * @param id ID of grid storage search + */ + public GridStorageSearch(final long id) { + this.id = id; + } + + @Override + public int hashCode() { + return ((Long) this.id).hashCode(); + } + + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + + final GridStorageSearch other = (GridStorageSearch) obj; + return this.id == other.id; + } + + public WeakReference getGridStorage() { + return this.gridStorage; + } + + public void setGridStorage(final WeakReference gridStorage) { + this.gridStorage = gridStorage; + } } diff --git a/src/main/java/appeng/me/MachineSet.java b/src/main/java/appeng/me/MachineSet.java index a3de198fd2e..018409473d1 100644 --- a/src/main/java/appeng/me/MachineSet.java +++ b/src/main/java/appeng/me/MachineSet.java @@ -18,29 +18,23 @@ package appeng.me; - import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.networking.IMachineSet; - import java.util.HashSet; +public class MachineSet extends HashSet implements IMachineSet { -public class MachineSet extends HashSet implements IMachineSet -{ - - private static final long serialVersionUID = 3224660708327386933L; + private static final long serialVersionUID = 3224660708327386933L; - private final Class machine; + private final Class machine; - MachineSet( final Class m ) - { - this.machine = m; - } + MachineSet(final Class m) { + this.machine = m; + } - @Override - public Class getMachineClass() - { - return this.machine; - } + @Override + public Class getMachineClass() { + return this.machine; + } } diff --git a/src/main/java/appeng/me/NetworkEventBus.java b/src/main/java/appeng/me/NetworkEventBus.java index f0b640841c2..61ee43d2e27 100644 --- a/src/main/java/appeng/me/NetworkEventBus.java +++ b/src/main/java/appeng/me/NetworkEventBus.java @@ -18,199 +18,155 @@ package appeng.me; - import appeng.api.networking.IGridNode; import appeng.api.networking.events.MENetworkEvent; import appeng.api.networking.events.MENetworkEventSubscribe; import appeng.core.AELog; - import java.lang.reflect.Method; import java.util.*; import java.util.Map.Entry; - -public class NetworkEventBus -{ - private static final Collection READ_CLASSES = new HashSet(); - private static final Map, Map> EVENTS = new HashMap, Map>(); - - void readClass( final Class listAs, final Class c ) - { - if( READ_CLASSES.contains( c ) ) - { - return; - } - READ_CLASSES.add( c ); - - try - { - for( final Method m : c.getMethods() ) - { - final MENetworkEventSubscribe s = m.getAnnotation( MENetworkEventSubscribe.class ); - if( s != null ) - { - final Class[] types = m.getParameterTypes(); - if( types.length == 1 ) - { - if( MENetworkEvent.class.isAssignableFrom( types[0] ) ) - { - - Map classEvents = EVENTS.get( types[0] ); - if( classEvents == null ) - { - EVENTS.put( types[0], classEvents = new HashMap() ); - } - - MENetworkEventInfo thisEvent = classEvents.get( listAs ); - if( thisEvent == null ) - { - thisEvent = new MENetworkEventInfo(); - } - - thisEvent.Add( types[0], c, m ); - - classEvents.put( listAs, thisEvent ); - } - else - { - throw new IllegalStateException( "Invalid ME Network Event Subscriber, " + m.getName() + "s Parameter must extend MENetworkEvent." ); - } - } - else - { - throw new IllegalStateException( "Invalid ME Network Event Subscriber, " + m.getName() + " must have exactly 1 parameter." ); - } - } - } - } - catch( final Throwable t ) - { - throw new IllegalStateException( "Error while adding " + c.getName() + " to event bus", t ); - } - } - - MENetworkEvent postEvent( final Grid g, final MENetworkEvent e ) - { - final Map subscribers = EVENTS.get( e.getClass() ); - int x = 0; - - try - { - if( subscribers != null ) - { - for( final Entry subscriber : subscribers.entrySet() ) - { - final MENetworkEventInfo target = subscriber.getValue(); - final GridCacheWrapper cache = g.getCaches().get( subscriber.getKey() ); - if( cache != null ) - { - x++; - target.invoke( cache.getCache(), e ); - } - - for( final IGridNode obj : g.getMachines( subscriber.getKey() ) ) - { - x++; - target.invoke( obj.getMachine(), e ); - } - } - } - } - catch( final NetworkEventDone done ) - { - // Early out. - } - - e.setVisitedObjects( x ); - return e; - } - - MENetworkEvent postEventTo( final Grid grid, final GridNode node, final MENetworkEvent e ) - { - final Map subscribers = EVENTS.get( e.getClass() ); - int x = 0; - - try - { - if( subscribers != null ) - { - final MENetworkEventInfo target = subscribers.get( node.getMachineClass() ); - if( target != null ) - { - x++; - target.invoke( node.getMachine(), e ); - } - } - } - catch( final NetworkEventDone done ) - { - // Early out. - } - - e.setVisitedObjects( x ); - return e; - } - - private static class NetworkEventDone extends Throwable - { - - private static final long serialVersionUID = -3079021487019171205L; - } - - - private class EventMethod - { - - private final Class objClass; - private final Method objMethod; - private final Class objEvent; - - public EventMethod( final Class Event, final Class ObjClass, final Method ObjMethod ) - { - this.objClass = ObjClass; - this.objMethod = ObjMethod; - this.objEvent = Event; - } - - private void invoke( final Object obj, final MENetworkEvent e ) throws NetworkEventDone - { - try - { - this.objMethod.invoke( obj, e ); - } - catch( final Throwable e1 ) - { - AELog.error( "[AppEng] Network Event caused exception:" ); - AELog.error( "Offending Class: " + obj.getClass().getName() ); - AELog.error( "Offending Object: " + obj.toString() ); - AELog.debug( e1 ); - throw new IllegalStateException( e1 ); - } - - if( e.isCanceled() ) - { - throw new NetworkEventDone(); - } - } - } - - - private class MENetworkEventInfo - { - - private final List methods = new ArrayList(); - - private void Add( final Class Event, final Class ObjClass, final Method ObjMethod ) - { - this.methods.add( new EventMethod( Event, ObjClass, ObjMethod ) ); - } - - private void invoke( final Object obj, final MENetworkEvent e ) throws NetworkEventDone - { - for( final EventMethod em : this.methods ) - { - em.invoke( obj, e ); - } - } - } +public class NetworkEventBus { + private static final Collection READ_CLASSES = new HashSet(); + private static final Map, Map> EVENTS = + new HashMap, Map>(); + + void readClass(final Class listAs, final Class c) { + if (READ_CLASSES.contains(c)) { + return; + } + READ_CLASSES.add(c); + + try { + for (final Method m : c.getMethods()) { + final MENetworkEventSubscribe s = m.getAnnotation(MENetworkEventSubscribe.class); + if (s != null) { + final Class[] types = m.getParameterTypes(); + if (types.length == 1) { + if (MENetworkEvent.class.isAssignableFrom(types[0])) { + + Map classEvents = EVENTS.get(types[0]); + if (classEvents == null) { + EVENTS.put(types[0], classEvents = new HashMap()); + } + + MENetworkEventInfo thisEvent = classEvents.get(listAs); + if (thisEvent == null) { + thisEvent = new MENetworkEventInfo(); + } + + thisEvent.Add(types[0], c, m); + + classEvents.put(listAs, thisEvent); + } else { + throw new IllegalStateException("Invalid ME Network Event Subscriber, " + m.getName() + + "s Parameter must extend MENetworkEvent."); + } + } else { + throw new IllegalStateException("Invalid ME Network Event Subscriber, " + m.getName() + + " must have exactly 1 parameter."); + } + } + } + } catch (final Throwable t) { + throw new IllegalStateException("Error while adding " + c.getName() + " to event bus", t); + } + } + + MENetworkEvent postEvent(final Grid g, final MENetworkEvent e) { + final Map subscribers = EVENTS.get(e.getClass()); + int x = 0; + + try { + if (subscribers != null) { + for (final Entry subscriber : subscribers.entrySet()) { + final MENetworkEventInfo target = subscriber.getValue(); + final GridCacheWrapper cache = g.getCaches().get(subscriber.getKey()); + if (cache != null) { + x++; + target.invoke(cache.getCache(), e); + } + + for (final IGridNode obj : g.getMachines(subscriber.getKey())) { + x++; + target.invoke(obj.getMachine(), e); + } + } + } + } catch (final NetworkEventDone done) { + // Early out. + } + + e.setVisitedObjects(x); + return e; + } + + MENetworkEvent postEventTo(final Grid grid, final GridNode node, final MENetworkEvent e) { + final Map subscribers = EVENTS.get(e.getClass()); + int x = 0; + + try { + if (subscribers != null) { + final MENetworkEventInfo target = subscribers.get(node.getMachineClass()); + if (target != null) { + x++; + target.invoke(node.getMachine(), e); + } + } + } catch (final NetworkEventDone done) { + // Early out. + } + + e.setVisitedObjects(x); + return e; + } + + private static class NetworkEventDone extends Throwable { + + private static final long serialVersionUID = -3079021487019171205L; + } + + private class EventMethod { + + private final Class objClass; + private final Method objMethod; + private final Class objEvent; + + public EventMethod(final Class Event, final Class ObjClass, final Method ObjMethod) { + this.objClass = ObjClass; + this.objMethod = ObjMethod; + this.objEvent = Event; + } + + private void invoke(final Object obj, final MENetworkEvent e) throws NetworkEventDone { + try { + this.objMethod.invoke(obj, e); + } catch (final Throwable e1) { + AELog.error("[AppEng] Network Event caused exception:"); + AELog.error("Offending Class: " + obj.getClass().getName()); + AELog.error("Offending Object: " + obj.toString()); + AELog.debug(e1); + throw new IllegalStateException(e1); + } + + if (e.isCanceled()) { + throw new NetworkEventDone(); + } + } + } + + private class MENetworkEventInfo { + + private final List methods = new ArrayList(); + + private void Add(final Class Event, final Class ObjClass, final Method ObjMethod) { + this.methods.add(new EventMethod(Event, ObjClass, ObjMethod)); + } + + private void invoke(final Object obj, final MENetworkEvent e) throws NetworkEventDone { + for (final EventMethod em : this.methods) { + em.invoke(obj, e); + } + } + } } diff --git a/src/main/java/appeng/me/NetworkList.java b/src/main/java/appeng/me/NetworkList.java index 9397d27621c..16118a51a0e 100644 --- a/src/main/java/appeng/me/NetworkList.java +++ b/src/main/java/appeng/me/NetworkList.java @@ -18,96 +18,80 @@ package appeng.me; - import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; - /** * TODO: Test if copy was actually necessary. */ -public class NetworkList implements Collection -{ - - private List networks = new CopyOnWriteArrayList(); - - @Override - public int size() - { - return this.networks.size(); - } - - @Override - public boolean isEmpty() - { - return this.networks.isEmpty(); - } - - @Override - public boolean contains( final Object o ) - { - return this.networks.contains( o ); - } - - @Override - public Iterator iterator() - { - return this.networks.iterator(); - } - - @Override - public Object[] toArray() - { - return this.networks.toArray(); - } - - @Override - public T[] toArray( final T[] a ) - { - return this.networks.toArray( a ); - } - - @Override - public boolean add( final Grid e ) - { - return this.networks.add( e ); - } - - @Override - public boolean remove( final Object o ) - { - return this.networks.remove( o ); - } - - @Override - public boolean containsAll( final Collection c ) - { - return this.networks.containsAll( c ); - } - - @Override - public boolean addAll( final Collection c ) - { - return this.networks.addAll( c ); - } - - @Override - public boolean removeAll( final Collection c ) - { - return this.networks.removeAll( c ); - } - - @Override - public boolean retainAll( final Collection c ) - { - return this.networks.retainAll( c ); - } - - @Override - public void clear() - { - this.networks.clear(); - } +public class NetworkList implements Collection { + + private List networks = new CopyOnWriteArrayList(); + + @Override + public int size() { + return this.networks.size(); + } + + @Override + public boolean isEmpty() { + return this.networks.isEmpty(); + } + + @Override + public boolean contains(final Object o) { + return this.networks.contains(o); + } + + @Override + public Iterator iterator() { + return this.networks.iterator(); + } + + @Override + public Object[] toArray() { + return this.networks.toArray(); + } + + @Override + public T[] toArray(final T[] a) { + return this.networks.toArray(a); + } + + @Override + public boolean add(final Grid e) { + return this.networks.add(e); + } + + @Override + public boolean remove(final Object o) { + return this.networks.remove(o); + } + + @Override + public boolean containsAll(final Collection c) { + return this.networks.containsAll(c); + } + + @Override + public boolean addAll(final Collection c) { + return this.networks.addAll(c); + } + + @Override + public boolean removeAll(final Collection c) { + return this.networks.removeAll(c); + } + + @Override + public boolean retainAll(final Collection c) { + return this.networks.retainAll(c); + } + + @Override + public void clear() { + this.networks.clear(); + } } diff --git a/src/main/java/appeng/me/cache/CraftingGridCache.java b/src/main/java/appeng/me/cache/CraftingGridCache.java index 61ac3354bf2..c5c23ab42d5 100644 --- a/src/main/java/appeng/me/cache/CraftingGridCache.java +++ b/src/main/java/appeng/me/cache/CraftingGridCache.java @@ -18,7 +18,6 @@ package appeng.me.cache; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.IGrid; @@ -49,599 +48,515 @@ import appeng.tile.crafting.TileCraftingTile; import appeng.util.ItemSorters; import com.google.common.collect.*; -import net.minecraft.world.World; - import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; -import java.util.stream.Stream; import java.util.stream.StreamSupport; +import net.minecraft.world.World; - -public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper, ICellProvider, IMEInventoryHandler -{ - - private static final ExecutorService CRAFTING_POOL; - private static final Comparator COMPARATOR = new Comparator() - { - @Override - public int compare( final ICraftingPatternDetails firstDetail, final ICraftingPatternDetails nextDetail ) - { - return nextDetail.getPriority() - firstDetail.getPriority(); - } - }; - - static - { - final ThreadFactory factory = new ThreadFactory() - { - - @Override - public Thread newThread( final Runnable ar ) - { - return new Thread( ar, "AE Crafting Calculator" ); - } - }; - - CRAFTING_POOL = Executors.newCachedThreadPool( factory ); - } - - private final Set craftingCPUClusters = new HashSet(); - private final Set craftingProviders = new HashSet(); - private final Map craftingWatchers = new HashMap(); - private final IGrid grid; - private final Map> craftingMethods = new HashMap>(); - private final Map> craftableItems = new HashMap>(); - private final Set emitableItems = new HashSet(); - private final Map craftingLinks = new HashMap(); - private final Multimap interests = HashMultimap.create(); - private final GenericInterestManager interestManager = new GenericInterestManager( this.interests ); - private IStorageGrid storageGrid; - private IEnergyGrid energyGrid; - private boolean updateList = false; - - public CraftingGridCache( final IGrid grid ) - { - this.grid = grid; - } - - @MENetworkEventSubscribe - public void afterCacheConstruction( final MENetworkPostCacheConstruction cacheConstruction ) - { - this.storageGrid = this.grid.getCache( IStorageGrid.class ); - this.energyGrid = this.grid.getCache( IEnergyGrid.class ); - - this.storageGrid.registerCellProvider( this ); - } - - @Override - public void onUpdateTick() - { - if( this.updateList ) - { - this.updateList = false; - this.updateCPUClusters(); - } - - final Iterator craftingLinkIterator = this.craftingLinks.values().iterator(); - while( craftingLinkIterator.hasNext() ) - { - if( craftingLinkIterator.next().isDead( this.grid, this ) ) - { - craftingLinkIterator.remove(); - } - } - - for( final CraftingCPUCluster cpu : this.craftingCPUClusters ) - { - cpu.updateCraftingLogic( this.grid, this.energyGrid, this ); - } - } - - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof ICraftingWatcherHost ) - { - final ICraftingWatcher craftingWatcher = this.craftingWatchers.get( machine ); - if( craftingWatcher != null ) - { - craftingWatcher.clear(); - this.craftingWatchers.remove( machine ); - } - } - - if( machine instanceof ICraftingRequester ) - { - for( final CraftingLinkNexus link : this.craftingLinks.values() ) - { - if( link.isMachine( machine ) ) - { - link.removeNode(); - } - } - } - - if( machine instanceof TileCraftingTile ) - { - this.updateList = true; - } - - if( machine instanceof ICraftingProvider ) - { - this.craftingProviders.remove( machine ); - this.updatePatterns(); - } - } - - @Override - public void addNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof ICraftingWatcherHost ) - { - final ICraftingWatcherHost watcherHost = (ICraftingWatcherHost) machine; - final CraftingWatcher watcher = new CraftingWatcher( this, watcherHost ); - this.craftingWatchers.put( gridNode, watcher ); - watcherHost.updateWatcher( watcher ); - } - - if( machine instanceof ICraftingRequester ) - { - for( final ICraftingLink link : ( (ICraftingRequester) machine ).getRequestedJobs() ) - { - if( link instanceof CraftingLink ) - { - this.addLink( (CraftingLink) link ); - } - } - } - - if( machine instanceof TileCraftingTile ) - { - this.updateList = true; - } - - if( machine instanceof ICraftingProvider ) - { - this.craftingProviders.add( (ICraftingProvider) machine ); - this.updatePatterns(); - } - } - - @Override - public void onSplit( final IGridStorage destinationStorage ) - { // nothing! - } - - @Override - public void onJoin( final IGridStorage sourceStorage ) - { - // nothing! - } - - @Override - public void populateGridStorage( final IGridStorage destinationStorage ) - { - // nothing! - } - - private void updatePatterns() - { - final Map> oldItems = this.craftableItems; - - // erase list. - this.craftingMethods.clear(); - this.craftableItems.clear(); - this.emitableItems.clear(); - - // update the stuff that was in the list... - this.storageGrid.postAlterationOfStoredItems( StorageChannel.ITEMS, oldItems.keySet(), new BaseActionSource() ); - - // re-create list.. - for( final ICraftingProvider provider : this.craftingProviders ) - { - provider.provideCrafting( this ); - } - - final Map> tmpCraft = new HashMap>(); - - // new craftables! - for( final ICraftingPatternDetails details : this.craftingMethods.keySet() ) - { - for( IAEItemStack out : details.getOutputs() ) - { - out = out.copy(); - out.reset(); - out.setCraftable( true ); - - Set methods = tmpCraft.get( out ); - - if( methods == null ) - { - tmpCraft.put( out, methods = new TreeSet( COMPARATOR ) ); - } - - methods.add( details ); - } - } - - // make them immutable - for( final Entry> e : tmpCraft.entrySet() ) - { - this.craftableItems.put( e.getKey(), ImmutableList.copyOf( e.getValue() ) ); - } - - this.storageGrid.postAlterationOfStoredItems( StorageChannel.ITEMS, this.craftableItems.keySet(), new BaseActionSource() ); - } - - private void updateCPUClusters() - { - this.craftingCPUClusters.clear(); - - for (Object cls: StreamSupport.stream(grid.getMachinesClasses().spliterator(),false).filter(c -> TileCraftingStorageTile.class.isAssignableFrom(c)).toArray()) - { - for( final IGridNode cst : this.grid.getMachines( (Class) cls ) ) - { - final TileCraftingStorageTile tile = (TileCraftingStorageTile) cst.getMachine(); - final CraftingCPUCluster cluster = (CraftingCPUCluster) tile.getCluster(); - if( cluster != null ) - { - this.craftingCPUClusters.add( cluster ); - - if( cluster.getLastCraftingLink() != null ) - { - this.addLink( (CraftingLink) cluster.getLastCraftingLink() ); - } - } - } - } - } - - public void addLink( final CraftingLink link ) - { - if( link.isStandalone() ) - { - return; - } - - CraftingLinkNexus nexus = this.craftingLinks.get( link.getCraftingID() ); - if( nexus == null ) - { - this.craftingLinks.put( link.getCraftingID(), nexus = new CraftingLinkNexus( link.getCraftingID() ) ); - } - - link.setNexus( nexus ); - } - - @MENetworkEventSubscribe - public void updateCPUClusters( final MENetworkCraftingCpuChange c ) - { - this.updateList = true; - } - - @MENetworkEventSubscribe - public void updateCPUClusters( final MENetworkCraftingPatternChange c ) - { - this.updatePatterns(); - } - - @Override - public void addCraftingOption( final ICraftingMedium medium, final ICraftingPatternDetails api ) - { - List details = this.craftingMethods.get( api ); - if( details == null ) - { - details = new ArrayList(); - details.add( medium ); - this.craftingMethods.put( api, details ); - } - else - { - details.add( medium ); - } - } - - @Override - public void setEmitable( final IAEItemStack someItem ) - { - this.emitableItems.add( someItem.copy() ); - } - - @Override - public List getCellArray( final StorageChannel channel ) - { - final List list = new ArrayList( 1 ); - - if( channel == StorageChannel.ITEMS ) - { - list.add( this ); - } - - return list; - } - - @Override - public int getPriority() - { - return Integer.MAX_VALUE; - } - - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.WRITE; - } - - @Override - public boolean isPrioritized( final IAEStack input ) - { - return true; - } - - @Override - public boolean canAccept( final IAEStack input ) - { - for( final CraftingCPUCluster cpu : this.craftingCPUClusters ) - { - if( cpu.canAccept( input ) ) - { - return true; - } - } - - return false; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return i == 1; - } - - @Override - public IAEStack injectItems( IAEStack input, final Actionable type, final BaseActionSource src ) - { - for( final CraftingCPUCluster cpu : this.craftingCPUClusters ) - { - input = cpu.injectItems( input, type, src ); - } - - return input; - } - - @Override - public IAEStack extractItems( final IAEStack request, final Actionable mode, final BaseActionSource src ) - { - return null; - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - // add craftable items! - for( final IAEItemStack stack : this.craftableItems.keySet() ) - { - out.addCrafting( stack ); - } - - for( final IAEItemStack st : this.emitableItems ) - { - out.addCrafting( st ); - } - - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public ImmutableCollection getCraftingFor( final IAEItemStack whatToCraft, final ICraftingPatternDetails details, final int slotIndex, final World world ) - { - final ImmutableList res = this.craftableItems.get( whatToCraft ); - - if( res == null ) - { - if( details != null && details.isCraftable() ) - { - for( final IAEItemStack ais : this.craftableItems.keySet() ) - { - if( ais.getItem() == whatToCraft.getItem() && ( !ais.getItem().getHasSubtypes() || ais.getItemDamage() == whatToCraft.getItemDamage() ) ) - { - if( details.isValidItemForSlot( slotIndex, ais.getItemStack(), world ) ) - { - return this.craftableItems.get( ais ); - } - } - } - } - - return ImmutableSet.of(); - } - - return res; - } - - @Override - public Future beginCraftingJob( final World world, final IGrid grid, final BaseActionSource actionSrc, final IAEItemStack slotItem, final ICraftingCallback cb ) - { - if( world == null || grid == null || actionSrc == null || slotItem == null ) - { - throw new IllegalArgumentException( "Invalid Crafting Job Request" ); - } - - final CraftingJob job = new CraftingJob( world, grid, actionSrc, slotItem, cb ); - - return CRAFTING_POOL.submit( job, (ICraftingJob) job ); - } - - @Override - public ICraftingLink submitJob( final ICraftingJob job, final ICraftingRequester requestingMachine, final ICraftingCPU target, final boolean prioritizePower, final BaseActionSource src ) - { - if( job.isSimulation() ) - { - return null; - } - - CraftingCPUCluster cpuCluster = null; - - if( target instanceof CraftingCPUCluster ) - { - cpuCluster = (CraftingCPUCluster) target; - } - - if( target == null ) - { - final List validCpusClusters = new ArrayList(); - for( final CraftingCPUCluster cpu : this.craftingCPUClusters ) - { - if( cpu.isActive() && !cpu.isBusy() && cpu.getAvailableStorage() >= job.getByteTotal() ) - { - validCpusClusters.add( cpu ); - } - } - - Collections.sort( validCpusClusters, new Comparator() - { - private int compareInternal(CraftingCPUCluster firstCluster, CraftingCPUCluster nextCluster) - { - int comparison = ItemSorters.compareLong( nextCluster.getCoProcessors(), firstCluster.getCoProcessors() ); - if( comparison == 0 ) - comparison = ItemSorters.compareLong( nextCluster.getAvailableStorage(), firstCluster.getAvailableStorage() ); - if( comparison == 0 ) - return nextCluster.getName().compareTo(firstCluster.getName()); - else - return comparison; - } - @Override - public int compare( final CraftingCPUCluster firstCluster, final CraftingCPUCluster nextCluster ) - { - if( prioritizePower ) - return compareInternal(firstCluster, nextCluster); - else - return compareInternal(nextCluster, firstCluster); - } - } ); - - if( !validCpusClusters.isEmpty() ) - { - cpuCluster = validCpusClusters.get( 0 ); - } - } - - if( cpuCluster != null ) - { - return cpuCluster.submitJob( this.grid, job, src, requestingMachine ); - } - - return null; - } - - @Override - public ImmutableSet getCpus() - { - return ImmutableSet.copyOf( new ActiveCpuIterator( this.craftingCPUClusters ) ); - } - - @Override - public boolean canEmitFor( final IAEItemStack someItem ) - { - return this.emitableItems.contains( someItem ); - } - - @Override - public boolean isRequesting( final IAEItemStack what ) - { - for( final CraftingCPUCluster cluster : this.craftingCPUClusters ) - { - if( cluster.isMaking( what ) ) - { - return true; - } - } - - return false; - } - - public List getMediums( final ICraftingPatternDetails key ) - { - List mediums = this.craftingMethods.get( key ); - - if( mediums == null ) - { - mediums = ImmutableList.of(); - } - - return mediums; - } - - public boolean hasCpu( final ICraftingCPU cpu ) - { - return this.craftingCPUClusters.contains( cpu ); - } - - public GenericInterestManager getInterestManager() - { - return this.interestManager; - } - - private static class ActiveCpuIterator implements Iterator - { - - private final Iterator iterator; - private CraftingCPUCluster cpuCluster; - - public ActiveCpuIterator( final Collection o ) - { - this.iterator = o.iterator(); - this.cpuCluster = null; - } - - @Override - public boolean hasNext() - { - this.findNext(); - - return this.cpuCluster != null; - } - - private void findNext() - { - while( this.iterator.hasNext() && this.cpuCluster == null ) - { - this.cpuCluster = this.iterator.next(); - if( !this.cpuCluster.isActive() || this.cpuCluster.isDestroyed() ) - { - this.cpuCluster = null; - } - } - } - - @Override - public ICraftingCPU next() - { - final ICraftingCPU o = this.cpuCluster; - this.cpuCluster = null; - - return o; - } - - @Override - public void remove() - { - // no.. - } - } +public class CraftingGridCache + implements ICraftingGrid, ICraftingProviderHelper, ICellProvider, IMEInventoryHandler { + + private static final ExecutorService CRAFTING_POOL; + private static final Comparator COMPARATOR = new Comparator() { + @Override + public int compare(final ICraftingPatternDetails firstDetail, final ICraftingPatternDetails nextDetail) { + return nextDetail.getPriority() - firstDetail.getPriority(); + } + }; + + static { + final ThreadFactory factory = new ThreadFactory() { + + @Override + public Thread newThread(final Runnable ar) { + return new Thread(ar, "AE Crafting Calculator"); + } + }; + + CRAFTING_POOL = Executors.newCachedThreadPool(factory); + } + + private final Set craftingCPUClusters = new HashSet(); + private final Set craftingProviders = new HashSet(); + private final Map craftingWatchers = new HashMap(); + private final IGrid grid; + private final Map> craftingMethods = + new HashMap>(); + private final Map> craftableItems = + new HashMap>(); + private final Set emitableItems = new HashSet(); + private final Map craftingLinks = new HashMap(); + private final Multimap interests = HashMultimap.create(); + private final GenericInterestManager interestManager = + new GenericInterestManager(this.interests); + private IStorageGrid storageGrid; + private IEnergyGrid energyGrid; + private boolean updateList = false; + + public CraftingGridCache(final IGrid grid) { + this.grid = grid; + } + + @MENetworkEventSubscribe + public void afterCacheConstruction(final MENetworkPostCacheConstruction cacheConstruction) { + this.storageGrid = this.grid.getCache(IStorageGrid.class); + this.energyGrid = this.grid.getCache(IEnergyGrid.class); + + this.storageGrid.registerCellProvider(this); + } + + @Override + public void onUpdateTick() { + if (this.updateList) { + this.updateList = false; + this.updateCPUClusters(); + } + + final Iterator craftingLinkIterator = + this.craftingLinks.values().iterator(); + while (craftingLinkIterator.hasNext()) { + if (craftingLinkIterator.next().isDead(this.grid, this)) { + craftingLinkIterator.remove(); + } + } + + for (final CraftingCPUCluster cpu : this.craftingCPUClusters) { + cpu.updateCraftingLogic(this.grid, this.energyGrid, this); + } + } + + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof ICraftingWatcherHost) { + final ICraftingWatcher craftingWatcher = this.craftingWatchers.get(machine); + if (craftingWatcher != null) { + craftingWatcher.clear(); + this.craftingWatchers.remove(machine); + } + } + + if (machine instanceof ICraftingRequester) { + for (final CraftingLinkNexus link : this.craftingLinks.values()) { + if (link.isMachine(machine)) { + link.removeNode(); + } + } + } + + if (machine instanceof TileCraftingTile) { + this.updateList = true; + } + + if (machine instanceof ICraftingProvider) { + this.craftingProviders.remove(machine); + this.updatePatterns(); + } + } + + @Override + public void addNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof ICraftingWatcherHost) { + final ICraftingWatcherHost watcherHost = (ICraftingWatcherHost) machine; + final CraftingWatcher watcher = new CraftingWatcher(this, watcherHost); + this.craftingWatchers.put(gridNode, watcher); + watcherHost.updateWatcher(watcher); + } + + if (machine instanceof ICraftingRequester) { + for (final ICraftingLink link : ((ICraftingRequester) machine).getRequestedJobs()) { + if (link instanceof CraftingLink) { + this.addLink((CraftingLink) link); + } + } + } + + if (machine instanceof TileCraftingTile) { + this.updateList = true; + } + + if (machine instanceof ICraftingProvider) { + this.craftingProviders.add((ICraftingProvider) machine); + this.updatePatterns(); + } + } + + @Override + public void onSplit(final IGridStorage destinationStorage) { // nothing! + } + + @Override + public void onJoin(final IGridStorage sourceStorage) { + // nothing! + } + + @Override + public void populateGridStorage(final IGridStorage destinationStorage) { + // nothing! + } + + private void updatePatterns() { + final Map> oldItems = this.craftableItems; + + // erase list. + this.craftingMethods.clear(); + this.craftableItems.clear(); + this.emitableItems.clear(); + + // update the stuff that was in the list... + this.storageGrid.postAlterationOfStoredItems(StorageChannel.ITEMS, oldItems.keySet(), new BaseActionSource()); + + // re-create list.. + for (final ICraftingProvider provider : this.craftingProviders) { + provider.provideCrafting(this); + } + + final Map> tmpCraft = + new HashMap>(); + + // new craftables! + for (final ICraftingPatternDetails details : this.craftingMethods.keySet()) { + for (IAEItemStack out : details.getOutputs()) { + out = out.copy(); + out.reset(); + out.setCraftable(true); + + Set methods = tmpCraft.get(out); + + if (methods == null) { + tmpCraft.put(out, methods = new TreeSet(COMPARATOR)); + } + + methods.add(details); + } + } + + // make them immutable + for (final Entry> e : tmpCraft.entrySet()) { + this.craftableItems.put(e.getKey(), ImmutableList.copyOf(e.getValue())); + } + + this.storageGrid.postAlterationOfStoredItems( + StorageChannel.ITEMS, this.craftableItems.keySet(), new BaseActionSource()); + } + + private void updateCPUClusters() { + this.craftingCPUClusters.clear(); + + for (Object cls : StreamSupport.stream(grid.getMachinesClasses().spliterator(), false) + .filter(c -> TileCraftingStorageTile.class.isAssignableFrom(c)) + .toArray()) { + for (final IGridNode cst : this.grid.getMachines((Class) cls)) { + final TileCraftingStorageTile tile = (TileCraftingStorageTile) cst.getMachine(); + final CraftingCPUCluster cluster = (CraftingCPUCluster) tile.getCluster(); + if (cluster != null) { + this.craftingCPUClusters.add(cluster); + + if (cluster.getLastCraftingLink() != null) { + this.addLink((CraftingLink) cluster.getLastCraftingLink()); + } + } + } + } + } + + public void addLink(final CraftingLink link) { + if (link.isStandalone()) { + return; + } + + CraftingLinkNexus nexus = this.craftingLinks.get(link.getCraftingID()); + if (nexus == null) { + this.craftingLinks.put(link.getCraftingID(), nexus = new CraftingLinkNexus(link.getCraftingID())); + } + + link.setNexus(nexus); + } + + @MENetworkEventSubscribe + public void updateCPUClusters(final MENetworkCraftingCpuChange c) { + this.updateList = true; + } + + @MENetworkEventSubscribe + public void updateCPUClusters(final MENetworkCraftingPatternChange c) { + this.updatePatterns(); + } + + @Override + public void addCraftingOption(final ICraftingMedium medium, final ICraftingPatternDetails api) { + List details = this.craftingMethods.get(api); + if (details == null) { + details = new ArrayList(); + details.add(medium); + this.craftingMethods.put(api, details); + } else { + details.add(medium); + } + } + + @Override + public void setEmitable(final IAEItemStack someItem) { + this.emitableItems.add(someItem.copy()); + } + + @Override + public List getCellArray(final StorageChannel channel) { + final List list = new ArrayList(1); + + if (channel == StorageChannel.ITEMS) { + list.add(this); + } + + return list; + } + + @Override + public int getPriority() { + return Integer.MAX_VALUE; + } + + @Override + public AccessRestriction getAccess() { + return AccessRestriction.WRITE; + } + + @Override + public boolean isPrioritized(final IAEStack input) { + return true; + } + + @Override + public boolean canAccept(final IAEStack input) { + for (final CraftingCPUCluster cpu : this.craftingCPUClusters) { + if (cpu.canAccept(input)) { + return true; + } + } + + return false; + } + + @Override + public int getSlot() { + return 0; + } + + @Override + public boolean validForPass(final int i) { + return i == 1; + } + + @Override + public IAEStack injectItems(IAEStack input, final Actionable type, final BaseActionSource src) { + for (final CraftingCPUCluster cpu : this.craftingCPUClusters) { + input = cpu.injectItems(input, type, src); + } + + return input; + } + + @Override + public IAEStack extractItems(final IAEStack request, final Actionable mode, final BaseActionSource src) { + return null; + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + // add craftable items! + for (final IAEItemStack stack : this.craftableItems.keySet()) { + out.addCrafting(stack); + } + + for (final IAEItemStack st : this.emitableItems) { + out.addCrafting(st); + } + + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } + + @Override + public ImmutableCollection getCraftingFor( + final IAEItemStack whatToCraft, + final ICraftingPatternDetails details, + final int slotIndex, + final World world) { + final ImmutableList res = this.craftableItems.get(whatToCraft); + + if (res == null) { + if (details != null && details.isCraftable()) { + for (final IAEItemStack ais : this.craftableItems.keySet()) { + if (ais.getItem() == whatToCraft.getItem() + && (!ais.getItem().getHasSubtypes() + || ais.getItemDamage() == whatToCraft.getItemDamage())) { + if (details.isValidItemForSlot(slotIndex, ais.getItemStack(), world)) { + return this.craftableItems.get(ais); + } + } + } + } + + return ImmutableSet.of(); + } + + return res; + } + + @Override + public Future beginCraftingJob( + final World world, + final IGrid grid, + final BaseActionSource actionSrc, + final IAEItemStack slotItem, + final ICraftingCallback cb) { + if (world == null || grid == null || actionSrc == null || slotItem == null) { + throw new IllegalArgumentException("Invalid Crafting Job Request"); + } + + final CraftingJob job = new CraftingJob(world, grid, actionSrc, slotItem, cb); + + return CRAFTING_POOL.submit(job, (ICraftingJob) job); + } + + @Override + public ICraftingLink submitJob( + final ICraftingJob job, + final ICraftingRequester requestingMachine, + final ICraftingCPU target, + final boolean prioritizePower, + final BaseActionSource src) { + if (job.isSimulation()) { + return null; + } + + CraftingCPUCluster cpuCluster = null; + + if (target instanceof CraftingCPUCluster) { + cpuCluster = (CraftingCPUCluster) target; + } + + if (target == null) { + final List validCpusClusters = new ArrayList(); + for (final CraftingCPUCluster cpu : this.craftingCPUClusters) { + if (cpu.isActive() && !cpu.isBusy() && cpu.getAvailableStorage() >= job.getByteTotal()) { + validCpusClusters.add(cpu); + } + } + + Collections.sort(validCpusClusters, new Comparator() { + private int compareInternal(CraftingCPUCluster firstCluster, CraftingCPUCluster nextCluster) { + int comparison = + ItemSorters.compareLong(nextCluster.getCoProcessors(), firstCluster.getCoProcessors()); + if (comparison == 0) + comparison = ItemSorters.compareLong( + nextCluster.getAvailableStorage(), firstCluster.getAvailableStorage()); + if (comparison == 0) return nextCluster.getName().compareTo(firstCluster.getName()); + else return comparison; + } + + @Override + public int compare(final CraftingCPUCluster firstCluster, final CraftingCPUCluster nextCluster) { + if (prioritizePower) return compareInternal(firstCluster, nextCluster); + else return compareInternal(nextCluster, firstCluster); + } + }); + + if (!validCpusClusters.isEmpty()) { + cpuCluster = validCpusClusters.get(0); + } + } + + if (cpuCluster != null) { + return cpuCluster.submitJob(this.grid, job, src, requestingMachine); + } + + return null; + } + + @Override + public ImmutableSet getCpus() { + return ImmutableSet.copyOf(new ActiveCpuIterator(this.craftingCPUClusters)); + } + + @Override + public boolean canEmitFor(final IAEItemStack someItem) { + return this.emitableItems.contains(someItem); + } + + @Override + public boolean isRequesting(final IAEItemStack what) { + for (final CraftingCPUCluster cluster : this.craftingCPUClusters) { + if (cluster.isMaking(what)) { + return true; + } + } + + return false; + } + + public List getMediums(final ICraftingPatternDetails key) { + List mediums = this.craftingMethods.get(key); + + if (mediums == null) { + mediums = ImmutableList.of(); + } + + return mediums; + } + + public boolean hasCpu(final ICraftingCPU cpu) { + return this.craftingCPUClusters.contains(cpu); + } + + public GenericInterestManager getInterestManager() { + return this.interestManager; + } + + private static class ActiveCpuIterator implements Iterator { + + private final Iterator iterator; + private CraftingCPUCluster cpuCluster; + + public ActiveCpuIterator(final Collection o) { + this.iterator = o.iterator(); + this.cpuCluster = null; + } + + @Override + public boolean hasNext() { + this.findNext(); + + return this.cpuCluster != null; + } + + private void findNext() { + while (this.iterator.hasNext() && this.cpuCluster == null) { + this.cpuCluster = this.iterator.next(); + if (!this.cpuCluster.isActive() || this.cpuCluster.isDestroyed()) { + this.cpuCluster = null; + } + } + } + + @Override + public ICraftingCPU next() { + final ICraftingCPU o = this.cpuCluster; + this.cpuCluster = null; + + return o; + } + + @Override + public void remove() { + // no.. + } + } } diff --git a/src/main/java/appeng/me/cache/EnergyGridCache.java b/src/main/java/appeng/me/cache/EnergyGridCache.java index 2a5cc7904a7..e9ace01ffa5 100644 --- a/src/main/java/appeng/me/cache/EnergyGridCache.java +++ b/src/main/java/appeng/me/cache/EnergyGridCache.java @@ -18,7 +18,6 @@ package appeng.me.cache; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -33,588 +32,499 @@ import appeng.me.energy.EnergyWatcher; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; - import java.util.*; - -public class EnergyGridCache implements IEnergyGrid -{ - - private final TreeSet interests = new TreeSet(); - private final double AvgLength = 40.0; - private final Set providers = new LinkedHashSet(); - private final Set requesters = new LinkedHashSet(); - private final Multiset energyGridProviders = HashMultiset.create(); - private final IGrid myGrid; - private final HashMap watchers = new HashMap(); - private final Set localSeen = new HashSet(); - /** - * estimated power available. - */ - private int availableTicksSinceUpdate = 0; - private double globalAvailablePower = 0; - private double globalMaxPower = 0; - /** - * idle draw. - */ - private double drainPerTick = 0; - private double avgDrainPerTick = 0; - private double avgInjectionPerTick = 0; - private double tickDrainPerTick = 0; - private double tickInjectionPerTick = 0; - /** - * power status - */ - private boolean publicHasPower = false; - private boolean hasPower = true; - private long ticksSinceHasPowerChange = 900; - /** - * excess power in the system. - */ - private double extra = 0; - private IAEPowerStorage lastProvider; - private IAEPowerStorage lastRequester; - private PathGridCache pgc; - private double lastStoredPower = -1; - - public EnergyGridCache( final IGrid g ) - { - this.myGrid = g; - } - - @MENetworkEventSubscribe - public void postInit( final MENetworkPostCacheConstruction pcc ) - { - this.pgc = this.myGrid.getCache( IPathingGrid.class ); - } - - @MENetworkEventSubscribe - public void EnergyNodeChanges( final MENetworkPowerIdleChange ev ) - { - // update power usage based on event. - final GridNode node = (GridNode) ev.node; - final IGridBlock gb = node.getGridBlock(); - - final double newDraw = gb.getIdlePowerUsage(); - final double diffDraw = newDraw - node.getPreviousDraw(); - node.setPreviousDraw( newDraw ); - - this.drainPerTick += diffDraw; - } - - @MENetworkEventSubscribe - public void EnergyNodeChanges( final MENetworkPowerStorage ev ) - { - if( ev.storage.isAEPublicPowerStorage() ) - { - switch( ev.type ) - { - case PROVIDE_POWER: - if( ev.storage.getPowerFlow() != AccessRestriction.WRITE ) - { - this.providers.add( ev.storage ); - } - break; - case REQUEST_POWER: - if( ev.storage.getPowerFlow() != AccessRestriction.READ ) - { - this.requesters.add( ev.storage ); - } - break; - } - } - else - { - ( new RuntimeException( "Attempt to ask the IEnergyGrid to charge a non public energy store." ) ).printStackTrace(); - } - } - - @Override - public void onUpdateTick() - { - if( !this.getInterests().isEmpty() ) - { - final double oldPower = this.lastStoredPower; - this.lastStoredPower = this.getStoredPower(); - - final EnergyThreshold low = new EnergyThreshold( Math.min( oldPower, this.lastStoredPower ), null ); - final EnergyThreshold high = new EnergyThreshold( Math.max( oldPower, this.lastStoredPower ), null ); - for( final EnergyThreshold th : this.getInterests().subSet( low, true, high, true ) ) - { - ( (EnergyWatcher) th.getWatcher() ).post( this ); - } - } - - this.avgDrainPerTick *= ( this.AvgLength - 1 ) / this.AvgLength; - this.avgInjectionPerTick *= ( this.AvgLength - 1 ) / this.AvgLength; - - this.avgDrainPerTick += this.tickDrainPerTick / this.AvgLength; - this.avgInjectionPerTick += this.tickInjectionPerTick / this.AvgLength; - - this.tickDrainPerTick = 0; - this.tickInjectionPerTick = 0; - - // power information. - boolean currentlyHasPower = false; - - if( this.drainPerTick > 0.0001 ) - { - final double drained = this.extractAEPower( this.getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG ); - currentlyHasPower = drained >= this.drainPerTick - 0.001; - } - else - { - currentlyHasPower = this.extractAEPower( 0.1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0; - } - - // ticks since change.. - if( currentlyHasPower == this.hasPower ) - { - this.ticksSinceHasPowerChange++; - } - else - { - this.ticksSinceHasPowerChange = 0; - } - - // update status.. - this.hasPower = currentlyHasPower; - - // update public status, this buffers power ups for 30 ticks. - if( this.hasPower && this.ticksSinceHasPowerChange > 30 ) - { - this.publicPowerState( true, this.myGrid ); - } - else if( !this.hasPower ) - { - this.publicPowerState( false, this.myGrid ); - } - - this.availableTicksSinceUpdate++; - } - - @Override - public double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier pm ) - { - this.localSeen.clear(); - return pm.divide( this.extractAEPower( pm.multiply( amt ), mode, this.localSeen ) ); - } - - @Override - public double getIdlePowerUsage() - { - return this.drainPerTick + this.pgc.getChannelPowerUsage(); - } - - private void publicPowerState( final boolean newState, final IGrid grid ) - { - if( this.publicHasPower == newState ) - { - return; - } - - this.publicHasPower = newState; - ( (Grid) this.myGrid ).setImportantFlag( 0, this.publicHasPower ); - grid.postEvent( new MENetworkPowerStatusChange() ); - } - - /** - * refresh current stored power. - */ - private void refreshPower() - { - this.availableTicksSinceUpdate = 0; - this.globalAvailablePower = 0; - for( final IAEPowerStorage p : this.providers ) - { - this.globalAvailablePower += p.getAECurrentPower(); - } - } - - @Override - public double extractAEPower( final double amt, final Actionable mode, final Set seen ) - { - if( !seen.add( this ) ) - { - return 0; - } - - double extractedPower = this.extra; - - if( mode == Actionable.SIMULATE ) - { - extractedPower += this.simulateExtract( extractedPower, amt ); - - if( extractedPower < amt ) - { - final Iterator i = this.energyGridProviders.iterator(); - while( extractedPower < amt && i.hasNext() ) - { - extractedPower += i.next().extractAEPower( amt - extractedPower, mode, seen ); - } - } - - return extractedPower; - } - else - { - this.extra = 0; - extractedPower = this.doExtract( extractedPower, amt ); - } - - // got more then we wanted? - if( extractedPower > amt ) - { - this.extra = extractedPower - amt; - this.globalAvailablePower -= amt; - - this.tickDrainPerTick += amt; - return amt; - } - - if( extractedPower < amt ) - { - final Iterator i = this.energyGridProviders.iterator(); - while( extractedPower < amt && i.hasNext() ) - { - extractedPower += i.next().extractAEPower( amt - extractedPower, mode, seen ); - } - } - - // go less or the correct amount? - this.globalAvailablePower -= extractedPower; - this.tickDrainPerTick += extractedPower; - return extractedPower; - } - - @Override - public double injectAEPower( double amt, final Actionable mode, final Set seen ) - { - if( !seen.add( this ) ) - { - return 0; - } - - final double ignore = this.extra; - amt += this.extra; - - if( mode == Actionable.SIMULATE ) - { - final Iterator it = this.requesters.iterator(); - while( amt > 0 && it.hasNext() ) - { - final IAEPowerStorage node = it.next(); - amt = node.injectAEPower( amt, Actionable.SIMULATE ); - } - - final Iterator i = this.energyGridProviders.iterator(); - while( amt > 0 && i.hasNext() ) - { - amt = i.next().injectAEPower( amt, mode, seen ); - } - } - else - { - this.tickInjectionPerTick += amt - ignore; - // totalInjectionPastTicks[0] += i; - - while( amt > 0 && !this.requesters.isEmpty() ) - { - final IAEPowerStorage node = this.getFirstRequester(); - - amt = node.injectAEPower( amt, Actionable.MODULATE ); - if( amt > 0 ) - { - this.requesters.remove( node ); - this.lastRequester = null; - } - } - - final Iterator i = this.energyGridProviders.iterator(); - while( amt > 0 && i.hasNext() ) - { - final IEnergyGridProvider what = i.next(); - final Set listCopy = new HashSet(); - listCopy.addAll( seen ); - - final double cannotHold = what.injectAEPower( amt, Actionable.SIMULATE, listCopy ); - what.injectAEPower( amt - cannotHold, mode, seen ); - - amt = cannotHold; - } - - this.extra = amt; - } - - return Math.max( 0.0, amt - this.buffer() ); - } - - @Override - public double getEnergyDemand( final double maxRequired, final Set seen ) - { - if( !seen.add( this ) ) - { - return 0; - } - - double required = this.buffer() - this.extra; - - final Iterator it = this.requesters.iterator(); - while( required < maxRequired && it.hasNext() ) - { - final IAEPowerStorage node = it.next(); - if( node.getPowerFlow() != AccessRestriction.READ ) - { - required += Math.max( 0.0, node.getAEMaxPower() - node.getAECurrentPower() ); - } - } - - final Iterator ix = this.energyGridProviders.iterator(); - while( required < maxRequired && ix.hasNext() ) - { - final IEnergyGridProvider node = ix.next(); - required += node.getEnergyDemand( maxRequired - required, seen ); - } - - return required; - } - - private double simulateExtract( double extractedPower, final double amt ) - { - final Iterator it = this.providers.iterator(); - - while( extractedPower < amt && it.hasNext() ) - { - final IAEPowerStorage node = it.next(); - - final double req = amt - extractedPower; - final double newPower = node.extractAEPower( req, Actionable.SIMULATE, PowerMultiplier.ONE ); - extractedPower += newPower; - } - - return extractedPower; - } - - private double doExtract( double extractedPower, final double amt ) - { - while( extractedPower < amt && !this.providers.isEmpty() ) - { - final IAEPowerStorage node = this.getFirstProvider(); - - final double req = amt - extractedPower; - final double newPower = node.extractAEPower( req, Actionable.MODULATE, PowerMultiplier.ONE ); - extractedPower += newPower; - - if( newPower < req ) - { - this.providers.remove( node ); - this.lastProvider = null; - } - } - - // totalDrainPastTicks[0] += extractedPower; - return extractedPower; - } - - private IAEPowerStorage getFirstProvider() - { - if( this.lastProvider == null ) - { - final Iterator i = this.providers.iterator(); - this.lastProvider = i.hasNext() ? i.next() : null; - } - - return this.lastProvider; - } - - @Override - public double getAvgPowerUsage() - { - return this.avgDrainPerTick; - } - - @Override - public double getAvgPowerInjection() - { - return this.avgInjectionPerTick; - } - - @Override - public boolean isNetworkPowered() - { - return this.publicHasPower; - } - - @Override - public double injectPower( final double amt, final Actionable mode ) - { - this.localSeen.clear(); - return this.injectAEPower( amt, mode, this.localSeen ); - } - - private IAEPowerStorage getFirstRequester() - { - if( this.lastRequester == null ) - { - final Iterator i = this.requesters.iterator(); - this.lastRequester = i.hasNext() ? i.next() : null; - } - - return this.lastRequester; - } - - private double buffer() - { - return this.providers.isEmpty() ? 1000.0 : 0.0; - } - - @Override - public double getStoredPower() - { - if( this.availableTicksSinceUpdate > 90 ) - { - this.refreshPower(); - } - - return Math.max( 0.0, this.globalAvailablePower ); - } - - @Override - public double getMaxStoredPower() - { - return this.globalMaxPower; - } - - @Override - public double getEnergyDemand( final double maxRequired ) - { - this.localSeen.clear(); - return this.getEnergyDemand( maxRequired, this.localSeen ); - } - - @Override - public void removeNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof IEnergyGridProvider ) - { - this.energyGridProviders.remove( machine ); - } - - // idle draw. - final GridNode gridNode = (GridNode) node; - this.drainPerTick -= gridNode.getPreviousDraw(); - - // power storage. - if( machine instanceof IAEPowerStorage ) - { - final IAEPowerStorage ps = (IAEPowerStorage) machine; - if( ps.isAEPublicPowerStorage() ) - { - if( ps.getPowerFlow() != AccessRestriction.WRITE ) - { - this.globalMaxPower -= ps.getAEMaxPower(); - this.globalAvailablePower -= ps.getAECurrentPower(); - } - - if( this.lastProvider == machine ) - { - this.lastProvider = null; - } - - if( this.lastRequester == machine ) - { - this.lastRequester = null; - } - - this.providers.remove( machine ); - this.requesters.remove( machine ); - } - } - - if( machine instanceof IStackWatcherHost ) - { - final IEnergyWatcher myWatcher = this.watchers.get( machine ); - if( myWatcher != null ) - { - myWatcher.clear(); - this.watchers.remove( machine ); - } - } - } - - @Override - public void addNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof IEnergyGridProvider ) - { - this.energyGridProviders.add( (IEnergyGridProvider) machine ); - } - - // idle draw... - final GridNode gridNode = (GridNode) node; - final IGridBlock gb = gridNode.getGridBlock(); - gridNode.setPreviousDraw( gb.getIdlePowerUsage() ); - this.drainPerTick += gridNode.getPreviousDraw(); - - // power storage - if( machine instanceof IAEPowerStorage ) - { - final IAEPowerStorage ps = (IAEPowerStorage) machine; - if( ps.isAEPublicPowerStorage() ) - { - final double max = ps.getAEMaxPower(); - final double current = ps.getAECurrentPower(); - - if( ps.getPowerFlow() != AccessRestriction.WRITE ) - { - this.globalMaxPower += ps.getAEMaxPower(); - } - - if( current > 0 && ps.getPowerFlow() != AccessRestriction.WRITE ) - { - this.globalAvailablePower += current; - this.providers.add( ps ); - } - - if( current < max && ps.getPowerFlow() != AccessRestriction.READ ) - { - this.requesters.add( ps ); - } - } - } - - if( machine instanceof IEnergyWatcherHost ) - { - final IEnergyWatcherHost swh = (IEnergyWatcherHost) machine; - final EnergyWatcher iw = new EnergyWatcher( this, swh ); - this.watchers.put( node, iw ); - swh.updateWatcher( iw ); - } - - this.myGrid.postEventTo( node, new MENetworkPowerStatusChange() ); - } - - @Override - public void onSplit( final IGridStorage storageB ) - { - this.extra /= 2; - storageB.dataObject().setDouble( "extraEnergy", this.extra ); - } - - @Override - public void onJoin( final IGridStorage storageB ) - { - this.extra += storageB.dataObject().getDouble( "extraEnergy" ); - } - - @Override - public void populateGridStorage( final IGridStorage storage ) - { - storage.dataObject().setDouble( "extraEnergy", this.extra ); - } - - public TreeSet getInterests() - { - return this.interests; - } +public class EnergyGridCache implements IEnergyGrid { + + private final TreeSet interests = new TreeSet(); + private final double AvgLength = 40.0; + private final Set providers = new LinkedHashSet(); + private final Set requesters = new LinkedHashSet(); + private final Multiset energyGridProviders = HashMultiset.create(); + private final IGrid myGrid; + private final HashMap watchers = new HashMap(); + private final Set localSeen = new HashSet(); + /** + * estimated power available. + */ + private int availableTicksSinceUpdate = 0; + + private double globalAvailablePower = 0; + private double globalMaxPower = 0; + /** + * idle draw. + */ + private double drainPerTick = 0; + + private double avgDrainPerTick = 0; + private double avgInjectionPerTick = 0; + private double tickDrainPerTick = 0; + private double tickInjectionPerTick = 0; + /** + * power status + */ + private boolean publicHasPower = false; + + private boolean hasPower = true; + private long ticksSinceHasPowerChange = 900; + /** + * excess power in the system. + */ + private double extra = 0; + + private IAEPowerStorage lastProvider; + private IAEPowerStorage lastRequester; + private PathGridCache pgc; + private double lastStoredPower = -1; + + public EnergyGridCache(final IGrid g) { + this.myGrid = g; + } + + @MENetworkEventSubscribe + public void postInit(final MENetworkPostCacheConstruction pcc) { + this.pgc = this.myGrid.getCache(IPathingGrid.class); + } + + @MENetworkEventSubscribe + public void EnergyNodeChanges(final MENetworkPowerIdleChange ev) { + // update power usage based on event. + final GridNode node = (GridNode) ev.node; + final IGridBlock gb = node.getGridBlock(); + + final double newDraw = gb.getIdlePowerUsage(); + final double diffDraw = newDraw - node.getPreviousDraw(); + node.setPreviousDraw(newDraw); + + this.drainPerTick += diffDraw; + } + + @MENetworkEventSubscribe + public void EnergyNodeChanges(final MENetworkPowerStorage ev) { + if (ev.storage.isAEPublicPowerStorage()) { + switch (ev.type) { + case PROVIDE_POWER: + if (ev.storage.getPowerFlow() != AccessRestriction.WRITE) { + this.providers.add(ev.storage); + } + break; + case REQUEST_POWER: + if (ev.storage.getPowerFlow() != AccessRestriction.READ) { + this.requesters.add(ev.storage); + } + break; + } + } else { + (new RuntimeException("Attempt to ask the IEnergyGrid to charge a non public energy store.")) + .printStackTrace(); + } + } + + @Override + public void onUpdateTick() { + if (!this.getInterests().isEmpty()) { + final double oldPower = this.lastStoredPower; + this.lastStoredPower = this.getStoredPower(); + + final EnergyThreshold low = new EnergyThreshold(Math.min(oldPower, this.lastStoredPower), null); + final EnergyThreshold high = new EnergyThreshold(Math.max(oldPower, this.lastStoredPower), null); + for (final EnergyThreshold th : this.getInterests().subSet(low, true, high, true)) { + ((EnergyWatcher) th.getWatcher()).post(this); + } + } + + this.avgDrainPerTick *= (this.AvgLength - 1) / this.AvgLength; + this.avgInjectionPerTick *= (this.AvgLength - 1) / this.AvgLength; + + this.avgDrainPerTick += this.tickDrainPerTick / this.AvgLength; + this.avgInjectionPerTick += this.tickInjectionPerTick / this.AvgLength; + + this.tickDrainPerTick = 0; + this.tickInjectionPerTick = 0; + + // power information. + boolean currentlyHasPower = false; + + if (this.drainPerTick > 0.0001) { + final double drained = + this.extractAEPower(this.getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG); + currentlyHasPower = drained >= this.drainPerTick - 0.001; + } else { + currentlyHasPower = this.extractAEPower(0.1, Actionable.SIMULATE, PowerMultiplier.CONFIG) > 0; + } + + // ticks since change.. + if (currentlyHasPower == this.hasPower) { + this.ticksSinceHasPowerChange++; + } else { + this.ticksSinceHasPowerChange = 0; + } + + // update status.. + this.hasPower = currentlyHasPower; + + // update public status, this buffers power ups for 30 ticks. + if (this.hasPower && this.ticksSinceHasPowerChange > 30) { + this.publicPowerState(true, this.myGrid); + } else if (!this.hasPower) { + this.publicPowerState(false, this.myGrid); + } + + this.availableTicksSinceUpdate++; + } + + @Override + public double extractAEPower(final double amt, final Actionable mode, final PowerMultiplier pm) { + this.localSeen.clear(); + return pm.divide(this.extractAEPower(pm.multiply(amt), mode, this.localSeen)); + } + + @Override + public double getIdlePowerUsage() { + return this.drainPerTick + this.pgc.getChannelPowerUsage(); + } + + private void publicPowerState(final boolean newState, final IGrid grid) { + if (this.publicHasPower == newState) { + return; + } + + this.publicHasPower = newState; + ((Grid) this.myGrid).setImportantFlag(0, this.publicHasPower); + grid.postEvent(new MENetworkPowerStatusChange()); + } + + /** + * refresh current stored power. + */ + private void refreshPower() { + this.availableTicksSinceUpdate = 0; + this.globalAvailablePower = 0; + for (final IAEPowerStorage p : this.providers) { + this.globalAvailablePower += p.getAECurrentPower(); + } + } + + @Override + public double extractAEPower(final double amt, final Actionable mode, final Set seen) { + if (!seen.add(this)) { + return 0; + } + + double extractedPower = this.extra; + + if (mode == Actionable.SIMULATE) { + extractedPower += this.simulateExtract(extractedPower, amt); + + if (extractedPower < amt) { + final Iterator i = this.energyGridProviders.iterator(); + while (extractedPower < amt && i.hasNext()) { + extractedPower += i.next().extractAEPower(amt - extractedPower, mode, seen); + } + } + + return extractedPower; + } else { + this.extra = 0; + extractedPower = this.doExtract(extractedPower, amt); + } + + // got more then we wanted? + if (extractedPower > amt) { + this.extra = extractedPower - amt; + this.globalAvailablePower -= amt; + + this.tickDrainPerTick += amt; + return amt; + } + + if (extractedPower < amt) { + final Iterator i = this.energyGridProviders.iterator(); + while (extractedPower < amt && i.hasNext()) { + extractedPower += i.next().extractAEPower(amt - extractedPower, mode, seen); + } + } + + // go less or the correct amount? + this.globalAvailablePower -= extractedPower; + this.tickDrainPerTick += extractedPower; + return extractedPower; + } + + @Override + public double injectAEPower(double amt, final Actionable mode, final Set seen) { + if (!seen.add(this)) { + return 0; + } + + final double ignore = this.extra; + amt += this.extra; + + if (mode == Actionable.SIMULATE) { + final Iterator it = this.requesters.iterator(); + while (amt > 0 && it.hasNext()) { + final IAEPowerStorage node = it.next(); + amt = node.injectAEPower(amt, Actionable.SIMULATE); + } + + final Iterator i = this.energyGridProviders.iterator(); + while (amt > 0 && i.hasNext()) { + amt = i.next().injectAEPower(amt, mode, seen); + } + } else { + this.tickInjectionPerTick += amt - ignore; + // totalInjectionPastTicks[0] += i; + + while (amt > 0 && !this.requesters.isEmpty()) { + final IAEPowerStorage node = this.getFirstRequester(); + + amt = node.injectAEPower(amt, Actionable.MODULATE); + if (amt > 0) { + this.requesters.remove(node); + this.lastRequester = null; + } + } + + final Iterator i = this.energyGridProviders.iterator(); + while (amt > 0 && i.hasNext()) { + final IEnergyGridProvider what = i.next(); + final Set listCopy = new HashSet(); + listCopy.addAll(seen); + + final double cannotHold = what.injectAEPower(amt, Actionable.SIMULATE, listCopy); + what.injectAEPower(amt - cannotHold, mode, seen); + + amt = cannotHold; + } + + this.extra = amt; + } + + return Math.max(0.0, amt - this.buffer()); + } + + @Override + public double getEnergyDemand(final double maxRequired, final Set seen) { + if (!seen.add(this)) { + return 0; + } + + double required = this.buffer() - this.extra; + + final Iterator it = this.requesters.iterator(); + while (required < maxRequired && it.hasNext()) { + final IAEPowerStorage node = it.next(); + if (node.getPowerFlow() != AccessRestriction.READ) { + required += Math.max(0.0, node.getAEMaxPower() - node.getAECurrentPower()); + } + } + + final Iterator ix = this.energyGridProviders.iterator(); + while (required < maxRequired && ix.hasNext()) { + final IEnergyGridProvider node = ix.next(); + required += node.getEnergyDemand(maxRequired - required, seen); + } + + return required; + } + + private double simulateExtract(double extractedPower, final double amt) { + final Iterator it = this.providers.iterator(); + + while (extractedPower < amt && it.hasNext()) { + final IAEPowerStorage node = it.next(); + + final double req = amt - extractedPower; + final double newPower = node.extractAEPower(req, Actionable.SIMULATE, PowerMultiplier.ONE); + extractedPower += newPower; + } + + return extractedPower; + } + + private double doExtract(double extractedPower, final double amt) { + while (extractedPower < amt && !this.providers.isEmpty()) { + final IAEPowerStorage node = this.getFirstProvider(); + + final double req = amt - extractedPower; + final double newPower = node.extractAEPower(req, Actionable.MODULATE, PowerMultiplier.ONE); + extractedPower += newPower; + + if (newPower < req) { + this.providers.remove(node); + this.lastProvider = null; + } + } + + // totalDrainPastTicks[0] += extractedPower; + return extractedPower; + } + + private IAEPowerStorage getFirstProvider() { + if (this.lastProvider == null) { + final Iterator i = this.providers.iterator(); + this.lastProvider = i.hasNext() ? i.next() : null; + } + + return this.lastProvider; + } + + @Override + public double getAvgPowerUsage() { + return this.avgDrainPerTick; + } + + @Override + public double getAvgPowerInjection() { + return this.avgInjectionPerTick; + } + + @Override + public boolean isNetworkPowered() { + return this.publicHasPower; + } + + @Override + public double injectPower(final double amt, final Actionable mode) { + this.localSeen.clear(); + return this.injectAEPower(amt, mode, this.localSeen); + } + + private IAEPowerStorage getFirstRequester() { + if (this.lastRequester == null) { + final Iterator i = this.requesters.iterator(); + this.lastRequester = i.hasNext() ? i.next() : null; + } + + return this.lastRequester; + } + + private double buffer() { + return this.providers.isEmpty() ? 1000.0 : 0.0; + } + + @Override + public double getStoredPower() { + if (this.availableTicksSinceUpdate > 90) { + this.refreshPower(); + } + + return Math.max(0.0, this.globalAvailablePower); + } + + @Override + public double getMaxStoredPower() { + return this.globalMaxPower; + } + + @Override + public double getEnergyDemand(final double maxRequired) { + this.localSeen.clear(); + return this.getEnergyDemand(maxRequired, this.localSeen); + } + + @Override + public void removeNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof IEnergyGridProvider) { + this.energyGridProviders.remove(machine); + } + + // idle draw. + final GridNode gridNode = (GridNode) node; + this.drainPerTick -= gridNode.getPreviousDraw(); + + // power storage. + if (machine instanceof IAEPowerStorage) { + final IAEPowerStorage ps = (IAEPowerStorage) machine; + if (ps.isAEPublicPowerStorage()) { + if (ps.getPowerFlow() != AccessRestriction.WRITE) { + this.globalMaxPower -= ps.getAEMaxPower(); + this.globalAvailablePower -= ps.getAECurrentPower(); + } + + if (this.lastProvider == machine) { + this.lastProvider = null; + } + + if (this.lastRequester == machine) { + this.lastRequester = null; + } + + this.providers.remove(machine); + this.requesters.remove(machine); + } + } + + if (machine instanceof IStackWatcherHost) { + final IEnergyWatcher myWatcher = this.watchers.get(machine); + if (myWatcher != null) { + myWatcher.clear(); + this.watchers.remove(machine); + } + } + } + + @Override + public void addNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof IEnergyGridProvider) { + this.energyGridProviders.add((IEnergyGridProvider) machine); + } + + // idle draw... + final GridNode gridNode = (GridNode) node; + final IGridBlock gb = gridNode.getGridBlock(); + gridNode.setPreviousDraw(gb.getIdlePowerUsage()); + this.drainPerTick += gridNode.getPreviousDraw(); + + // power storage + if (machine instanceof IAEPowerStorage) { + final IAEPowerStorage ps = (IAEPowerStorage) machine; + if (ps.isAEPublicPowerStorage()) { + final double max = ps.getAEMaxPower(); + final double current = ps.getAECurrentPower(); + + if (ps.getPowerFlow() != AccessRestriction.WRITE) { + this.globalMaxPower += ps.getAEMaxPower(); + } + + if (current > 0 && ps.getPowerFlow() != AccessRestriction.WRITE) { + this.globalAvailablePower += current; + this.providers.add(ps); + } + + if (current < max && ps.getPowerFlow() != AccessRestriction.READ) { + this.requesters.add(ps); + } + } + } + + if (machine instanceof IEnergyWatcherHost) { + final IEnergyWatcherHost swh = (IEnergyWatcherHost) machine; + final EnergyWatcher iw = new EnergyWatcher(this, swh); + this.watchers.put(node, iw); + swh.updateWatcher(iw); + } + + this.myGrid.postEventTo(node, new MENetworkPowerStatusChange()); + } + + @Override + public void onSplit(final IGridStorage storageB) { + this.extra /= 2; + storageB.dataObject().setDouble("extraEnergy", this.extra); + } + + @Override + public void onJoin(final IGridStorage storageB) { + this.extra += storageB.dataObject().getDouble("extraEnergy"); + } + + @Override + public void populateGridStorage(final IGridStorage storage) { + storage.dataObject().setDouble("extraEnergy", this.extra); + } + + public TreeSet getInterests() { + return this.interests; + } } diff --git a/src/main/java/appeng/me/cache/GridStorageCache.java b/src/main/java/appeng/me/cache/GridStorageCache.java index 722a2fbe07f..4ef5866d812 100644 --- a/src/main/java/appeng/me/cache/GridStorageCache.java +++ b/src/main/java/appeng/me/cache/GridStorageCache.java @@ -18,7 +18,6 @@ package appeng.me.cache; - import appeng.api.AEApi; import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; @@ -43,367 +42,309 @@ import appeng.me.storage.NetworkInventoryHandler; import com.google.common.collect.HashMultimap; import com.google.common.collect.SetMultimap; - import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; - -public class GridStorageCache implements IStorageGrid -{ - - private final IGrid myGrid; - private final HashSet activeCellProviders = new HashSet(); - private final HashSet inactiveCellProviders = new HashSet(); - private final SetMultimap interests = HashMultimap.create(); - private final GenericInterestManager interestManager = new GenericInterestManager( this.interests ); - private final NetworkMonitor itemMonitor = new NetworkMonitor( this, StorageChannel.ITEMS ); - private final NetworkMonitor fluidMonitor = new NetworkMonitor( this, StorageChannel.FLUIDS ); - private final HashMap watchers = new HashMap(); - private NetworkInventoryHandler myItemNetwork; - private NetworkInventoryHandler myFluidNetwork; - - public GridStorageCache( final IGrid g ) - { - this.myGrid = g; - } - - @Override - public void onUpdateTick() - { - this.itemMonitor.onTick(); - this.fluidMonitor.onTick(); - } - - @Override - public void removeNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof ICellContainer ) - { - final ICellContainer cc = (ICellContainer) machine; - final CellChangeTracker tracker = new CellChangeTracker(); - - this.removeCellProvider( cc, tracker ); - this.inactiveCellProviders.remove( cc ); - this.getGrid().postEvent( new MENetworkCellArrayUpdate() ); - - tracker.applyChanges(); - } - - if( machine instanceof IStackWatcherHost ) - { - final IStackWatcher myWatcher = this.watchers.get( machine ); - - if( myWatcher != null ) - { - myWatcher.clear(); - this.watchers.remove( machine ); - } - } - } - - @Override - public void addNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof ICellContainer ) - { - final ICellContainer cc = (ICellContainer) machine; - this.inactiveCellProviders.add( cc ); - - this.getGrid().postEvent( new MENetworkCellArrayUpdate() ); - - if( node.isActive() ) - { - final CellChangeTracker tracker = new CellChangeTracker(); - - this.addCellProvider( cc, tracker ); - tracker.applyChanges(); - } - } - - if( machine instanceof IStackWatcherHost ) - { - final IStackWatcherHost swh = (IStackWatcherHost) machine; - final ItemWatcher iw = new ItemWatcher( this, swh ); - this.watchers.put( node, iw ); - swh.updateWatcher( iw ); - } - } - - @Override - public void onSplit( final IGridStorage storageB ) - { - - } - - @Override - public void onJoin( final IGridStorage storageB ) - { - - } - - @Override - public void populateGridStorage( final IGridStorage storage ) - { - - } - - private CellChangeTracker addCellProvider( final ICellProvider cc, final CellChangeTracker tracker ) - { - if( this.inactiveCellProviders.contains( cc ) ) - { - this.inactiveCellProviders.remove( cc ); - this.activeCellProviders.add( cc ); - - BaseActionSource actionSrc = new BaseActionSource(); - if( cc instanceof IActionHost ) - { - actionSrc = new MachineSource( (IActionHost) cc ); - } - - for( final IMEInventoryHandler h : cc.getCellArray( StorageChannel.ITEMS ) ) - { - tracker.postChanges( StorageChannel.ITEMS, 1, h, actionSrc ); - } - - for( final IMEInventoryHandler h : cc.getCellArray( StorageChannel.FLUIDS ) ) - { - tracker.postChanges( StorageChannel.FLUIDS, 1, h, actionSrc ); - } - } - - return tracker; - } - - private CellChangeTracker removeCellProvider( final ICellProvider cc, final CellChangeTracker tracker ) - { - if( this.activeCellProviders.contains( cc ) ) - { - this.activeCellProviders.remove( cc ); - this.inactiveCellProviders.add( cc ); - - BaseActionSource actionSrc = new BaseActionSource(); - - if( cc instanceof IActionHost ) - { - actionSrc = new MachineSource( (IActionHost) cc ); - } - - for( final IMEInventoryHandler h : cc.getCellArray( StorageChannel.ITEMS ) ) - { - tracker.postChanges( StorageChannel.ITEMS, -1, h, actionSrc ); - } - - for( final IMEInventoryHandler h : cc.getCellArray( StorageChannel.FLUIDS ) ) - { - tracker.postChanges( StorageChannel.FLUIDS, -1, h, actionSrc ); - } - } - - return tracker; - } - - @MENetworkEventSubscribe - public void cellUpdate( final MENetworkCellArrayUpdate ev ) - { - this.myItemNetwork = null; - this.myFluidNetwork = null; - - final LinkedList ll = new LinkedList(); - ll.addAll( this.inactiveCellProviders ); - ll.addAll( this.activeCellProviders ); - - final CellChangeTracker tracker = new CellChangeTracker(); - - for( final ICellProvider cc : ll ) - { - boolean active = true; - - if( cc instanceof IActionHost ) - { - final IGridNode node = ( (IActionHost) cc ).getActionableNode(); - active = node != null && node.isActive(); - } - - if( active ) - { - this.addCellProvider( cc, tracker ); - } - else - { - this.removeCellProvider( cc, tracker ); - } - } - - this.itemMonitor.forceUpdate(); - this.fluidMonitor.forceUpdate(); - - tracker.applyChanges(); - } - - private void postChangesToNetwork( final StorageChannel chan, final int upOrDown, final IItemList availableItems, final BaseActionSource src ) - { - switch( chan ) - { - case FLUIDS: - this.fluidMonitor.postChange( upOrDown > 0, availableItems, src ); - break; - case ITEMS: - this.itemMonitor.postChange( upOrDown > 0, availableItems, src ); - break; - default: - } - } - - IMEInventoryHandler getItemInventoryHandler() - { - if( this.myItemNetwork == null ) - { - this.buildNetworkStorage( StorageChannel.ITEMS ); - } - return this.myItemNetwork; - } - - private void buildNetworkStorage( final StorageChannel chan ) - { - final SecurityCache security = this.getGrid().getCache( ISecurityGrid.class ); - - switch( chan ) - { - case FLUIDS: - this.myFluidNetwork = new NetworkInventoryHandler( StorageChannel.FLUIDS, security ); - for( final ICellProvider cc : this.activeCellProviders ) - { - for( final IMEInventoryHandler h : cc.getCellArray( chan ) ) - { - this.myFluidNetwork.addNewStorage( h ); - } - } - break; - case ITEMS: - this.myItemNetwork = new NetworkInventoryHandler( StorageChannel.ITEMS, security ); - for( final ICellProvider cc : this.activeCellProviders ) - { - for( final IMEInventoryHandler h : cc.getCellArray( chan ) ) - { - this.myItemNetwork.addNewStorage( h ); - } - } - break; - default: - } - } - - IMEInventoryHandler getFluidInventoryHandler() - { - if( this.myFluidNetwork == null ) - { - this.buildNetworkStorage( StorageChannel.FLUIDS ); - } - return this.myFluidNetwork; - } - - @Override - public void postAlterationOfStoredItems( final StorageChannel chan, final Iterable input, final BaseActionSource src ) - { - if( chan == StorageChannel.ITEMS ) - { - this.itemMonitor.postChange( true, (Iterable) input, src ); - } - else if( chan == StorageChannel.FLUIDS ) - { - this.fluidMonitor.postChange( true, (Iterable) input, src ); - } - } - - @Override - public void registerCellProvider( final ICellProvider provider ) - { - this.inactiveCellProviders.add( provider ); - this.addCellProvider( provider, new CellChangeTracker() ).applyChanges(); - } - - @Override - public void unregisterCellProvider( final ICellProvider provider ) - { - this.removeCellProvider( provider, new CellChangeTracker() ).applyChanges(); - this.inactiveCellProviders.remove( provider ); - } - - @Override - public IMEMonitor getItemInventory() - { - return this.itemMonitor; - } - - @Override - public IMEMonitor getFluidInventory() - { - return this.fluidMonitor; - } - - public GenericInterestManager getInterestManager() - { - return this.interestManager; - } - - IGrid getGrid() - { - return this.myGrid; - } - - private class CellChangeTrackerRecord - { - - final StorageChannel channel; - final int up_or_down; - final IItemList list; - final BaseActionSource src; - - public CellChangeTrackerRecord( final StorageChannel channel, final int i, final IMEInventoryHandler h, final BaseActionSource actionSrc ) - { - this.channel = channel; - this.up_or_down = i; - this.src = actionSrc; - - if( channel == StorageChannel.ITEMS ) - { - this.list = ( (IMEInventoryHandler) h ).getAvailableItems( AEApi.instance().storage().createItemList() ); - } - else if( channel == StorageChannel.FLUIDS ) - { - this.list = ( (IMEInventoryHandler) h ).getAvailableItems( AEApi.instance().storage().createFluidList() ); - } - else - { - this.list = null; - } - } - - public void applyChanges() - { - GridStorageCache.this.postChangesToNetwork( this.channel, this.up_or_down, this.list, this.src ); - } - } - - - private class CellChangeTracker - { - - final List data = new LinkedList(); - - public void postChanges( final StorageChannel channel, final int i, final IMEInventoryHandler h, final BaseActionSource actionSrc ) - { - this.data.add( new CellChangeTrackerRecord( channel, i, h, actionSrc ) ); - } - - public void applyChanges() - { - for( final CellChangeTrackerRecord rec : this.data ) - { - rec.applyChanges(); - } - } - } +public class GridStorageCache implements IStorageGrid { + + private final IGrid myGrid; + private final HashSet activeCellProviders = new HashSet(); + private final HashSet inactiveCellProviders = new HashSet(); + private final SetMultimap interests = HashMultimap.create(); + private final GenericInterestManager interestManager = + new GenericInterestManager(this.interests); + private final NetworkMonitor itemMonitor = + new NetworkMonitor(this, StorageChannel.ITEMS); + private final NetworkMonitor fluidMonitor = + new NetworkMonitor(this, StorageChannel.FLUIDS); + private final HashMap watchers = new HashMap(); + private NetworkInventoryHandler myItemNetwork; + private NetworkInventoryHandler myFluidNetwork; + + public GridStorageCache(final IGrid g) { + this.myGrid = g; + } + + @Override + public void onUpdateTick() { + this.itemMonitor.onTick(); + this.fluidMonitor.onTick(); + } + + @Override + public void removeNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof ICellContainer) { + final ICellContainer cc = (ICellContainer) machine; + final CellChangeTracker tracker = new CellChangeTracker(); + + this.removeCellProvider(cc, tracker); + this.inactiveCellProviders.remove(cc); + this.getGrid().postEvent(new MENetworkCellArrayUpdate()); + + tracker.applyChanges(); + } + + if (machine instanceof IStackWatcherHost) { + final IStackWatcher myWatcher = this.watchers.get(machine); + + if (myWatcher != null) { + myWatcher.clear(); + this.watchers.remove(machine); + } + } + } + + @Override + public void addNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof ICellContainer) { + final ICellContainer cc = (ICellContainer) machine; + this.inactiveCellProviders.add(cc); + + this.getGrid().postEvent(new MENetworkCellArrayUpdate()); + + if (node.isActive()) { + final CellChangeTracker tracker = new CellChangeTracker(); + + this.addCellProvider(cc, tracker); + tracker.applyChanges(); + } + } + + if (machine instanceof IStackWatcherHost) { + final IStackWatcherHost swh = (IStackWatcherHost) machine; + final ItemWatcher iw = new ItemWatcher(this, swh); + this.watchers.put(node, iw); + swh.updateWatcher(iw); + } + } + + @Override + public void onSplit(final IGridStorage storageB) {} + + @Override + public void onJoin(final IGridStorage storageB) {} + + @Override + public void populateGridStorage(final IGridStorage storage) {} + + private CellChangeTracker addCellProvider(final ICellProvider cc, final CellChangeTracker tracker) { + if (this.inactiveCellProviders.contains(cc)) { + this.inactiveCellProviders.remove(cc); + this.activeCellProviders.add(cc); + + BaseActionSource actionSrc = new BaseActionSource(); + if (cc instanceof IActionHost) { + actionSrc = new MachineSource((IActionHost) cc); + } + + for (final IMEInventoryHandler h : cc.getCellArray(StorageChannel.ITEMS)) { + tracker.postChanges(StorageChannel.ITEMS, 1, h, actionSrc); + } + + for (final IMEInventoryHandler h : cc.getCellArray(StorageChannel.FLUIDS)) { + tracker.postChanges(StorageChannel.FLUIDS, 1, h, actionSrc); + } + } + + return tracker; + } + + private CellChangeTracker removeCellProvider(final ICellProvider cc, final CellChangeTracker tracker) { + if (this.activeCellProviders.contains(cc)) { + this.activeCellProviders.remove(cc); + this.inactiveCellProviders.add(cc); + + BaseActionSource actionSrc = new BaseActionSource(); + + if (cc instanceof IActionHost) { + actionSrc = new MachineSource((IActionHost) cc); + } + + for (final IMEInventoryHandler h : cc.getCellArray(StorageChannel.ITEMS)) { + tracker.postChanges(StorageChannel.ITEMS, -1, h, actionSrc); + } + + for (final IMEInventoryHandler h : cc.getCellArray(StorageChannel.FLUIDS)) { + tracker.postChanges(StorageChannel.FLUIDS, -1, h, actionSrc); + } + } + + return tracker; + } + + @MENetworkEventSubscribe + public void cellUpdate(final MENetworkCellArrayUpdate ev) { + this.myItemNetwork = null; + this.myFluidNetwork = null; + + final LinkedList ll = new LinkedList(); + ll.addAll(this.inactiveCellProviders); + ll.addAll(this.activeCellProviders); + + final CellChangeTracker tracker = new CellChangeTracker(); + + for (final ICellProvider cc : ll) { + boolean active = true; + + if (cc instanceof IActionHost) { + final IGridNode node = ((IActionHost) cc).getActionableNode(); + active = node != null && node.isActive(); + } + + if (active) { + this.addCellProvider(cc, tracker); + } else { + this.removeCellProvider(cc, tracker); + } + } + + this.itemMonitor.forceUpdate(); + this.fluidMonitor.forceUpdate(); + + tracker.applyChanges(); + } + + private void postChangesToNetwork( + final StorageChannel chan, final int upOrDown, final IItemList availableItems, final BaseActionSource src) { + switch (chan) { + case FLUIDS: + this.fluidMonitor.postChange(upOrDown > 0, availableItems, src); + break; + case ITEMS: + this.itemMonitor.postChange(upOrDown > 0, availableItems, src); + break; + default: + } + } + + IMEInventoryHandler getItemInventoryHandler() { + if (this.myItemNetwork == null) { + this.buildNetworkStorage(StorageChannel.ITEMS); + } + return this.myItemNetwork; + } + + private void buildNetworkStorage(final StorageChannel chan) { + final SecurityCache security = this.getGrid().getCache(ISecurityGrid.class); + + switch (chan) { + case FLUIDS: + this.myFluidNetwork = new NetworkInventoryHandler(StorageChannel.FLUIDS, security); + for (final ICellProvider cc : this.activeCellProviders) { + for (final IMEInventoryHandler h : cc.getCellArray(chan)) { + this.myFluidNetwork.addNewStorage(h); + } + } + break; + case ITEMS: + this.myItemNetwork = new NetworkInventoryHandler(StorageChannel.ITEMS, security); + for (final ICellProvider cc : this.activeCellProviders) { + for (final IMEInventoryHandler h : cc.getCellArray(chan)) { + this.myItemNetwork.addNewStorage(h); + } + } + break; + default: + } + } + + IMEInventoryHandler getFluidInventoryHandler() { + if (this.myFluidNetwork == null) { + this.buildNetworkStorage(StorageChannel.FLUIDS); + } + return this.myFluidNetwork; + } + + @Override + public void postAlterationOfStoredItems( + final StorageChannel chan, final Iterable input, final BaseActionSource src) { + if (chan == StorageChannel.ITEMS) { + this.itemMonitor.postChange(true, (Iterable) input, src); + } else if (chan == StorageChannel.FLUIDS) { + this.fluidMonitor.postChange(true, (Iterable) input, src); + } + } + + @Override + public void registerCellProvider(final ICellProvider provider) { + this.inactiveCellProviders.add(provider); + this.addCellProvider(provider, new CellChangeTracker()).applyChanges(); + } + + @Override + public void unregisterCellProvider(final ICellProvider provider) { + this.removeCellProvider(provider, new CellChangeTracker()).applyChanges(); + this.inactiveCellProviders.remove(provider); + } + + @Override + public IMEMonitor getItemInventory() { + return this.itemMonitor; + } + + @Override + public IMEMonitor getFluidInventory() { + return this.fluidMonitor; + } + + public GenericInterestManager getInterestManager() { + return this.interestManager; + } + + IGrid getGrid() { + return this.myGrid; + } + + private class CellChangeTrackerRecord { + + final StorageChannel channel; + final int up_or_down; + final IItemList list; + final BaseActionSource src; + + public CellChangeTrackerRecord( + final StorageChannel channel, + final int i, + final IMEInventoryHandler h, + final BaseActionSource actionSrc) { + this.channel = channel; + this.up_or_down = i; + this.src = actionSrc; + + if (channel == StorageChannel.ITEMS) { + this.list = ((IMEInventoryHandler) h) + .getAvailableItems(AEApi.instance().storage().createItemList()); + } else if (channel == StorageChannel.FLUIDS) { + this.list = ((IMEInventoryHandler) h) + .getAvailableItems(AEApi.instance().storage().createFluidList()); + } else { + this.list = null; + } + } + + public void applyChanges() { + GridStorageCache.this.postChangesToNetwork(this.channel, this.up_or_down, this.list, this.src); + } + } + + private class CellChangeTracker { + + final List data = new LinkedList(); + + public void postChanges( + final StorageChannel channel, + final int i, + final IMEInventoryHandler h, + final BaseActionSource actionSrc) { + this.data.add(new CellChangeTrackerRecord(channel, i, h, actionSrc)); + } + + public void applyChanges() { + for (final CellChangeTrackerRecord rec : this.data) { + rec.applyChanges(); + } + } + } } diff --git a/src/main/java/appeng/me/cache/NetworkMonitor.java b/src/main/java/appeng/me/cache/NetworkMonitor.java index 6b33d5e9ade..080844cd16c 100644 --- a/src/main/java/appeng/me/cache/NetworkMonitor.java +++ b/src/main/java/appeng/me/cache/NetworkMonitor.java @@ -18,7 +18,6 @@ package appeng.me.cache; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.events.MENetworkStorageEvent; @@ -32,308 +31,262 @@ import appeng.me.storage.ItemWatcher; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; - +import java.util.*; +import java.util.Map.Entry; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.*; -import java.util.Map.Entry; - - -public class NetworkMonitor> implements IMEMonitor -{ - @Nonnull - private static final Deque> GLOBAL_DEPTH = Lists.newLinkedList(); - - @Nonnull - private final GridStorageCache myGridCache; - @Nonnull - private final StorageChannel myChannel; - @Nonnull - private final IItemList cachedList; - @Nonnull - private final Map, Object> listeners; - - private boolean sendEvent = false; - private boolean hasChanged = false; - @Nonnegative - private int localDepthSemaphore = 0; - - public NetworkMonitor( final GridStorageCache cache, final StorageChannel chan ) - { - this.myGridCache = cache; - this.myChannel = chan; - this.cachedList = (IItemList) chan.createList(); - this.listeners = new HashMap, Object>(); - } - - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } - - @Override - public boolean canAccept( final T input ) - { - return this.getHandler().canAccept( input ); - } - - @Override - public T extractItems( final T request, final Actionable mode, final BaseActionSource src ) - { - if( mode == Actionable.SIMULATE ) - { - return this.getHandler().extractItems( request, mode, src ); - } - - localDepthSemaphore++; - final T leftover = this.getHandler().extractItems( request, mode, src ); - localDepthSemaphore--; - - if( localDepthSemaphore == 0 ) - { - this.monitorDifference( request.copy(), leftover, true, src ); - } - - return leftover; - } - - @Override - public AccessRestriction getAccess() - { - return this.getHandler().getAccess(); - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return this.getHandler().getAvailableItems( out ); - } - - @Override - public StorageChannel getChannel() - { - return this.getHandler().getChannel(); - } - - @Override - public int getPriority() - { - return this.getHandler().getPriority(); - } - - @Override - public int getSlot() - { - return this.getHandler().getSlot(); - } - - @Nonnull - @Override - public IItemList getStorageList() - { - if( this.hasChanged ) - { - this.hasChanged = false; - this.cachedList.resetStatus(); - return this.getAvailableItems( this.cachedList ); - } - - return this.cachedList; - } - - @Override - public T injectItems( final T input, final Actionable mode, final BaseActionSource src ) - { - if( mode == Actionable.SIMULATE ) - { - return this.getHandler().injectItems( input, mode, src ); - } - - localDepthSemaphore++; - final T leftover = this.getHandler().injectItems( input, mode, src ); - localDepthSemaphore--; - - if( localDepthSemaphore == 0 ) - { - this.monitorDifference( input.copy(), leftover, false, src ); - } - - return leftover; - } - - @Override - public boolean isPrioritized( final T input ) - { - return this.getHandler().isPrioritized( input ); - } - - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } - - @Override - public boolean validForPass( final int i ) - { - return this.getHandler().validForPass( i ); - } - - @Nullable - @SuppressWarnings( "unchecked" ) - private IMEInventoryHandler getHandler() - { - switch( this.myChannel ) - { - case ITEMS: - return (IMEInventoryHandler) this.myGridCache.getItemInventoryHandler(); - case FLUIDS: - return (IMEInventoryHandler) this.myGridCache.getFluidInventoryHandler(); - default: - } - return null; - } - - private Iterator, Object>> getListeners() - { - return this.listeners.entrySet().iterator(); - } - - private T monitorDifference( final IAEStack original, final T leftOvers, final boolean extraction, final BaseActionSource src ) - { - final T diff = (T) original.copy(); - - if( extraction ) - { - diff.setStackSize( leftOvers == null ? 0 : -leftOvers.getStackSize() ); - } - else if( leftOvers != null ) - { - diff.decStackSize( leftOvers.getStackSize() ); - } - - if( diff.getStackSize() != 0 ) - { - this.postChangesToListeners( ImmutableList.of( diff ), src ); - } - - return leftOvers; - } - - private void notifyListenersOfChange( final Iterable diff, final BaseActionSource src ) - { - this.hasChanged = true; - final Iterator, Object>> i = this.getListeners(); - - while( i.hasNext() ) - { - final Entry, Object> o = i.next(); - final IMEMonitorHandlerReceiver receiver = o.getKey(); - if( receiver.isValid( o.getValue() ) ) - { - receiver.postChange( this, diff, src ); - } - else - { - i.remove(); - } - } - } - - private void postChangesToListeners( final Iterable changes, final BaseActionSource src ) - { - this.postChange( true, changes, src ); - } - - protected void postChange( final boolean add, final Iterable changes, final BaseActionSource src ) - { - if( localDepthSemaphore > 0 || GLOBAL_DEPTH.contains( this ) ) - { - return; - } - - GLOBAL_DEPTH.push( this ); - localDepthSemaphore++; - - this.sendEvent = true; - - this.notifyListenersOfChange( changes, src ); - - for( final T changedItem : changes ) - { - T difference = changedItem; - - if( !add && changedItem != null ) - { - difference = changedItem.copy(); - difference.setStackSize( -changedItem.getStackSize() ); - } - - if( this.myGridCache.getInterestManager().containsKey( changedItem ) ) - { - final Collection list = this.myGridCache.getInterestManager().get( changedItem ); - - if( !list.isEmpty() ) - { - IAEStack fullStack = this.getStorageList().findPrecise( changedItem ); - - if( fullStack == null ) - { - fullStack = changedItem.copy(); - fullStack.setStackSize( 0 ); - } - - this.myGridCache.getInterestManager().enableTransactions(); - - for( final ItemWatcher iw : list ) - { - iw.getHost().onStackChange( this.getStorageList(), fullStack, difference, src, this.getChannel() ); - } - - this.myGridCache.getInterestManager().disableTransactions(); - } - } - } - - final NetworkMonitor last = GLOBAL_DEPTH.pop(); - localDepthSemaphore--; - - if( last != this ) - { - throw new IllegalStateException( "Invalid Access to Networked Storage API detected." ); - } - } - - void forceUpdate() - { - this.hasChanged = true; - - final Iterator, Object>> i = this.getListeners(); - while( i.hasNext() ) - { - final Entry, Object> o = i.next(); - final IMEMonitorHandlerReceiver receiver = o.getKey(); - - if( receiver.isValid( o.getValue() ) ) - { - receiver.onListUpdate(); - } - else - { - i.remove(); - } - } - } - - void onTick() - { - if( this.sendEvent ) - { - this.sendEvent = false; - this.myGridCache.getGrid().postEvent( new MENetworkStorageEvent( this, this.myChannel ) ); - } - } +public class NetworkMonitor> implements IMEMonitor { + @Nonnull + private static final Deque> GLOBAL_DEPTH = Lists.newLinkedList(); + + @Nonnull + private final GridStorageCache myGridCache; + + @Nonnull + private final StorageChannel myChannel; + + @Nonnull + private final IItemList cachedList; + + @Nonnull + private final Map, Object> listeners; + + private boolean sendEvent = false; + private boolean hasChanged = false; + + @Nonnegative + private int localDepthSemaphore = 0; + + public NetworkMonitor(final GridStorageCache cache, final StorageChannel chan) { + this.myGridCache = cache; + this.myChannel = chan; + this.cachedList = (IItemList) chan.createList(); + this.listeners = new HashMap, Object>(); + } + + @Override + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + this.listeners.put(l, verificationToken); + } + + @Override + public boolean canAccept(final T input) { + return this.getHandler().canAccept(input); + } + + @Override + public T extractItems(final T request, final Actionable mode, final BaseActionSource src) { + if (mode == Actionable.SIMULATE) { + return this.getHandler().extractItems(request, mode, src); + } + + localDepthSemaphore++; + final T leftover = this.getHandler().extractItems(request, mode, src); + localDepthSemaphore--; + + if (localDepthSemaphore == 0) { + this.monitorDifference(request.copy(), leftover, true, src); + } + + return leftover; + } + + @Override + public AccessRestriction getAccess() { + return this.getHandler().getAccess(); + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + return this.getHandler().getAvailableItems(out); + } + + @Override + public StorageChannel getChannel() { + return this.getHandler().getChannel(); + } + + @Override + public int getPriority() { + return this.getHandler().getPriority(); + } + + @Override + public int getSlot() { + return this.getHandler().getSlot(); + } + + @Nonnull + @Override + public IItemList getStorageList() { + if (this.hasChanged) { + this.hasChanged = false; + this.cachedList.resetStatus(); + return this.getAvailableItems(this.cachedList); + } + + return this.cachedList; + } + + @Override + public T injectItems(final T input, final Actionable mode, final BaseActionSource src) { + if (mode == Actionable.SIMULATE) { + return this.getHandler().injectItems(input, mode, src); + } + + localDepthSemaphore++; + final T leftover = this.getHandler().injectItems(input, mode, src); + localDepthSemaphore--; + + if (localDepthSemaphore == 0) { + this.monitorDifference(input.copy(), leftover, false, src); + } + + return leftover; + } + + @Override + public boolean isPrioritized(final T input) { + return this.getHandler().isPrioritized(input); + } + + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } + + @Override + public boolean validForPass(final int i) { + return this.getHandler().validForPass(i); + } + + @Nullable + @SuppressWarnings("unchecked") + private IMEInventoryHandler getHandler() { + switch (this.myChannel) { + case ITEMS: + return (IMEInventoryHandler) this.myGridCache.getItemInventoryHandler(); + case FLUIDS: + return (IMEInventoryHandler) this.myGridCache.getFluidInventoryHandler(); + default: + } + return null; + } + + private Iterator, Object>> getListeners() { + return this.listeners.entrySet().iterator(); + } + + private T monitorDifference( + final IAEStack original, final T leftOvers, final boolean extraction, final BaseActionSource src) { + final T diff = (T) original.copy(); + + if (extraction) { + diff.setStackSize(leftOvers == null ? 0 : -leftOvers.getStackSize()); + } else if (leftOvers != null) { + diff.decStackSize(leftOvers.getStackSize()); + } + + if (diff.getStackSize() != 0) { + this.postChangesToListeners(ImmutableList.of(diff), src); + } + + return leftOvers; + } + + private void notifyListenersOfChange(final Iterable diff, final BaseActionSource src) { + this.hasChanged = true; + final Iterator, Object>> i = this.getListeners(); + + while (i.hasNext()) { + final Entry, Object> o = i.next(); + final IMEMonitorHandlerReceiver receiver = o.getKey(); + if (receiver.isValid(o.getValue())) { + receiver.postChange(this, diff, src); + } else { + i.remove(); + } + } + } + + private void postChangesToListeners(final Iterable changes, final BaseActionSource src) { + this.postChange(true, changes, src); + } + + protected void postChange(final boolean add, final Iterable changes, final BaseActionSource src) { + if (localDepthSemaphore > 0 || GLOBAL_DEPTH.contains(this)) { + return; + } + + GLOBAL_DEPTH.push(this); + localDepthSemaphore++; + + this.sendEvent = true; + + this.notifyListenersOfChange(changes, src); + + for (final T changedItem : changes) { + T difference = changedItem; + + if (!add && changedItem != null) { + difference = changedItem.copy(); + difference.setStackSize(-changedItem.getStackSize()); + } + + if (this.myGridCache.getInterestManager().containsKey(changedItem)) { + final Collection list = + this.myGridCache.getInterestManager().get(changedItem); + + if (!list.isEmpty()) { + IAEStack fullStack = this.getStorageList().findPrecise(changedItem); + + if (fullStack == null) { + fullStack = changedItem.copy(); + fullStack.setStackSize(0); + } + + this.myGridCache.getInterestManager().enableTransactions(); + + for (final ItemWatcher iw : list) { + iw.getHost() + .onStackChange(this.getStorageList(), fullStack, difference, src, this.getChannel()); + } + + this.myGridCache.getInterestManager().disableTransactions(); + } + } + } + + final NetworkMonitor last = GLOBAL_DEPTH.pop(); + localDepthSemaphore--; + + if (last != this) { + throw new IllegalStateException("Invalid Access to Networked Storage API detected."); + } + } + + void forceUpdate() { + this.hasChanged = true; + + final Iterator, Object>> i = this.getListeners(); + while (i.hasNext()) { + final Entry, Object> o = i.next(); + final IMEMonitorHandlerReceiver receiver = o.getKey(); + + if (receiver.isValid(o.getValue())) { + receiver.onListUpdate(); + } else { + i.remove(); + } + } + } + + void onTick() { + if (this.sendEvent) { + this.sendEvent = false; + this.myGridCache.getGrid().postEvent(new MENetworkStorageEvent(this, this.myChannel)); + } + } } diff --git a/src/main/java/appeng/me/cache/P2PCache.java b/src/main/java/appeng/me/cache/P2PCache.java index b3a57c62943..89d172d9aa0 100644 --- a/src/main/java/appeng/me/cache/P2PCache.java +++ b/src/main/java/appeng/me/cache/P2PCache.java @@ -18,7 +18,6 @@ package appeng.me.cache; - import appeng.api.networking.*; import appeng.api.networking.events.MENetworkBootingStatusChange; import appeng.api.networking.events.MENetworkEventSubscribe; @@ -29,203 +28,152 @@ import appeng.parts.p2p.PartP2PTunnelME; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; - import java.util.HashMap; - -public class P2PCache implements IGridCache -{ - - private final IGrid myGrid; - private final HashMap inputs = new HashMap(); - private final Multimap outputs = LinkedHashMultimap.create(); - private final TunnelCollection NullColl = new TunnelCollection( null, null ); - - public P2PCache( final IGrid g ) - { - this.myGrid = g; - } - - @MENetworkEventSubscribe - public void bootComplete( final MENetworkBootingStatusChange bootStatus ) - { - final ITickManager tm = this.myGrid.getCache( ITickManager.class ); - for( final PartP2PTunnel me : this.inputs.values() ) - { - if( me instanceof PartP2PTunnelME ) - { - tm.wakeDevice( me.getGridNode() ); - } - } - } - - @MENetworkEventSubscribe - public void bootComplete( final MENetworkPowerStatusChange power ) - { - final ITickManager tm = this.myGrid.getCache( ITickManager.class ); - for( final PartP2PTunnel me : this.inputs.values() ) - { - if( me instanceof PartP2PTunnelME ) - { - tm.wakeDevice( me.getGridNode() ); - } - } - } - - @Override - public void onUpdateTick() - { - - } - - @Override - public void removeNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof PartP2PTunnel ) - { - if( machine instanceof PartP2PTunnelME ) - { - if( !node.hasFlag( GridFlags.REQUIRE_CHANNEL ) ) - { - return; - } - } - - final PartP2PTunnel t = (PartP2PTunnel) machine; - // AELog.info( "rmv-" + (t.output ? "output: " : "input: ") + t.freq - // ); - - if( t.isOutput() ) - { - this.outputs.remove( t.getFrequency(), t ); - } - else - { - this.inputs.remove( t.getFrequency() ); - } - - this.updateTunnel( t.getFrequency(), !t.isOutput(), false ); - } - } - - @Override - public void addNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof PartP2PTunnel ) - { - if( machine instanceof PartP2PTunnelME ) - { - if( !node.hasFlag( GridFlags.REQUIRE_CHANNEL ) ) - { - return; - } - } - - final PartP2PTunnel t = (PartP2PTunnel) machine; - // AELog.info( "add-" + (t.output ? "output: " : "input: ") + t.freq - // ); - - if( t.isOutput() ) - { - this.outputs.put( t.getFrequency(), t ); - } - else - { - this.inputs.put( t.getFrequency(), t ); - } - - this.updateTunnel( t.getFrequency(), !t.isOutput(), false ); - } - } - - @Override - public void onSplit( final IGridStorage storageB ) - { - - } - - @Override - public void onJoin( final IGridStorage storageB ) - { - - } - - @Override - public void populateGridStorage( final IGridStorage storage ) - { - - } - - private void updateTunnel( final long freq, final boolean updateOutputs, final boolean configChange ) - { - for( final PartP2PTunnel p : this.outputs.get( freq ) ) - { - if( configChange ) - { - p.onTunnelConfigChange(); - } - p.onTunnelNetworkChange(); - } - - final PartP2PTunnel in = this.inputs.get( freq ); - if( in != null ) - { - if( configChange ) - { - in.onTunnelConfigChange(); - } - in.onTunnelNetworkChange(); - } - } - - public void updateFreq( final PartP2PTunnel t, final long newFrequency ) - { - if( this.outputs.containsValue( t ) ) - { - this.outputs.remove( t.getFrequency(), t ); - } - - if( this.inputs.containsValue( t ) ) - { - this.inputs.remove( t.getFrequency() ); - } - - t.setFrequency( newFrequency ); - - if( t.isOutput() ) - { - this.outputs.put( t.getFrequency(), t ); - } - else - { - this.inputs.put( t.getFrequency(), t ); - } - - // AELog.info( "update-" + (t.output ? "output: " : "input: ") + t.freq - // ); - this.updateTunnel( t.getFrequency(), t.isOutput(), true ); - this.updateTunnel( t.getFrequency(), !t.isOutput(), true ); - } - - public TunnelCollection getOutputs( final long freq, final Class c ) - { - final PartP2PTunnel in = this.inputs.get( freq ); - if( in == null ) - { - return this.NullColl; - } - - final TunnelCollection out = this.inputs.get( freq ).getCollection( this.outputs.get( freq ), c ); - if( out == null ) - { - return this.NullColl; - } - - return out; - } - - public PartP2PTunnel getInput( final long freq ) - { - return this.inputs.get( freq ); - } +public class P2PCache implements IGridCache { + + private final IGrid myGrid; + private final HashMap inputs = new HashMap(); + private final Multimap outputs = LinkedHashMultimap.create(); + private final TunnelCollection NullColl = new TunnelCollection(null, null); + + public P2PCache(final IGrid g) { + this.myGrid = g; + } + + @MENetworkEventSubscribe + public void bootComplete(final MENetworkBootingStatusChange bootStatus) { + final ITickManager tm = this.myGrid.getCache(ITickManager.class); + for (final PartP2PTunnel me : this.inputs.values()) { + if (me instanceof PartP2PTunnelME) { + tm.wakeDevice(me.getGridNode()); + } + } + } + + @MENetworkEventSubscribe + public void bootComplete(final MENetworkPowerStatusChange power) { + final ITickManager tm = this.myGrid.getCache(ITickManager.class); + for (final PartP2PTunnel me : this.inputs.values()) { + if (me instanceof PartP2PTunnelME) { + tm.wakeDevice(me.getGridNode()); + } + } + } + + @Override + public void onUpdateTick() {} + + @Override + public void removeNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof PartP2PTunnel) { + if (machine instanceof PartP2PTunnelME) { + if (!node.hasFlag(GridFlags.REQUIRE_CHANNEL)) { + return; + } + } + + final PartP2PTunnel t = (PartP2PTunnel) machine; + // AELog.info( "rmv-" + (t.output ? "output: " : "input: ") + t.freq + // ); + + if (t.isOutput()) { + this.outputs.remove(t.getFrequency(), t); + } else { + this.inputs.remove(t.getFrequency()); + } + + this.updateTunnel(t.getFrequency(), !t.isOutput(), false); + } + } + + @Override + public void addNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof PartP2PTunnel) { + if (machine instanceof PartP2PTunnelME) { + if (!node.hasFlag(GridFlags.REQUIRE_CHANNEL)) { + return; + } + } + + final PartP2PTunnel t = (PartP2PTunnel) machine; + // AELog.info( "add-" + (t.output ? "output: " : "input: ") + t.freq + // ); + + if (t.isOutput()) { + this.outputs.put(t.getFrequency(), t); + } else { + this.inputs.put(t.getFrequency(), t); + } + + this.updateTunnel(t.getFrequency(), !t.isOutput(), false); + } + } + + @Override + public void onSplit(final IGridStorage storageB) {} + + @Override + public void onJoin(final IGridStorage storageB) {} + + @Override + public void populateGridStorage(final IGridStorage storage) {} + + private void updateTunnel(final long freq, final boolean updateOutputs, final boolean configChange) { + for (final PartP2PTunnel p : this.outputs.get(freq)) { + if (configChange) { + p.onTunnelConfigChange(); + } + p.onTunnelNetworkChange(); + } + + final PartP2PTunnel in = this.inputs.get(freq); + if (in != null) { + if (configChange) { + in.onTunnelConfigChange(); + } + in.onTunnelNetworkChange(); + } + } + + public void updateFreq(final PartP2PTunnel t, final long newFrequency) { + if (this.outputs.containsValue(t)) { + this.outputs.remove(t.getFrequency(), t); + } + + if (this.inputs.containsValue(t)) { + this.inputs.remove(t.getFrequency()); + } + + t.setFrequency(newFrequency); + + if (t.isOutput()) { + this.outputs.put(t.getFrequency(), t); + } else { + this.inputs.put(t.getFrequency(), t); + } + + // AELog.info( "update-" + (t.output ? "output: " : "input: ") + t.freq + // ); + this.updateTunnel(t.getFrequency(), t.isOutput(), true); + this.updateTunnel(t.getFrequency(), !t.isOutput(), true); + } + + public TunnelCollection getOutputs(final long freq, final Class c) { + final PartP2PTunnel in = this.inputs.get(freq); + if (in == null) { + return this.NullColl; + } + + final TunnelCollection out = this.inputs.get(freq).getCollection(this.outputs.get(freq), c); + if (out == null) { + return this.NullColl; + } + + return out; + } + + public PartP2PTunnel getInput(final long freq) { + return this.inputs.get(freq); + } } diff --git a/src/main/java/appeng/me/cache/PathGridCache.java b/src/main/java/appeng/me/cache/PathGridCache.java index e9fd7d1d426..6d27b115254 100644 --- a/src/main/java/appeng/me/cache/PathGridCache.java +++ b/src/main/java/appeng/me/cache/PathGridCache.java @@ -18,7 +18,6 @@ package appeng.me.cache; - import appeng.api.networking.*; import appeng.api.networking.events.MENetworkBootingStatusChange; import appeng.api.networking.events.MENetworkChannelChanged; @@ -36,472 +35,381 @@ import appeng.me.pathfinding.*; import appeng.tile.networking.TileController; import appeng.util.Platform; +import java.util.*; import net.minecraftforge.common.util.ForgeDirection; import org.apache.logging.log4j.Level; -import java.util.*; +public class PathGridCache implements IPathingGrid { + + private final LinkedList active = new LinkedList<>(); + private final Map backbone = new HashMap<>(); + private final Set controllers = new HashSet<>(); + private final Set requireChannels = new HashSet<>(); + private final Set blockDense = new HashSet<>(); + private final IGrid myGrid; + private int channelsInUse = 0; + private int channelsByBlocks = 0; + private double channelPowerUsage = 0.0; + private boolean recalculateControllerNextTick = true; + private boolean updateNetwork = true; + private boolean booting = false; + private ControllerState controllerState = ControllerState.NO_CONTROLLER; + private int ticksUntilReady = 20; + private int lastChannels = 0; + private HashSet semiOpen = new HashSet(); + + public PathGridCache(final IGrid g) { + this.myGrid = g; + } + + @Override + public void onUpdateTick() { + if (this.recalculateControllerNextTick) { + this.recalcController(); + } + if (this.updateNetwork) { + if (!this.booting) { + this.myGrid.postEvent(new MENetworkBootingStatusChange()); + } + + this.booting = true; + this.updateNetwork = false; + this.setChannelsInUse(0); + + if (!AEConfig.instance.isFeatureEnabled(AEFeature.Channels)) { + final int used = this.calculateRequiredChannels(); + + final int nodes = this.myGrid.getNodes().size(); + this.ticksUntilReady = 20 + Math.max(0, nodes / 100 - 20); + this.setChannelsByBlocks(nodes * used); + this.setChannelPowerUsage(this.getChannelsByBlocks() / 128.0); + + this.myGrid.getPivot().beginVisit(new AdHocChannelUpdater(used)); + } else if (this.controllerState == ControllerState.NO_CONTROLLER) { + final int requiredChannels = this.calculateRequiredChannels(); + int used = requiredChannels; + if (requiredChannels > 8) { + used = 0; + } + + final int nodes = this.myGrid.getNodes().size(); + this.setChannelsInUse(used); + + this.ticksUntilReady = 20 + Math.max(0, nodes / 100 - 20); + this.setChannelsByBlocks(nodes * used); + this.setChannelPowerUsage(this.getChannelsByBlocks() / 128.0); + + this.myGrid.getPivot().beginVisit(new AdHocChannelUpdater(used)); + } else if (this.controllerState == ControllerState.CONTROLLER_CONFLICT) { + this.ticksUntilReady = 20; + this.myGrid.getPivot().beginVisit(new AdHocChannelUpdater(0)); + } else { + final int nodes = this.myGrid.getNodes().size(); + this.ticksUntilReady = 20 + Math.max(0, nodes / 100 - 20); + final HashSet closedList = new HashSet(); + this.semiOpen = new HashSet(); + + // myGrid.getPivot().beginVisit( new AdHocChannelUpdater( 0 ) + // ); + for (final IGridNode node : this.myGrid.getMachines(TileController.class)) { + closedList.add((IPathItem) node); + for (final IGridConnection gcc : node.getConnections()) { + final GridConnection gc = (GridConnection) gcc; + if (!(gc.getOtherSide(node).getMachine() instanceof TileController)) { + final List open = new LinkedList(); + closedList.add(gc); + open.add(gc); + gc.setControllerRoute((GridNode) node, true); + this.active.add(new PathSegment(this, open, this.semiOpen, closedList)); + } + } + } + } + } -public class PathGridCache implements IPathingGrid -{ - - private final LinkedList active = new LinkedList<>(); - private final Map backbone = new HashMap<>(); - private final Set controllers = new HashSet<>(); - private final Set requireChannels = new HashSet<>(); - private final Set blockDense = new HashSet<>(); - private final IGrid myGrid; - private int channelsInUse = 0; - private int channelsByBlocks = 0; - private double channelPowerUsage = 0.0; - private boolean recalculateControllerNextTick = true; - private boolean updateNetwork = true; - private boolean booting = false; - private ControllerState controllerState = ControllerState.NO_CONTROLLER; - private int ticksUntilReady = 20; - private int lastChannels = 0; - private HashSet semiOpen = new HashSet(); - - public PathGridCache( final IGrid g ) - { - this.myGrid = g; - } - - @Override - public void onUpdateTick() - { - if( this.recalculateControllerNextTick ) - { - this.recalcController(); - } - - if( this.updateNetwork ) - { - if( !this.booting ) - { - this.myGrid.postEvent( new MENetworkBootingStatusChange() ); - } - - this.booting = true; - this.updateNetwork = false; - this.setChannelsInUse( 0 ); - - if( !AEConfig.instance.isFeatureEnabled( AEFeature.Channels ) ) - { - final int used = this.calculateRequiredChannels(); - - final int nodes = this.myGrid.getNodes().size(); - this.ticksUntilReady = 20 + Math.max( 0, nodes / 100 - 20 ); - this.setChannelsByBlocks( nodes * used ); - this.setChannelPowerUsage( this.getChannelsByBlocks() / 128.0 ); - - this.myGrid.getPivot().beginVisit( new AdHocChannelUpdater( used ) ); - } - else if( this.controllerState == ControllerState.NO_CONTROLLER ) - { - final int requiredChannels = this.calculateRequiredChannels(); - int used = requiredChannels; - if( requiredChannels > 8 ) - { - used = 0; - } - - final int nodes = this.myGrid.getNodes().size(); - this.setChannelsInUse( used ); - - this.ticksUntilReady = 20 + Math.max( 0, nodes / 100 - 20 ); - this.setChannelsByBlocks( nodes * used ); - this.setChannelPowerUsage( this.getChannelsByBlocks() / 128.0 ); - - this.myGrid.getPivot().beginVisit( new AdHocChannelUpdater( used ) ); - } - else if( this.controllerState == ControllerState.CONTROLLER_CONFLICT ) - { - this.ticksUntilReady = 20; - this.myGrid.getPivot().beginVisit( new AdHocChannelUpdater( 0 ) ); - } - else - { - final int nodes = this.myGrid.getNodes().size(); - this.ticksUntilReady = 20 + Math.max( 0, nodes / 100 - 20 ); - final HashSet closedList = new HashSet(); - this.semiOpen = new HashSet(); - - // myGrid.getPivot().beginVisit( new AdHocChannelUpdater( 0 ) - // ); - for( final IGridNode node : this.myGrid.getMachines( TileController.class ) ) - { - closedList.add( (IPathItem) node ); - for( final IGridConnection gcc : node.getConnections() ) - { - final GridConnection gc = (GridConnection) gcc; - if( !( gc.getOtherSide( node ).getMachine() instanceof TileController ) ) - { - final List open = new LinkedList(); - closedList.add( gc ); - open.add( gc ); - gc.setControllerRoute( (GridNode) node, true ); - this.active.add( new PathSegment( this, open, this.semiOpen, closedList ) ); - } - } - } - } - } - - if( !this.active.isEmpty() || !backbone.isEmpty() || this.ticksUntilReady > 0 ) - { - boolean firstStage = !this.active.isEmpty(); - final Iterator i = this.active.iterator(); - while( i.hasNext() ) - { - final PathSegment pat = i.next(); - if( pat.step(backbone, TopologyStage.CONTROLLER_TO_BACKBONE) ) - { - pat.setDead( true ); - i.remove(); - } - } - if (active.isEmpty() && !backbone.isEmpty()) { - if (firstStage) { - for (BackbonePathSegment ps : backbone.values()){ - BackbonePathSegment.reset(backbone); - //noinspection StatementWithEmptyBody - while (!ps.step(backbone, TopologyStage.BACKBONE)){} // just establish backbone topology, that is fast - ps.selectControllerRoute(); - } - BackbonePathSegment.reset(backbone); - } - else - { - final Iterator bsi = this.backbone.values().iterator(); - boolean hasAliveSegments = false; - while (bsi.hasNext()) - { - final PathSegment pat = bsi.next(); - if (pat.isDead()) - continue; - hasAliveSegments = true; - if( pat.step(backbone, TopologyStage.PERIPHERALS) ) - pat.setDead( true ); - } - if (AEConfig.instance.debugPathFinding) - { - AELog.debug("Pathfinding: Backbone 2nd phase, hasAliveSegments = %b", hasAliveSegments); - } - if (!hasAliveSegments) - backbone.clear(); - } - } - - this.ticksUntilReady--; - - if( this.active.isEmpty() && this.backbone.isEmpty() && this.ticksUntilReady <= 0 ) - { - if( this.controllerState == ControllerState.CONTROLLER_ONLINE ) - { - final Iterator controllerIterator = this.controllers.iterator(); - if( controllerIterator.hasNext() ) - { - final TileController controller = controllerIterator.next(); - controller.getGridNode( ForgeDirection.UNKNOWN ).beginVisit( new ControllerChannelUpdater() ); - } - } - - // check for achievements - this.achievementPost(); - - this.booting = false; - this.setChannelPowerUsage( this.getChannelsByBlocks() / 128.0 ); - this.myGrid.postEvent( new MENetworkBootingStatusChange() ); - } - } - } - - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - if (AEConfig.instance.debugPathFinding) - { + if (!this.active.isEmpty() || !backbone.isEmpty() || this.ticksUntilReady > 0) { + boolean firstStage = !this.active.isEmpty(); + final Iterator i = this.active.iterator(); + while (i.hasNext()) { + final PathSegment pat = i.next(); + if (pat.step(backbone, TopologyStage.CONTROLLER_TO_BACKBONE)) { + pat.setDead(true); + i.remove(); + } + } + if (active.isEmpty() && !backbone.isEmpty()) { + if (firstStage) { + for (BackbonePathSegment ps : backbone.values()) { + BackbonePathSegment.reset(backbone); + //noinspection StatementWithEmptyBody + while (!ps.step( + backbone, TopologyStage.BACKBONE)) {} // just establish backbone topology, that is fast + ps.selectControllerRoute(); + } + BackbonePathSegment.reset(backbone); + } else { + final Iterator bsi = + this.backbone.values().iterator(); + boolean hasAliveSegments = false; + while (bsi.hasNext()) { + final PathSegment pat = bsi.next(); + if (pat.isDead()) continue; + hasAliveSegments = true; + if (pat.step(backbone, TopologyStage.PERIPHERALS)) pat.setDead(true); + } + if (AEConfig.instance.debugPathFinding) { + AELog.debug("Pathfinding: Backbone 2nd phase, hasAliveSegments = %b", hasAliveSegments); + } + if (!hasAliveSegments) backbone.clear(); + } + } + + this.ticksUntilReady--; + + if (this.active.isEmpty() && this.backbone.isEmpty() && this.ticksUntilReady <= 0) { + if (this.controllerState == ControllerState.CONTROLLER_ONLINE) { + final Iterator controllerIterator = this.controllers.iterator(); + if (controllerIterator.hasNext()) { + final TileController controller = controllerIterator.next(); + controller.getGridNode(ForgeDirection.UNKNOWN).beginVisit(new ControllerChannelUpdater()); + } + } + + // check for achievements + this.achievementPost(); + + this.booting = false; + this.setChannelPowerUsage(this.getChannelsByBlocks() / 128.0); + this.myGrid.postEvent(new MENetworkBootingStatusChange()); + } + } + } + + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + if (AEConfig.instance.debugPathFinding) { final String coordinates = gridNode.getGridBlock().getLocation().toString(); - AELog.info( "Repath is triggered by removing a node at [%s]", coordinates); - AELog.printStackTrace( Level.INFO ); + AELog.info("Repath is triggered by removing a node at [%s]", coordinates); + AELog.printStackTrace(Level.INFO); } - if( machine instanceof TileController ) - { - this.controllers.remove( machine ); - this.recalculateControllerNextTick = true; - } + if (machine instanceof TileController) { + this.controllers.remove(machine); + this.recalculateControllerNextTick = true; + } - final EnumSet flags = gridNode.getGridBlock().getFlags(); + final EnumSet flags = gridNode.getGridBlock().getFlags(); - if( flags.contains( GridFlags.REQUIRE_CHANNEL ) ) - { - this.requireChannels.remove( gridNode ); - } + if (flags.contains(GridFlags.REQUIRE_CHANNEL)) { + this.requireChannels.remove(gridNode); + } - if( flags.contains( GridFlags.CANNOT_CARRY_COMPRESSED ) ) - { - this.blockDense.remove( gridNode ); - } + if (flags.contains(GridFlags.CANNOT_CARRY_COMPRESSED)) { + this.blockDense.remove(gridNode); + } - this.repath(); - } + this.repath(); + } - @Override - public void addNode( final IGridNode gridNode, final IGridHost machine ) - { - if (AEConfig.instance.debugPathFinding) - { + @Override + public void addNode(final IGridNode gridNode, final IGridHost machine) { + if (AEConfig.instance.debugPathFinding) { final String coordinates = gridNode.getGridBlock().getLocation().toString(); - AELog.info( "Repath is triggered by adding a node at [%s]", coordinates); - AELog.printStackTrace( Level.INFO ); + AELog.info("Repath is triggered by adding a node at [%s]", coordinates); + AELog.printStackTrace(Level.INFO); + } + + if (machine instanceof TileController) { + this.controllers.add((TileController) machine); + this.recalculateControllerNextTick = true; + } + + final EnumSet flags = gridNode.getGridBlock().getFlags(); + + if (flags.contains(GridFlags.REQUIRE_CHANNEL)) { + this.requireChannels.add(gridNode); + } + + if (flags.contains(GridFlags.CANNOT_CARRY_COMPRESSED)) { + this.blockDense.add(gridNode); + } + + this.repath(); + } + + @Override + public void onSplit(final IGridStorage storageB) {} + + @Override + public void onJoin(final IGridStorage storageB) {} + + @Override + public void populateGridStorage(final IGridStorage storage) {} + + private void recalcController() { + this.recalculateControllerNextTick = false; + final ControllerState old = this.controllerState; + + if (this.controllers.isEmpty()) { + this.controllerState = ControllerState.NO_CONTROLLER; + } else { + final IGridNode startingNode = this.controllers.iterator().next().getGridNode(ForgeDirection.UNKNOWN); + if (startingNode == null) { + this.controllerState = ControllerState.CONTROLLER_CONFLICT; + return; + } + + final DimensionalCoord dc = startingNode.getGridBlock().getLocation(); + final ControllerValidator cv = new ControllerValidator(dc.x, dc.y, dc.z); + + startingNode.beginVisit(cv); + + if (cv.isValid() && cv.getFound() == this.controllers.size()) { + this.controllerState = ControllerState.CONTROLLER_ONLINE; + } else { + this.controllerState = ControllerState.CONTROLLER_CONFLICT; + } + } + + if (old != this.controllerState) { + this.myGrid.postEvent(new MENetworkControllerChange()); + } + } + + private int calculateRequiredChannels() { + this.semiOpen.clear(); + + int depth = 0; + for (final IGridNode nodes : this.requireChannels) { + if (!this.semiOpen.contains(nodes)) { + final IGridBlock gb = nodes.getGridBlock(); + final EnumSet flags = gb.getFlags(); + + if (flags.contains(GridFlags.COMPRESSED_CHANNEL) && !this.blockDense.isEmpty()) { + return 9; + } + + depth++; + + if (flags.contains(GridFlags.MULTIBLOCK)) { + final IGridMultiblock gmb = (IGridMultiblock) gb; + final Iterator i = gmb.getMultiblockNodes(); + while (i.hasNext()) { + this.semiOpen.add((IPathItem) i.next()); + } + } + } + } + + return depth; + } + + private void achievementPost() { + if (this.lastChannels != this.getChannelsInUse() && AEConfig.instance.isFeatureEnabled(AEFeature.Channels)) { + final Achievements currentBracket = this.getAchievementBracket(this.getChannelsInUse()); + final Achievements lastBracket = this.getAchievementBracket(this.lastChannels); + if (currentBracket != lastBracket && currentBracket != null) { + final Set players = new HashSet(); + for (final IGridNode n : this.requireChannels) { + players.add(n.getPlayerID()); + } + + for (final int id : players) { + Platform.addStat(id, currentBracket.getAchievement()); + } + } } + this.lastChannels = this.getChannelsInUse(); + } - if( machine instanceof TileController ) - { - this.controllers.add( (TileController) machine ); - this.recalculateControllerNextTick = true; - } - - final EnumSet flags = gridNode.getGridBlock().getFlags(); - - if( flags.contains( GridFlags.REQUIRE_CHANNEL ) ) - { - this.requireChannels.add( gridNode ); - } - - if( flags.contains( GridFlags.CANNOT_CARRY_COMPRESSED ) ) - { - this.blockDense.add( gridNode ); - } - - this.repath(); - } - - @Override - public void onSplit( final IGridStorage storageB ) - { - - } - - @Override - public void onJoin( final IGridStorage storageB ) - { - - } - - @Override - public void populateGridStorage( final IGridStorage storage ) - { - - } - - private void recalcController() - { - this.recalculateControllerNextTick = false; - final ControllerState old = this.controllerState; - - if( this.controllers.isEmpty() ) - { - this.controllerState = ControllerState.NO_CONTROLLER; - } - else - { - final IGridNode startingNode = this.controllers.iterator().next().getGridNode( ForgeDirection.UNKNOWN ); - if( startingNode == null ) - { - this.controllerState = ControllerState.CONTROLLER_CONFLICT; - return; - } - - final DimensionalCoord dc = startingNode.getGridBlock().getLocation(); - final ControllerValidator cv = new ControllerValidator( dc.x, dc.y, dc.z ); - - startingNode.beginVisit( cv ); - - if( cv.isValid() && cv.getFound() == this.controllers.size() ) - { - this.controllerState = ControllerState.CONTROLLER_ONLINE; - } - else - { - this.controllerState = ControllerState.CONTROLLER_CONFLICT; - } - } - - if( old != this.controllerState ) - { - this.myGrid.postEvent( new MENetworkControllerChange() ); - } - } - - private int calculateRequiredChannels() - { - this.semiOpen.clear(); - - int depth = 0; - for( final IGridNode nodes : this.requireChannels ) - { - if( !this.semiOpen.contains( nodes ) ) - { - final IGridBlock gb = nodes.getGridBlock(); - final EnumSet flags = gb.getFlags(); - - if( flags.contains( GridFlags.COMPRESSED_CHANNEL ) && !this.blockDense.isEmpty() ) - { - return 9; - } - - depth++; - - if( flags.contains( GridFlags.MULTIBLOCK ) ) - { - final IGridMultiblock gmb = (IGridMultiblock) gb; - final Iterator i = gmb.getMultiblockNodes(); - while( i.hasNext() ) - { - this.semiOpen.add( (IPathItem) i.next() ); - } - } - } - } - - return depth; - } - - private void achievementPost() - { - if( this.lastChannels != this.getChannelsInUse() && AEConfig.instance.isFeatureEnabled( AEFeature.Channels ) ) - { - final Achievements currentBracket = this.getAchievementBracket( this.getChannelsInUse() ); - final Achievements lastBracket = this.getAchievementBracket( this.lastChannels ); - if( currentBracket != lastBracket && currentBracket != null ) - { - final Set players = new HashSet(); - for( final IGridNode n : this.requireChannels ) - { - players.add( n.getPlayerID() ); - } - - for( final int id : players ) - { - Platform.addStat( id, currentBracket.getAchievement() ); - } - } - } - this.lastChannels = this.getChannelsInUse(); - } - - private Achievements getAchievementBracket( final int ch ) - { - if( ch < 8 ) - { - return null; - } - - if( ch < 128 ) - { - return Achievements.Networking1; - } - - if( ch < 2048 ) - { - return Achievements.Networking2; - } - - return Achievements.Networking3; - } - - @MENetworkEventSubscribe - void updateNodReq( final MENetworkChannelChanged ev ) - { - final IGridNode gridNode = ev.node; - - if (AEConfig.instance.debugPathFinding) - { + private Achievements getAchievementBracket(final int ch) { + if (ch < 8) { + return null; + } + + if (ch < 128) { + return Achievements.Networking1; + } + + if (ch < 2048) { + return Achievements.Networking2; + } + + return Achievements.Networking3; + } + + @MENetworkEventSubscribe + void updateNodReq(final MENetworkChannelChanged ev) { + final IGridNode gridNode = ev.node; + + if (AEConfig.instance.debugPathFinding) { final String coordinates = gridNode.getGridBlock().getLocation().toString(); - AELog.info( "Repath is triggered by changing a node at [%s]", coordinates); - AELog.printStackTrace( Level.INFO ); + AELog.info("Repath is triggered by changing a node at [%s]", coordinates); + AELog.printStackTrace(Level.INFO); + } + + if (gridNode.getGridBlock().getFlags().contains(GridFlags.REQUIRE_CHANNEL)) { + this.requireChannels.add(gridNode); + } else { + this.requireChannels.remove(gridNode); } - if( gridNode.getGridBlock().getFlags().contains( GridFlags.REQUIRE_CHANNEL ) ) - { - this.requireChannels.add( gridNode ); - } - else - { - this.requireChannels.remove( gridNode ); - } - - this.repath(); - } - - @Override - public boolean isNetworkBooting() - { - return (!this.active.isEmpty() || !this.backbone.isEmpty()) && !this.booting; - } - - @Override - public ControllerState getControllerState() - { - return this.controllerState; - } - - @Override - public void repath() - { - // clean up... - this.active.clear(); - this.backbone.clear(); - this.setChannelsByBlocks( 0 ); - this.updateNetwork = true; - } - - double getChannelPowerUsage() - { - return this.channelPowerUsage; - } - - private void setChannelPowerUsage( final double channelPowerUsage ) - { - this.channelPowerUsage = channelPowerUsage; - } - - public int getChannelsByBlocks() - { - return this.channelsByBlocks; - } - - public void setChannelsByBlocks( final int channelsByBlocks ) - { - this.channelsByBlocks = channelsByBlocks; - } - - public int getChannelsInUse() - { - return this.channelsInUse; - } - - public void setChannelsInUse( final int channelsInUse ) - { - this.channelsInUse = channelsInUse; - } - - public boolean isValidBackboneConnection(IPathItem pi) - { - BackbonePathSegment bs = backbone.get(pi); - if (bs == null) - return false; - return bs.isValid(); - } - - public void repathBackboneConnection(IPathItem pi) { - BackbonePathSegment bs = backbone.get(pi); - if (bs == null) - return; - if (!bs.switchControllerRoute()) - bs.transferToNeighbours(); - } + this.repath(); + } + + @Override + public boolean isNetworkBooting() { + return (!this.active.isEmpty() || !this.backbone.isEmpty()) && !this.booting; + } + + @Override + public ControllerState getControllerState() { + return this.controllerState; + } + + @Override + public void repath() { + // clean up... + this.active.clear(); + this.backbone.clear(); + this.setChannelsByBlocks(0); + this.updateNetwork = true; + } + + double getChannelPowerUsage() { + return this.channelPowerUsage; + } + + private void setChannelPowerUsage(final double channelPowerUsage) { + this.channelPowerUsage = channelPowerUsage; + } + + public int getChannelsByBlocks() { + return this.channelsByBlocks; + } + + public void setChannelsByBlocks(final int channelsByBlocks) { + this.channelsByBlocks = channelsByBlocks; + } + + public int getChannelsInUse() { + return this.channelsInUse; + } + + public void setChannelsInUse(final int channelsInUse) { + this.channelsInUse = channelsInUse; + } + + public boolean isValidBackboneConnection(IPathItem pi) { + BackbonePathSegment bs = backbone.get(pi); + if (bs == null) return false; + return bs.isValid(); + } + + public void repathBackboneConnection(IPathItem pi) { + BackbonePathSegment bs = backbone.get(pi); + if (bs == null) return; + if (!bs.switchControllerRoute()) bs.transferToNeighbours(); + } } diff --git a/src/main/java/appeng/me/cache/SecurityCache.java b/src/main/java/appeng/me/cache/SecurityCache.java index 4bb613a1a70..f29f11cb59b 100644 --- a/src/main/java/appeng/me/cache/SecurityCache.java +++ b/src/main/java/appeng/me/cache/SecurityCache.java @@ -18,7 +18,6 @@ package appeng.me.cache; - import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; @@ -32,184 +31,142 @@ import appeng.me.GridNode; import com.google.common.base.Preconditions; import com.mojang.authlib.GameProfile; -import net.minecraft.entity.player.EntityPlayer; - import java.util.*; +import net.minecraft.entity.player.EntityPlayer; - -public class SecurityCache implements ISecurityGrid -{ - private final IGrid myGrid; - private final List securityProvider = new ArrayList<>(); - private final HashMap> playerPerms = new HashMap<>(); - private long securityKey = -1; - static final int STARTUP_DELAY = 20; - private int startupTicks = 0; - private final static Set opPlayers = new HashSet<>(); - - public SecurityCache( final IGrid g ) - { - this.myGrid = g; - } - - @MENetworkEventSubscribe - public void updatePermissions( final MENetworkSecurityChange ev ) - { - this.playerPerms.clear(); - if( this.securityProvider.isEmpty() ) - { - return; - } - - this.securityProvider.get( 0 ).readPermissions( this.playerPerms ); - } - - public long getSecurityKey() - { - return this.securityKey; - } - - @Override - public void onUpdateTick() - { - if (startupTicks < STARTUP_DELAY) - startupTicks++; - } - - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof ISecurityProvider ) - { - this.securityProvider.remove( machine ); - this.updateSecurityKey(); - } - } - - private void updateSecurityKey() - { - final long lastCode = this.securityKey; - - if( this.securityProvider.size() == 1 ) - { - this.securityKey = this.securityProvider.get( 0 ).getSecurityKey(); - } - else - { - this.securityKey = -1; - } - - if( lastCode != this.securityKey ) - { - this.getGrid().postEvent( new MENetworkSecurityChange() ); - for( final IGridNode n : this.getGrid().getNodes() ) - { - ( (GridNode) n ).setLastSecurityKey( this.securityKey ); - } - } - } - - @Override - public void addNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof ISecurityProvider ) - { - this.securityProvider.add( (ISecurityProvider) machine ); - this.updateSecurityKey(); - } - else - { - ( (GridNode) gridNode ).setLastSecurityKey( this.securityKey ); - } - } - - @Override - public void onSplit( final IGridStorage destinationStorage ) - { - - } - - @Override - public void onJoin( final IGridStorage sourceStorage ) - { - - } - - @Override - public void populateGridStorage( final IGridStorage destinationStorage ) - { - - } - - @Override - public boolean isAvailable() - { - return startupTicks >= STARTUP_DELAY && this.securityProvider.size() == 1 && this.securityProvider.get( 0 ).isSecurityEnabled(); - } - - @Override - public boolean hasPermission( final EntityPlayer player, final SecurityPermissions perm ) - { - Preconditions.checkNotNull( player ); - Preconditions.checkNotNull( perm ); - - final GameProfile profile = player.getGameProfile(); - if (isPlayerOP(profile)) - return true; - return this.hasPermission( WorldData.instance().playerData().getPlayerID( profile ), perm ); - } - - @Override - public boolean hasPermission( final int playerID, final SecurityPermissions perm ) - { - if( this.isAvailable() ) - { - final EnumSet perms = this.playerPerms.get( playerID ); - - if( perms == null ) - { - if( playerID == -1 ) // no default? - { - return false; - } - else - { - return this.hasPermission( -1, perm ); - } - } - - return perms.contains( perm ); - } - return true; - } - - @Override - public int getOwner() - { - if( this.isAvailable() ) - { - return this.securityProvider.get( 0 ).getOwner(); - } - return -1; - } - - public IGrid getGrid() - { - return this.myGrid; - } - - public static void registerOpPlayer(GameProfile profile) - { - opPlayers.add(profile); - } - - public static void unregisterOpPlayer(GameProfile profile) - { - opPlayers.remove(profile); - } - - public static boolean isPlayerOP(GameProfile profile) - { - return opPlayers.contains(profile); - } +public class SecurityCache implements ISecurityGrid { + private final IGrid myGrid; + private final List securityProvider = new ArrayList<>(); + private final HashMap> playerPerms = new HashMap<>(); + private long securityKey = -1; + static final int STARTUP_DELAY = 20; + private int startupTicks = 0; + private static final Set opPlayers = new HashSet<>(); + + public SecurityCache(final IGrid g) { + this.myGrid = g; + } + + @MENetworkEventSubscribe + public void updatePermissions(final MENetworkSecurityChange ev) { + this.playerPerms.clear(); + if (this.securityProvider.isEmpty()) { + return; + } + + this.securityProvider.get(0).readPermissions(this.playerPerms); + } + + public long getSecurityKey() { + return this.securityKey; + } + + @Override + public void onUpdateTick() { + if (startupTicks < STARTUP_DELAY) startupTicks++; + } + + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof ISecurityProvider) { + this.securityProvider.remove(machine); + this.updateSecurityKey(); + } + } + + private void updateSecurityKey() { + final long lastCode = this.securityKey; + + if (this.securityProvider.size() == 1) { + this.securityKey = this.securityProvider.get(0).getSecurityKey(); + } else { + this.securityKey = -1; + } + + if (lastCode != this.securityKey) { + this.getGrid().postEvent(new MENetworkSecurityChange()); + for (final IGridNode n : this.getGrid().getNodes()) { + ((GridNode) n).setLastSecurityKey(this.securityKey); + } + } + } + + @Override + public void addNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof ISecurityProvider) { + this.securityProvider.add((ISecurityProvider) machine); + this.updateSecurityKey(); + } else { + ((GridNode) gridNode).setLastSecurityKey(this.securityKey); + } + } + + @Override + public void onSplit(final IGridStorage destinationStorage) {} + + @Override + public void onJoin(final IGridStorage sourceStorage) {} + + @Override + public void populateGridStorage(final IGridStorage destinationStorage) {} + + @Override + public boolean isAvailable() { + return startupTicks >= STARTUP_DELAY + && this.securityProvider.size() == 1 + && this.securityProvider.get(0).isSecurityEnabled(); + } + + @Override + public boolean hasPermission(final EntityPlayer player, final SecurityPermissions perm) { + Preconditions.checkNotNull(player); + Preconditions.checkNotNull(perm); + + final GameProfile profile = player.getGameProfile(); + if (isPlayerOP(profile)) return true; + return this.hasPermission(WorldData.instance().playerData().getPlayerID(profile), perm); + } + + @Override + public boolean hasPermission(final int playerID, final SecurityPermissions perm) { + if (this.isAvailable()) { + final EnumSet perms = this.playerPerms.get(playerID); + + if (perms == null) { + if (playerID == -1) // no default? + { + return false; + } else { + return this.hasPermission(-1, perm); + } + } + + return perms.contains(perm); + } + return true; + } + + @Override + public int getOwner() { + if (this.isAvailable()) { + return this.securityProvider.get(0).getOwner(); + } + return -1; + } + + public IGrid getGrid() { + return this.myGrid; + } + + public static void registerOpPlayer(GameProfile profile) { + opPlayers.add(profile); + } + + public static void unregisterOpPlayer(GameProfile profile) { + opPlayers.remove(profile); + } + + public static boolean isPlayerOP(GameProfile profile) { + return opPlayers.contains(profile); + } } diff --git a/src/main/java/appeng/me/cache/SpatialPylonCache.java b/src/main/java/appeng/me/cache/SpatialPylonCache.java index f1adba5e808..c7270d580b7 100644 --- a/src/main/java/appeng/me/cache/SpatialPylonCache.java +++ b/src/main/java/appeng/me/cache/SpatialPylonCache.java @@ -18,7 +18,6 @@ package appeng.me.cache; - import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; @@ -32,219 +31,188 @@ import appeng.me.cluster.implementations.SpatialPylonCluster; import appeng.tile.spatial.TileSpatialIOPort; import appeng.tile.spatial.TileSpatialPylon; - import java.util.HashMap; import java.util.LinkedList; import java.util.List; - -public class SpatialPylonCache implements ISpatialCache -{ - - private final IGrid myGrid; - private long powerRequired = 0; - private double efficiency = 0.0; - private DimensionalCoord captureMin; - private DimensionalCoord captureMax; - private boolean isValid = false; - private List ioPorts = new LinkedList(); - private HashMap clusters = new HashMap(); - - public SpatialPylonCache( final IGrid g ) - { - this.myGrid = g; - } - - @MENetworkEventSubscribe - public void bootingRender( final MENetworkBootingStatusChange c ) - { - this.reset( this.myGrid ); - } - - private void reset( final IGrid grid ) - { - - this.clusters = new HashMap(); - this.ioPorts = new LinkedList(); - - for( final IGridNode gm : grid.getMachines( TileSpatialIOPort.class ) ) - { - this.ioPorts.add( (TileSpatialIOPort) gm.getMachine() ); - } - - final IReadOnlyCollection set = grid.getMachines( TileSpatialPylon.class ); - for( final IGridNode gm : set ) - { - if( gm.meetsChannelRequirements() ) - { - final SpatialPylonCluster c = ( (TileSpatialPylon) gm.getMachine() ).getCluster(); - if( c != null ) - { - this.clusters.put( c, c ); - } - } - } - - this.captureMax = null; - this.captureMin = null; - this.isValid = true; - - int pylonBlocks = 0; - for( final SpatialPylonCluster cl : this.clusters.values() ) - { - if( this.captureMax == null ) - { - this.captureMax = cl.getMax().copy(); - } - if( this.captureMin == null ) - { - this.captureMin = cl.getMin().copy(); - } - - pylonBlocks += cl.tileCount(); - - this.captureMin.x = Math.min( this.captureMin.x, cl.getMin().x ); - this.captureMin.y = Math.min( this.captureMin.y, cl.getMin().y ); - this.captureMin.z = Math.min( this.captureMin.z, cl.getMin().z ); - - this.captureMax.x = Math.max( this.captureMax.x, cl.getMax().x ); - this.captureMax.y = Math.max( this.captureMax.y, cl.getMax().y ); - this.captureMax.z = Math.max( this.captureMax.z, cl.getMax().z ); - } - - double maxPower = 0; - double minPower = 0; - if( this.hasRegion() ) - { - this.isValid = this.captureMax.x - this.captureMin.x > 1 && this.captureMax.y - this.captureMin.y > 1 && this.captureMax.z - this.captureMin.z > 1; - - for( final SpatialPylonCluster cl : this.clusters.values() ) - { - switch( cl.getCurrentAxis() ) - { - case X: - - this.isValid = this.isValid && ( ( this.captureMax.y == cl.getMin().y || this.captureMin.y == cl.getMax().y ) || ( this.captureMax.z == cl.getMin().z || this.captureMin.z == cl.getMax().z ) ) && ( ( this.captureMax.y == cl.getMax().y || this.captureMin.y == cl.getMin().y ) || ( this.captureMax.z == cl.getMax().z || this.captureMin.z == cl.getMin().z ) ); - - break; - case Y: - - this.isValid = this.isValid && ( ( this.captureMax.x == cl.getMin().x || this.captureMin.x == cl.getMax().x ) || ( this.captureMax.z == cl.getMin().z || this.captureMin.z == cl.getMax().z ) ) && ( ( this.captureMax.x == cl.getMax().x || this.captureMin.x == cl.getMin().x ) || ( this.captureMax.z == cl.getMax().z || this.captureMin.z == cl.getMin().z ) ); - - break; - case Z: - - this.isValid = this.isValid && ( ( this.captureMax.y == cl.getMin().y || this.captureMin.y == cl.getMax().y ) || ( this.captureMax.x == cl.getMin().x || this.captureMin.x == cl.getMax().x ) ) && ( ( this.captureMax.y == cl.getMax().y || this.captureMin.y == cl.getMin().y ) || ( this.captureMax.x == cl.getMax().x || this.captureMin.x == cl.getMin().x ) ); - - break; - case UNFORMED: - this.isValid = false; - break; - } - } - - final int reqX = this.captureMax.x - this.captureMin.x; - final int reqY = this.captureMax.y - this.captureMin.y; - final int reqZ = this.captureMax.z - this.captureMin.z; - final int requirePylonBlocks = Math.max( 6, ( ( reqX * reqZ + reqX * reqY + reqY * reqZ ) * 3 ) / 8 ); - - this.efficiency = (double) pylonBlocks / (double) requirePylonBlocks; - - if( this.efficiency > 1.0 ) - { - this.efficiency = 1.0; - } - if( this.efficiency < 0.0 ) - { - this.efficiency = 0.0; - } - - minPower = (double) reqX * (double) reqY * reqZ * AEConfig.instance.spatialPowerMultiplier; - maxPower = Math.pow( minPower, AEConfig.instance.spatialPowerExponent ); - } - - final double affective_efficiency = Math.pow( this.efficiency, 0.25 ); - this.powerRequired = (long) ( affective_efficiency * minPower + ( 1.0 - affective_efficiency ) * maxPower ); - - for( final SpatialPylonCluster cl : this.clusters.values() ) - { - final boolean myWasValid = cl.isValid(); - cl.setValid( this.isValid ); - if( myWasValid != this.isValid ) - { - cl.updateStatus( false ); - } - } - } - - @Override - public boolean hasRegion() - { - return this.captureMin != null; - } - - @Override - public boolean isValidRegion() - { - return this.hasRegion() && this.isValid; - } - - @Override - public DimensionalCoord getMin() - { - return this.captureMin; - } - - @Override - public DimensionalCoord getMax() - { - return this.captureMax; - } - - @Override - public long requiredPower() - { - return this.powerRequired; - } - - @Override - public float currentEfficiency() - { - return (float) this.efficiency * 100; - } - - @Override - public void onUpdateTick() - { - } - - @Override - public void removeNode( final IGridNode node, final IGridHost machine ) - { - - } - - @Override - public void addNode( final IGridNode node, final IGridHost machine ) - { - - } - - @Override - public void onSplit( final IGridStorage storageB ) - { - - } - - @Override - public void onJoin( final IGridStorage storageB ) - { - - } - - @Override - public void populateGridStorage( final IGridStorage storage ) - { - - } +public class SpatialPylonCache implements ISpatialCache { + + private final IGrid myGrid; + private long powerRequired = 0; + private double efficiency = 0.0; + private DimensionalCoord captureMin; + private DimensionalCoord captureMax; + private boolean isValid = false; + private List ioPorts = new LinkedList(); + private HashMap clusters = + new HashMap(); + + public SpatialPylonCache(final IGrid g) { + this.myGrid = g; + } + + @MENetworkEventSubscribe + public void bootingRender(final MENetworkBootingStatusChange c) { + this.reset(this.myGrid); + } + + private void reset(final IGrid grid) { + + this.clusters = new HashMap(); + this.ioPorts = new LinkedList(); + + for (final IGridNode gm : grid.getMachines(TileSpatialIOPort.class)) { + this.ioPorts.add((TileSpatialIOPort) gm.getMachine()); + } + + final IReadOnlyCollection set = grid.getMachines(TileSpatialPylon.class); + for (final IGridNode gm : set) { + if (gm.meetsChannelRequirements()) { + final SpatialPylonCluster c = ((TileSpatialPylon) gm.getMachine()).getCluster(); + if (c != null) { + this.clusters.put(c, c); + } + } + } + + this.captureMax = null; + this.captureMin = null; + this.isValid = true; + + int pylonBlocks = 0; + for (final SpatialPylonCluster cl : this.clusters.values()) { + if (this.captureMax == null) { + this.captureMax = cl.getMax().copy(); + } + if (this.captureMin == null) { + this.captureMin = cl.getMin().copy(); + } + + pylonBlocks += cl.tileCount(); + + this.captureMin.x = Math.min(this.captureMin.x, cl.getMin().x); + this.captureMin.y = Math.min(this.captureMin.y, cl.getMin().y); + this.captureMin.z = Math.min(this.captureMin.z, cl.getMin().z); + + this.captureMax.x = Math.max(this.captureMax.x, cl.getMax().x); + this.captureMax.y = Math.max(this.captureMax.y, cl.getMax().y); + this.captureMax.z = Math.max(this.captureMax.z, cl.getMax().z); + } + + double maxPower = 0; + double minPower = 0; + if (this.hasRegion()) { + this.isValid = this.captureMax.x - this.captureMin.x > 1 + && this.captureMax.y - this.captureMin.y > 1 + && this.captureMax.z - this.captureMin.z > 1; + + for (final SpatialPylonCluster cl : this.clusters.values()) { + switch (cl.getCurrentAxis()) { + case X: + this.isValid = this.isValid + && ((this.captureMax.y == cl.getMin().y || this.captureMin.y == cl.getMax().y) + || (this.captureMax.z == cl.getMin().z || this.captureMin.z == cl.getMax().z)) + && ((this.captureMax.y == cl.getMax().y || this.captureMin.y == cl.getMin().y) + || (this.captureMax.z == cl.getMax().z || this.captureMin.z == cl.getMin().z)); + + break; + case Y: + this.isValid = this.isValid + && ((this.captureMax.x == cl.getMin().x || this.captureMin.x == cl.getMax().x) + || (this.captureMax.z == cl.getMin().z || this.captureMin.z == cl.getMax().z)) + && ((this.captureMax.x == cl.getMax().x || this.captureMin.x == cl.getMin().x) + || (this.captureMax.z == cl.getMax().z || this.captureMin.z == cl.getMin().z)); + + break; + case Z: + this.isValid = this.isValid + && ((this.captureMax.y == cl.getMin().y || this.captureMin.y == cl.getMax().y) + || (this.captureMax.x == cl.getMin().x || this.captureMin.x == cl.getMax().x)) + && ((this.captureMax.y == cl.getMax().y || this.captureMin.y == cl.getMin().y) + || (this.captureMax.x == cl.getMax().x || this.captureMin.x == cl.getMin().x)); + + break; + case UNFORMED: + this.isValid = false; + break; + } + } + + final int reqX = this.captureMax.x - this.captureMin.x; + final int reqY = this.captureMax.y - this.captureMin.y; + final int reqZ = this.captureMax.z - this.captureMin.z; + final int requirePylonBlocks = Math.max(6, ((reqX * reqZ + reqX * reqY + reqY * reqZ) * 3) / 8); + + this.efficiency = (double) pylonBlocks / (double) requirePylonBlocks; + + if (this.efficiency > 1.0) { + this.efficiency = 1.0; + } + if (this.efficiency < 0.0) { + this.efficiency = 0.0; + } + + minPower = (double) reqX * (double) reqY * reqZ * AEConfig.instance.spatialPowerMultiplier; + maxPower = Math.pow(minPower, AEConfig.instance.spatialPowerExponent); + } + + final double affective_efficiency = Math.pow(this.efficiency, 0.25); + this.powerRequired = (long) (affective_efficiency * minPower + (1.0 - affective_efficiency) * maxPower); + + for (final SpatialPylonCluster cl : this.clusters.values()) { + final boolean myWasValid = cl.isValid(); + cl.setValid(this.isValid); + if (myWasValid != this.isValid) { + cl.updateStatus(false); + } + } + } + + @Override + public boolean hasRegion() { + return this.captureMin != null; + } + + @Override + public boolean isValidRegion() { + return this.hasRegion() && this.isValid; + } + + @Override + public DimensionalCoord getMin() { + return this.captureMin; + } + + @Override + public DimensionalCoord getMax() { + return this.captureMax; + } + + @Override + public long requiredPower() { + return this.powerRequired; + } + + @Override + public float currentEfficiency() { + return (float) this.efficiency * 100; + } + + @Override + public void onUpdateTick() {} + + @Override + public void removeNode(final IGridNode node, final IGridHost machine) {} + + @Override + public void addNode(final IGridNode node, final IGridHost machine) {} + + @Override + public void onSplit(final IGridStorage storageB) {} + + @Override + public void onJoin(final IGridStorage storageB) {} + + @Override + public void populateGridStorage(final IGridStorage storage) {} } diff --git a/src/main/java/appeng/me/cache/TickManagerCache.java b/src/main/java/appeng/me/cache/TickManagerCache.java index 6115dcf1587..6a3038f3cf4 100644 --- a/src/main/java/appeng/me/cache/TickManagerCache.java +++ b/src/main/java/appeng/me/cache/TickManagerCache.java @@ -18,7 +18,6 @@ package appeng.me.cache; - import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; @@ -31,236 +30,193 @@ import appeng.core.AEConfig; import appeng.core.AELog; import appeng.me.cache.helpers.TickTracker; -import appeng.util.ConfigManager; +import java.util.HashMap; +import java.util.PriorityQueue; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.util.ReportedException; -import java.util.HashMap; -import java.util.PriorityQueue; - - -public class TickManagerCache implements ITickManager -{ - - private final IGrid myGrid; - private final HashMap alertable = new HashMap(); - private final HashMap sleeping = new HashMap(); - private final HashMap awake = new HashMap(); - private final PriorityQueue upcomingTicks = new PriorityQueue(); - private long currentTick = 0; - - public TickManagerCache( final IGrid g ) - { - this.myGrid = g; - } - - public long getCurrentTick() - { - return this.currentTick; - } - - public long getAvgNanoTime( final IGridNode node ) - { - TickTracker tt = this.awake.get( node ); - - if( tt == null ) - { - tt = this.sleeping.get( node ); - } - - if( tt == null ) - { - return -1; - } - - return tt.getAvgNanos(); - } - - @Override - public void onUpdateTick() - { - TickTracker tt = null; - try - { - this.currentTick++; - while( !this.upcomingTicks.isEmpty() ) - { - tt = this.upcomingTicks.peek(); - final int diff = (int) ( this.currentTick - tt.getLastTick() ); - if( diff >= tt.getCurrentRate() ) - { - // remove tt.. - this.upcomingTicks.poll(); - long tickStartTime = 0; - if (AEConfig.instance.debugLogTiming) - tickStartTime = System.nanoTime(); - final TickRateModulation mod = tt.getGridTickable().tickingRequest( tt.getNode(), diff ); - if (AEConfig.instance.debugLogTiming) - { - DimensionalCoord c = tt.getNode().getGridBlock().getLocation(); - AELog.debug("Timing: machine tick at (%d %d %d) took %d ns, new state is %s", c.x, c.y, c.z, System.nanoTime() - tickStartTime, mod.toString()); - } - switch( mod ) - { - case FASTER: - tt.setRate( tt.getCurrentRate() - 2 ); - break; - case IDLE: - tt.setRate( tt.getRequest().maxTickRate ); - break; - case SAME: - break; - case SLEEP: - this.sleepDevice( tt.getNode() ); - break; - case SLOWER: - tt.setRate( tt.getCurrentRate() + 1 ); - break; - case URGENT: - tt.setRate( 0 ); - break; - default: - break; - } - - if( this.awake.containsKey( tt.getNode() ) ) - { - this.addToQueue( tt ); - } - } - else - { - return; // done! - } - } - } - catch( final Throwable t ) - { - final CrashReport crashreport = CrashReport.makeCrashReport( t, "Ticking GridNode" ); - final CrashReportCategory crashreportcategory = crashreport.makeCategory( tt.getGridTickable().getClass().getSimpleName() + " being ticked." ); - tt.addEntityCrashInfo( crashreportcategory ); - throw new ReportedException( crashreport ); - } - } - - private void addToQueue( final TickTracker tt ) - { - tt.setLastTick( this.currentTick ); - this.upcomingTicks.add( tt ); - } - - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof IGridTickable ) - { - this.alertable.remove( gridNode ); - this.sleeping.remove( gridNode ); - this.awake.remove( gridNode ); - } - } - - @Override - public void addNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof IGridTickable ) - { - final TickingRequest tr = ( (IGridTickable) machine ).getTickingRequest( gridNode ); - if( tr != null ) - { - final TickTracker tt = new TickTracker( tr, gridNode, (IGridTickable) machine, this.currentTick, this ); - - if( tr.canBeAlerted ) - { - this.alertable.put( gridNode, tt ); - } - - if( tr.isSleeping ) - { - this.sleeping.put( gridNode, tt ); - } - else - { - this.awake.put( gridNode, tt ); - this.addToQueue( tt ); - } - } - } - } - - @Override - public void onSplit( final IGridStorage storageB ) - { - - } - - @Override - public void onJoin( final IGridStorage storageB ) - { - - } - - @Override - public void populateGridStorage( final IGridStorage storage ) - { - - } - - @Override - public boolean alertDevice( final IGridNode node ) - { - final TickTracker tt = this.alertable.get( node ); - if( tt == null ) - { - return false; - } - // throw new RuntimeException( - // "Invalid alerted device, this node is not marked as alertable, or part of this grid." ); - - // set to awake, this is for sanity. - this.sleeping.remove( node ); - this.awake.put( node, tt ); - - // configure sort. - tt.setLastTick( tt.getLastTick() - tt.getRequest().maxTickRate ); - tt.setCurrentRate( tt.getRequest().minTickRate ); - - // prevent dupes and tick build up. - this.upcomingTicks.remove( tt ); - this.upcomingTicks.add( tt ); - - return true; - } - - @Override - public boolean sleepDevice( final IGridNode node ) - { - if( this.awake.containsKey( node ) ) - { - final TickTracker gt = this.awake.get( node ); - this.awake.remove( node ); - this.sleeping.put( node, gt ); - - return true; - } - - return false; - } - - @Override - public boolean wakeDevice( final IGridNode node ) - { - if( this.sleeping.containsKey( node ) ) - { - final TickTracker gt = this.sleeping.get( node ); - this.sleeping.remove( node ); - this.awake.put( node, gt ); - this.addToQueue( gt ); - - return true; - } - - return false; - } +public class TickManagerCache implements ITickManager { + + private final IGrid myGrid; + private final HashMap alertable = new HashMap(); + private final HashMap sleeping = new HashMap(); + private final HashMap awake = new HashMap(); + private final PriorityQueue upcomingTicks = new PriorityQueue(); + private long currentTick = 0; + + public TickManagerCache(final IGrid g) { + this.myGrid = g; + } + + public long getCurrentTick() { + return this.currentTick; + } + + public long getAvgNanoTime(final IGridNode node) { + TickTracker tt = this.awake.get(node); + + if (tt == null) { + tt = this.sleeping.get(node); + } + + if (tt == null) { + return -1; + } + + return tt.getAvgNanos(); + } + + @Override + public void onUpdateTick() { + TickTracker tt = null; + try { + this.currentTick++; + while (!this.upcomingTicks.isEmpty()) { + tt = this.upcomingTicks.peek(); + final int diff = (int) (this.currentTick - tt.getLastTick()); + if (diff >= tt.getCurrentRate()) { + // remove tt.. + this.upcomingTicks.poll(); + long tickStartTime = 0; + if (AEConfig.instance.debugLogTiming) tickStartTime = System.nanoTime(); + final TickRateModulation mod = tt.getGridTickable().tickingRequest(tt.getNode(), diff); + if (AEConfig.instance.debugLogTiming) { + DimensionalCoord c = tt.getNode().getGridBlock().getLocation(); + AELog.debug( + "Timing: machine tick at (%d %d %d) took %d ns, new state is %s", + c.x, c.y, c.z, System.nanoTime() - tickStartTime, mod.toString()); + } + switch (mod) { + case FASTER: + tt.setRate(tt.getCurrentRate() - 2); + break; + case IDLE: + tt.setRate(tt.getRequest().maxTickRate); + break; + case SAME: + break; + case SLEEP: + this.sleepDevice(tt.getNode()); + break; + case SLOWER: + tt.setRate(tt.getCurrentRate() + 1); + break; + case URGENT: + tt.setRate(0); + break; + default: + break; + } + + if (this.awake.containsKey(tt.getNode())) { + this.addToQueue(tt); + } + } else { + return; // done! + } + } + } catch (final Throwable t) { + final CrashReport crashreport = CrashReport.makeCrashReport(t, "Ticking GridNode"); + final CrashReportCategory crashreportcategory = + crashreport.makeCategory(tt.getGridTickable().getClass().getSimpleName() + " being ticked."); + tt.addEntityCrashInfo(crashreportcategory); + throw new ReportedException(crashreport); + } + } + + private void addToQueue(final TickTracker tt) { + tt.setLastTick(this.currentTick); + this.upcomingTicks.add(tt); + } + + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof IGridTickable) { + this.alertable.remove(gridNode); + this.sleeping.remove(gridNode); + this.awake.remove(gridNode); + } + } + + @Override + public void addNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof IGridTickable) { + final TickingRequest tr = ((IGridTickable) machine).getTickingRequest(gridNode); + if (tr != null) { + final TickTracker tt = new TickTracker(tr, gridNode, (IGridTickable) machine, this.currentTick, this); + + if (tr.canBeAlerted) { + this.alertable.put(gridNode, tt); + } + + if (tr.isSleeping) { + this.sleeping.put(gridNode, tt); + } else { + this.awake.put(gridNode, tt); + this.addToQueue(tt); + } + } + } + } + + @Override + public void onSplit(final IGridStorage storageB) {} + + @Override + public void onJoin(final IGridStorage storageB) {} + + @Override + public void populateGridStorage(final IGridStorage storage) {} + + @Override + public boolean alertDevice(final IGridNode node) { + final TickTracker tt = this.alertable.get(node); + if (tt == null) { + return false; + } + // throw new RuntimeException( + // "Invalid alerted device, this node is not marked as alertable, or part of this grid." ); + + // set to awake, this is for sanity. + this.sleeping.remove(node); + this.awake.put(node, tt); + + // configure sort. + tt.setLastTick(tt.getLastTick() - tt.getRequest().maxTickRate); + tt.setCurrentRate(tt.getRequest().minTickRate); + + // prevent dupes and tick build up. + this.upcomingTicks.remove(tt); + this.upcomingTicks.add(tt); + + return true; + } + + @Override + public boolean sleepDevice(final IGridNode node) { + if (this.awake.containsKey(node)) { + final TickTracker gt = this.awake.get(node); + this.awake.remove(node); + this.sleeping.put(node, gt); + + return true; + } + + return false; + } + + @Override + public boolean wakeDevice(final IGridNode node) { + if (this.sleeping.containsKey(node)) { + final TickTracker gt = this.sleeping.get(node); + this.sleeping.remove(node); + this.awake.put(node, gt); + this.addToQueue(gt); + + return true; + } + + return false; + } } diff --git a/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java b/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java index 759a9408034..d80d1b74621 100644 --- a/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java +++ b/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java @@ -18,27 +18,21 @@ package appeng.me.cache.helpers; - import appeng.api.networking.IGridConnection; +public class ConnectionWrapper { -public class ConnectionWrapper -{ - - private IGridConnection connection; + private IGridConnection connection; - public ConnectionWrapper( final IGridConnection gc ) - { - this.setConnection( gc ); - } + public ConnectionWrapper(final IGridConnection gc) { + this.setConnection(gc); + } - public IGridConnection getConnection() - { - return this.connection; - } + public IGridConnection getConnection() { + return this.connection; + } - public void setConnection( final IGridConnection connection ) - { - this.connection = connection; - } -} \ No newline at end of file + public void setConnection(final IGridConnection connection) { + this.connection = connection; + } +} diff --git a/src/main/java/appeng/me/cache/helpers/Connections.java b/src/main/java/appeng/me/cache/helpers/Connections.java index dabd4c5d616..89ac1179633 100644 --- a/src/main/java/appeng/me/cache/helpers/Connections.java +++ b/src/main/java/appeng/me/cache/helpers/Connections.java @@ -18,70 +18,57 @@ package appeng.me.cache.helpers; - import appeng.api.networking.IGridNode; import appeng.parts.p2p.PartP2PTunnelME; import appeng.util.IWorldCallable; -import net.minecraft.world.World; - import java.util.HashMap; +import net.minecraft.world.World; +public class Connections implements IWorldCallable { -public class Connections implements IWorldCallable -{ - - private final HashMap connections = new HashMap(); - private final PartP2PTunnelME me; - private boolean create = false; - private boolean destroy = false; + private final HashMap connections = new HashMap(); + private final PartP2PTunnelME me; + private boolean create = false; + private boolean destroy = false; - public Connections( final PartP2PTunnelME o ) - { - this.me = o; - } + public Connections(final PartP2PTunnelME o) { + this.me = o; + } - @Override - public Void call( final World world ) throws Exception - { - this.me.updateConnections( this ); + @Override + public Void call(final World world) throws Exception { + this.me.updateConnections(this); - return null; - } + return null; + } - public void markDestroy() - { - this.setCreate( false ); - this.setDestroy( true ); - } + public void markDestroy() { + this.setCreate(false); + this.setDestroy(true); + } - public void markCreate() - { - this.setCreate( true ); - this.setDestroy( false ); - } + public void markCreate() { + this.setCreate(true); + this.setDestroy(false); + } - public HashMap getConnections() - { - return this.connections; - } + public HashMap getConnections() { + return this.connections; + } - public boolean isCreate() - { - return this.create; - } + public boolean isCreate() { + return this.create; + } - private void setCreate( final boolean create ) - { - this.create = create; - } + private void setCreate(final boolean create) { + this.create = create; + } - public boolean isDestroy() - { - return this.destroy; - } + public boolean isDestroy() { + return this.destroy; + } - private void setDestroy( final boolean destroy ) - { - this.destroy = destroy; - } + private void setDestroy(final boolean destroy) { + this.destroy = destroy; + } } diff --git a/src/main/java/appeng/me/cache/helpers/TickTracker.java b/src/main/java/appeng/me/cache/helpers/TickTracker.java index 2f254a1f988..dfb0466dbed 100644 --- a/src/main/java/appeng/me/cache/helpers/TickTracker.java +++ b/src/main/java/appeng/me/cache/helpers/TickTracker.java @@ -18,123 +18,110 @@ package appeng.me.cache.helpers; - import appeng.api.networking.IGridNode; import appeng.api.networking.ticking.IGridTickable; import appeng.api.networking.ticking.TickingRequest; import appeng.api.util.DimensionalCoord; import appeng.me.cache.TickManagerCache; import appeng.parts.AEBasePart; -import net.minecraft.crash.CrashReportCategory; - import javax.annotation.Nonnull; +import net.minecraft.crash.CrashReportCategory; - -public class TickTracker implements Comparable -{ - - private final TickingRequest request; - private final IGridTickable gt; - private final IGridNode node; - private final TickManagerCache host; - - private final long LastFiveTicksTime = 0; - - private long lastTick; - private int currentRate; - - public TickTracker( final TickingRequest req, final IGridNode node, final IGridTickable gt, final long currentTick, final TickManagerCache tickManagerCache ) - { - this.request = req; - this.gt = gt; - this.node = node; - this.setCurrentRate( ( req.minTickRate + req.maxTickRate ) / 2 ); - this.setLastTick( currentTick ); - this.host = tickManagerCache; - } - - public long getAvgNanos() - { - return ( this.LastFiveTicksTime / 5 ); - } - - public void setRate( final int rate ) - { - this.setCurrentRate( rate ); - - if( this.getCurrentRate() < this.getRequest().minTickRate ) - { - this.setCurrentRate( this.getRequest().minTickRate ); - } - - if( this.getCurrentRate() > this.getRequest().maxTickRate ) - { - this.setCurrentRate( this.getRequest().maxTickRate ); - } - } - - @Override - public int compareTo( @Nonnull final TickTracker t ) - { - final int nextTick = (int) ( ( this.getLastTick() - this.host.getCurrentTick() ) + this.getCurrentRate() ); - final int ts_nextTick = (int) ( ( t.getLastTick() - this.host.getCurrentTick() ) + t.getCurrentRate() ); - return nextTick - ts_nextTick; - } - - public void addEntityCrashInfo( final CrashReportCategory crashreportcategory ) - { - if( this.getGridTickable() instanceof AEBasePart ) - { - final AEBasePart part = (AEBasePart) this.getGridTickable(); - part.addEntityCrashInfo( crashreportcategory ); - } - - crashreportcategory.addCrashSection( "CurrentTickRate", this.getCurrentRate() ); - crashreportcategory.addCrashSection( "MinTickRate", this.getRequest().minTickRate ); - crashreportcategory.addCrashSection( "MaxTickRate", this.getRequest().maxTickRate ); - crashreportcategory.addCrashSection( "MachineType", this.getGridTickable().getClass().getName() ); - crashreportcategory.addCrashSection( "GridBlockType", this.getNode().getGridBlock().getClass().getName() ); - crashreportcategory.addCrashSection( "ConnectedSides", this.getNode().getConnectedSides() ); - - final DimensionalCoord dc = this.getNode().getGridBlock().getLocation(); - if( dc != null ) - { - crashreportcategory.addCrashSection( "Location", dc ); - } - } - - public int getCurrentRate() - { - return this.currentRate; - } - - public void setCurrentRate( final int currentRate ) - { - this.currentRate = currentRate; - } - - public long getLastTick() - { - return this.lastTick; - } - - public void setLastTick( final long lastTick ) - { - this.lastTick = lastTick; - } - - public IGridNode getNode() - { - return this.node; - } - - public IGridTickable getGridTickable() - { - return this.gt; - } - - public TickingRequest getRequest() - { - return this.request; - } +public class TickTracker implements Comparable { + + private final TickingRequest request; + private final IGridTickable gt; + private final IGridNode node; + private final TickManagerCache host; + + private final long LastFiveTicksTime = 0; + + private long lastTick; + private int currentRate; + + public TickTracker( + final TickingRequest req, + final IGridNode node, + final IGridTickable gt, + final long currentTick, + final TickManagerCache tickManagerCache) { + this.request = req; + this.gt = gt; + this.node = node; + this.setCurrentRate((req.minTickRate + req.maxTickRate) / 2); + this.setLastTick(currentTick); + this.host = tickManagerCache; + } + + public long getAvgNanos() { + return (this.LastFiveTicksTime / 5); + } + + public void setRate(final int rate) { + this.setCurrentRate(rate); + + if (this.getCurrentRate() < this.getRequest().minTickRate) { + this.setCurrentRate(this.getRequest().minTickRate); + } + + if (this.getCurrentRate() > this.getRequest().maxTickRate) { + this.setCurrentRate(this.getRequest().maxTickRate); + } + } + + @Override + public int compareTo(@Nonnull final TickTracker t) { + final int nextTick = (int) ((this.getLastTick() - this.host.getCurrentTick()) + this.getCurrentRate()); + final int ts_nextTick = (int) ((t.getLastTick() - this.host.getCurrentTick()) + t.getCurrentRate()); + return nextTick - ts_nextTick; + } + + public void addEntityCrashInfo(final CrashReportCategory crashreportcategory) { + if (this.getGridTickable() instanceof AEBasePart) { + final AEBasePart part = (AEBasePart) this.getGridTickable(); + part.addEntityCrashInfo(crashreportcategory); + } + + crashreportcategory.addCrashSection("CurrentTickRate", this.getCurrentRate()); + crashreportcategory.addCrashSection("MinTickRate", this.getRequest().minTickRate); + crashreportcategory.addCrashSection("MaxTickRate", this.getRequest().maxTickRate); + crashreportcategory.addCrashSection( + "MachineType", this.getGridTickable().getClass().getName()); + crashreportcategory.addCrashSection( + "GridBlockType", this.getNode().getGridBlock().getClass().getName()); + crashreportcategory.addCrashSection("ConnectedSides", this.getNode().getConnectedSides()); + + final DimensionalCoord dc = this.getNode().getGridBlock().getLocation(); + if (dc != null) { + crashreportcategory.addCrashSection("Location", dc); + } + } + + public int getCurrentRate() { + return this.currentRate; + } + + public void setCurrentRate(final int currentRate) { + this.currentRate = currentRate; + } + + public long getLastTick() { + return this.lastTick; + } + + public void setLastTick(final long lastTick) { + this.lastTick = lastTick; + } + + public IGridNode getNode() { + return this.node; + } + + public IGridTickable getGridTickable() { + return this.gt; + } + + public TickingRequest getRequest() { + return this.request; + } } diff --git a/src/main/java/appeng/me/cache/helpers/TunnelCollection.java b/src/main/java/appeng/me/cache/helpers/TunnelCollection.java index 45f16f90fb1..f8b3bc2da45 100644 --- a/src/main/java/appeng/me/cache/helpers/TunnelCollection.java +++ b/src/main/java/appeng/me/cache/helpers/TunnelCollection.java @@ -18,53 +18,42 @@ package appeng.me.cache.helpers; - import appeng.parts.p2p.PartP2PTunnel; import appeng.util.iterators.NullIterator; - import java.util.Collection; import java.util.Iterator; +public class TunnelCollection implements Iterable { -public class TunnelCollection implements Iterable -{ - - private final Class clz; - private Collection tunnelSources; + private final Class clz; + private Collection tunnelSources; - public TunnelCollection( final Collection src, final Class c ) - { - this.tunnelSources = src; - this.clz = c; - } + public TunnelCollection(final Collection src, final Class c) { + this.tunnelSources = src; + this.clz = c; + } - public void setSource( final Collection c ) - { - this.tunnelSources = c; - } + public void setSource(final Collection c) { + this.tunnelSources = c; + } - public boolean isEmpty() - { - return !this.iterator().hasNext(); - } + public boolean isEmpty() { + return !this.iterator().hasNext(); + } - @Override - public Iterator iterator() - { - if( this.tunnelSources == null ) - { - return new NullIterator(); - } - return new TunnelIterator( this.tunnelSources, this.clz ); - } + @Override + public Iterator iterator() { + if (this.tunnelSources == null) { + return new NullIterator(); + } + return new TunnelIterator(this.tunnelSources, this.clz); + } - public boolean matches( final Class c ) - { - return this.clz == c; - } + public boolean matches(final Class c) { + return this.clz == c; + } - public Class getClz() - { - return this.clz; - } + public Class getClz() { + return this.clz; + } } diff --git a/src/main/java/appeng/me/cache/helpers/TunnelConnection.java b/src/main/java/appeng/me/cache/helpers/TunnelConnection.java index b4abb1b3461..66b191e0468 100644 --- a/src/main/java/appeng/me/cache/helpers/TunnelConnection.java +++ b/src/main/java/appeng/me/cache/helpers/TunnelConnection.java @@ -18,30 +18,24 @@ package appeng.me.cache.helpers; - import appeng.api.networking.IGridConnection; import appeng.parts.p2p.PartP2PTunnelME; +public class TunnelConnection { -public class TunnelConnection -{ - - private final PartP2PTunnelME tunnel; - private final IGridConnection c; + private final PartP2PTunnelME tunnel; + private final IGridConnection c; - public TunnelConnection( final PartP2PTunnelME t, final IGridConnection con ) - { - this.tunnel = t; - this.c = con; - } + public TunnelConnection(final PartP2PTunnelME t, final IGridConnection con) { + this.tunnel = t; + this.c = con; + } - public IGridConnection getConnection() - { - return this.c; - } + public IGridConnection getConnection() { + return this.c; + } - public PartP2PTunnelME getTunnel() - { - return this.tunnel; - } -} \ No newline at end of file + public PartP2PTunnelME getTunnel() { + return this.tunnel; + } +} diff --git a/src/main/java/appeng/me/cache/helpers/TunnelIterator.java b/src/main/java/appeng/me/cache/helpers/TunnelIterator.java index 7e9a5f55e61..bffa50dc3c0 100644 --- a/src/main/java/appeng/me/cache/helpers/TunnelIterator.java +++ b/src/main/java/appeng/me/cache/helpers/TunnelIterator.java @@ -18,57 +18,46 @@ package appeng.me.cache.helpers; - import appeng.parts.p2p.PartP2PTunnel; - import java.util.Collection; import java.util.Iterator; - -public class TunnelIterator implements Iterator -{ - - private final Iterator wrapped; - private final Class targetType; - private T Next; - - public TunnelIterator( final Collection tunnelSources, final Class clz ) - { - this.wrapped = tunnelSources.iterator(); - this.targetType = clz; - this.findNext(); - } - - private void findNext() - { - while( this.Next == null && this.wrapped.hasNext() ) - { - this.Next = this.wrapped.next(); - if( !this.targetType.isInstance( this.Next ) ) - { - this.Next = null; - } - } - } - - @Override - public boolean hasNext() - { - this.findNext(); - return this.Next != null; - } - - @Override - public T next() - { - final T tmp = this.Next; - this.Next = null; - return tmp; - } - - @Override - public void remove() - { - // no. - } +public class TunnelIterator implements Iterator { + + private final Iterator wrapped; + private final Class targetType; + private T Next; + + public TunnelIterator(final Collection tunnelSources, final Class clz) { + this.wrapped = tunnelSources.iterator(); + this.targetType = clz; + this.findNext(); + } + + private void findNext() { + while (this.Next == null && this.wrapped.hasNext()) { + this.Next = this.wrapped.next(); + if (!this.targetType.isInstance(this.Next)) { + this.Next = null; + } + } + } + + @Override + public boolean hasNext() { + this.findNext(); + return this.Next != null; + } + + @Override + public T next() { + final T tmp = this.Next; + this.Next = null; + return tmp; + } + + @Override + public void remove() { + // no. + } } diff --git a/src/main/java/appeng/me/cluster/IAECluster.java b/src/main/java/appeng/me/cluster/IAECluster.java index caff5a0b317..81775078326 100644 --- a/src/main/java/appeng/me/cluster/IAECluster.java +++ b/src/main/java/appeng/me/cluster/IAECluster.java @@ -18,18 +18,14 @@ package appeng.me.cluster; - import appeng.api.networking.IGridHost; - import java.util.Iterator; +public interface IAECluster { -public interface IAECluster -{ - - void updateStatus( boolean updateGrid ); + void updateStatus(boolean updateGrid); - void destroy(); + void destroy(); - Iterator getTiles(); + Iterator getTiles(); } diff --git a/src/main/java/appeng/me/cluster/IAEMultiBlock.java b/src/main/java/appeng/me/cluster/IAEMultiBlock.java index 8dc36f998a2..a7889885574 100644 --- a/src/main/java/appeng/me/cluster/IAEMultiBlock.java +++ b/src/main/java/appeng/me/cluster/IAEMultiBlock.java @@ -18,13 +18,11 @@ package appeng.me.cluster; +public interface IAEMultiBlock { -public interface IAEMultiBlock -{ + void disconnect(boolean b); - void disconnect( boolean b ); + IAECluster getCluster(); - IAECluster getCluster(); - - boolean isValid(); + boolean isValid(); } diff --git a/src/main/java/appeng/me/cluster/MBCalculator.java b/src/main/java/appeng/me/cluster/MBCalculator.java index 939273f5ba7..b5fa4fbdf32 100644 --- a/src/main/java/appeng/me/cluster/MBCalculator.java +++ b/src/main/java/appeng/me/cluster/MBCalculator.java @@ -18,7 +18,6 @@ package appeng.me.cluster; - import appeng.api.util.WorldCoord; import appeng.core.AELog; import appeng.util.Platform; @@ -26,210 +25,178 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; - -public abstract class MBCalculator -{ - - private final IAEMultiBlock target; - - public MBCalculator( final IAEMultiBlock t ) - { - this.target = t; - } - - public void calculateMultiblock( final World world, final WorldCoord loc ) - { - if( Platform.isClient() ) - { - return; - } - - try - { - final WorldCoord min = loc.copy(); - final WorldCoord max = loc.copy(); - - // find size of MB structure... - while( this.isValidTileAt( world, min.x - 1, min.y, min.z ) ) - { - min.x--; - } - while( this.isValidTileAt( world, min.x, min.y - 1, min.z ) ) - { - min.y--; - } - while( this.isValidTileAt( world, min.x, min.y, min.z - 1 ) ) - { - min.z--; - } - while( this.isValidTileAt( world, max.x + 1, max.y, max.z ) ) - { - max.x++; - } - while( this.isValidTileAt( world, max.x, max.y + 1, max.z ) ) - { - max.y++; - } - while( this.isValidTileAt( world, max.x, max.y, max.z + 1 ) ) - { - max.z++; - } - - if( this.checkMultiblockScale( min, max ) ) - { - if( this.verifyUnownedRegion( world, min, max ) ) - { - IAECluster c = this.createCluster( world, min, max ); - - try - { - if( !this.verifyInternalStructure( world, min, max ) ) - { - this.disconnect(); - return; - } - } - catch( final Exception err ) - { - this.disconnect(); - return; - } - - boolean updateGrid = false; - final IAECluster cluster = this.target.getCluster(); - if( cluster == null ) - { - this.updateTiles( c, world, min, max ); - - updateGrid = true; - } - else - { - c = cluster; - } - - c.updateStatus( updateGrid ); - return; - } - } - } - catch( final Throwable err ) - { - AELog.debug( err ); - } - - this.disconnect(); - } - - private boolean isValidTileAt( final World w, final int x, final int y, final int z ) - { - return this.isValidTile( w.getTileEntity( x, y, z ) ); - } - - /** - * verify if the structure is the correct dimensions, or size - * - * @param min min world coord - * @param max max world coord - * @return true if structure has correct dimensions or size - */ - public abstract boolean checkMultiblockScale( WorldCoord min, WorldCoord max ); - - private boolean verifyUnownedRegion( final World w, final WorldCoord min, final WorldCoord max ) - { - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.verifyUnownedRegionInner( w, min.x, min.y, min.z, max.x, max.y, max.z, side ) ) - { - return false; - } - } - - return true; - } - - /** - * construct the correct cluster, usually very simple. - * - * @param w world - * @param min min world coord - * @param max max world coord - * @return created cluster - */ - public abstract IAECluster createCluster( World w, WorldCoord min, WorldCoord max ); - - public abstract boolean verifyInternalStructure( World worldObj, WorldCoord min, WorldCoord max ); - - /** - * disassembles the multi-block. - */ - public abstract void disconnect(); - - /** - * configure the multi-block tiles, most of the important stuff is in here. - * - * @param c updated cluster - * @param w in world - * @param min min world coord - * @param max max world coord - */ - public abstract void updateTiles( IAECluster c, World w, WorldCoord min, WorldCoord max ); - - /** - * check if the tile entities are correct for the structure. - * - * @param te to be checked tile entity - * @return true if tile entity is valid for structure - */ - public abstract boolean isValidTile( TileEntity te ); - - private boolean verifyUnownedRegionInner( final World w, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, final ForgeDirection side ) - { - switch( side ) - { - case WEST: - minX -= 1; - maxX = minX; - break; - case EAST: - maxX += 1; - minX = maxX; - break; - case DOWN: - minY -= 1; - maxY = minY; - break; - case NORTH: - maxZ += 1; - minZ = maxZ; - break; - case SOUTH: - minZ -= 1; - maxZ = minZ; - break; - case UP: - maxY += 1; - minY = maxY; - break; - case UNKNOWN: - return false; - } - - for( int x = minX; x <= maxX; x++ ) - { - for( int y = minY; y <= maxY; y++ ) - { - for( int z = minZ; z <= maxZ; z++ ) - { - final TileEntity te = w.getTileEntity( x, y, z ); - if( this.isValidTile( te ) ) - { - return true; - } - } - } - } - - return false; - } +public abstract class MBCalculator { + + private final IAEMultiBlock target; + + public MBCalculator(final IAEMultiBlock t) { + this.target = t; + } + + public void calculateMultiblock(final World world, final WorldCoord loc) { + if (Platform.isClient()) { + return; + } + + try { + final WorldCoord min = loc.copy(); + final WorldCoord max = loc.copy(); + + // find size of MB structure... + while (this.isValidTileAt(world, min.x - 1, min.y, min.z)) { + min.x--; + } + while (this.isValidTileAt(world, min.x, min.y - 1, min.z)) { + min.y--; + } + while (this.isValidTileAt(world, min.x, min.y, min.z - 1)) { + min.z--; + } + while (this.isValidTileAt(world, max.x + 1, max.y, max.z)) { + max.x++; + } + while (this.isValidTileAt(world, max.x, max.y + 1, max.z)) { + max.y++; + } + while (this.isValidTileAt(world, max.x, max.y, max.z + 1)) { + max.z++; + } + + if (this.checkMultiblockScale(min, max)) { + if (this.verifyUnownedRegion(world, min, max)) { + IAECluster c = this.createCluster(world, min, max); + + try { + if (!this.verifyInternalStructure(world, min, max)) { + this.disconnect(); + return; + } + } catch (final Exception err) { + this.disconnect(); + return; + } + + boolean updateGrid = false; + final IAECluster cluster = this.target.getCluster(); + if (cluster == null) { + this.updateTiles(c, world, min, max); + + updateGrid = true; + } else { + c = cluster; + } + + c.updateStatus(updateGrid); + return; + } + } + } catch (final Throwable err) { + AELog.debug(err); + } + + this.disconnect(); + } + + private boolean isValidTileAt(final World w, final int x, final int y, final int z) { + return this.isValidTile(w.getTileEntity(x, y, z)); + } + + /** + * verify if the structure is the correct dimensions, or size + * + * @param min min world coord + * @param max max world coord + * @return true if structure has correct dimensions or size + */ + public abstract boolean checkMultiblockScale(WorldCoord min, WorldCoord max); + + private boolean verifyUnownedRegion(final World w, final WorldCoord min, final WorldCoord max) { + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + if (this.verifyUnownedRegionInner(w, min.x, min.y, min.z, max.x, max.y, max.z, side)) { + return false; + } + } + + return true; + } + + /** + * construct the correct cluster, usually very simple. + * + * @param w world + * @param min min world coord + * @param max max world coord + * @return created cluster + */ + public abstract IAECluster createCluster(World w, WorldCoord min, WorldCoord max); + + public abstract boolean verifyInternalStructure(World worldObj, WorldCoord min, WorldCoord max); + + /** + * disassembles the multi-block. + */ + public abstract void disconnect(); + + /** + * configure the multi-block tiles, most of the important stuff is in here. + * + * @param c updated cluster + * @param w in world + * @param min min world coord + * @param max max world coord + */ + public abstract void updateTiles(IAECluster c, World w, WorldCoord min, WorldCoord max); + + /** + * check if the tile entities are correct for the structure. + * + * @param te to be checked tile entity + * @return true if tile entity is valid for structure + */ + public abstract boolean isValidTile(TileEntity te); + + private boolean verifyUnownedRegionInner( + final World w, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, final ForgeDirection side) { + switch (side) { + case WEST: + minX -= 1; + maxX = minX; + break; + case EAST: + maxX += 1; + minX = maxX; + break; + case DOWN: + minY -= 1; + maxY = minY; + break; + case NORTH: + maxZ += 1; + minZ = maxZ; + break; + case SOUTH: + minZ -= 1; + maxZ = minZ; + break; + case UP: + maxY += 1; + minY = maxY; + break; + case UNKNOWN: + return false; + } + + for (int x = minX; x <= maxX; x++) { + for (int y = minY; y <= maxY; y++) { + for (int z = minZ; z <= maxZ; z++) { + final TileEntity te = w.getTileEntity(x, y, z); + if (this.isValidTile(te)) { + return true; + } + } + } + } + + return false; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/CraftingCPUCalculator.java b/src/main/java/appeng/me/cluster/implementations/CraftingCPUCalculator.java index eb985a45e9d..6a8d9d78fd3 100644 --- a/src/main/java/appeng/me/cluster/implementations/CraftingCPUCalculator.java +++ b/src/main/java/appeng/me/cluster/implementations/CraftingCPUCalculator.java @@ -18,7 +18,6 @@ package appeng.me.cluster.implementations; - import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; @@ -28,121 +27,98 @@ import appeng.me.cluster.IAEMultiBlock; import appeng.me.cluster.MBCalculator; import appeng.tile.crafting.TileCraftingTile; +import java.util.Iterator; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Iterator; - - -public class CraftingCPUCalculator extends MBCalculator -{ - - private final TileCraftingTile tqb; - - public CraftingCPUCalculator( final IAEMultiBlock t ) - { - super( t ); - this.tqb = (TileCraftingTile) t; - } - - @Override - public boolean checkMultiblockScale( final WorldCoord min, final WorldCoord max ) - { - if( max.x - min.x > 16 ) - { - return false; - } - - if( max.y - min.y > 16 ) - { - return false; - } - - return max.z - min.z <= 16; - } - - @Override - public IAECluster createCluster( final World w, final WorldCoord min, final WorldCoord max ) - { - return new CraftingCPUCluster( min, max ); - } - - @Override - public boolean verifyInternalStructure( final World w, final WorldCoord min, final WorldCoord max ) - { - boolean storage = false; - - for( int x = min.x; x <= max.x; x++ ) - { - for( int y = min.y; y <= max.y; y++ ) - { - for( int z = min.z; z <= max.z; z++ ) - { - final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity( x, y, z ); - - if( !te.isValid() ) - { - return false; - } - - if( !storage && te instanceof TileCraftingTile ) - { - storage = ( (TileCraftingTile) te ).getStorageBytes() > 0; - } - } - } - } - - return storage; - } - - @Override - public void disconnect() - { - this.tqb.disconnect( true ); - } - - @Override - public void updateTiles( final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max ) - { - final CraftingCPUCluster c = (CraftingCPUCluster) cl; - - for( int x = min.x; x <= max.x; x++ ) - { - for( int y = min.y; y <= max.y; y++ ) - { - for( int z = min.z; z <= max.z; z++ ) - { - final TileCraftingTile te = (TileCraftingTile) w.getTileEntity( x, y, z ); - te.updateStatus( c ); - c.addTile( te ); - } - } - } - - c.done(); - - final Iterator i = c.getTiles(); - while( i.hasNext() ) - { - final IGridHost gh = i.next(); - final IGridNode n = gh.getGridNode( ForgeDirection.UNKNOWN ); - if( n != null ) - { - final IGrid g = n.getGrid(); - if( g != null ) - { - g.postEvent( new MENetworkCraftingCpuChange( n ) ); - return; - } - } - } - } - - @Override - public boolean isValidTile( final TileEntity te ) - { - return te instanceof TileCraftingTile; - } +public class CraftingCPUCalculator extends MBCalculator { + + private final TileCraftingTile tqb; + + public CraftingCPUCalculator(final IAEMultiBlock t) { + super(t); + this.tqb = (TileCraftingTile) t; + } + + @Override + public boolean checkMultiblockScale(final WorldCoord min, final WorldCoord max) { + if (max.x - min.x > 16) { + return false; + } + + if (max.y - min.y > 16) { + return false; + } + + return max.z - min.z <= 16; + } + + @Override + public IAECluster createCluster(final World w, final WorldCoord min, final WorldCoord max) { + return new CraftingCPUCluster(min, max); + } + + @Override + public boolean verifyInternalStructure(final World w, final WorldCoord min, final WorldCoord max) { + boolean storage = false; + + for (int x = min.x; x <= max.x; x++) { + for (int y = min.y; y <= max.y; y++) { + for (int z = min.z; z <= max.z; z++) { + final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity(x, y, z); + + if (!te.isValid()) { + return false; + } + + if (!storage && te instanceof TileCraftingTile) { + storage = ((TileCraftingTile) te).getStorageBytes() > 0; + } + } + } + } + + return storage; + } + + @Override + public void disconnect() { + this.tqb.disconnect(true); + } + + @Override + public void updateTiles(final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max) { + final CraftingCPUCluster c = (CraftingCPUCluster) cl; + + for (int x = min.x; x <= max.x; x++) { + for (int y = min.y; y <= max.y; y++) { + for (int z = min.z; z <= max.z; z++) { + final TileCraftingTile te = (TileCraftingTile) w.getTileEntity(x, y, z); + te.updateStatus(c); + c.addTile(te); + } + } + } + + c.done(); + + final Iterator i = c.getTiles(); + while (i.hasNext()) { + final IGridHost gh = i.next(); + final IGridNode n = gh.getGridNode(ForgeDirection.UNKNOWN); + if (n != null) { + final IGrid g = n.getGrid(); + if (g != null) { + g.postEvent(new MENetworkCraftingCpuChange(n)); + return; + } + } + } + } + + @Override + public boolean isValidTile(final TileEntity te) { + return te instanceof TileCraftingTile; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java b/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java index e529b451735..2a3f1e0d001 100644 --- a/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java +++ b/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java @@ -18,7 +18,6 @@ package appeng.me.cluster.implementations; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.FuzzyMode; @@ -53,6 +52,8 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import cpw.mods.fml.common.FMLCommonHandler; +import java.util.*; +import java.util.Map.Entry; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -60,1282 +61,1088 @@ import net.minecraft.world.World; import net.minecraft.world.WorldServer; -import java.util.*; -import java.util.Map.Entry; +public final class CraftingCPUCluster implements IAECluster, ICraftingCPU { + + private static final String LOG_MARK_AS_COMPLETE = "Completed job for %s."; + + private final WorldCoord min; + private final WorldCoord max; + private final int[] usedOps = new int[3]; + private final Map tasks = + new HashMap(); + // INSTANCE sate + private final LinkedList tiles = new LinkedList(); + private final LinkedList storage = new LinkedList(); + private final LinkedList status = new LinkedList(); + private final HashMap, Object> listeners = + new HashMap, Object>(); + private ICraftingLink myLastLink; + private String myName = ""; + private boolean isDestroyed = false; + /** + * crafting job info + */ + private MECraftingInventory inventory = new MECraftingInventory(); + + private IAEItemStack finalOutput; + private boolean waiting = false; + private IItemList waitingFor = AEApi.instance().storage().createItemList(); + private long availableStorage = 0; + private MachineSource machineSrc = null; + private int accelerator = 0; + private boolean isComplete = true; + private int remainingOperations; + private boolean somethingChanged; + + private long lastTime; + private long elapsedTime; + private long startItemCount; + private long remainingItemCount; + + public CraftingCPUCluster(final WorldCoord min, final WorldCoord max) { + this.min = min; + this.max = max; + } + @Override + public IAEItemStack getFinalOutput() { + return finalOutput; + } + + public boolean isDestroyed() { + return this.isDestroyed; + } -public final class CraftingCPUCluster implements IAECluster, ICraftingCPU -{ - - private static final String LOG_MARK_AS_COMPLETE = "Completed job for %s."; - - private final WorldCoord min; - private final WorldCoord max; - private final int[] usedOps = new int[3]; - private final Map tasks = new HashMap(); - // INSTANCE sate - private final LinkedList tiles = new LinkedList(); - private final LinkedList storage = new LinkedList(); - private final LinkedList status = new LinkedList(); - private final HashMap, Object> listeners = new HashMap, Object>(); - private ICraftingLink myLastLink; - private String myName = ""; - private boolean isDestroyed = false; - /** - * crafting job info - */ - private MECraftingInventory inventory = new MECraftingInventory(); - private IAEItemStack finalOutput; - private boolean waiting = false; - private IItemList waitingFor = AEApi.instance().storage().createItemList(); - private long availableStorage = 0; - private MachineSource machineSrc = null; - private int accelerator = 0; - private boolean isComplete = true; - private int remainingOperations; - private boolean somethingChanged; - - private long lastTime; - private long elapsedTime; - private long startItemCount; - private long remainingItemCount; - - public CraftingCPUCluster( final WorldCoord min, final WorldCoord max ) - { - this.min = min; - this.max = max; - } + public ICraftingLink getLastCraftingLink() { + return this.myLastLink; + } + /** + * add a new Listener to the monitor, be sure to properly remove yourself when your done. + */ @Override - public IAEItemStack getFinalOutput() - { - return finalOutput; + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + this.listeners.put(l, verificationToken); } - public boolean isDestroyed() - { - return this.isDestroyed; - } - - public ICraftingLink getLastCraftingLink() - { - return this.myLastLink; - } - - /** - * add a new Listener to the monitor, be sure to properly remove yourself when your done. - */ - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } - - /** - * remove a Listener to the monitor. - */ - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } - - public IMEInventory getInventory() - { - return this.inventory; - } - - @Override - public void updateStatus( final boolean updateGrid ) - { - for( final TileCraftingTile r : this.tiles ) - { - r.updateMeta( true ); - } - } - - @Override - public void destroy() - { - if( this.isDestroyed ) - { - return; - } - this.isDestroyed = true; - - boolean posted = false; - - for( final TileCraftingTile r : this.tiles ) - { - final IGridNode n = r.getActionableNode(); - if( n != null && !posted ) - { - final IGrid g = n.getGrid(); - if( g != null ) - { - g.postEvent( new MENetworkCraftingCpuChange( n ) ); - posted = true; - } - } - - r.updateStatus( null ); - } - } - - @Override - public Iterator getTiles() - { - return (Iterator) this.tiles.iterator(); - } - - void addTile( final TileCraftingTile te ) - { - if( this.machineSrc == null || te.isCoreBlock() ) - { - this.machineSrc = new MachineSource( te ); - } - - te.setCoreBlock( false ); - te.markDirty(); - this.tiles.push( te ); - - if( te.isStorage() ) - { - this.availableStorage += te.getStorageBytes(); - this.storage.add( te ); - } - else if( te.isStatus() ) - { - this.status.add( (TileCraftingMonitorTile) te ); - } - else if( te.isAccelerator() ) - { - this.accelerator += te.acceleratorValue(); - } - } - - public boolean canAccept( final IAEStack input ) - { - if( input instanceof IAEItemStack ) - { - final IAEItemStack is = this.waitingFor.findPrecise( (IAEItemStack) input ); - if( is != null && is.getStackSize() > 0 ) - { - return true; - } - } - return false; - } - - public IAEStack injectItems( final IAEStack input, final Actionable type, final BaseActionSource src ) - { - if( !( input instanceof IAEItemStack ) ) - { - return input; - } - - final IAEItemStack what = (IAEItemStack) input.copy(); - final IAEItemStack is = this.waitingFor.findPrecise( what ); - - if( type == Actionable.SIMULATE )// causes crafting to lock up? - { - if( is != null && is.getStackSize() > 0 ) - { - if( is.getStackSize() >= what.getStackSize() ) - { - if( this.finalOutput.equals( what ) ) - { - if( this.myLastLink != null ) - { - return ( (CraftingLink) this.myLastLink ).injectItems( what.copy(), type ); - } - - return what; // ignore it. - } - - return null; - } - - final IAEItemStack leftOver = what.copy(); - leftOver.decStackSize( is.getStackSize() ); - - final IAEItemStack used = what.copy(); - used.setStackSize( is.getStackSize() ); - - if( this.finalOutput.equals( what ) ) - { - if( this.myLastLink != null ) - { - leftOver.add( ( (CraftingLink) this.myLastLink ).injectItems( used.copy(), type ) ); - return leftOver; - } - - return what; // ignore it. - } - - return leftOver; - } - } - else if( type == Actionable.MODULATE ) - { - if( is != null && is.getStackSize() > 0 ) - { - this.waiting = false; - - this.postChange( what, src ); - - if( is.getStackSize() >= what.getStackSize() ) - { - is.decStackSize( what.getStackSize() ); - - this.updateElapsedTime( what ); - this.markDirty(); - this.postCraftingStatusChange( is ); - - if( this.finalOutput.equals( what ) ) - { - IAEStack leftover = what; - - this.finalOutput.decStackSize( what.getStackSize() ); - - if( this.myLastLink != null ) - { - leftover = ( (CraftingLink) this.myLastLink ).injectItems( what, type ); - } - - if( this.finalOutput.getStackSize() <= 0 ) - { - this.completeJob(); - } - - this.updateCPU(); - - return leftover; // ignore it. - } - - // 2000 - return this.inventory.injectItems( what, type, src ); - } - - final IAEItemStack insert = what.copy(); - insert.setStackSize( is.getStackSize() ); - what.decStackSize( is.getStackSize() ); - - is.setStackSize( 0 ); - - if( this.finalOutput.equals( insert ) ) - { - IAEStack leftover = input; - - this.finalOutput.decStackSize( insert.getStackSize() ); - - if( this.myLastLink != null ) - { - what.add( ( (CraftingLink) this.myLastLink ).injectItems( insert.copy(), type ) ); - leftover = what; - } - - if( this.finalOutput.getStackSize() <= 0 ) - { - this.completeJob(); - } - - this.updateCPU(); - this.markDirty(); - - return leftover; // ignore it. - } - - this.inventory.injectItems( insert, type, src ); - this.markDirty(); - - return what; - } - } - - return input; - } - - private void postChange( final IAEItemStack diff, final BaseActionSource src ) - { - final Iterator, Object>> i = this.getListeners(); - - // protect integrity - if( i.hasNext() ) - { - final ImmutableList single = ImmutableList.of( diff.copy() ); - - while( i.hasNext() ) - { - final Entry, Object> o = i.next(); - final IMEMonitorHandlerReceiver receiver = o.getKey(); - - if( receiver.isValid( o.getValue() ) ) - { - receiver.postChange( null, single, src ); - } - else - { - i.remove(); - } - } - } - - } - - private void markDirty() - { - this.getCore().markDirty(); - } - - private void postCraftingStatusChange( final IAEItemStack diff ) - { - if( this.getGrid() == null ) - { - return; - } - - final CraftingGridCache sg = this.getGrid().getCache( ICraftingGrid.class ); - - if( sg.getInterestManager().containsKey( diff ) ) - { - final Collection list = sg.getInterestManager().get( diff ); - - if( !list.isEmpty() ) - { - for( final CraftingWatcher iw : list ) - - { - iw.getHost().onRequestChange( sg, diff ); - } - } - } - } - - private void completeJob() - { - if( this.myLastLink != null ) - { - ( (CraftingLink) this.myLastLink ).markDone(); - } - - if( AELog.isCraftingLogEnabled() ) - { - final IAEItemStack logStack = this.finalOutput.copy(); - logStack.setStackSize( this.startItemCount ); - AELog.crafting( LOG_MARK_AS_COMPLETE, logStack ); - } - - this.remainingItemCount = 0; - this.startItemCount = 0; - this.lastTime = 0; - this.elapsedTime = 0; - this.isComplete = true; - - } - - private void updateCPU() - { - IAEItemStack send = this.finalOutput; - - if( this.finalOutput != null && this.finalOutput.getStackSize() <= 0 ) - { - send = null; - } - - for( final TileCraftingMonitorTile t : this.status ) - { - t.setJob( send ); - } - } - - private Iterator, Object>> getListeners() - { - return this.listeners.entrySet().iterator(); - } - - private TileCraftingTile getCore() - { - return (TileCraftingTile) this.machineSrc.via; - } - - private IGrid getGrid() - { - for( final TileCraftingTile r : this.tiles ) - { - final IGridNode gn = r.getActionableNode(); - if( gn != null ) - { - final IGrid g = gn.getGrid(); - if( g != null ) - { - return r.getActionableNode().getGrid(); - } - } - } - - return null; - } - - private boolean canCraft( final ICraftingPatternDetails details, final IAEItemStack[] condensedInputs ) - { - for( IAEItemStack g : condensedInputs ) - { - - if( details.isCraftable() ) - { - boolean found = false; - - for( IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( g, FuzzyMode.IGNORE_ALL ) ) - { - fuzz = fuzz.copy(); - fuzz.setStackSize( g.getStackSize() ); - final IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.SIMULATE, this.machineSrc ); - final ItemStack is = ais == null ? null : ais.getItemStack(); - - if( is != null && is.stackSize == g.getStackSize() ) - { - found = true; - break; - } - else if( is != null ) - { - g = g.copy(); - g.decStackSize( is.stackSize ); - } - } - - if( !found ) - { - return false; - } - } - else - { - final IAEItemStack ais = this.inventory.extractItems( g.copy(), Actionable.SIMULATE, this.machineSrc ); - final ItemStack is = ais == null ? null : ais.getItemStack(); - - if( is == null || is.stackSize < g.getStackSize() ) - { - return false; - } - } - } - - return true; - } - - public void cancel() - { - if( this.myLastLink != null ) - { - this.myLastLink.cancel(); - } - - final IItemList list; - this.getListOfItem( list = AEApi.instance().storage().createItemList(), CraftingItemList.ALL ); - for( final IAEItemStack is : list ) - { - this.postChange( is, this.machineSrc ); - } - - this.isComplete = true; - this.myLastLink = null; - this.tasks.clear(); - - final ImmutableSet items = ImmutableSet.copyOf( this.waitingFor ); - - this.waitingFor.resetStatus(); - - for( final IAEItemStack is : items ) - { - this.postCraftingStatusChange( is ); - } - - this.finalOutput = null; - this.updateCPU(); - - this.storeItems(); // marks dirty - } - - public void updateCraftingLogic( final IGrid grid, final IEnergyGrid eg, final CraftingGridCache cc ) - { - if( !this.getCore().isActive() ) - { - return; - } - - if( this.myLastLink != null ) - { - if( this.myLastLink.isCanceled() ) - { - this.myLastLink = null; - this.cancel(); - } - } - - if( this.isComplete ) - { - if( this.inventory.getItemList().isEmpty() ) - { - return; - } - - this.storeItems(); - return; - } - - this.waiting = false; - if( this.waiting || this.tasks.isEmpty() ) // nothing to do here... - { - return; - } - - this.remainingOperations = this.accelerator + 1 - ( this.usedOps[0] + this.usedOps[1] + this.usedOps[2] ); - final int started = this.remainingOperations; - - if( this.remainingOperations > 0 ) - { - do - { - this.somethingChanged = false; - this.executeCrafting( eg, cc ); - } - while( this.somethingChanged && this.remainingOperations > 0 ); - } - this.usedOps[2] = this.usedOps[1]; - this.usedOps[1] = this.usedOps[0]; - this.usedOps[0] = started - this.remainingOperations; - - if( this.remainingOperations > 0 && !this.somethingChanged ) - { - this.waiting = true; - } - } - - private void executeCrafting( final IEnergyGrid eg, final CraftingGridCache cc ) - { - final Iterator> i = this.tasks.entrySet().iterator(); - - while( i.hasNext() ) - { - final Entry e = i.next(); - - if( e.getValue().value <= 0 ) - { - i.remove(); - continue; - } - - final ICraftingPatternDetails details = e.getKey(); - - if( this.canCraft( details, details.getCondensedInputs() ) ) - { - InventoryCrafting ic = null; - - for( final ICraftingMedium m : cc.getMediums( e.getKey() ) ) - { - if( e.getValue().value <= 0 ) - { - continue; - } - - if( !m.isBusy() ) - { - double sum = 0; - if( ic == null ) - { - final IAEItemStack[] input = details.getInputs(); - - for( final IAEItemStack anInput : input ) - { - if( anInput != null ) - { - sum += anInput.getStackSize(); - } - } - // upgraded interface uses more power - if (m instanceof DualityInterface) - sum *= Math.pow(4.0, ((DualityInterface)m).getInstalledUpgrades(Upgrades.PATTERN_CAPACITY)); - - // check if there is enough power - if (eg.extractAEPower( sum, Actionable.SIMULATE, PowerMultiplier.CONFIG ) < sum - 0.01) - continue; - - ic = details.isCraftable() ? new InventoryCrafting( new ContainerNull(), 3, 3 ): - new InventoryCrafting( new ContainerNull(), details.getInputs().length, 1 ); - boolean found = false; - - for( int x = 0; x < input.length; x++ ) - { - if( input[x] != null ) - { - found = false; - - if( details.isCraftable() ) - { - for( IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( input[x], FuzzyMode.IGNORE_ALL ) ) - { - fuzz = fuzz.copy(); - fuzz.setStackSize( input[x].getStackSize() ); - - if( details.isValidItemForSlot( x, fuzz.getItemStack(), this.getWorld() ) ) - { - final IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.MODULATE, this.machineSrc ); - final ItemStack is = ais == null ? null : ais.getItemStack(); - - if( is != null ) - { - this.postChange( AEItemStack.create( is ), this.machineSrc ); - ic.setInventorySlotContents( x, is ); - found = true; - break; - } - } - } - } - else - { - final IAEItemStack ais = this.inventory.extractItems( input[x].copy(), Actionable.MODULATE, this.machineSrc ); - final ItemStack is = ais == null ? null : ais.getItemStack(); - - if( is != null ) - { - this.postChange( input[x], this.machineSrc ); - ic.setInventorySlotContents( x, is ); - if( is.stackSize == input[x].getStackSize() ) - { - found = true; - continue; - } - } - } - - if( !found ) - { - break; - } - } - } - - if( !found ) - { - // put stuff back.. - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - final ItemStack is = ic.getStackInSlot( x ); - if( is != null ) - { - this.inventory.injectItems( AEItemStack.create( is ), Actionable.MODULATE, this.machineSrc ); - } - } - ic = null; - break; - } - } - - if( m.pushPattern( details, ic ) ) - { - eg.extractAEPower( sum, Actionable.MODULATE, PowerMultiplier.CONFIG ); - this.somethingChanged = true; - this.remainingOperations--; - - for( final IAEItemStack out : details.getCondensedOutputs() ) - { - this.postChange( out, this.machineSrc ); - this.waitingFor.add( out.copy() ); - this.postCraftingStatusChange( out.copy() ); - } - - if( details.isCraftable() ) - { - FMLCommonHandler.instance().firePlayerCraftingEvent( Platform.getPlayer( (WorldServer) this.getWorld() ), details.getOutput( ic, this.getWorld() ), ic ); - - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - final ItemStack output = Platform.getContainerItem( ic.getStackInSlot( x ) ); - if( output != null ) - { - final IAEItemStack cItem = AEItemStack.create( output ); - this.postChange( cItem, this.machineSrc ); - this.waitingFor.add( cItem ); - this.postCraftingStatusChange( cItem ); - } - } - } - - ic = null; // hand off complete! - this.markDirty(); - - e.getValue().value--; - if( e.getValue().value <= 0 ) - { - continue; - } - - if( this.remainingOperations == 0 ) - { - return; - } - } - } - } - - if( ic != null ) - { - // put stuff back.. - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - final ItemStack is = ic.getStackInSlot( x ); - if( is != null ) - { - this.inventory.injectItems( AEItemStack.create( is ), Actionable.MODULATE, this.machineSrc ); - } - } - } - } - } - } - - private void storeItems() - { - final IGrid g = this.getGrid(); - - if( g == null ) - { - return; - } - - final IStorageGrid sg = g.getCache( IStorageGrid.class ); - final IMEInventory ii = sg.getItemInventory(); - - for( IAEItemStack is : this.inventory.getItemList() ) - { - is = this.inventory.extractItems( is.copy(), Actionable.MODULATE, this.machineSrc ); - - if( is != null ) - { - this.postChange( is, this.machineSrc ); - is = ii.injectItems( is, Actionable.MODULATE, this.machineSrc ); - } - - if( is != null ) - { - this.inventory.injectItems( is, Actionable.MODULATE, this.machineSrc ); - } - } - - if( this.inventory.getItemList().isEmpty() ) - { - this.inventory = new MECraftingInventory(); - } - - this.markDirty(); - } - - public ICraftingLink submitJob( final IGrid g, final ICraftingJob job, final BaseActionSource src, final ICraftingRequester requestingMachine ) - { - if( !this.tasks.isEmpty() || !this.waitingFor.isEmpty() ) - { - return null; - } - - if( !( job instanceof CraftingJob ) ) - { - return null; - } - - if( this.isBusy() || !this.isActive() || this.availableStorage < job.getByteTotal() ) - { - return null; - } - - final IStorageGrid sg = g.getCache( IStorageGrid.class ); - final IMEInventory storage = sg.getItemInventory(); - final MECraftingInventory ci = new MECraftingInventory( storage, true, false, false ); - - try - { - this.waitingFor.resetStatus(); - ( (CraftingJob) job ).getTree().setJob( ci, this, src ); - if( ci.commit( src ) ) - { - this.finalOutput = job.getOutput(); - this.waiting = false; - this.isComplete = false; - this.markDirty(); - - this.updateCPU(); - final String craftID = this.generateCraftingID(); - - this.myLastLink = new CraftingLink( this.generateLinkData( craftID, requestingMachine == null, false ), this ); - - this.prepareElapsedTime(); - - if( requestingMachine == null ) - { - return this.myLastLink; - } - - final ICraftingLink whatLink = new CraftingLink( this.generateLinkData( craftID, false, true ), requestingMachine ); - - this.submitLink( this.myLastLink ); - this.submitLink( whatLink ); - - final IItemList list = AEApi.instance().storage().createItemList(); - this.getListOfItem( list, CraftingItemList.ALL ); - for( final IAEItemStack ge : list ) - { - this.postChange( ge, this.machineSrc ); - } - - return whatLink; - } - else - { - this.tasks.clear(); - this.inventory.getItemList().resetStatus(); - } - } - catch( final CraftBranchFailure e ) - { - this.tasks.clear(); - this.inventory.getItemList().resetStatus(); - // AELog.error( e ); - } - - return null; - } - - @Override - public boolean isBusy() - { - final Iterator> i = this.tasks.entrySet().iterator(); - - while( i.hasNext() ) - { - if( i.next().getValue().value <= 0 ) - { - i.remove(); - } - } - - return !this.tasks.isEmpty() || !this.waitingFor.isEmpty(); - } - - @Override - public BaseActionSource getActionSource() - { - return this.machineSrc; - } - - @Override - public long getAvailableStorage() - { - return this.availableStorage; - } - - @Override - public int getCoProcessors() - { - return this.accelerator; - } - - @Override - public String getName() - { - return this.myName; - } - - public boolean isActive() - { - final TileCraftingTile core = this.getCore(); - - if( core == null ) - { - return false; - } - - final IGridNode node = core.getActionableNode(); - if( node == null ) - { - return false; - } - - return node.isActive(); - } - - private String generateCraftingID() - { - final long now = System.currentTimeMillis(); - final int hash = System.identityHashCode( this ); - final int hmm = this.finalOutput == null ? 0 : this.finalOutput.hashCode(); - - return Long.toString( now, Character.MAX_RADIX ) + '-' + Integer.toString( hash, Character.MAX_RADIX ) + '-' + Integer.toString( hmm, Character.MAX_RADIX ); - } - - private NBTTagCompound generateLinkData( final String craftingID, final boolean standalone, final boolean req ) - { - final NBTTagCompound tag = new NBTTagCompound(); - - tag.setString( "CraftID", craftingID ); - tag.setBoolean( "canceled", false ); - tag.setBoolean( "done", false ); - tag.setBoolean( "standalone", standalone ); - tag.setBoolean( "req", req ); - - return tag; - } - - private void submitLink( final ICraftingLink myLastLink2 ) - { - if( this.getGrid() != null ) - { - final CraftingGridCache cc = this.getGrid().getCache( ICraftingGrid.class ); - cc.addLink( (CraftingLink) myLastLink2 ); - } - } - - public void getListOfItem( final IItemList list, final CraftingItemList whichList ) - { - switch( whichList ) - { - case ACTIVE: - for( final IAEItemStack ais : this.waitingFor ) - { - list.add( ais ); - } - break; - case PENDING: - for( final Entry t : this.tasks.entrySet() ) - { - for( IAEItemStack ais : t.getKey().getCondensedOutputs() ) - { - ais = ais.copy(); - ais.setStackSize( ais.getStackSize() * t.getValue().value ); - list.add( ais ); - } - } - break; - case STORAGE: - this.inventory.getAvailableItems( list ); - break; - default: - case ALL: - this.inventory.getAvailableItems( list ); - - for( final IAEItemStack ais : this.waitingFor ) - { - list.add( ais ); - } - - for( final Entry t : this.tasks.entrySet() ) - { - for( IAEItemStack ais : t.getKey().getCondensedOutputs() ) - { - ais = ais.copy(); - ais.setStackSize( ais.getStackSize() * t.getValue().value ); - list.add( ais ); - } - } - break; - } - } - - public void addStorage( final IAEItemStack extractItems ) - { - this.inventory.injectItems( extractItems, Actionable.MODULATE, null ); - } - - public void addEmitable( final IAEItemStack i ) - { - this.waitingFor.add( i ); - this.postCraftingStatusChange( i ); - } - - public void addCrafting( final ICraftingPatternDetails details, final long crafts ) - { - TaskProgress i = this.tasks.get( details ); - - if( i == null ) - { - this.tasks.put( details, i = new TaskProgress() ); - } - - i.value += crafts; - } - - public IAEItemStack getItemStack( final IAEItemStack what, final CraftingItemList storage2 ) - { - IAEItemStack is; - - switch( storage2 ) - { - case STORAGE: - is = this.inventory.getItemList().findPrecise( what ); - break; - case ACTIVE: - is = this.waitingFor.findPrecise( what ); - break; - case PENDING: - - is = what.copy(); - is.setStackSize( 0 ); - - for( final Entry t : this.tasks.entrySet() ) - { - for( final IAEItemStack ais : t.getKey().getCondensedOutputs() ) - { - if( ais.equals( is ) ) - { - is.setStackSize( is.getStackSize() + ais.getStackSize() * t.getValue().value ); - } - } - } - - break; - default: - case ALL: - throw new IllegalStateException( "Invalid Operation" ); - } - - if( is != null ) - { - return is.copy(); - } - - is = what.copy(); - is.setStackSize( 0 ); - return is; - } - - public void writeToNBT( final NBTTagCompound data ) - { - data.setTag( "finalOutput", this.writeItem( this.finalOutput ) ); - data.setTag( "inventory", this.writeList( this.inventory.getItemList() ) ); - data.setBoolean( "waiting", this.waiting ); - data.setBoolean( "isComplete", this.isComplete ); - - if( this.myLastLink != null ) - { - final NBTTagCompound link = new NBTTagCompound(); - this.myLastLink.writeToNBT( link ); - data.setTag( "link", link ); - } - - final NBTTagList list = new NBTTagList(); - for( final Entry e : this.tasks.entrySet() ) - { - final NBTTagCompound item = this.writeItem( AEItemStack.create( e.getKey().getPattern() ) ); - item.setLong( "craftingProgress", e.getValue().value ); - list.appendTag( item ); - } - data.setTag( "tasks", list ); - - data.setTag( "waitingFor", this.writeList( this.waitingFor ) ); - - data.setLong( "elapsedTime", this.getElapsedTime() ); - data.setLong( "startItemCount", this.getStartItemCount() ); - data.setLong( "remainingItemCount", this.getRemainingItemCount() ); - } - - private NBTTagCompound writeItem( final IAEItemStack finalOutput2 ) - { - final NBTTagCompound out = new NBTTagCompound(); - - if( finalOutput2 != null ) - { - finalOutput2.writeToNBT( out ); - } - - return out; - } - - private NBTTagList writeList( final IItemList myList ) - { - final NBTTagList out = new NBTTagList(); - - for( final IAEItemStack ais : myList ) - { - out.appendTag( this.writeItem( ais ) ); - } - - return out; - } - - void done() - { - final TileCraftingTile core = this.getCore(); - - core.setCoreBlock( true ); - - if( core.getPreviousState() != null ) - { - this.readFromNBT( core.getPreviousState() ); - core.setPreviousState( null ); - } - - this.updateCPU(); - this.updateName(); - } - - public void readFromNBT( final NBTTagCompound data ) - { - this.finalOutput = AEItemStack.loadItemStackFromNBT( (NBTTagCompound) data.getTag( "finalOutput" ) ); - for( final IAEItemStack ais : this.readList( (NBTTagList) data.getTag( "inventory" ) ) ) - { - this.inventory.injectItems( ais, Actionable.MODULATE, this.machineSrc ); - } - - this.waiting = data.getBoolean( "waiting" ); - this.isComplete = data.getBoolean( "isComplete" ); - - if( data.hasKey( "link" ) ) - { - final NBTTagCompound link = data.getCompoundTag( "link" ); - this.myLastLink = new CraftingLink( link, this ); - this.submitLink( this.myLastLink ); - } - - final NBTTagList list = data.getTagList( "tasks", 10 ); - for( int x = 0; x < list.tagCount(); x++ ) - { - final NBTTagCompound item = list.getCompoundTagAt( x ); - final IAEItemStack pattern = AEItemStack.loadItemStackFromNBT( item ); - if( pattern != null && pattern.getItem() instanceof ICraftingPatternItem ) - { - final ICraftingPatternItem cpi = (ICraftingPatternItem) pattern.getItem(); - final ICraftingPatternDetails details = cpi.getPatternForItem( pattern.getItemStack(), this.getWorld() ); - if( details != null ) - { - final TaskProgress tp = new TaskProgress(); - tp.value = item.getLong( "craftingProgress" ); - this.tasks.put( details, tp ); - } - } - } - - this.waitingFor = this.readList( (NBTTagList) data.getTag( "waitingFor" ) ); - for( final IAEItemStack is : this.waitingFor ) - { - this.postCraftingStatusChange( is.copy() ); - } - - this.lastTime = System.nanoTime(); - this.elapsedTime = data.getLong( "elapsedTime" ); - this.startItemCount = data.getLong( "startItemCount" ); - this.remainingItemCount = data.getLong( "remainingItemCount" ); - } - - public void updateName() - { - this.myName = ""; - for( final TileCraftingTile te : this.tiles ) - { - - if( te.hasCustomName() ) - { - if( this.myName.length() > 0 ) - { - this.myName += ' ' + te.getCustomName(); - } - else - { - this.myName = te.getCustomName(); - } - } - } - } - - private IItemList readList( final NBTTagList tag ) - { - final IItemList out = AEApi.instance().storage().createItemList(); - - if( tag == null ) - { - return out; - } - - for( int x = 0; x < tag.tagCount(); x++ ) - { - final IAEItemStack ais = AEItemStack.loadItemStackFromNBT( tag.getCompoundTagAt( x ) ); - if( ais != null ) - { - out.add( ais ); - } - } - - return out; - } - - private World getWorld() - { - return this.getCore().getWorldObj(); - } - - public boolean isMaking( final IAEItemStack what ) - { - final IAEItemStack wat = this.waitingFor.findPrecise( what ); - return wat != null && wat.getStackSize() > 0; - } - - public void breakCluster() - { - final TileCraftingTile t = this.getCore(); - - if( t != null ) - { - t.breakCluster(); - } - } - - private void prepareElapsedTime() - { - this.lastTime = System.nanoTime(); - this.elapsedTime = 0; - - final IItemList list = AEApi.instance().storage().createItemList(); - - this.getListOfItem( list, CraftingItemList.ACTIVE ); - this.getListOfItem( list, CraftingItemList.PENDING ); - - long itemCount = 0; - for( final IAEItemStack ge : list ) - { - itemCount += ge.getStackSize(); - } - - this.startItemCount = itemCount; - this.remainingItemCount = itemCount; - } - - private void updateElapsedTime( final IAEItemStack is ) - { - final long nextStartTime = System.nanoTime(); - this.elapsedTime = this.getElapsedTime() + nextStartTime - this.lastTime; - this.lastTime = nextStartTime; - this.remainingItemCount = this.getRemainingItemCount() - is.getStackSize(); - } - - public long getElapsedTime() - { - return this.elapsedTime; - } + /** + * remove a Listener to the monitor. + */ + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } + + public IMEInventory getInventory() { + return this.inventory; + } @Override - public long getRemainingItemCount() - { - return this.remainingItemCount; - } + public void updateStatus(final boolean updateGrid) { + for (final TileCraftingTile r : this.tiles) { + r.updateMeta(true); + } + } @Override - public long getStartItemCount() - { - return this.startItemCount; - } - - private static class TaskProgress - { - private long value; - } + public void destroy() { + if (this.isDestroyed) { + return; + } + this.isDestroyed = true; + + boolean posted = false; + + for (final TileCraftingTile r : this.tiles) { + final IGridNode n = r.getActionableNode(); + if (n != null && !posted) { + final IGrid g = n.getGrid(); + if (g != null) { + g.postEvent(new MENetworkCraftingCpuChange(n)); + posted = true; + } + } + + r.updateStatus(null); + } + } + + @Override + public Iterator getTiles() { + return (Iterator) this.tiles.iterator(); + } + + void addTile(final TileCraftingTile te) { + if (this.machineSrc == null || te.isCoreBlock()) { + this.machineSrc = new MachineSource(te); + } + + te.setCoreBlock(false); + te.markDirty(); + this.tiles.push(te); + + if (te.isStorage()) { + this.availableStorage += te.getStorageBytes(); + this.storage.add(te); + } else if (te.isStatus()) { + this.status.add((TileCraftingMonitorTile) te); + } else if (te.isAccelerator()) { + this.accelerator += te.acceleratorValue(); + } + } + + public boolean canAccept(final IAEStack input) { + if (input instanceof IAEItemStack) { + final IAEItemStack is = this.waitingFor.findPrecise((IAEItemStack) input); + if (is != null && is.getStackSize() > 0) { + return true; + } + } + return false; + } + + public IAEStack injectItems(final IAEStack input, final Actionable type, final BaseActionSource src) { + if (!(input instanceof IAEItemStack)) { + return input; + } + + final IAEItemStack what = (IAEItemStack) input.copy(); + final IAEItemStack is = this.waitingFor.findPrecise(what); + + if (type == Actionable.SIMULATE) // causes crafting to lock up? + { + if (is != null && is.getStackSize() > 0) { + if (is.getStackSize() >= what.getStackSize()) { + if (this.finalOutput.equals(what)) { + if (this.myLastLink != null) { + return ((CraftingLink) this.myLastLink).injectItems(what.copy(), type); + } + + return what; // ignore it. + } + + return null; + } + + final IAEItemStack leftOver = what.copy(); + leftOver.decStackSize(is.getStackSize()); + + final IAEItemStack used = what.copy(); + used.setStackSize(is.getStackSize()); + + if (this.finalOutput.equals(what)) { + if (this.myLastLink != null) { + leftOver.add(((CraftingLink) this.myLastLink).injectItems(used.copy(), type)); + return leftOver; + } + + return what; // ignore it. + } + + return leftOver; + } + } else if (type == Actionable.MODULATE) { + if (is != null && is.getStackSize() > 0) { + this.waiting = false; + + this.postChange(what, src); + + if (is.getStackSize() >= what.getStackSize()) { + is.decStackSize(what.getStackSize()); + + this.updateElapsedTime(what); + this.markDirty(); + this.postCraftingStatusChange(is); + + if (this.finalOutput.equals(what)) { + IAEStack leftover = what; + + this.finalOutput.decStackSize(what.getStackSize()); + + if (this.myLastLink != null) { + leftover = ((CraftingLink) this.myLastLink).injectItems(what, type); + } + + if (this.finalOutput.getStackSize() <= 0) { + this.completeJob(); + } + + this.updateCPU(); + + return leftover; // ignore it. + } + + // 2000 + return this.inventory.injectItems(what, type, src); + } + + final IAEItemStack insert = what.copy(); + insert.setStackSize(is.getStackSize()); + what.decStackSize(is.getStackSize()); + + is.setStackSize(0); + + if (this.finalOutput.equals(insert)) { + IAEStack leftover = input; + + this.finalOutput.decStackSize(insert.getStackSize()); + + if (this.myLastLink != null) { + what.add(((CraftingLink) this.myLastLink).injectItems(insert.copy(), type)); + leftover = what; + } + + if (this.finalOutput.getStackSize() <= 0) { + this.completeJob(); + } + + this.updateCPU(); + this.markDirty(); + + return leftover; // ignore it. + } + + this.inventory.injectItems(insert, type, src); + this.markDirty(); + + return what; + } + } + + return input; + } + + private void postChange(final IAEItemStack diff, final BaseActionSource src) { + final Iterator, Object>> i = this.getListeners(); + + // protect integrity + if (i.hasNext()) { + final ImmutableList single = ImmutableList.of(diff.copy()); + + while (i.hasNext()) { + final Entry, Object> o = i.next(); + final IMEMonitorHandlerReceiver receiver = o.getKey(); + + if (receiver.isValid(o.getValue())) { + receiver.postChange(null, single, src); + } else { + i.remove(); + } + } + } + } + + private void markDirty() { + this.getCore().markDirty(); + } + + private void postCraftingStatusChange(final IAEItemStack diff) { + if (this.getGrid() == null) { + return; + } + + final CraftingGridCache sg = this.getGrid().getCache(ICraftingGrid.class); + + if (sg.getInterestManager().containsKey(diff)) { + final Collection list = sg.getInterestManager().get(diff); + + if (!list.isEmpty()) { + for (final CraftingWatcher iw : list) { + + iw.getHost().onRequestChange(sg, diff); + } + } + } + } + + private void completeJob() { + if (this.myLastLink != null) { + ((CraftingLink) this.myLastLink).markDone(); + } + + if (AELog.isCraftingLogEnabled()) { + final IAEItemStack logStack = this.finalOutput.copy(); + logStack.setStackSize(this.startItemCount); + AELog.crafting(LOG_MARK_AS_COMPLETE, logStack); + } + + this.remainingItemCount = 0; + this.startItemCount = 0; + this.lastTime = 0; + this.elapsedTime = 0; + this.isComplete = true; + } + + private void updateCPU() { + IAEItemStack send = this.finalOutput; + + if (this.finalOutput != null && this.finalOutput.getStackSize() <= 0) { + send = null; + } + + for (final TileCraftingMonitorTile t : this.status) { + t.setJob(send); + } + } + + private Iterator, Object>> getListeners() { + return this.listeners.entrySet().iterator(); + } + + private TileCraftingTile getCore() { + return (TileCraftingTile) this.machineSrc.via; + } + + private IGrid getGrid() { + for (final TileCraftingTile r : this.tiles) { + final IGridNode gn = r.getActionableNode(); + if (gn != null) { + final IGrid g = gn.getGrid(); + if (g != null) { + return r.getActionableNode().getGrid(); + } + } + } + + return null; + } + + private boolean canCraft(final ICraftingPatternDetails details, final IAEItemStack[] condensedInputs) { + for (IAEItemStack g : condensedInputs) { + + if (details.isCraftable()) { + boolean found = false; + + for (IAEItemStack fuzz : this.inventory.getItemList().findFuzzy(g, FuzzyMode.IGNORE_ALL)) { + fuzz = fuzz.copy(); + fuzz.setStackSize(g.getStackSize()); + final IAEItemStack ais = this.inventory.extractItems(fuzz, Actionable.SIMULATE, this.machineSrc); + final ItemStack is = ais == null ? null : ais.getItemStack(); + + if (is != null && is.stackSize == g.getStackSize()) { + found = true; + break; + } else if (is != null) { + g = g.copy(); + g.decStackSize(is.stackSize); + } + } + + if (!found) { + return false; + } + } else { + final IAEItemStack ais = this.inventory.extractItems(g.copy(), Actionable.SIMULATE, this.machineSrc); + final ItemStack is = ais == null ? null : ais.getItemStack(); + + if (is == null || is.stackSize < g.getStackSize()) { + return false; + } + } + } + + return true; + } + + public void cancel() { + if (this.myLastLink != null) { + this.myLastLink.cancel(); + } + + final IItemList list; + this.getListOfItem(list = AEApi.instance().storage().createItemList(), CraftingItemList.ALL); + for (final IAEItemStack is : list) { + this.postChange(is, this.machineSrc); + } + + this.isComplete = true; + this.myLastLink = null; + this.tasks.clear(); + + final ImmutableSet items = ImmutableSet.copyOf(this.waitingFor); + + this.waitingFor.resetStatus(); + + for (final IAEItemStack is : items) { + this.postCraftingStatusChange(is); + } + + this.finalOutput = null; + this.updateCPU(); + + this.storeItems(); // marks dirty + } + + public void updateCraftingLogic(final IGrid grid, final IEnergyGrid eg, final CraftingGridCache cc) { + if (!this.getCore().isActive()) { + return; + } + + if (this.myLastLink != null) { + if (this.myLastLink.isCanceled()) { + this.myLastLink = null; + this.cancel(); + } + } + + if (this.isComplete) { + if (this.inventory.getItemList().isEmpty()) { + return; + } + + this.storeItems(); + return; + } + + this.waiting = false; + if (this.waiting || this.tasks.isEmpty()) // nothing to do here... + { + return; + } + + this.remainingOperations = this.accelerator + 1 - (this.usedOps[0] + this.usedOps[1] + this.usedOps[2]); + final int started = this.remainingOperations; + + if (this.remainingOperations > 0) { + do { + this.somethingChanged = false; + this.executeCrafting(eg, cc); + } while (this.somethingChanged && this.remainingOperations > 0); + } + this.usedOps[2] = this.usedOps[1]; + this.usedOps[1] = this.usedOps[0]; + this.usedOps[0] = started - this.remainingOperations; + + if (this.remainingOperations > 0 && !this.somethingChanged) { + this.waiting = true; + } + } + + private void executeCrafting(final IEnergyGrid eg, final CraftingGridCache cc) { + final Iterator> i = + this.tasks.entrySet().iterator(); + + while (i.hasNext()) { + final Entry e = i.next(); + + if (e.getValue().value <= 0) { + i.remove(); + continue; + } + + final ICraftingPatternDetails details = e.getKey(); + + if (this.canCraft(details, details.getCondensedInputs())) { + InventoryCrafting ic = null; + + for (final ICraftingMedium m : cc.getMediums(e.getKey())) { + if (e.getValue().value <= 0) { + continue; + } + + if (!m.isBusy()) { + double sum = 0; + if (ic == null) { + final IAEItemStack[] input = details.getInputs(); + + for (final IAEItemStack anInput : input) { + if (anInput != null) { + sum += anInput.getStackSize(); + } + } + // upgraded interface uses more power + if (m instanceof DualityInterface) + sum *= Math.pow( + 4.0, ((DualityInterface) m).getInstalledUpgrades(Upgrades.PATTERN_CAPACITY)); + + // check if there is enough power + if (eg.extractAEPower(sum, Actionable.SIMULATE, PowerMultiplier.CONFIG) < sum - 0.01) + continue; + + ic = details.isCraftable() + ? new InventoryCrafting(new ContainerNull(), 3, 3) + : new InventoryCrafting(new ContainerNull(), details.getInputs().length, 1); + boolean found = false; + + for (int x = 0; x < input.length; x++) { + if (input[x] != null) { + found = false; + + if (details.isCraftable()) { + for (IAEItemStack fuzz : this.inventory + .getItemList() + .findFuzzy(input[x], FuzzyMode.IGNORE_ALL)) { + fuzz = fuzz.copy(); + fuzz.setStackSize(input[x].getStackSize()); + + if (details.isValidItemForSlot(x, fuzz.getItemStack(), this.getWorld())) { + final IAEItemStack ais = this.inventory.extractItems( + fuzz, Actionable.MODULATE, this.machineSrc); + final ItemStack is = ais == null ? null : ais.getItemStack(); + + if (is != null) { + this.postChange(AEItemStack.create(is), this.machineSrc); + ic.setInventorySlotContents(x, is); + found = true; + break; + } + } + } + } else { + final IAEItemStack ais = this.inventory.extractItems( + input[x].copy(), Actionable.MODULATE, this.machineSrc); + final ItemStack is = ais == null ? null : ais.getItemStack(); + + if (is != null) { + this.postChange(input[x], this.machineSrc); + ic.setInventorySlotContents(x, is); + if (is.stackSize == input[x].getStackSize()) { + found = true; + continue; + } + } + } + + if (!found) { + break; + } + } + } + + if (!found) { + // put stuff back.. + for (int x = 0; x < ic.getSizeInventory(); x++) { + final ItemStack is = ic.getStackInSlot(x); + if (is != null) { + this.inventory.injectItems( + AEItemStack.create(is), Actionable.MODULATE, this.machineSrc); + } + } + ic = null; + break; + } + } + + if (m.pushPattern(details, ic)) { + eg.extractAEPower(sum, Actionable.MODULATE, PowerMultiplier.CONFIG); + this.somethingChanged = true; + this.remainingOperations--; + + for (final IAEItemStack out : details.getCondensedOutputs()) { + this.postChange(out, this.machineSrc); + this.waitingFor.add(out.copy()); + this.postCraftingStatusChange(out.copy()); + } + + if (details.isCraftable()) { + FMLCommonHandler.instance() + .firePlayerCraftingEvent( + Platform.getPlayer((WorldServer) this.getWorld()), + details.getOutput(ic, this.getWorld()), + ic); + + for (int x = 0; x < ic.getSizeInventory(); x++) { + final ItemStack output = Platform.getContainerItem(ic.getStackInSlot(x)); + if (output != null) { + final IAEItemStack cItem = AEItemStack.create(output); + this.postChange(cItem, this.machineSrc); + this.waitingFor.add(cItem); + this.postCraftingStatusChange(cItem); + } + } + } + + ic = null; // hand off complete! + this.markDirty(); + + e.getValue().value--; + if (e.getValue().value <= 0) { + continue; + } + + if (this.remainingOperations == 0) { + return; + } + } + } + } + + if (ic != null) { + // put stuff back.. + for (int x = 0; x < ic.getSizeInventory(); x++) { + final ItemStack is = ic.getStackInSlot(x); + if (is != null) { + this.inventory.injectItems(AEItemStack.create(is), Actionable.MODULATE, this.machineSrc); + } + } + } + } + } + } + + private void storeItems() { + final IGrid g = this.getGrid(); + + if (g == null) { + return; + } + + final IStorageGrid sg = g.getCache(IStorageGrid.class); + final IMEInventory ii = sg.getItemInventory(); + + for (IAEItemStack is : this.inventory.getItemList()) { + is = this.inventory.extractItems(is.copy(), Actionable.MODULATE, this.machineSrc); + + if (is != null) { + this.postChange(is, this.machineSrc); + is = ii.injectItems(is, Actionable.MODULATE, this.machineSrc); + } + + if (is != null) { + this.inventory.injectItems(is, Actionable.MODULATE, this.machineSrc); + } + } + + if (this.inventory.getItemList().isEmpty()) { + this.inventory = new MECraftingInventory(); + } + + this.markDirty(); + } + + public ICraftingLink submitJob( + final IGrid g, + final ICraftingJob job, + final BaseActionSource src, + final ICraftingRequester requestingMachine) { + if (!this.tasks.isEmpty() || !this.waitingFor.isEmpty()) { + return null; + } + + if (!(job instanceof CraftingJob)) { + return null; + } + + if (this.isBusy() || !this.isActive() || this.availableStorage < job.getByteTotal()) { + return null; + } + + final IStorageGrid sg = g.getCache(IStorageGrid.class); + final IMEInventory storage = sg.getItemInventory(); + final MECraftingInventory ci = new MECraftingInventory(storage, true, false, false); + + try { + this.waitingFor.resetStatus(); + ((CraftingJob) job).getTree().setJob(ci, this, src); + if (ci.commit(src)) { + this.finalOutput = job.getOutput(); + this.waiting = false; + this.isComplete = false; + this.markDirty(); + + this.updateCPU(); + final String craftID = this.generateCraftingID(); + + this.myLastLink = + new CraftingLink(this.generateLinkData(craftID, requestingMachine == null, false), this); + + this.prepareElapsedTime(); + + if (requestingMachine == null) { + return this.myLastLink; + } + + final ICraftingLink whatLink = + new CraftingLink(this.generateLinkData(craftID, false, true), requestingMachine); + + this.submitLink(this.myLastLink); + this.submitLink(whatLink); + + final IItemList list = AEApi.instance().storage().createItemList(); + this.getListOfItem(list, CraftingItemList.ALL); + for (final IAEItemStack ge : list) { + this.postChange(ge, this.machineSrc); + } + + return whatLink; + } else { + this.tasks.clear(); + this.inventory.getItemList().resetStatus(); + } + } catch (final CraftBranchFailure e) { + this.tasks.clear(); + this.inventory.getItemList().resetStatus(); + // AELog.error( e ); + } + + return null; + } + + @Override + public boolean isBusy() { + final Iterator> i = + this.tasks.entrySet().iterator(); + + while (i.hasNext()) { + if (i.next().getValue().value <= 0) { + i.remove(); + } + } + + return !this.tasks.isEmpty() || !this.waitingFor.isEmpty(); + } + + @Override + public BaseActionSource getActionSource() { + return this.machineSrc; + } + + @Override + public long getAvailableStorage() { + return this.availableStorage; + } + + @Override + public int getCoProcessors() { + return this.accelerator; + } + + @Override + public String getName() { + return this.myName; + } + + public boolean isActive() { + final TileCraftingTile core = this.getCore(); + + if (core == null) { + return false; + } + + final IGridNode node = core.getActionableNode(); + if (node == null) { + return false; + } + + return node.isActive(); + } + + private String generateCraftingID() { + final long now = System.currentTimeMillis(); + final int hash = System.identityHashCode(this); + final int hmm = this.finalOutput == null ? 0 : this.finalOutput.hashCode(); + + return Long.toString(now, Character.MAX_RADIX) + + '-' + + Integer.toString(hash, Character.MAX_RADIX) + + '-' + + Integer.toString(hmm, Character.MAX_RADIX); + } + + private NBTTagCompound generateLinkData(final String craftingID, final boolean standalone, final boolean req) { + final NBTTagCompound tag = new NBTTagCompound(); + + tag.setString("CraftID", craftingID); + tag.setBoolean("canceled", false); + tag.setBoolean("done", false); + tag.setBoolean("standalone", standalone); + tag.setBoolean("req", req); + + return tag; + } + + private void submitLink(final ICraftingLink myLastLink2) { + if (this.getGrid() != null) { + final CraftingGridCache cc = this.getGrid().getCache(ICraftingGrid.class); + cc.addLink((CraftingLink) myLastLink2); + } + } + + public void getListOfItem(final IItemList list, final CraftingItemList whichList) { + switch (whichList) { + case ACTIVE: + for (final IAEItemStack ais : this.waitingFor) { + list.add(ais); + } + break; + case PENDING: + for (final Entry t : this.tasks.entrySet()) { + for (IAEItemStack ais : t.getKey().getCondensedOutputs()) { + ais = ais.copy(); + ais.setStackSize(ais.getStackSize() * t.getValue().value); + list.add(ais); + } + } + break; + case STORAGE: + this.inventory.getAvailableItems(list); + break; + default: + case ALL: + this.inventory.getAvailableItems(list); + + for (final IAEItemStack ais : this.waitingFor) { + list.add(ais); + } + + for (final Entry t : this.tasks.entrySet()) { + for (IAEItemStack ais : t.getKey().getCondensedOutputs()) { + ais = ais.copy(); + ais.setStackSize(ais.getStackSize() * t.getValue().value); + list.add(ais); + } + } + break; + } + } + + public void addStorage(final IAEItemStack extractItems) { + this.inventory.injectItems(extractItems, Actionable.MODULATE, null); + } + + public void addEmitable(final IAEItemStack i) { + this.waitingFor.add(i); + this.postCraftingStatusChange(i); + } + + public void addCrafting(final ICraftingPatternDetails details, final long crafts) { + TaskProgress i = this.tasks.get(details); + + if (i == null) { + this.tasks.put(details, i = new TaskProgress()); + } + + i.value += crafts; + } + + public IAEItemStack getItemStack(final IAEItemStack what, final CraftingItemList storage2) { + IAEItemStack is; + + switch (storage2) { + case STORAGE: + is = this.inventory.getItemList().findPrecise(what); + break; + case ACTIVE: + is = this.waitingFor.findPrecise(what); + break; + case PENDING: + is = what.copy(); + is.setStackSize(0); + + for (final Entry t : this.tasks.entrySet()) { + for (final IAEItemStack ais : t.getKey().getCondensedOutputs()) { + if (ais.equals(is)) { + is.setStackSize(is.getStackSize() + ais.getStackSize() * t.getValue().value); + } + } + } + + break; + default: + case ALL: + throw new IllegalStateException("Invalid Operation"); + } + + if (is != null) { + return is.copy(); + } + + is = what.copy(); + is.setStackSize(0); + return is; + } + + public void writeToNBT(final NBTTagCompound data) { + data.setTag("finalOutput", this.writeItem(this.finalOutput)); + data.setTag("inventory", this.writeList(this.inventory.getItemList())); + data.setBoolean("waiting", this.waiting); + data.setBoolean("isComplete", this.isComplete); + + if (this.myLastLink != null) { + final NBTTagCompound link = new NBTTagCompound(); + this.myLastLink.writeToNBT(link); + data.setTag("link", link); + } + + final NBTTagList list = new NBTTagList(); + for (final Entry e : this.tasks.entrySet()) { + final NBTTagCompound item = + this.writeItem(AEItemStack.create(e.getKey().getPattern())); + item.setLong("craftingProgress", e.getValue().value); + list.appendTag(item); + } + data.setTag("tasks", list); + + data.setTag("waitingFor", this.writeList(this.waitingFor)); + + data.setLong("elapsedTime", this.getElapsedTime()); + data.setLong("startItemCount", this.getStartItemCount()); + data.setLong("remainingItemCount", this.getRemainingItemCount()); + } + + private NBTTagCompound writeItem(final IAEItemStack finalOutput2) { + final NBTTagCompound out = new NBTTagCompound(); + + if (finalOutput2 != null) { + finalOutput2.writeToNBT(out); + } + + return out; + } + + private NBTTagList writeList(final IItemList myList) { + final NBTTagList out = new NBTTagList(); + + for (final IAEItemStack ais : myList) { + out.appendTag(this.writeItem(ais)); + } + + return out; + } + + void done() { + final TileCraftingTile core = this.getCore(); + + core.setCoreBlock(true); + + if (core.getPreviousState() != null) { + this.readFromNBT(core.getPreviousState()); + core.setPreviousState(null); + } + + this.updateCPU(); + this.updateName(); + } + + public void readFromNBT(final NBTTagCompound data) { + this.finalOutput = AEItemStack.loadItemStackFromNBT((NBTTagCompound) data.getTag("finalOutput")); + for (final IAEItemStack ais : this.readList((NBTTagList) data.getTag("inventory"))) { + this.inventory.injectItems(ais, Actionable.MODULATE, this.machineSrc); + } + + this.waiting = data.getBoolean("waiting"); + this.isComplete = data.getBoolean("isComplete"); + + if (data.hasKey("link")) { + final NBTTagCompound link = data.getCompoundTag("link"); + this.myLastLink = new CraftingLink(link, this); + this.submitLink(this.myLastLink); + } + + final NBTTagList list = data.getTagList("tasks", 10); + for (int x = 0; x < list.tagCount(); x++) { + final NBTTagCompound item = list.getCompoundTagAt(x); + final IAEItemStack pattern = AEItemStack.loadItemStackFromNBT(item); + if (pattern != null && pattern.getItem() instanceof ICraftingPatternItem) { + final ICraftingPatternItem cpi = (ICraftingPatternItem) pattern.getItem(); + final ICraftingPatternDetails details = cpi.getPatternForItem(pattern.getItemStack(), this.getWorld()); + if (details != null) { + final TaskProgress tp = new TaskProgress(); + tp.value = item.getLong("craftingProgress"); + this.tasks.put(details, tp); + } + } + } + + this.waitingFor = this.readList((NBTTagList) data.getTag("waitingFor")); + for (final IAEItemStack is : this.waitingFor) { + this.postCraftingStatusChange(is.copy()); + } + + this.lastTime = System.nanoTime(); + this.elapsedTime = data.getLong("elapsedTime"); + this.startItemCount = data.getLong("startItemCount"); + this.remainingItemCount = data.getLong("remainingItemCount"); + } + + public void updateName() { + this.myName = ""; + for (final TileCraftingTile te : this.tiles) { + + if (te.hasCustomName()) { + if (this.myName.length() > 0) { + this.myName += ' ' + te.getCustomName(); + } else { + this.myName = te.getCustomName(); + } + } + } + } + + private IItemList readList(final NBTTagList tag) { + final IItemList out = AEApi.instance().storage().createItemList(); + + if (tag == null) { + return out; + } + + for (int x = 0; x < tag.tagCount(); x++) { + final IAEItemStack ais = AEItemStack.loadItemStackFromNBT(tag.getCompoundTagAt(x)); + if (ais != null) { + out.add(ais); + } + } + + return out; + } + + private World getWorld() { + return this.getCore().getWorldObj(); + } + + public boolean isMaking(final IAEItemStack what) { + final IAEItemStack wat = this.waitingFor.findPrecise(what); + return wat != null && wat.getStackSize() > 0; + } + + public void breakCluster() { + final TileCraftingTile t = this.getCore(); + + if (t != null) { + t.breakCluster(); + } + } + + private void prepareElapsedTime() { + this.lastTime = System.nanoTime(); + this.elapsedTime = 0; + + final IItemList list = AEApi.instance().storage().createItemList(); + + this.getListOfItem(list, CraftingItemList.ACTIVE); + this.getListOfItem(list, CraftingItemList.PENDING); + + long itemCount = 0; + for (final IAEItemStack ge : list) { + itemCount += ge.getStackSize(); + } + + this.startItemCount = itemCount; + this.remainingItemCount = itemCount; + } + + private void updateElapsedTime(final IAEItemStack is) { + final long nextStartTime = System.nanoTime(); + this.elapsedTime = this.getElapsedTime() + nextStartTime - this.lastTime; + this.lastTime = nextStartTime; + this.remainingItemCount = this.getRemainingItemCount() - is.getStackSize(); + } + + public long getElapsedTime() { + return this.elapsedTime; + } + + @Override + public long getRemainingItemCount() { + return this.remainingItemCount; + } + + @Override + public long getStartItemCount() { + return this.startItemCount; + } + + private static class TaskProgress { + private long value; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/QuantumCalculator.java b/src/main/java/appeng/me/cluster/implementations/QuantumCalculator.java index 6e127730ab8..f8770dabe00 100644 --- a/src/main/java/appeng/me/cluster/implementations/QuantumCalculator.java +++ b/src/main/java/appeng/me/cluster/implementations/QuantumCalculator.java @@ -18,7 +18,6 @@ package appeng.me.cluster.implementations; - import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IBlocks; @@ -32,141 +31,114 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - -public class QuantumCalculator extends MBCalculator -{ - - private final TileQuantumBridge tqb; - - public QuantumCalculator( final IAEMultiBlock t ) - { - super( t ); - this.tqb = (TileQuantumBridge) t; - } - - @Override - public boolean checkMultiblockScale( final WorldCoord min, final WorldCoord max ) - { - - if( ( max.x - min.x + 1 ) * ( max.y - min.y + 1 ) * ( max.z - min.z + 1 ) == 9 ) - { - final int ones = ( ( max.x - min.x ) == 0 ? 1 : 0 ) + ( ( max.y - min.y ) == 0 ? 1 : 0 ) + ( ( max.z - min.z ) == 0 ? 1 : 0 ); - - final int threes = ( ( max.x - min.x ) == 2 ? 1 : 0 ) + ( ( max.y - min.y ) == 2 ? 1 : 0 ) + ( ( max.z - min.z ) == 2 ? 1 : 0 ); - - return ones == 1 && threes == 2; - } - return false; - } - - @Override - public IAECluster createCluster( final World w, final WorldCoord min, final WorldCoord max ) - { - return new QuantumCluster( min, max ); - } - - @Override - public boolean verifyInternalStructure( final World w, final WorldCoord min, final WorldCoord max ) - { - - byte num = 0; - - for( int x = min.x; x <= max.x; x++ ) - { - for( int y = min.y; y <= max.y; y++ ) - { - for( int z = min.z; z <= max.z; z++ ) - { - final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity( x, y, z ); - - if( !te.isValid() ) - { - return false; - } - - num++; - final IBlocks blocks = AEApi.instance().definitions().blocks(); - if( num == 5 ) - { - if( !this.isBlockAtLocation( w, x, y, z, blocks.quantumLink() ) ) - { - return false; - } - } - else - { - if( !this.isBlockAtLocation( w, x, y, z, blocks.quantumRing() ) ) - { - return false; - } - } - } - } - } - return true; - } - - @Override - public void disconnect() - { - this.tqb.disconnect( true ); - } - - @Override - public void updateTiles( final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max ) - { - byte num = 0; - byte ringNum = 0; - final QuantumCluster c = (QuantumCluster) cl; - - for( int x = min.x; x <= max.x; x++ ) - { - for( int y = min.y; y <= max.y; y++ ) - { - for( int z = min.z; z <= max.z; z++ ) - { - final TileQuantumBridge te = (TileQuantumBridge) w.getTileEntity( x, y, z ); - - num++; - final byte flags; - if( num == 5 ) - { - flags = num; - c.setCenter( te ); - } - else - { - if( num == 1 || num == 3 || num == 7 || num == 9 ) - { - flags = (byte) ( this.tqb.getCorner() | num ); - } - else - { - flags = num; - } - c.getRing()[ringNum] = te; - ringNum++; - } - - te.updateStatus( c, flags, true ); - } - } - } - } - - @Override - public boolean isValidTile( final TileEntity te ) - { - return te instanceof TileQuantumBridge; - } - - private boolean isBlockAtLocation( final IBlockAccess w, final int x, final int y, final int z, final IBlockDefinition def ) - { - for( final Block block : def.maybeBlock().asSet() ) - { - return block == w.getBlock( x, y, z ); - } - - return false; - } +public class QuantumCalculator extends MBCalculator { + + private final TileQuantumBridge tqb; + + public QuantumCalculator(final IAEMultiBlock t) { + super(t); + this.tqb = (TileQuantumBridge) t; + } + + @Override + public boolean checkMultiblockScale(final WorldCoord min, final WorldCoord max) { + + if ((max.x - min.x + 1) * (max.y - min.y + 1) * (max.z - min.z + 1) == 9) { + final int ones = + ((max.x - min.x) == 0 ? 1 : 0) + ((max.y - min.y) == 0 ? 1 : 0) + ((max.z - min.z) == 0 ? 1 : 0); + + final int threes = + ((max.x - min.x) == 2 ? 1 : 0) + ((max.y - min.y) == 2 ? 1 : 0) + ((max.z - min.z) == 2 ? 1 : 0); + + return ones == 1 && threes == 2; + } + return false; + } + + @Override + public IAECluster createCluster(final World w, final WorldCoord min, final WorldCoord max) { + return new QuantumCluster(min, max); + } + + @Override + public boolean verifyInternalStructure(final World w, final WorldCoord min, final WorldCoord max) { + + byte num = 0; + + for (int x = min.x; x <= max.x; x++) { + for (int y = min.y; y <= max.y; y++) { + for (int z = min.z; z <= max.z; z++) { + final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity(x, y, z); + + if (!te.isValid()) { + return false; + } + + num++; + final IBlocks blocks = AEApi.instance().definitions().blocks(); + if (num == 5) { + if (!this.isBlockAtLocation(w, x, y, z, blocks.quantumLink())) { + return false; + } + } else { + if (!this.isBlockAtLocation(w, x, y, z, blocks.quantumRing())) { + return false; + } + } + } + } + } + return true; + } + + @Override + public void disconnect() { + this.tqb.disconnect(true); + } + + @Override + public void updateTiles(final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max) { + byte num = 0; + byte ringNum = 0; + final QuantumCluster c = (QuantumCluster) cl; + + for (int x = min.x; x <= max.x; x++) { + for (int y = min.y; y <= max.y; y++) { + for (int z = min.z; z <= max.z; z++) { + final TileQuantumBridge te = (TileQuantumBridge) w.getTileEntity(x, y, z); + + num++; + final byte flags; + if (num == 5) { + flags = num; + c.setCenter(te); + } else { + if (num == 1 || num == 3 || num == 7 || num == 9) { + flags = (byte) (this.tqb.getCorner() | num); + } else { + flags = num; + } + c.getRing()[ringNum] = te; + ringNum++; + } + + te.updateStatus(c, flags, true); + } + } + } + } + + @Override + public boolean isValidTile(final TileEntity te) { + return te instanceof TileQuantumBridge; + } + + private boolean isBlockAtLocation( + final IBlockAccess w, final int x, final int y, final int z, final IBlockDefinition def) { + for (final Block block : def.maybeBlock().asSet()) { + return block == w.getBlock(x, y, z); + } + + return false; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/QuantumCluster.java b/src/main/java/appeng/me/cluster/implementations/QuantumCluster.java index 76eadc9a937..8737deb1fea 100644 --- a/src/main/java/appeng/me/cluster/implementations/QuantumCluster.java +++ b/src/main/java/appeng/me/cluster/implementations/QuantumCluster.java @@ -18,7 +18,6 @@ package appeng.me.cluster.implementations; - import appeng.api.AEApi; import appeng.api.events.LocatableEventAnnounce; import appeng.api.events.LocatableEventAnnounce.LocatableEvent; @@ -32,6 +31,7 @@ import appeng.tile.qnb.TileQuantumBridge; import appeng.util.iterators.ChainedIterator; import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import java.util.Iterator; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; @@ -40,267 +40,228 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.world.WorldEvent; -import java.util.Iterator; - - -public class QuantumCluster implements ILocatable, IAECluster -{ - - private final WorldCoord min; - private final WorldCoord max; - private boolean isDestroyed = false; - private boolean updateStatus = true; - private TileQuantumBridge[] Ring; - private boolean registered = false; - private ConnectionWrapper connection; - private long thisSide; - private long otherSide; - private TileQuantumBridge center; - - public QuantumCluster( final WorldCoord min, final WorldCoord max ) - { - this.min = min; - this.max = max; - this.setRing( new TileQuantumBridge[8] ); - } - - @SubscribeEvent - public void onUnload( final WorldEvent.Unload e ) - { - if( this.center != null && this.center.getWorldObj() == e.world ) - { - this.setUpdateStatus( false ); - this.destroy(); - } - } - - @Override - public void updateStatus( final boolean updateGrid ) - { - final long qe = this.center.getQEFrequency(); - - if( this.thisSide != qe && this.thisSide != -qe ) - { - if( qe != 0 ) - { - if( this.thisSide != 0 ) - { - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); - } - - if( this.canUseNode( -qe ) ) - { - this.otherSide = qe; - this.thisSide = -qe; - } - else if( this.canUseNode( qe ) ) - { - this.thisSide = qe; - this.otherSide = -qe; - } - - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Register ) ); - } - else - { - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); - - this.otherSide = 0; - this.thisSide = 0; - } - } - - final ILocatable myOtherSide = this.otherSide == 0 ? null : AEApi.instance().registries().locatable().getLocatableBy( this.otherSide ); - - boolean shutdown = false; - - if( myOtherSide instanceof QuantumCluster ) - { - final QuantumCluster sideA = this; - final QuantumCluster sideB = (QuantumCluster) myOtherSide; - - if( sideA.isActive() && sideB.isActive() ) - { - if( this.connection != null && this.connection.getConnection() != null ) - { - final IGridNode a = this.connection.getConnection().a(); - final IGridNode b = this.connection.getConnection().b(); - final IGridNode sa = sideA.getNode(); - final IGridNode sb = sideB.getNode(); - if( ( a == sa || b == sa ) && ( a == sb || b == sb ) ) - { - return; - } - } - - try - { - if( sideA.connection != null ) - { - if( sideA.connection.getConnection() != null ) - { - sideA.connection.getConnection().destroy(); - sideA.connection = new ConnectionWrapper( null ); - } - } - - if( sideB.connection != null ) - { - if( sideB.connection.getConnection() != null ) - { - sideB.connection.getConnection().destroy(); - sideB.connection = new ConnectionWrapper( null ); - } - } - - sideA.connection = sideB.connection = new ConnectionWrapper( AEApi.instance().createGridConnection( sideA.getNode(), sideB.getNode() ) ); - } - catch( final FailedConnection e ) - { - // :( - } - } - else - { - shutdown = true; - } - } - else - { - shutdown = true; - } - - if( shutdown && this.connection != null ) - { - if( this.connection.getConnection() != null ) - { - this.connection.getConnection().destroy(); - this.connection.setConnection( null ); - this.connection = new ConnectionWrapper( null ); - } - } - } - - private boolean canUseNode( final long qe ) - { - final QuantumCluster qc = (QuantumCluster) AEApi.instance().registries().locatable().getLocatableBy( qe ); - if( qc != null ) - { - final World theWorld = qc.center.getWorldObj(); - if( !qc.isDestroyed ) - { - final Chunk c = theWorld.getChunkFromBlockCoords( qc.center.xCoord, qc.center.zCoord ); - if( c.isChunkLoaded ) - { - final int id = theWorld.provider.dimensionId; - final World cur = DimensionManager.getWorld( id ); - - final TileEntity te = theWorld.getTileEntity( qc.center.xCoord, qc.center.yCoord, qc.center.zCoord ); - return te != qc.center || theWorld != cur; - } - } - } - return true; - } - - private boolean isActive() - { - if( this.isDestroyed || !this.registered ) - { - return false; - } - - return this.center.isPowered() && this.hasQES(); - } - - private IGridNode getNode() - { - return this.center.getGridNode( ForgeDirection.UNKNOWN ); - } - - private boolean hasQES() - { - return this.thisSide != 0; - } - - @Override - public void destroy() - { - if( this.isDestroyed ) - { - return; - } - this.isDestroyed = true; - - if( this.registered ) - { - MinecraftForge.EVENT_BUS.unregister( this ); - this.registered = false; - } - - if( this.thisSide != 0 ) - { - this.updateStatus( true ); - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); - } - - this.center.updateStatus( null, (byte) -1, this.isUpdateStatus() ); - - for( final TileQuantumBridge r : this.getRing() ) - { - r.updateStatus( null, (byte) -1, this.isUpdateStatus() ); - } - - this.center = null; - this.setRing( new TileQuantumBridge[8] ); - } - - @Override - public Iterator getTiles() - { - return new ChainedIterator( this.getRing()[0], this.getRing()[1], this.getRing()[2], this.getRing()[3], this.getRing()[4], this.getRing()[5], this.getRing()[6], this.getRing()[7], this.center ); - } - - public boolean isCorner( final TileQuantumBridge tileQuantumBridge ) - { - return this.getRing()[0] == tileQuantumBridge || this.getRing()[2] == tileQuantumBridge || this.getRing()[4] == tileQuantumBridge || this.getRing()[6] == tileQuantumBridge; - } - - @Override - public long getLocatableSerial() - { - return this.thisSide; - } - - public TileQuantumBridge getCenter() - { - return this.center; - } - - void setCenter( final TileQuantumBridge c ) - { - this.registered = true; - MinecraftForge.EVENT_BUS.register( this ); - this.center = c; - } - - private boolean isUpdateStatus() - { - return this.updateStatus; - } - - public void setUpdateStatus( final boolean updateStatus ) - { - this.updateStatus = updateStatus; - } - - TileQuantumBridge[] getRing() - { - return this.Ring; - } - - private void setRing( final TileQuantumBridge[] ring ) - { - this.Ring = ring; - } +public class QuantumCluster implements ILocatable, IAECluster { + + private final WorldCoord min; + private final WorldCoord max; + private boolean isDestroyed = false; + private boolean updateStatus = true; + private TileQuantumBridge[] Ring; + private boolean registered = false; + private ConnectionWrapper connection; + private long thisSide; + private long otherSide; + private TileQuantumBridge center; + + public QuantumCluster(final WorldCoord min, final WorldCoord max) { + this.min = min; + this.max = max; + this.setRing(new TileQuantumBridge[8]); + } + + @SubscribeEvent + public void onUnload(final WorldEvent.Unload e) { + if (this.center != null && this.center.getWorldObj() == e.world) { + this.setUpdateStatus(false); + this.destroy(); + } + } + + @Override + public void updateStatus(final boolean updateGrid) { + final long qe = this.center.getQEFrequency(); + + if (this.thisSide != qe && this.thisSide != -qe) { + if (qe != 0) { + if (this.thisSide != 0) { + MinecraftForge.EVENT_BUS.post(new LocatableEventAnnounce(this, LocatableEvent.Unregister)); + } + + if (this.canUseNode(-qe)) { + this.otherSide = qe; + this.thisSide = -qe; + } else if (this.canUseNode(qe)) { + this.thisSide = qe; + this.otherSide = -qe; + } + + MinecraftForge.EVENT_BUS.post(new LocatableEventAnnounce(this, LocatableEvent.Register)); + } else { + MinecraftForge.EVENT_BUS.post(new LocatableEventAnnounce(this, LocatableEvent.Unregister)); + + this.otherSide = 0; + this.thisSide = 0; + } + } + + final ILocatable myOtherSide = this.otherSide == 0 + ? null + : AEApi.instance().registries().locatable().getLocatableBy(this.otherSide); + + boolean shutdown = false; + + if (myOtherSide instanceof QuantumCluster) { + final QuantumCluster sideA = this; + final QuantumCluster sideB = (QuantumCluster) myOtherSide; + + if (sideA.isActive() && sideB.isActive()) { + if (this.connection != null && this.connection.getConnection() != null) { + final IGridNode a = this.connection.getConnection().a(); + final IGridNode b = this.connection.getConnection().b(); + final IGridNode sa = sideA.getNode(); + final IGridNode sb = sideB.getNode(); + if ((a == sa || b == sa) && (a == sb || b == sb)) { + return; + } + } + + try { + if (sideA.connection != null) { + if (sideA.connection.getConnection() != null) { + sideA.connection.getConnection().destroy(); + sideA.connection = new ConnectionWrapper(null); + } + } + + if (sideB.connection != null) { + if (sideB.connection.getConnection() != null) { + sideB.connection.getConnection().destroy(); + sideB.connection = new ConnectionWrapper(null); + } + } + + sideA.connection = sideB.connection = new ConnectionWrapper( + AEApi.instance().createGridConnection(sideA.getNode(), sideB.getNode())); + } catch (final FailedConnection e) { + // :( + } + } else { + shutdown = true; + } + } else { + shutdown = true; + } + + if (shutdown && this.connection != null) { + if (this.connection.getConnection() != null) { + this.connection.getConnection().destroy(); + this.connection.setConnection(null); + this.connection = new ConnectionWrapper(null); + } + } + } + + private boolean canUseNode(final long qe) { + final QuantumCluster qc = + (QuantumCluster) AEApi.instance().registries().locatable().getLocatableBy(qe); + if (qc != null) { + final World theWorld = qc.center.getWorldObj(); + if (!qc.isDestroyed) { + final Chunk c = theWorld.getChunkFromBlockCoords(qc.center.xCoord, qc.center.zCoord); + if (c.isChunkLoaded) { + final int id = theWorld.provider.dimensionId; + final World cur = DimensionManager.getWorld(id); + + final TileEntity te = theWorld.getTileEntity(qc.center.xCoord, qc.center.yCoord, qc.center.zCoord); + return te != qc.center || theWorld != cur; + } + } + } + return true; + } + + private boolean isActive() { + if (this.isDestroyed || !this.registered) { + return false; + } + + return this.center.isPowered() && this.hasQES(); + } + + private IGridNode getNode() { + return this.center.getGridNode(ForgeDirection.UNKNOWN); + } + + private boolean hasQES() { + return this.thisSide != 0; + } + + @Override + public void destroy() { + if (this.isDestroyed) { + return; + } + this.isDestroyed = true; + + if (this.registered) { + MinecraftForge.EVENT_BUS.unregister(this); + this.registered = false; + } + + if (this.thisSide != 0) { + this.updateStatus(true); + MinecraftForge.EVENT_BUS.post(new LocatableEventAnnounce(this, LocatableEvent.Unregister)); + } + + this.center.updateStatus(null, (byte) -1, this.isUpdateStatus()); + + for (final TileQuantumBridge r : this.getRing()) { + r.updateStatus(null, (byte) -1, this.isUpdateStatus()); + } + + this.center = null; + this.setRing(new TileQuantumBridge[8]); + } + + @Override + public Iterator getTiles() { + return new ChainedIterator( + this.getRing()[0], + this.getRing()[1], + this.getRing()[2], + this.getRing()[3], + this.getRing()[4], + this.getRing()[5], + this.getRing()[6], + this.getRing()[7], + this.center); + } + + public boolean isCorner(final TileQuantumBridge tileQuantumBridge) { + return this.getRing()[0] == tileQuantumBridge + || this.getRing()[2] == tileQuantumBridge + || this.getRing()[4] == tileQuantumBridge + || this.getRing()[6] == tileQuantumBridge; + } + + @Override + public long getLocatableSerial() { + return this.thisSide; + } + + public TileQuantumBridge getCenter() { + return this.center; + } + + void setCenter(final TileQuantumBridge c) { + this.registered = true; + MinecraftForge.EVENT_BUS.register(this); + this.center = c; + } + + private boolean isUpdateStatus() { + return this.updateStatus; + } + + public void setUpdateStatus(final boolean updateStatus) { + this.updateStatus = updateStatus; + } + + TileQuantumBridge[] getRing() { + return this.Ring; + } + + private void setRing(final TileQuantumBridge[] ring) { + this.Ring = ring; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java b/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java index 68b73edaaea..617b76d83e9 100644 --- a/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java +++ b/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java @@ -18,7 +18,6 @@ package appeng.me.cluster.implementations; - import appeng.api.util.DimensionalCoord; import appeng.api.util.WorldCoord; import appeng.me.cluster.IAECluster; @@ -28,81 +27,68 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; - -public class SpatialPylonCalculator extends MBCalculator -{ - - private final TileSpatialPylon tqb; - - public SpatialPylonCalculator( final IAEMultiBlock t ) - { - super( t ); - this.tqb = (TileSpatialPylon) t; - } - - @Override - public boolean checkMultiblockScale( final WorldCoord min, final WorldCoord max ) - { - return ( min.x == max.x && min.y == max.y && min.z != max.z ) || ( min.x == max.x && min.y != max.y && min.z == max.z ) || ( min.x != max.x && min.y == max.y && min.z == max.z ); - } - - @Override - public IAECluster createCluster( final World w, final WorldCoord min, final WorldCoord max ) - { - return new SpatialPylonCluster( new DimensionalCoord( w, min.x, min.y, min.z ), new DimensionalCoord( w, max.x, max.y, max.z ) ); - } - - @Override - public boolean verifyInternalStructure( final World w, final WorldCoord min, final WorldCoord max ) - { - - for( int x = min.x; x <= max.x; x++ ) - { - for( int y = min.y; y <= max.y; y++ ) - { - for( int z = min.z; z <= max.z; z++ ) - { - final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity( x, y, z ); - - if( !te.isValid() ) - { - return false; - } - } - } - } - - return true; - } - - @Override - public void disconnect() - { - this.tqb.disconnect( true ); - } - - @Override - public void updateTiles( final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max ) - { - final SpatialPylonCluster c = (SpatialPylonCluster) cl; - - for( int x = min.x; x <= max.x; x++ ) - { - for( int y = min.y; y <= max.y; y++ ) - { - for( int z = min.z; z <= max.z; z++ ) - { - final TileSpatialPylon te = (TileSpatialPylon) w.getTileEntity( x, y, z ); - te.updateStatus( c ); - c.getLine().add( ( te ) ); - } - } - } - } - - @Override - public boolean isValidTile( final TileEntity te ) - { - return te instanceof TileSpatialPylon; - } +public class SpatialPylonCalculator extends MBCalculator { + + private final TileSpatialPylon tqb; + + public SpatialPylonCalculator(final IAEMultiBlock t) { + super(t); + this.tqb = (TileSpatialPylon) t; + } + + @Override + public boolean checkMultiblockScale(final WorldCoord min, final WorldCoord max) { + return (min.x == max.x && min.y == max.y && min.z != max.z) + || (min.x == max.x && min.y != max.y && min.z == max.z) + || (min.x != max.x && min.y == max.y && min.z == max.z); + } + + @Override + public IAECluster createCluster(final World w, final WorldCoord min, final WorldCoord max) { + return new SpatialPylonCluster( + new DimensionalCoord(w, min.x, min.y, min.z), new DimensionalCoord(w, max.x, max.y, max.z)); + } + + @Override + public boolean verifyInternalStructure(final World w, final WorldCoord min, final WorldCoord max) { + + for (int x = min.x; x <= max.x; x++) { + for (int y = min.y; y <= max.y; y++) { + for (int z = min.z; z <= max.z; z++) { + final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity(x, y, z); + + if (!te.isValid()) { + return false; + } + } + } + } + + return true; + } + + @Override + public void disconnect() { + this.tqb.disconnect(true); + } + + @Override + public void updateTiles(final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max) { + final SpatialPylonCluster c = (SpatialPylonCluster) cl; + + for (int x = min.x; x <= max.x; x++) { + for (int y = min.y; y <= max.y; y++) { + for (int z = min.z; z <= max.z; z++) { + final TileSpatialPylon te = (TileSpatialPylon) w.getTileEntity(x, y, z); + te.updateStatus(c); + c.getLine().add((te)); + } + } + } + } + + @Override + public boolean isValidTile(final TileEntity te) { + return te instanceof TileSpatialPylon; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/SpatialPylonCluster.java b/src/main/java/appeng/me/cluster/implementations/SpatialPylonCluster.java index fd57add59f9..80545fe4414 100644 --- a/src/main/java/appeng/me/cluster/implementations/SpatialPylonCluster.java +++ b/src/main/java/appeng/me/cluster/implementations/SpatialPylonCluster.java @@ -18,124 +18,100 @@ package appeng.me.cluster.implementations; - import appeng.api.networking.IGridHost; import appeng.api.util.DimensionalCoord; import appeng.me.cluster.IAECluster; import appeng.tile.spatial.TileSpatialPylon; - import java.util.ArrayList; import java.util.Iterator; import java.util.List; - -public class SpatialPylonCluster implements IAECluster -{ - - private final DimensionalCoord min; - private final DimensionalCoord max; - private final List line = new ArrayList(); - private boolean isDestroyed = false; - - private Axis currentAxis = Axis.UNFORMED; - private boolean isValid; - - public SpatialPylonCluster( final DimensionalCoord min, final DimensionalCoord max ) - { - this.min = min.copy(); - this.max = max.copy(); - - if( this.getMin().x != this.getMax().x ) - { - this.setCurrentAxis( Axis.X ); - } - else if( this.getMin().y != this.getMax().y ) - { - this.setCurrentAxis( Axis.Y ); - } - else if( this.getMin().z != this.getMax().z ) - { - this.setCurrentAxis( Axis.Z ); - } - else - { - this.setCurrentAxis( Axis.UNFORMED ); - } - } - - @Override - public void updateStatus( final boolean updateGrid ) - { - for( final TileSpatialPylon r : this.getLine() ) - { - r.recalculateDisplay(); - } - } - - @Override - public void destroy() - { - - if( this.isDestroyed ) - { - return; - } - this.isDestroyed = true; - - for( final TileSpatialPylon r : this.getLine() ) - { - r.updateStatus( null ); - } - } - - @Override - public Iterator getTiles() - { - return (Iterator) this.getLine().iterator(); - } - - public int tileCount() - { - return this.getLine().size(); - } - - public Axis getCurrentAxis() - { - return this.currentAxis; - } - - private void setCurrentAxis( final Axis currentAxis ) - { - this.currentAxis = currentAxis; - } - - public boolean isValid() - { - return this.isValid; - } - - public void setValid( final boolean isValid ) - { - this.isValid = isValid; - } - - public DimensionalCoord getMax() - { - return this.max; - } - - public DimensionalCoord getMin() - { - return this.min; - } - - List getLine() - { - return this.line; - } - - public enum Axis - { - X, Y, Z, UNFORMED - } +public class SpatialPylonCluster implements IAECluster { + + private final DimensionalCoord min; + private final DimensionalCoord max; + private final List line = new ArrayList(); + private boolean isDestroyed = false; + + private Axis currentAxis = Axis.UNFORMED; + private boolean isValid; + + public SpatialPylonCluster(final DimensionalCoord min, final DimensionalCoord max) { + this.min = min.copy(); + this.max = max.copy(); + + if (this.getMin().x != this.getMax().x) { + this.setCurrentAxis(Axis.X); + } else if (this.getMin().y != this.getMax().y) { + this.setCurrentAxis(Axis.Y); + } else if (this.getMin().z != this.getMax().z) { + this.setCurrentAxis(Axis.Z); + } else { + this.setCurrentAxis(Axis.UNFORMED); + } + } + + @Override + public void updateStatus(final boolean updateGrid) { + for (final TileSpatialPylon r : this.getLine()) { + r.recalculateDisplay(); + } + } + + @Override + public void destroy() { + + if (this.isDestroyed) { + return; + } + this.isDestroyed = true; + + for (final TileSpatialPylon r : this.getLine()) { + r.updateStatus(null); + } + } + + @Override + public Iterator getTiles() { + return (Iterator) this.getLine().iterator(); + } + + public int tileCount() { + return this.getLine().size(); + } + + public Axis getCurrentAxis() { + return this.currentAxis; + } + + private void setCurrentAxis(final Axis currentAxis) { + this.currentAxis = currentAxis; + } + + public boolean isValid() { + return this.isValid; + } + + public void setValid(final boolean isValid) { + this.isValid = isValid; + } + + public DimensionalCoord getMax() { + return this.max; + } + + public DimensionalCoord getMin() { + return this.min; + } + + List getLine() { + return this.line; + } + + public enum Axis { + X, + Y, + Z, + UNFORMED + } } diff --git a/src/main/java/appeng/me/energy/EnergyThreshold.java b/src/main/java/appeng/me/energy/EnergyThreshold.java index 3bf4d055224..8204d717428 100644 --- a/src/main/java/appeng/me/energy/EnergyThreshold.java +++ b/src/main/java/appeng/me/energy/EnergyThreshold.java @@ -18,52 +18,41 @@ package appeng.me.energy; - import appeng.api.networking.energy.IEnergyWatcher; import appeng.util.ItemSorters; +public class EnergyThreshold implements Comparable { -public class EnergyThreshold implements Comparable -{ - - private final double Limit; - private final IEnergyWatcher watcher; - private final int hash; + private final double Limit; + private final IEnergyWatcher watcher; + private final int hash; - public EnergyThreshold( final double lim, final IEnergyWatcher wat ) - { - this.Limit = lim; - this.watcher = wat; + public EnergyThreshold(final double lim, final IEnergyWatcher wat) { + this.Limit = lim; + this.watcher = wat; - if( this.getWatcher() != null ) - { - this.hash = this.getWatcher().hashCode() ^ ( (Double) lim ).hashCode(); - } - else - { - this.hash = ( (Double) lim ).hashCode(); - } - } + if (this.getWatcher() != null) { + this.hash = this.getWatcher().hashCode() ^ ((Double) lim).hashCode(); + } else { + this.hash = ((Double) lim).hashCode(); + } + } - @Override - public int hashCode() - { - return this.hash; - } + @Override + public int hashCode() { + return this.hash; + } - @Override - public int compareTo( final EnergyThreshold o ) - { - return ItemSorters.compareDouble( this.getLimit(), o.getLimit() ); - } + @Override + public int compareTo(final EnergyThreshold o) { + return ItemSorters.compareDouble(this.getLimit(), o.getLimit()); + } - double getLimit() - { - return this.Limit; - } + double getLimit() { + return this.Limit; + } - public IEnergyWatcher getWatcher() - { - return this.watcher; - } + public IEnergyWatcher getWatcher() { + return this.watcher; + } } diff --git a/src/main/java/appeng/me/energy/EnergyWatcher.java b/src/main/java/appeng/me/energy/EnergyWatcher.java index 34d93df68b0..70d923ed09b 100644 --- a/src/main/java/appeng/me/energy/EnergyWatcher.java +++ b/src/main/java/appeng/me/energy/EnergyWatcher.java @@ -18,187 +18,156 @@ package appeng.me.energy; - import appeng.api.networking.energy.IEnergyWatcher; import appeng.api.networking.energy.IEnergyWatcherHost; import appeng.me.cache.EnergyGridCache; - import java.util.Collection; import java.util.HashSet; import java.util.Iterator; - /** * Maintain my interests, and a global watch list, they should always be fully synchronized. */ -public class EnergyWatcher implements IEnergyWatcher -{ - - private final EnergyGridCache gsc; - private final IEnergyWatcherHost myObject; - private final HashSet myInterests = new HashSet(); - - public EnergyWatcher( final EnergyGridCache cache, final IEnergyWatcherHost host ) - { - this.gsc = cache; - this.myObject = host; - } - - public void post( final EnergyGridCache energyGridCache ) - { - this.myObject.onThresholdPass( energyGridCache ); - } - - public IEnergyWatcherHost getHost() - { - return this.myObject; - } - - @Override - public int size() - { - return this.myInterests.size(); - } - - @Override - public boolean isEmpty() - { - return this.myInterests.isEmpty(); - } - - @Override - public boolean contains( final Object o ) - { - return this.myInterests.contains( o ); - } - - @Override - public Iterator iterator() - { - return new EnergyWatcherIterator( this, this.myInterests.iterator() ); - } - - @Override - public Object[] toArray() - { - return this.myInterests.toArray(); - } - - @Override - public T[] toArray( final T[] a ) - { - return this.myInterests.toArray( a ); - } - - @Override - public boolean add( final Double e ) - { - if( this.myInterests.contains( e ) ) - { - return false; - } - - final EnergyThreshold eh = new EnergyThreshold( e, this ); - return this.gsc.getInterests().add( eh ) && this.myInterests.add( eh ); - } - - @Override - public boolean remove( final Object o ) - { - final EnergyThreshold eh = new EnergyThreshold( (Double) o, this ); - return this.myInterests.remove( eh ) && this.gsc.getInterests().remove( eh ); - } - - @Override - public boolean containsAll( final Collection c ) - { - return this.myInterests.containsAll( c ); - } - - @Override - public boolean addAll( final Collection c ) - { - boolean didChange = false; - - for( final Double o : c ) - { - didChange = this.add( o ) || didChange; - } - - return didChange; - } - - @Override - public boolean removeAll( final Collection c ) - { - boolean didSomething = false; - for( final Object o : c ) - { - didSomething = this.remove( o ) || didSomething; - } - return didSomething; - } - - @Override - public boolean retainAll( final Collection c ) - { - boolean changed = false; - final Iterator i = this.iterator(); - - while( i.hasNext() ) - { - if( !c.contains( i.next() ) ) - { - i.remove(); - changed = true; - } - } - - return changed; - } - - @Override - public void clear() - { - final Iterator i = this.myInterests.iterator(); - while( i.hasNext() ) - { - this.gsc.getInterests().remove( i.next() ); - i.remove(); - } - } - - private class EnergyWatcherIterator implements Iterator - { - - private final EnergyWatcher watcher; - private final Iterator interestIterator; - private EnergyThreshold myLast; - - public EnergyWatcherIterator( final EnergyWatcher parent, final Iterator i ) - { - this.watcher = parent; - this.interestIterator = i; - } - - @Override - public boolean hasNext() - { - return this.interestIterator.hasNext(); - } - - @Override - public Double next() - { - this.myLast = this.interestIterator.next(); - return this.myLast.getLimit(); - } - - @Override - public void remove() - { - EnergyWatcher.this.gsc.getInterests().remove( this.myLast ); - this.interestIterator.remove(); - } - } +public class EnergyWatcher implements IEnergyWatcher { + + private final EnergyGridCache gsc; + private final IEnergyWatcherHost myObject; + private final HashSet myInterests = new HashSet(); + + public EnergyWatcher(final EnergyGridCache cache, final IEnergyWatcherHost host) { + this.gsc = cache; + this.myObject = host; + } + + public void post(final EnergyGridCache energyGridCache) { + this.myObject.onThresholdPass(energyGridCache); + } + + public IEnergyWatcherHost getHost() { + return this.myObject; + } + + @Override + public int size() { + return this.myInterests.size(); + } + + @Override + public boolean isEmpty() { + return this.myInterests.isEmpty(); + } + + @Override + public boolean contains(final Object o) { + return this.myInterests.contains(o); + } + + @Override + public Iterator iterator() { + return new EnergyWatcherIterator(this, this.myInterests.iterator()); + } + + @Override + public Object[] toArray() { + return this.myInterests.toArray(); + } + + @Override + public T[] toArray(final T[] a) { + return this.myInterests.toArray(a); + } + + @Override + public boolean add(final Double e) { + if (this.myInterests.contains(e)) { + return false; + } + + final EnergyThreshold eh = new EnergyThreshold(e, this); + return this.gsc.getInterests().add(eh) && this.myInterests.add(eh); + } + + @Override + public boolean remove(final Object o) { + final EnergyThreshold eh = new EnergyThreshold((Double) o, this); + return this.myInterests.remove(eh) && this.gsc.getInterests().remove(eh); + } + + @Override + public boolean containsAll(final Collection c) { + return this.myInterests.containsAll(c); + } + + @Override + public boolean addAll(final Collection c) { + boolean didChange = false; + + for (final Double o : c) { + didChange = this.add(o) || didChange; + } + + return didChange; + } + + @Override + public boolean removeAll(final Collection c) { + boolean didSomething = false; + for (final Object o : c) { + didSomething = this.remove(o) || didSomething; + } + return didSomething; + } + + @Override + public boolean retainAll(final Collection c) { + boolean changed = false; + final Iterator i = this.iterator(); + + while (i.hasNext()) { + if (!c.contains(i.next())) { + i.remove(); + changed = true; + } + } + + return changed; + } + + @Override + public void clear() { + final Iterator i = this.myInterests.iterator(); + while (i.hasNext()) { + this.gsc.getInterests().remove(i.next()); + i.remove(); + } + } + + private class EnergyWatcherIterator implements Iterator { + + private final EnergyWatcher watcher; + private final Iterator interestIterator; + private EnergyThreshold myLast; + + public EnergyWatcherIterator(final EnergyWatcher parent, final Iterator i) { + this.watcher = parent; + this.interestIterator = i; + } + + @Override + public boolean hasNext() { + return this.interestIterator.hasNext(); + } + + @Override + public Double next() { + this.myLast = this.interestIterator.next(); + return this.myLast.getLimit(); + } + + @Override + public void remove() { + EnergyWatcher.this.gsc.getInterests().remove(this.myLast); + this.interestIterator.remove(); + } + } } diff --git a/src/main/java/appeng/me/helpers/AENetworkProxy.java b/src/main/java/appeng/me/helpers/AENetworkProxy.java index 1b06f5b1bea..4e8cccfce78 100644 --- a/src/main/java/appeng/me/helpers/AENetworkProxy.java +++ b/src/main/java/appeng/me/helpers/AENetworkProxy.java @@ -18,7 +18,6 @@ package appeng.me.helpers; - import appeng.api.AEApi; import appeng.api.networking.*; import appeng.api.networking.crafting.ICraftingGrid; @@ -39,405 +38,329 @@ import appeng.tile.AEBaseTile; import appeng.util.Platform; import com.mojang.authlib.GameProfile; +import java.util.Collections; +import java.util.EnumSet; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; - - -public class AENetworkProxy implements IGridBlock -{ - - private final IGridProxyable gp; - private final boolean worldNode; - private final String nbtName; // name - private AEColor myColor = AEColor.Transparent; - private NBTTagCompound data = null; // input - private ItemStack myRepInstance; - private boolean isReady = false; - private IGridNode node = null; - private EnumSet validSides; - private EnumSet flags = EnumSet.noneOf( GridFlags.class ); - private double idleDraw = 1.0; - private EntityPlayer owner; - - public AENetworkProxy( final IGridProxyable te, final String nbtName, final ItemStack visual, final boolean inWorld ) - { - this.gp = te; - this.nbtName = nbtName; - this.worldNode = inWorld; - this.myRepInstance = visual; - this.validSides = EnumSet.allOf( ForgeDirection.class ); - } - - public void setVisualRepresentation( final ItemStack is ) - { - this.myRepInstance = is; - } - - public void writeToNBT( final NBTTagCompound tag ) - { - if( this.node != null ) - { - this.node.saveToNBT( this.nbtName, tag ); - } - } - - public void setValidSides( final EnumSet validSides ) - { - this.validSides = validSides; - if( this.node != null ) - { - this.node.updateState(); - } - } - - public void validate() - { - if( this.gp instanceof AEBaseTile ) - { - TickHandler.INSTANCE.addInit( (AEBaseTile) this.gp ); - } - } - - public void onChunkUnload() - { - this.isReady = false; - this.invalidate(); - } - - public void invalidate() - { - this.isReady = false; - if( this.node != null ) - { - this.node.destroy(); - this.node = null; - } - } - - public void onReady() - { - this.isReady = true; - - // send orientation based directionality to the node. - if( this.gp instanceof IOrientable ) - { - final IOrientable ori = (IOrientable) this.gp; - if( ori.canBeRotated() ) - { - ori.setOrientation( ori.getForward(), ori.getUp() ); - } - } - - this.getNode(); - } - - public IGridNode getNode() - { - if( this.node == null && Platform.isServer() && this.isReady ) - { - this.node = AEApi.instance().createGridNode( this ); - this.readFromNBT( this.data ); - this.node.updateState(); - } - - return this.node; - } - - public void readFromNBT( final NBTTagCompound tag ) - { - this.data = tag; - if( this.node != null && this.data != null ) - { - this.node.loadFromNBT( this.nbtName, this.data ); - this.data = null; - } - else if( this.node != null && this.owner != null ) - { - final GameProfile profile = this.owner.getGameProfile(); - final int playerID = WorldData.instance().playerData().getPlayerID( profile ); - - this.node.setPlayerID( playerID ); - this.owner = null; - } - } - - public IPathingGrid getPath() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - final IPathingGrid pg = grid.getCache( IPathingGrid.class ); - if( pg == null ) - { - throw new GridAccessException(); - } - return pg; - } - - /** - * short cut! - * - * @return grid of node - * @throws GridAccessException of node or grid is null - */ - public IGrid getGrid() throws GridAccessException - { - if( this.node == null ) - { - throw new GridAccessException(); - } - final IGrid grid = this.node.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - return grid; - } - - public ITickManager getTick() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - final ITickManager pg = grid.getCache( ITickManager.class ); - if( pg == null ) - { - throw new GridAccessException(); - } - return pg; - } - - public IStorageGrid getStorage() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - - final IStorageGrid pg = grid.getCache( IStorageGrid.class ); - - if( pg == null ) - { - throw new GridAccessException(); - } - - return pg; - } - - public P2PCache getP2P() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - - final P2PCache pg = grid.getCache( P2PCache.class ); - - if( pg == null ) - { - throw new GridAccessException(); - } - - return pg; - } - - public ISecurityGrid getSecurity() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - - final ISecurityGrid sg = grid.getCache( ISecurityGrid.class ); - - if( sg == null ) - { - throw new GridAccessException(); - } - - return sg; - } - - public ICraftingGrid getCrafting() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - - final ICraftingGrid sg = grid.getCache( ICraftingGrid.class ); - - if( sg == null ) - { - throw new GridAccessException(); - } - - return sg; - } - - @Override - public double getIdlePowerUsage() - { - return this.idleDraw; - } - - @Override - public EnumSet getFlags() - { - return this.flags; - } - - @Override - public boolean isWorldAccessible() - { - return this.worldNode; - } - - @Override - public DimensionalCoord getLocation() - { - return this.gp.getLocation(); - } - - @Override - public AEColor getGridColor() - { - return this.getColor(); - } - - @Override - public void onGridNotification( final GridNotification notification ) - { - if( this.gp instanceof PartCable ) - { - ( (PartCable) this.gp ).markForUpdate(); - } - } - - @Override - public void setNetworkStatus( final IGrid grid, final int channelsInUse ) - { - - } - - @Override - public EnumSet getConnectableSides() - { - return this.validSides; - } - - @Override - public IGridHost getMachine() - { - return this.gp; - } - - @Override - public void gridChanged() - { - this.gp.gridChanged(); - } - - @Override - public ItemStack getMachineRepresentation() - { - return this.myRepInstance; - } - - public void setFlags( final GridFlags... requireChannel ) - { - final EnumSet flags = EnumSet.noneOf( GridFlags.class ); - - Collections.addAll( flags, requireChannel ); - - this.flags = flags; - } - - public void setIdlePowerUsage( final double idle ) - { - this.idleDraw = idle; - - if( this.node != null ) - { - try - { - final IGrid g = this.getGrid(); - g.postEvent( new MENetworkPowerIdleChange( this.node ) ); - } - catch( final GridAccessException e ) - { - // not ready for this yet.. - } - } - } - - public boolean isReady() - { - return this.isReady; - } - - public boolean isActive() - { - if( this.node == null ) - { - return false; - } - - return this.node.isActive(); - } - - public boolean isPowered() - { - try - { - return this.getEnergy().isNetworkPowered(); - } - catch( final GridAccessException e ) - { - return false; - } - } - - public IEnergyGrid getEnergy() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - final IEnergyGrid eg = grid.getCache( IEnergyGrid.class ); - if( eg == null ) - { - throw new GridAccessException(); - } - return eg; - } - - public void setOwner( final EntityPlayer player ) - { - this.owner = player; - } - - public AEColor getColor() - { - return this.myColor; - } - - public void setColor( final AEColor myColor ) - { - this.myColor = myColor; - } +public class AENetworkProxy implements IGridBlock { + + private final IGridProxyable gp; + private final boolean worldNode; + private final String nbtName; // name + private AEColor myColor = AEColor.Transparent; + private NBTTagCompound data = null; // input + private ItemStack myRepInstance; + private boolean isReady = false; + private IGridNode node = null; + private EnumSet validSides; + private EnumSet flags = EnumSet.noneOf(GridFlags.class); + private double idleDraw = 1.0; + private EntityPlayer owner; + + public AENetworkProxy( + final IGridProxyable te, final String nbtName, final ItemStack visual, final boolean inWorld) { + this.gp = te; + this.nbtName = nbtName; + this.worldNode = inWorld; + this.myRepInstance = visual; + this.validSides = EnumSet.allOf(ForgeDirection.class); + } + + public void setVisualRepresentation(final ItemStack is) { + this.myRepInstance = is; + } + + public void writeToNBT(final NBTTagCompound tag) { + if (this.node != null) { + this.node.saveToNBT(this.nbtName, tag); + } + } + + public void setValidSides(final EnumSet validSides) { + this.validSides = validSides; + if (this.node != null) { + this.node.updateState(); + } + } + + public void validate() { + if (this.gp instanceof AEBaseTile) { + TickHandler.INSTANCE.addInit((AEBaseTile) this.gp); + } + } + + public void onChunkUnload() { + this.isReady = false; + this.invalidate(); + } + + public void invalidate() { + this.isReady = false; + if (this.node != null) { + this.node.destroy(); + this.node = null; + } + } + + public void onReady() { + this.isReady = true; + + // send orientation based directionality to the node. + if (this.gp instanceof IOrientable) { + final IOrientable ori = (IOrientable) this.gp; + if (ori.canBeRotated()) { + ori.setOrientation(ori.getForward(), ori.getUp()); + } + } + + this.getNode(); + } + + public IGridNode getNode() { + if (this.node == null && Platform.isServer() && this.isReady) { + this.node = AEApi.instance().createGridNode(this); + this.readFromNBT(this.data); + this.node.updateState(); + } + + return this.node; + } + + public void readFromNBT(final NBTTagCompound tag) { + this.data = tag; + if (this.node != null && this.data != null) { + this.node.loadFromNBT(this.nbtName, this.data); + this.data = null; + } else if (this.node != null && this.owner != null) { + final GameProfile profile = this.owner.getGameProfile(); + final int playerID = WorldData.instance().playerData().getPlayerID(profile); + + this.node.setPlayerID(playerID); + this.owner = null; + } + } + + public IPathingGrid getPath() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + final IPathingGrid pg = grid.getCache(IPathingGrid.class); + if (pg == null) { + throw new GridAccessException(); + } + return pg; + } + + /** + * short cut! + * + * @return grid of node + * @throws GridAccessException of node or grid is null + */ + public IGrid getGrid() throws GridAccessException { + if (this.node == null) { + throw new GridAccessException(); + } + final IGrid grid = this.node.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + return grid; + } + + public ITickManager getTick() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + final ITickManager pg = grid.getCache(ITickManager.class); + if (pg == null) { + throw new GridAccessException(); + } + return pg; + } + + public IStorageGrid getStorage() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + + final IStorageGrid pg = grid.getCache(IStorageGrid.class); + + if (pg == null) { + throw new GridAccessException(); + } + + return pg; + } + + public P2PCache getP2P() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + + final P2PCache pg = grid.getCache(P2PCache.class); + + if (pg == null) { + throw new GridAccessException(); + } + + return pg; + } + + public ISecurityGrid getSecurity() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + + final ISecurityGrid sg = grid.getCache(ISecurityGrid.class); + + if (sg == null) { + throw new GridAccessException(); + } + + return sg; + } + + public ICraftingGrid getCrafting() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + + final ICraftingGrid sg = grid.getCache(ICraftingGrid.class); + + if (sg == null) { + throw new GridAccessException(); + } + + return sg; + } + + @Override + public double getIdlePowerUsage() { + return this.idleDraw; + } + + @Override + public EnumSet getFlags() { + return this.flags; + } + + @Override + public boolean isWorldAccessible() { + return this.worldNode; + } + + @Override + public DimensionalCoord getLocation() { + return this.gp.getLocation(); + } + + @Override + public AEColor getGridColor() { + return this.getColor(); + } + + @Override + public void onGridNotification(final GridNotification notification) { + if (this.gp instanceof PartCable) { + ((PartCable) this.gp).markForUpdate(); + } + } + + @Override + public void setNetworkStatus(final IGrid grid, final int channelsInUse) {} + + @Override + public EnumSet getConnectableSides() { + return this.validSides; + } + + @Override + public IGridHost getMachine() { + return this.gp; + } + + @Override + public void gridChanged() { + this.gp.gridChanged(); + } + + @Override + public ItemStack getMachineRepresentation() { + return this.myRepInstance; + } + + public void setFlags(final GridFlags... requireChannel) { + final EnumSet flags = EnumSet.noneOf(GridFlags.class); + + Collections.addAll(flags, requireChannel); + + this.flags = flags; + } + + public void setIdlePowerUsage(final double idle) { + this.idleDraw = idle; + + if (this.node != null) { + try { + final IGrid g = this.getGrid(); + g.postEvent(new MENetworkPowerIdleChange(this.node)); + } catch (final GridAccessException e) { + // not ready for this yet.. + } + } + } + + public boolean isReady() { + return this.isReady; + } + + public boolean isActive() { + if (this.node == null) { + return false; + } + + return this.node.isActive(); + } + + public boolean isPowered() { + try { + return this.getEnergy().isNetworkPowered(); + } catch (final GridAccessException e) { + return false; + } + } + + public IEnergyGrid getEnergy() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + final IEnergyGrid eg = grid.getCache(IEnergyGrid.class); + if (eg == null) { + throw new GridAccessException(); + } + return eg; + } + + public void setOwner(final EntityPlayer player) { + this.owner = player; + } + + public AEColor getColor() { + return this.myColor; + } + + public void setColor(final AEColor myColor) { + this.myColor = myColor; + } } diff --git a/src/main/java/appeng/me/helpers/AENetworkProxyMultiblock.java b/src/main/java/appeng/me/helpers/AENetworkProxyMultiblock.java index 6272ef994a5..1574269455e 100644 --- a/src/main/java/appeng/me/helpers/AENetworkProxyMultiblock.java +++ b/src/main/java/appeng/me/helpers/AENetworkProxyMultiblock.java @@ -18,39 +18,32 @@ package appeng.me.helpers; - import appeng.api.networking.IGridMultiblock; import appeng.api.networking.IGridNode; import appeng.me.cluster.IAECluster; import appeng.me.cluster.IAEMultiBlock; import appeng.util.iterators.ChainedIterator; import appeng.util.iterators.ProxyNodeIterator; -import net.minecraft.item.ItemStack; - import java.util.Iterator; +import net.minecraft.item.ItemStack; +public class AENetworkProxyMultiblock extends AENetworkProxy implements IGridMultiblock { -public class AENetworkProxyMultiblock extends AENetworkProxy implements IGridMultiblock -{ - - public AENetworkProxyMultiblock( final IGridProxyable te, final String nbtName, final ItemStack itemStack, final boolean inWorld ) - { - super( te, nbtName, itemStack, inWorld ); - } + public AENetworkProxyMultiblock( + final IGridProxyable te, final String nbtName, final ItemStack itemStack, final boolean inWorld) { + super(te, nbtName, itemStack, inWorld); + } - @Override - public Iterator getMultiblockNodes() - { - if( this.getCluster() == null ) - { - return new ChainedIterator(); - } + @Override + public Iterator getMultiblockNodes() { + if (this.getCluster() == null) { + return new ChainedIterator(); + } - return new ProxyNodeIterator( this.getCluster().getTiles() ); - } + return new ProxyNodeIterator(this.getCluster().getTiles()); + } - private IAECluster getCluster() - { - return ( (IAEMultiBlock) this.getMachine() ).getCluster(); - } + private IAECluster getCluster() { + return ((IAEMultiBlock) this.getMachine()).getCluster(); + } } diff --git a/src/main/java/appeng/me/helpers/ChannelPowerSrc.java b/src/main/java/appeng/me/helpers/ChannelPowerSrc.java index 8ca76443cb4..2b088aaa2e9 100644 --- a/src/main/java/appeng/me/helpers/ChannelPowerSrc.java +++ b/src/main/java/appeng/me/helpers/ChannelPowerSrc.java @@ -18,32 +18,26 @@ package appeng.me.helpers; - import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; import appeng.api.networking.IGridNode; import appeng.api.networking.energy.IEnergySource; +public class ChannelPowerSrc implements IEnergySource { -public class ChannelPowerSrc implements IEnergySource -{ - - private final IGridNode node; - private final IEnergySource realSrc; + private final IGridNode node; + private final IEnergySource realSrc; - public ChannelPowerSrc( final IGridNode networkNode, final IEnergySource src ) - { - this.node = networkNode; - this.realSrc = src; - } + public ChannelPowerSrc(final IGridNode networkNode, final IEnergySource src) { + this.node = networkNode; + this.realSrc = src; + } - @Override - public double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier ) - { - if( this.node.isActive() ) - { - return this.realSrc.extractAEPower( amt, mode, usePowerMultiplier ); - } - return 0.0; - } + @Override + public double extractAEPower(final double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier) { + if (this.node.isActive()) { + return this.realSrc.extractAEPower(amt, mode, usePowerMultiplier); + } + return 0.0; + } } diff --git a/src/main/java/appeng/me/helpers/GenericInterestManager.java b/src/main/java/appeng/me/helpers/GenericInterestManager.java index 4c99e54b468..54a76f6ae85 100644 --- a/src/main/java/appeng/me/helpers/GenericInterestManager.java +++ b/src/main/java/appeng/me/helpers/GenericInterestManager.java @@ -18,107 +18,82 @@ package appeng.me.helpers; - import appeng.api.storage.data.IAEStack; import com.google.common.collect.Multimap; - import java.util.Collection; import java.util.LinkedList; - -public class GenericInterestManager -{ - - private final Multimap container; - private LinkedList transactions = null; - private int transDepth = 0; - - public GenericInterestManager( final Multimap interests ) - { - this.container = interests; - } - - public void enableTransactions() - { - if( this.transDepth == 0 ) - { - this.transactions = new LinkedList(); - } - - this.transDepth++; - } - - public void disableTransactions() - { - this.transDepth--; - - if( this.transDepth == 0 ) - { - final LinkedList myActions = this.transactions; - this.transactions = null; - - for( final SavedTransactions t : myActions ) - { - if( t.put ) - { - this.put( t.stack, t.iw ); - } - else - { - this.remove( t.stack, t.iw ); - } - } - } - } - - public boolean put( final IAEStack stack, final T iw ) - { - if( this.transactions != null ) - { - this.transactions.add( new SavedTransactions( true, stack, iw ) ); - return true; - } - else - { - return this.container.put( stack, iw ); - } - } - - public boolean remove( final IAEStack stack, final T iw ) - { - if( this.transactions != null ) - { - this.transactions.add( new SavedTransactions( true, stack, iw ) ); - return true; - } - else - { - return this.container.remove( stack, iw ); - } - } - - public boolean containsKey( final IAEStack stack ) - { - return this.container.containsKey( stack ); - } - - public Collection get( final IAEStack stack ) - { - return this.container.get( stack ); - } - - private class SavedTransactions - { - - private final boolean put; - private final IAEStack stack; - private final T iw; - - public SavedTransactions( final boolean putOperation, final IAEStack myStack, final T watcher ) - { - this.put = putOperation; - this.stack = myStack; - this.iw = watcher; - } - } +public class GenericInterestManager { + + private final Multimap container; + private LinkedList transactions = null; + private int transDepth = 0; + + public GenericInterestManager(final Multimap interests) { + this.container = interests; + } + + public void enableTransactions() { + if (this.transDepth == 0) { + this.transactions = new LinkedList(); + } + + this.transDepth++; + } + + public void disableTransactions() { + this.transDepth--; + + if (this.transDepth == 0) { + final LinkedList myActions = this.transactions; + this.transactions = null; + + for (final SavedTransactions t : myActions) { + if (t.put) { + this.put(t.stack, t.iw); + } else { + this.remove(t.stack, t.iw); + } + } + } + } + + public boolean put(final IAEStack stack, final T iw) { + if (this.transactions != null) { + this.transactions.add(new SavedTransactions(true, stack, iw)); + return true; + } else { + return this.container.put(stack, iw); + } + } + + public boolean remove(final IAEStack stack, final T iw) { + if (this.transactions != null) { + this.transactions.add(new SavedTransactions(true, stack, iw)); + return true; + } else { + return this.container.remove(stack, iw); + } + } + + public boolean containsKey(final IAEStack stack) { + return this.container.containsKey(stack); + } + + public Collection get(final IAEStack stack) { + return this.container.get(stack); + } + + private class SavedTransactions { + + private final boolean put; + private final IAEStack stack; + private final T iw; + + public SavedTransactions(final boolean putOperation, final IAEStack myStack, final T watcher) { + this.put = putOperation; + this.stack = myStack; + this.iw = watcher; + } + } } diff --git a/src/main/java/appeng/me/helpers/IGridProxyable.java b/src/main/java/appeng/me/helpers/IGridProxyable.java index 916a5659aff..4f47bdb9109 100644 --- a/src/main/java/appeng/me/helpers/IGridProxyable.java +++ b/src/main/java/appeng/me/helpers/IGridProxyable.java @@ -18,17 +18,14 @@ package appeng.me.helpers; - import appeng.api.networking.IGridHost; import appeng.api.util.DimensionalCoord; +public interface IGridProxyable extends IGridHost { -public interface IGridProxyable extends IGridHost -{ - - AENetworkProxy getProxy(); + AENetworkProxy getProxy(); - DimensionalCoord getLocation(); + DimensionalCoord getLocation(); - void gridChanged(); + void gridChanged(); } diff --git a/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java b/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java index 8a0afab1fd1..18534b576b6 100644 --- a/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java +++ b/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java @@ -18,40 +18,34 @@ package appeng.me.pathfinding; - import appeng.api.networking.IGridConnection; import appeng.api.networking.IGridConnectionVisitor; import appeng.api.networking.IGridNode; import appeng.me.GridConnection; import appeng.me.GridNode; - -public class AdHocChannelUpdater implements IGridConnectionVisitor -{ - - private final int usedChannels; - - public AdHocChannelUpdater( final int used ) - { - this.usedChannels = used; - } - - @Override - public boolean visitNode( final IGridNode n ) - { - final GridNode gn = (GridNode) n; - gn.setControllerRoute( null, true ); - gn.incrementChannelCount( this.usedChannels ); - gn.finalizeChannels(); - return true; - } - - @Override - public void visitConnection( final IGridConnection gcc ) - { - final GridConnection gc = (GridConnection) gcc; - gc.setControllerRoute( null, true ); - gc.incrementChannelCount( this.usedChannels ); - gc.finalizeChannels(); - } +public class AdHocChannelUpdater implements IGridConnectionVisitor { + + private final int usedChannels; + + public AdHocChannelUpdater(final int used) { + this.usedChannels = used; + } + + @Override + public boolean visitNode(final IGridNode n) { + final GridNode gn = (GridNode) n; + gn.setControllerRoute(null, true); + gn.incrementChannelCount(this.usedChannels); + gn.finalizeChannels(); + return true; + } + + @Override + public void visitConnection(final IGridConnection gcc) { + final GridConnection gc = (GridConnection) gcc; + gc.setControllerRoute(null, true); + gc.incrementChannelCount(this.usedChannels); + gc.finalizeChannels(); + } } diff --git a/src/main/java/appeng/me/pathfinding/BackbonePathSegment.java b/src/main/java/appeng/me/pathfinding/BackbonePathSegment.java index 70e5898cb74..18be135c086 100644 --- a/src/main/java/appeng/me/pathfinding/BackbonePathSegment.java +++ b/src/main/java/appeng/me/pathfinding/BackbonePathSegment.java @@ -1,57 +1,47 @@ package appeng.me.pathfinding; import appeng.me.cache.PathGridCache; - import java.util.*; -public class BackbonePathSegment extends PathSegment -{ +public class BackbonePathSegment extends PathSegment { IPathItem startNode; private Set controllerRoutes = new HashSet<>(); Map> neighbours = new HashMap<>(); - public BackbonePathSegment(IPathItem node, final PathGridCache myPGC, final Set semiOpen, final Set closed ) - { + public BackbonePathSegment( + IPathItem node, final PathGridCache myPGC, final Set semiOpen, final Set closed) { super(myPGC, new LinkedList(), semiOpen, closed); startNode = node; } - void addControllerRoute(IPathItem pi) - { + void addControllerRoute(IPathItem pi) { controllerRoutes.add(pi); } - void addPathToNeighbour(BackbonePathSegment nb, IPathItem connection) - { + void addPathToNeighbour(BackbonePathSegment nb, IPathItem connection) { List path = new LinkedList<>(); - for (IPathItem pi = connection; pi != null && pi != nb.startNode; pi = pi.getControllerRoute()) - path.add(0, pi); + for (IPathItem pi = connection; pi != null && pi != nb.startNode; pi = pi.getControllerRoute()) path.add(0, pi); neighbours.put(nb, path); } - public void selectControllerRoute() - { + public void selectControllerRoute() { startNode.setControllerRoute(controllerRoutes.iterator().next(), false); } - public boolean switchControllerRoute() - { - if (controllerRoutes.isEmpty() || startNode.getControllerRoute() == null) - return false; - if (startNode.getControllerRoute().getControllerRoute() != null && startNode.getControllerRoute().getControllerRoute().canSupportMoreChannels()) - return true; + public boolean switchControllerRoute() { + if (controllerRoutes.isEmpty() || startNode.getControllerRoute() == null) return false; + if (startNode.getControllerRoute().getControllerRoute() != null + && startNode.getControllerRoute().getControllerRoute().canSupportMoreChannels()) return true; controllerRoutes.remove(startNode.getControllerRoute()); - if (controllerRoutes.isEmpty()) - return false; + if (controllerRoutes.isEmpty()) return false; startNode.setControllerRoute(controllerRoutes.iterator().next(), false); return true; } + void removeNeigbour(BackbonePathSegment bs) { List pathToRemoved = neighbours.get(bs); - for (BackbonePathSegment nb : bs.neighbours.keySet()) - { - if (nb == this || neighbours.containsKey(nb)) - continue; + for (BackbonePathSegment nb : bs.neighbours.keySet()) { + if (nb == this || neighbours.containsKey(nb)) continue; List path = bs.neighbours.get(nb); path.addAll(pathToRemoved); neighbours.put(nb, path); @@ -59,40 +49,33 @@ void removeNeigbour(BackbonePathSegment bs) { neighbours.remove(bs); } - public void transferToNeighbours() - { - if (neighbours.isEmpty()) - return; - for (BackbonePathSegment nb : neighbours.keySet()) - nb.removeNeigbour(this); + + public void transferToNeighbours() { + if (neighbours.isEmpty()) return; + for (BackbonePathSegment nb : neighbours.keySet()) nb.removeNeigbour(this); BackbonePathSegment nb = neighbours.keySet().iterator().next(); List path = neighbours.get(nb); IPathItem controller = nb.startNode; - for (IPathItem pi : path) - { + for (IPathItem pi : path) { pi.setControllerRoute(controller, false); controller = pi; } startNode.setControllerRoute(controller, false); } - private void reset() - { + private void reset() { open.add(startNode); closed.add(startNode); closed.addAll(controllerRoutes); } - static public void reset(Map backbone) - { - if (backbone.isEmpty()) - return; + public static void reset(Map backbone) { + if (backbone.isEmpty()) return; backbone.values().iterator().next().closed.clear(); - for (BackbonePathSegment bs: backbone.values()) - bs.reset(); + for (BackbonePathSegment bs : backbone.values()) bs.reset(); } - public boolean isValid() - { - return !controllerRoutes.isEmpty(); + + public boolean isValid() { + return !controllerRoutes.isEmpty(); } } diff --git a/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java b/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java index f6bb4ff7caf..b2b581bd7e0 100644 --- a/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java +++ b/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java @@ -18,29 +18,24 @@ package appeng.me.pathfinding; - import appeng.api.networking.IGridConnection; import appeng.api.networking.IGridConnectionVisitor; import appeng.api.networking.IGridNode; import appeng.me.GridConnection; import appeng.me.GridNode; +public class ControllerChannelUpdater implements IGridConnectionVisitor { -public class ControllerChannelUpdater implements IGridConnectionVisitor -{ - - @Override - public boolean visitNode( final IGridNode n ) - { - final GridNode gn = (GridNode) n; - gn.finalizeChannels(); - return true; - } + @Override + public boolean visitNode(final IGridNode n) { + final GridNode gn = (GridNode) n; + gn.finalizeChannels(); + return true; + } - @Override - public void visitConnection( final IGridConnection gcc ) - { - final GridConnection gc = (GridConnection) gcc; - gc.finalizeChannels(); - } + @Override + public void visitConnection(final IGridConnection gcc) { + final GridConnection gc = (GridConnection) gcc; + gc.finalizeChannels(); + } } diff --git a/src/main/java/appeng/me/pathfinding/ControllerValidator.java b/src/main/java/appeng/me/pathfinding/ControllerValidator.java index 7b7cb4c088f..f22bad2ba50 100644 --- a/src/main/java/appeng/me/pathfinding/ControllerValidator.java +++ b/src/main/java/appeng/me/pathfinding/ControllerValidator.java @@ -18,83 +18,70 @@ package appeng.me.pathfinding; - import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.networking.IGridVisitor; import appeng.tile.networking.TileController; - -public class ControllerValidator implements IGridVisitor -{ - - private boolean isValid = true; - private int found = 0; - private int minX; - private int minY; - private int minZ; - private int maxX; - private int maxY; - private int maxZ; - - public ControllerValidator( final int x, final int y, final int z ) - { - this.minX = x; - this.minY = y; - this.minZ = z; - this.maxX = x; - this.maxY = y; - this.maxZ = z; - } - - @Override - public boolean visitNode( final IGridNode n ) - { - final IGridHost host = n.getMachine(); - if( this.isValid() && host instanceof TileController ) - { - final TileController c = (TileController) host; - - this.minX = Math.min( c.xCoord, this.minX ); - this.maxX = Math.max( c.xCoord, this.maxX ); - this.minY = Math.min( c.yCoord, this.minY ); - this.maxY = Math.max( c.yCoord, this.maxY ); - this.minZ = Math.min( c.zCoord, this.minZ ); - this.maxZ = Math.max( c.zCoord, this.maxZ ); - - if( this.maxX - this.minX < 7 && this.maxY - this.minY < 7 && this.maxZ - this.minZ < 7 ) - { - this.setFound( this.getFound() + 1 ); - return true; - } - - this.setValid( false ); - } - else - { - return false; - } - - return this.isValid(); - } - - public boolean isValid() - { - return this.isValid; - } - - private void setValid( final boolean isValid ) - { - this.isValid = isValid; - } - - public int getFound() - { - return this.found; - } - - private void setFound( final int found ) - { - this.found = found; - } +public class ControllerValidator implements IGridVisitor { + + private boolean isValid = true; + private int found = 0; + private int minX; + private int minY; + private int minZ; + private int maxX; + private int maxY; + private int maxZ; + + public ControllerValidator(final int x, final int y, final int z) { + this.minX = x; + this.minY = y; + this.minZ = z; + this.maxX = x; + this.maxY = y; + this.maxZ = z; + } + + @Override + public boolean visitNode(final IGridNode n) { + final IGridHost host = n.getMachine(); + if (this.isValid() && host instanceof TileController) { + final TileController c = (TileController) host; + + this.minX = Math.min(c.xCoord, this.minX); + this.maxX = Math.max(c.xCoord, this.maxX); + this.minY = Math.min(c.yCoord, this.minY); + this.maxY = Math.max(c.yCoord, this.maxY); + this.minZ = Math.min(c.zCoord, this.minZ); + this.maxZ = Math.max(c.zCoord, this.maxZ); + + if (this.maxX - this.minX < 7 && this.maxY - this.minY < 7 && this.maxZ - this.minZ < 7) { + this.setFound(this.getFound() + 1); + return true; + } + + this.setValid(false); + } else { + return false; + } + + return this.isValid(); + } + + public boolean isValid() { + return this.isValid; + } + + private void setValid(final boolean isValid) { + this.isValid = isValid; + } + + public int getFound() { + return this.found; + } + + private void setFound(final int found) { + this.found = found; + } } diff --git a/src/main/java/appeng/me/pathfinding/IPathItem.java b/src/main/java/appeng/me/pathfinding/IPathItem.java index e05e8037ee6..08591122a44 100644 --- a/src/main/java/appeng/me/pathfinding/IPathItem.java +++ b/src/main/java/appeng/me/pathfinding/IPathItem.java @@ -18,44 +18,40 @@ package appeng.me.pathfinding; - import appeng.api.networking.GridFlags; import appeng.api.util.IReadOnlyCollection; - import java.util.EnumSet; +public interface IPathItem { -public interface IPathItem -{ - - IPathItem getControllerRoute(); + IPathItem getControllerRoute(); - void setControllerRoute( IPathItem fast, boolean zeroOut ); + void setControllerRoute(IPathItem fast, boolean zeroOut); - /** - * used to determine if the finder can continue. - */ - boolean canSupportMoreChannels(); + /** + * used to determine if the finder can continue. + */ + boolean canSupportMoreChannels(); - /** - * find possible choices for other pathing. - */ - IReadOnlyCollection getPossibleOptions(); + /** + * find possible choices for other pathing. + */ + IReadOnlyCollection getPossibleOptions(); - /** - * add one to the channel count, this is mostly for cables. - */ - void incrementChannelCount( int usedChannels ); + /** + * add one to the channel count, this is mostly for cables. + */ + void incrementChannelCount(int usedChannels); - /** - * get the grid flags for this IPathItem. - * - * @return the flag set. - */ - EnumSet getFlags(); + /** + * get the grid flags for this IPathItem. + * + * @return the flag set. + */ + EnumSet getFlags(); - /** - * channels are done, wrap it up. - */ - void finalizeChannels(); + /** + * channels are done, wrap it up. + */ + void finalizeChannels(); } diff --git a/src/main/java/appeng/me/pathfinding/PathSegment.java b/src/main/java/appeng/me/pathfinding/PathSegment.java index 561ca05fa59..1ee3a60466b 100644 --- a/src/main/java/appeng/me/pathfinding/PathSegment.java +++ b/src/main/java/appeng/me/pathfinding/PathSegment.java @@ -18,134 +18,112 @@ package appeng.me.pathfinding; - import appeng.api.networking.GridFlags; import appeng.api.networking.IGridMultiblock; import appeng.api.networking.IGridNode; import appeng.me.cache.PathGridCache; - import java.util.*; - -public class PathSegment -{ - - private final PathGridCache pgc; - private final Set semiOpen; - protected final Set closed; - private boolean isDead; - protected List open; - - public PathSegment( final PathGridCache myPGC, final List open, final Set semiOpen, final Set closed ) - { - this.open = open; - this.semiOpen = semiOpen; - this.closed = closed; - this.pgc = myPGC; - this.setDead( false ); - } - - public boolean step(Map backbone, TopologyStage stage) - { - final List oldOpen = this.open; - this.open = new LinkedList<>(); - - for( final IPathItem i : oldOpen ) - { - for( final IPathItem pi : i.getPossibleOptions() ) - { - final EnumSet flags = pi.getFlags(); - if( !this.closed.contains( pi ) ) - { - boolean stopHere = false; - if (flags.contains(GridFlags.ULTRA_DENSE_CAPACITY) && stage == TopologyStage.CONTROLLER_TO_BACKBONE) - { - backbone.computeIfAbsent(pi, k -> new BackbonePathSegment(pi, pgc, semiOpen, closed)).addControllerRoute(i); - stopHere = true; - } - pi.setControllerRoute( i, true ); - - if( flags.contains( GridFlags.REQUIRE_CHANNEL ) && stage != TopologyStage.BACKBONE) - { - // close the semi open. - if( !this.semiOpen.contains( pi ) ) - { - final boolean worked = this.useChannel( pi, flags.contains( GridFlags.COMPRESSED_CHANNEL ) ); - - if( worked && flags.contains( GridFlags.MULTIBLOCK ) ) - { - final Iterator oni = ( (IGridMultiblock) ( (IGridNode) pi ).getGridBlock() ).getMultiblockNodes(); - while( oni.hasNext() ) - { - final IGridNode otherNodes = oni.next(); - if( otherNodes != pi ) - { - this.semiOpen.add( (IPathItem) otherNodes ); - } - } - } - } - else - { - pi.incrementChannelCount( 1 ); // give a channel. - this.semiOpen.remove( pi ); - } - } - - if (!stopHere) - { - this.closed.add( pi ); - this.open.add(pi); - } - } - else if (stage == TopologyStage.BACKBONE) - { - BackbonePathSegment bb = backbone.get(pi); - if (bb != null && bb != this) { - bb.addPathToNeighbour((BackbonePathSegment) this, i); - } - } - } - } - - return this.open.isEmpty(); - } - - private boolean useChannel( final IPathItem start, boolean p2p ) - { - for (IPathItem pi = start; pi != null; pi = pi.getControllerRoute()) - { - if (!pi.canSupportMoreChannels() || (p2p && pi.getFlags().contains(GridFlags.CANNOT_CARRY_COMPRESSED))) - return false; - } - - boolean haveBlockingNode = false; - IPathItem lastBackboneConnection = null; - for (IPathItem pi = start; pi != null; pi = pi.getControllerRoute()) - { - this.pgc.setChannelsByBlocks( this.pgc.getChannelsByBlocks() + 1 ); - pi.incrementChannelCount( 1 ); - if (!pi.canSupportMoreChannels()) - haveBlockingNode = true; - if (pgc.isValidBackboneConnection(pi)) - lastBackboneConnection = pi; - } - - if (haveBlockingNode && lastBackboneConnection != null) - pgc.repathBackboneConnection(lastBackboneConnection); - - this.pgc.setChannelsInUse( this.pgc.getChannelsInUse() + 1 ); - return true; - } - - - public boolean isDead() - { - return this.isDead; - } - - public void setDead( final boolean isDead ) - { - this.isDead = isDead; - } +public class PathSegment { + + private final PathGridCache pgc; + private final Set semiOpen; + protected final Set closed; + private boolean isDead; + protected List open; + + public PathSegment( + final PathGridCache myPGC, + final List open, + final Set semiOpen, + final Set closed) { + this.open = open; + this.semiOpen = semiOpen; + this.closed = closed; + this.pgc = myPGC; + this.setDead(false); + } + + public boolean step(Map backbone, TopologyStage stage) { + final List oldOpen = this.open; + this.open = new LinkedList<>(); + + for (final IPathItem i : oldOpen) { + for (final IPathItem pi : i.getPossibleOptions()) { + final EnumSet flags = pi.getFlags(); + if (!this.closed.contains(pi)) { + boolean stopHere = false; + if (flags.contains(GridFlags.ULTRA_DENSE_CAPACITY) + && stage == TopologyStage.CONTROLLER_TO_BACKBONE) { + backbone.computeIfAbsent(pi, k -> new BackbonePathSegment(pi, pgc, semiOpen, closed)) + .addControllerRoute(i); + stopHere = true; + } + pi.setControllerRoute(i, true); + + if (flags.contains(GridFlags.REQUIRE_CHANNEL) && stage != TopologyStage.BACKBONE) { + // close the semi open. + if (!this.semiOpen.contains(pi)) { + final boolean worked = this.useChannel(pi, flags.contains(GridFlags.COMPRESSED_CHANNEL)); + + if (worked && flags.contains(GridFlags.MULTIBLOCK)) { + final Iterator oni = + ((IGridMultiblock) ((IGridNode) pi).getGridBlock()).getMultiblockNodes(); + while (oni.hasNext()) { + final IGridNode otherNodes = oni.next(); + if (otherNodes != pi) { + this.semiOpen.add((IPathItem) otherNodes); + } + } + } + } else { + pi.incrementChannelCount(1); // give a channel. + this.semiOpen.remove(pi); + } + } + + if (!stopHere) { + this.closed.add(pi); + this.open.add(pi); + } + } else if (stage == TopologyStage.BACKBONE) { + BackbonePathSegment bb = backbone.get(pi); + if (bb != null && bb != this) { + bb.addPathToNeighbour((BackbonePathSegment) this, i); + } + } + } + } + + return this.open.isEmpty(); + } + + private boolean useChannel(final IPathItem start, boolean p2p) { + for (IPathItem pi = start; pi != null; pi = pi.getControllerRoute()) { + if (!pi.canSupportMoreChannels() || (p2p && pi.getFlags().contains(GridFlags.CANNOT_CARRY_COMPRESSED))) + return false; + } + + boolean haveBlockingNode = false; + IPathItem lastBackboneConnection = null; + for (IPathItem pi = start; pi != null; pi = pi.getControllerRoute()) { + this.pgc.setChannelsByBlocks(this.pgc.getChannelsByBlocks() + 1); + pi.incrementChannelCount(1); + if (!pi.canSupportMoreChannels()) haveBlockingNode = true; + if (pgc.isValidBackboneConnection(pi)) lastBackboneConnection = pi; + } + + if (haveBlockingNode && lastBackboneConnection != null) pgc.repathBackboneConnection(lastBackboneConnection); + + this.pgc.setChannelsInUse(this.pgc.getChannelsInUse() + 1); + return true; + } + + public boolean isDead() { + return this.isDead; + } + + public void setDead(final boolean isDead) { + this.isDead = isDead; + } } diff --git a/src/main/java/appeng/me/pathfinding/TopologyStage.java b/src/main/java/appeng/me/pathfinding/TopologyStage.java index b86a7f9ef78..dd93acaefa0 100644 --- a/src/main/java/appeng/me/pathfinding/TopologyStage.java +++ b/src/main/java/appeng/me/pathfinding/TopologyStage.java @@ -1,7 +1,10 @@ package appeng.me.pathfinding; public enum TopologyStage { - CONTROLLER_TO_BACKBONE, // at this stage we set paths from controller to backbone and set the channels along these paths if necessary - BACKBONE, // at this stage we establish backbone cables relationships (paths to controller connections), no channels increment here - PERIPHERALS // here we set up channels of all the nodes requiring channels, removing filled controller connections as necessary + CONTROLLER_TO_BACKBONE, // at this stage we set paths from controller to backbone and set the channels along these + // paths if necessary + BACKBONE, // at this stage we establish backbone cables relationships (paths to controller connections), no channels + // increment here + PERIPHERALS // here we set up channels of all the nodes requiring channels, removing filled controller connections + // as necessary } diff --git a/src/main/java/appeng/me/storage/AEExternalHandler.java b/src/main/java/appeng/me/storage/AEExternalHandler.java index 4d23b4341ac..8b6288342f7 100644 --- a/src/main/java/appeng/me/storage/AEExternalHandler.java +++ b/src/main/java/appeng/me/storage/AEExternalHandler.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.implementations.tiles.ITileStorageMonitorable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageHandler; @@ -31,60 +30,48 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +public class AEExternalHandler implements IExternalStorageHandler { -public class AEExternalHandler implements IExternalStorageHandler -{ - - @Override - public boolean canHandle( final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource mySrc ) - { - if( channel == StorageChannel.ITEMS && te instanceof ITileStorageMonitorable ) - { - return ( (ITileStorageMonitorable) te ).getMonitorable( d, mySrc ) != null; - } + @Override + public boolean canHandle( + final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource mySrc) { + if (channel == StorageChannel.ITEMS && te instanceof ITileStorageMonitorable) { + return ((ITileStorageMonitorable) te).getMonitorable(d, mySrc) != null; + } - return te instanceof TileCondenser; - } + return te instanceof TileCondenser; + } - @Override - public IMEInventory getInventory( final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource src ) - { - if( te instanceof TileCondenser ) - { - if( channel == StorageChannel.ITEMS ) - { - return new VoidItemInventory( (TileCondenser) te ); - } - else - { - return new VoidFluidInventory( (TileCondenser) te ); - } - } + @Override + public IMEInventory getInventory( + final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource src) { + if (te instanceof TileCondenser) { + if (channel == StorageChannel.ITEMS) { + return new VoidItemInventory((TileCondenser) te); + } else { + return new VoidFluidInventory((TileCondenser) te); + } + } - if( te instanceof ITileStorageMonitorable ) - { - final ITileStorageMonitorable iface = (ITileStorageMonitorable) te; - final IStorageMonitorable sm = iface.getMonitorable( d, src ); + if (te instanceof ITileStorageMonitorable) { + final ITileStorageMonitorable iface = (ITileStorageMonitorable) te; + final IStorageMonitorable sm = iface.getMonitorable(d, src); - if( channel == StorageChannel.ITEMS && sm != null ) - { - final IMEInventory ii = sm.getItemInventory(); - if( ii != null ) - { - return ii; - } - } + if (channel == StorageChannel.ITEMS && sm != null) { + final IMEInventory ii = sm.getItemInventory(); + if (ii != null) { + return ii; + } + } - if( channel == StorageChannel.FLUIDS && sm != null ) - { - final IMEInventory fi = sm.getFluidInventory(); - if( fi != null ) - { - return fi; - } - } - } + if (channel == StorageChannel.FLUIDS && sm != null) { + final IMEInventory fi = sm.getFluidInventory(); + if (fi != null) { + return fi; + } + } + } - return null; - } + return null; + } } diff --git a/src/main/java/appeng/me/storage/CellInventory.java b/src/main/java/appeng/me/storage/CellInventory.java index 794ce636bcd..3242d68cb0e 100644 --- a/src/main/java/appeng/me/storage/CellInventory.java +++ b/src/main/java/appeng/me/storage/CellInventory.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.FuzzyMode; @@ -30,6 +29,8 @@ import appeng.api.storage.data.IItemList; import appeng.util.Platform; import appeng.util.item.AEItemStack; +import java.util.HashSet; +import java.util.Set; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -37,580 +38,486 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.oredict.OreDictionary; -import java.util.HashSet; -import java.util.Set; - - -public class CellInventory implements ICellInventory -{ - - private static final String ITEM_TYPE_TAG = "it"; - private static final String ITEM_COUNT_TAG = "ic"; - private static final String ITEM_SLOT = "#"; - private static final String ITEM_SLOT_COUNT = "@"; - private static final Set BLACK_LIST = new HashSet(); - private static String[] itemSlots; - private static String[] itemSlotCount; - private final NBTTagCompound tagCompound; - private final ISaveProvider container; - private int maxItemTypes = 63; - private short storedItems = 0; - private int storedItemCount = 0; - private IItemList cellItems; - private final ItemStack cellItem; - private IStorageCell cellType; - - private CellInventory( final ItemStack o, final ISaveProvider container ) throws AppEngException - { - if( itemSlots == null ) - { - itemSlots = new String[this.maxItemTypes]; - itemSlotCount = new String[this.maxItemTypes]; - - for( int x = 0; x < this.maxItemTypes; x++ ) - { - itemSlots[x] = ITEM_SLOT + x; - itemSlotCount[x] = ITEM_SLOT_COUNT + x; - } - } - - if( o == null ) - { - throw new AppEngException( "ItemStack was used as a cell, but was not a cell!" ); - } - - this.cellType = null; - this.cellItem = o; - - final Item type = this.cellItem.getItem(); - - if( type instanceof IStorageCell ) - { - this.cellType = (IStorageCell) this.cellItem.getItem(); - this.maxItemTypes = this.cellType.getTotalTypes( this.cellItem ); - } - - if( this.cellType == null ) - { - throw new AppEngException( "ItemStack was used as a cell, but was not a cell!" ); - } - - if( !this.cellType.isStorageCell( this.cellItem ) ) - { - throw new AppEngException( "ItemStack was used as a cell, but was not a cell!" ); - } - - if( this.maxItemTypes > 63 ) - { - this.maxItemTypes = 63; - } - if( this.maxItemTypes < 1 ) - { - this.maxItemTypes = 1; - } - - this.container = container; - this.tagCompound = Platform.openNbtData( o ); - this.storedItems = this.tagCompound.getShort( ITEM_TYPE_TAG ); - this.storedItemCount = this.tagCompound.getInteger( ITEM_COUNT_TAG ); - this.cellItems = null; - } - - public static IMEInventoryHandler getCell( final ItemStack o, final ISaveProvider container2 ) - { - try - { - return new CellInventoryHandler( new CellInventory( o, container2 ) ); - } - catch( final AppEngException e ) - { - return null; - } - } - - private static boolean isStorageCell( final ItemStack itemStack ) - { - if( itemStack == null ) - { - return false; - } - - try - { - final Item type = itemStack.getItem(); - - if( type instanceof IStorageCell ) - { - return !( (IStorageCell) type ).storableInStorageCell(); - } - } - catch( final Throwable err ) - { - return true; - } - - return false; - } - - public static boolean isCell( final ItemStack itemStack ) - { - if( itemStack == null ) - { - return false; - } - - final Item type = itemStack.getItem(); - - if( type instanceof IStorageCell ) - { - return ( (IStorageCell) type ).isStorageCell( itemStack ); - } - - return false; - } - - public static void addBasicBlackList( final int itemID, final int meta ) - { - BLACK_LIST.add( ( meta << Platform.DEF_OFFSET ) | itemID ); - } - - private static boolean isBlackListed( final IAEItemStack input ) - { - if( BLACK_LIST.contains( ( OreDictionary.WILDCARD_VALUE << Platform.DEF_OFFSET ) | Item.getIdFromItem( input.getItem() ) ) ) - { - return true; - } - - return BLACK_LIST.contains( ( input.getItemDamage() << Platform.DEF_OFFSET ) | Item.getIdFromItem( input.getItem() ) ); - } - - private boolean isEmpty( final IMEInventory meInventory ) - { - return meInventory.getAvailableItems( AEApi.instance().storage().createItemList() ).isEmpty(); - } - - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - if( input == null ) - { - return null; - } - - if( input.getStackSize() == 0 ) - { - return null; - } - - if( isBlackListed( input ) || this.cellType.isBlackListed( this.cellItem, input ) ) - { - return input; - } - - final ItemStack sharedItemStack = input.getItemStack(); - - if( CellInventory.isStorageCell( sharedItemStack ) ) - { - final IMEInventory meInventory = getCell( sharedItemStack, null ); - - if( meInventory != null && !this.isEmpty( meInventory ) ) - { - return input; - } - } - - final IAEItemStack l = this.getCellItems().findPrecise( input ); - - if( l != null ) - { - final long remainingItemSlots = this.getRemainingItemCount(); - - if( remainingItemSlots < 0 ) - { - return input; - } - - if( input.getStackSize() > remainingItemSlots ) - { - final IAEItemStack r = input.copy(); - r.setStackSize( r.getStackSize() - remainingItemSlots ); - - if( mode == Actionable.MODULATE ) - { - l.setStackSize( l.getStackSize() + remainingItemSlots ); - this.updateItemCount( remainingItemSlots ); - this.saveChanges(); - } - - return r; - } - else - { - if( mode == Actionable.MODULATE ) - { - l.setStackSize( l.getStackSize() + input.getStackSize() ); - this.updateItemCount( input.getStackSize() ); - this.saveChanges(); - } - - return null; - } - } - - if( this.canHoldNewItem() ) // room for new type, and for at least one item! - { - final int remainingItemCount = (int) this.getRemainingItemCount() - this.getBytesPerType() * 8; - - if( remainingItemCount > 0 ) - { - if( input.getStackSize() > remainingItemCount ) - { - final ItemStack toReturn = Platform.cloneItemStack( sharedItemStack ); - toReturn.stackSize = sharedItemStack.stackSize - remainingItemCount; - - if( mode == Actionable.MODULATE ) - { - final ItemStack toWrite = Platform.cloneItemStack( sharedItemStack ); - toWrite.stackSize = remainingItemCount; - - this.cellItems.add( AEItemStack.create( toWrite ) ); - this.updateItemCount( toWrite.stackSize ); - - this.saveChanges(); - } - - return AEItemStack.create( toReturn ); - } - - if( mode == Actionable.MODULATE ) - { - this.updateItemCount( input.getStackSize() ); - this.cellItems.add( input ); - this.saveChanges(); - } - - return null; - } - } - - return input; - } - - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - if( request == null ) - { - return null; - } - - final long size = Math.min( Integer.MAX_VALUE, request.getStackSize() ); - - IAEItemStack results = null; - - final IAEItemStack l = this.getCellItems().findPrecise( request ); - - if( l != null ) - { - results = l.copy(); - - if( l.getStackSize() <= size ) - { - results.setStackSize( l.getStackSize() ); - - if( mode == Actionable.MODULATE ) - { - this.updateItemCount( -l.getStackSize() ); - l.setStackSize( 0 ); - this.saveChanges(); - } - } - else - { - results.setStackSize( size ); - - if( mode == Actionable.MODULATE ) - { - l.setStackSize( l.getStackSize() - size ); - this.updateItemCount( -size ); - this.saveChanges(); - } - } - } - - return results; - } - - private IItemList getCellItems() - { - if( this.cellItems == null ) - { - this.loadCellItems(); - } - - return this.cellItems; - } - - private void updateItemCount( final long delta ) - { - this.storedItemCount += delta; - this.tagCompound.setInteger( ITEM_COUNT_TAG, this.storedItemCount ); - } - - private void saveChanges() - { - // cellItems.clean(); - int itemCount = 0; - - // add new pretty stuff... - int x = 0; - - for( final IAEItemStack v : this.cellItems ) - { - itemCount += v.getStackSize(); - - final NBTBase c = this.tagCompound.getTag( itemSlots[x] ); - - if( c instanceof NBTTagCompound ) - { - v.writeToNBT( (NBTTagCompound) c ); - } - else - { - final NBTTagCompound g = new NBTTagCompound(); - v.writeToNBT( g ); - this.tagCompound.setTag( itemSlots[x], g ); - } - - /* - * NBTBase tagSlotCount = tagCompound.getTag( itemSlotCount[x] ); if ( tagSlotCount instanceof - * NBTTagInt ) ((NBTTagInt) tagSlotCount).data = (int) v.getStackSize(); else - */ - this.tagCompound.setInteger( itemSlotCount[x], (int) v.getStackSize() ); - - x++; - } - - // NBTBase tagType = tagCompound.getTag( ITEM_TYPE_TAG ); - // NBTBase tagCount = tagCompound.getTag( ITEM_COUNT_TAG ); - final short oldStoredItems = this.storedItems; - - /* - * if ( tagType instanceof NBTTagShort ) ((NBTTagShort) tagType).data = storedItems = (short) cellItems.size(); - * else - */ - this.storedItems = (short) this.cellItems.size(); - - if( this.cellItems.isEmpty() ) - { - this.tagCompound.removeTag( ITEM_TYPE_TAG ); - } - else - { - this.tagCompound.setShort( ITEM_TYPE_TAG, this.storedItems ); - } - - /* - * if ( tagCount instanceof NBTTagInt ) ((NBTTagInt) tagCount).data = storedItemCount = itemCount; else - */ - this.storedItemCount = itemCount; - - if( itemCount == 0 ) - { - this.tagCompound.removeTag( ITEM_COUNT_TAG ); - } - else - { - this.tagCompound.setInteger( ITEM_COUNT_TAG, itemCount ); - } - - // clean any old crusty stuff... - for( ; x < oldStoredItems && x < this.maxItemTypes; x++ ) - { - this.tagCompound.removeTag( itemSlots[x] ); - this.tagCompound.removeTag( itemSlotCount[x] ); - } - - if( this.container != null ) - { - this.container.saveChanges( this ); - } - } - - private void loadCellItems() - { - if( this.cellItems == null ) - { - this.cellItems = AEApi.instance().storage().createPrimitiveItemList(); - } - - this.cellItems.resetStatus(); // clears totals and stuff. - - final int types = (int) this.getStoredItemTypes(); - - for( int x = 0; x < types; x++ ) - { - final ItemStack t = ItemStack.loadItemStackFromNBT( this.tagCompound.getCompoundTag( itemSlots[x] ) ); - - if( t != null ) - { - t.stackSize = this.tagCompound.getInteger( itemSlotCount[x] ); - - if( t.stackSize > 0 ) - { - this.cellItems.add( AEItemStack.create( t ) ); - } - } - } - - // cellItems.clean(); - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final IAEItemStack i : this.getCellItems() ) - { - out.add( i ); - } - - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public ItemStack getItemStack() - { - return this.cellItem; - } - - @Override - public double getIdleDrain() - { - return this.cellType.getIdleDrain(this.cellItem); - } - - @Override - public FuzzyMode getFuzzyMode() - { - return this.cellType.getFuzzyMode( this.cellItem ); - } - @Override - public String getOreFilter() - { - return this.cellType.getOreFilter( this.cellItem ); - } - - @Override - public IInventory getConfigInventory() - { - return this.cellType.getConfigInventory( this.cellItem ); - } - - @Override - public IInventory getUpgradesInventory() - { - return this.cellType.getUpgradesInventory( this.cellItem ); - } - - @Override - public int getBytesPerType() - { - return this.cellType.getBytesPerType( this.cellItem ); - } - - @Override - public boolean canHoldNewItem() - { - final long bytesFree = this.getFreeBytes(); - - return ( bytesFree > this.getBytesPerType() || ( bytesFree == this.getBytesPerType() && this.getUnusedItemCount() > 0 ) ) && this.getRemainingItemTypes() > 0; - } - - @Override - public long getTotalBytes() - { - return this.cellType.getBytes( this.cellItem ); - } - - @Override - public long getFreeBytes() - { - return this.getTotalBytes() - this.getUsedBytes(); - } - - @Override - public long getUsedBytes() - { - final long bytesForItemCount = ( this.getStoredItemCount() + this.getUnusedItemCount() ) / 8; - - return this.getStoredItemTypes() * this.getBytesPerType() + bytesForItemCount; - } - - @Override - public long getTotalItemTypes() - { - return this.maxItemTypes; - } - - @Override - public long getStoredItemCount() - { - return this.storedItemCount; - } - - @Override - public long getStoredItemTypes() - { - return this.storedItems; - } - - @Override - public long getRemainingItemTypes() - { - final long basedOnStorage = this.getFreeBytes() / this.getBytesPerType(); - final long baseOnTotal = this.getTotalItemTypes() - this.getStoredItemTypes(); - - return basedOnStorage > baseOnTotal ? baseOnTotal : basedOnStorage; - } - - @Override - public long getRemainingItemCount() - { - final long remaining = this.getFreeBytes() * 8 + this.getUnusedItemCount(); - - return remaining > 0 ? remaining : 0; - } - - @Override - public int getUnusedItemCount() - { - final int div = (int) ( this.getStoredItemCount() % 8 ); - - if( div == 0 ) - { - return 0; - } - - return 8 - div; - } - - @Override - public int getStatusForCell() - { - if( this.canHoldNewItem() ) - { - return 1; - } - if( this.getRemainingItemCount() > 0 ) - { - return 2; - } - return 3; - } +public class CellInventory implements ICellInventory { + + private static final String ITEM_TYPE_TAG = "it"; + private static final String ITEM_COUNT_TAG = "ic"; + private static final String ITEM_SLOT = "#"; + private static final String ITEM_SLOT_COUNT = "@"; + private static final Set BLACK_LIST = new HashSet(); + private static String[] itemSlots; + private static String[] itemSlotCount; + private final NBTTagCompound tagCompound; + private final ISaveProvider container; + private int maxItemTypes = 63; + private short storedItems = 0; + private int storedItemCount = 0; + private IItemList cellItems; + private final ItemStack cellItem; + private IStorageCell cellType; + + private CellInventory(final ItemStack o, final ISaveProvider container) throws AppEngException { + if (itemSlots == null) { + itemSlots = new String[this.maxItemTypes]; + itemSlotCount = new String[this.maxItemTypes]; + + for (int x = 0; x < this.maxItemTypes; x++) { + itemSlots[x] = ITEM_SLOT + x; + itemSlotCount[x] = ITEM_SLOT_COUNT + x; + } + } + + if (o == null) { + throw new AppEngException("ItemStack was used as a cell, but was not a cell!"); + } + + this.cellType = null; + this.cellItem = o; + + final Item type = this.cellItem.getItem(); + + if (type instanceof IStorageCell) { + this.cellType = (IStorageCell) this.cellItem.getItem(); + this.maxItemTypes = this.cellType.getTotalTypes(this.cellItem); + } + + if (this.cellType == null) { + throw new AppEngException("ItemStack was used as a cell, but was not a cell!"); + } + + if (!this.cellType.isStorageCell(this.cellItem)) { + throw new AppEngException("ItemStack was used as a cell, but was not a cell!"); + } + + if (this.maxItemTypes > 63) { + this.maxItemTypes = 63; + } + if (this.maxItemTypes < 1) { + this.maxItemTypes = 1; + } + + this.container = container; + this.tagCompound = Platform.openNbtData(o); + this.storedItems = this.tagCompound.getShort(ITEM_TYPE_TAG); + this.storedItemCount = this.tagCompound.getInteger(ITEM_COUNT_TAG); + this.cellItems = null; + } + + public static IMEInventoryHandler getCell(final ItemStack o, final ISaveProvider container2) { + try { + return new CellInventoryHandler(new CellInventory(o, container2)); + } catch (final AppEngException e) { + return null; + } + } + + private static boolean isStorageCell(final ItemStack itemStack) { + if (itemStack == null) { + return false; + } + + try { + final Item type = itemStack.getItem(); + + if (type instanceof IStorageCell) { + return !((IStorageCell) type).storableInStorageCell(); + } + } catch (final Throwable err) { + return true; + } + + return false; + } + + public static boolean isCell(final ItemStack itemStack) { + if (itemStack == null) { + return false; + } + + final Item type = itemStack.getItem(); + + if (type instanceof IStorageCell) { + return ((IStorageCell) type).isStorageCell(itemStack); + } + + return false; + } + + public static void addBasicBlackList(final int itemID, final int meta) { + BLACK_LIST.add((meta << Platform.DEF_OFFSET) | itemID); + } + + private static boolean isBlackListed(final IAEItemStack input) { + if (BLACK_LIST.contains( + (OreDictionary.WILDCARD_VALUE << Platform.DEF_OFFSET) | Item.getIdFromItem(input.getItem()))) { + return true; + } + + return BLACK_LIST.contains( + (input.getItemDamage() << Platform.DEF_OFFSET) | Item.getIdFromItem(input.getItem())); + } + + private boolean isEmpty(final IMEInventory meInventory) { + return meInventory + .getAvailableItems(AEApi.instance().storage().createItemList()) + .isEmpty(); + } + + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode, final BaseActionSource src) { + if (input == null) { + return null; + } + + if (input.getStackSize() == 0) { + return null; + } + + if (isBlackListed(input) || this.cellType.isBlackListed(this.cellItem, input)) { + return input; + } + + final ItemStack sharedItemStack = input.getItemStack(); + + if (CellInventory.isStorageCell(sharedItemStack)) { + final IMEInventory meInventory = getCell(sharedItemStack, null); + + if (meInventory != null && !this.isEmpty(meInventory)) { + return input; + } + } + + final IAEItemStack l = this.getCellItems().findPrecise(input); + + if (l != null) { + final long remainingItemSlots = this.getRemainingItemCount(); + + if (remainingItemSlots < 0) { + return input; + } + + if (input.getStackSize() > remainingItemSlots) { + final IAEItemStack r = input.copy(); + r.setStackSize(r.getStackSize() - remainingItemSlots); + + if (mode == Actionable.MODULATE) { + l.setStackSize(l.getStackSize() + remainingItemSlots); + this.updateItemCount(remainingItemSlots); + this.saveChanges(); + } + + return r; + } else { + if (mode == Actionable.MODULATE) { + l.setStackSize(l.getStackSize() + input.getStackSize()); + this.updateItemCount(input.getStackSize()); + this.saveChanges(); + } + + return null; + } + } + + if (this.canHoldNewItem()) // room for new type, and for at least one item! + { + final int remainingItemCount = (int) this.getRemainingItemCount() - this.getBytesPerType() * 8; + + if (remainingItemCount > 0) { + if (input.getStackSize() > remainingItemCount) { + final ItemStack toReturn = Platform.cloneItemStack(sharedItemStack); + toReturn.stackSize = sharedItemStack.stackSize - remainingItemCount; + + if (mode == Actionable.MODULATE) { + final ItemStack toWrite = Platform.cloneItemStack(sharedItemStack); + toWrite.stackSize = remainingItemCount; + + this.cellItems.add(AEItemStack.create(toWrite)); + this.updateItemCount(toWrite.stackSize); + + this.saveChanges(); + } + + return AEItemStack.create(toReturn); + } + + if (mode == Actionable.MODULATE) { + this.updateItemCount(input.getStackSize()); + this.cellItems.add(input); + this.saveChanges(); + } + + return null; + } + } + + return input; + } + + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final BaseActionSource src) { + if (request == null) { + return null; + } + + final long size = Math.min(Integer.MAX_VALUE, request.getStackSize()); + + IAEItemStack results = null; + + final IAEItemStack l = this.getCellItems().findPrecise(request); + + if (l != null) { + results = l.copy(); + + if (l.getStackSize() <= size) { + results.setStackSize(l.getStackSize()); + + if (mode == Actionable.MODULATE) { + this.updateItemCount(-l.getStackSize()); + l.setStackSize(0); + this.saveChanges(); + } + } else { + results.setStackSize(size); + + if (mode == Actionable.MODULATE) { + l.setStackSize(l.getStackSize() - size); + this.updateItemCount(-size); + this.saveChanges(); + } + } + } + + return results; + } + + private IItemList getCellItems() { + if (this.cellItems == null) { + this.loadCellItems(); + } + + return this.cellItems; + } + + private void updateItemCount(final long delta) { + this.storedItemCount += delta; + this.tagCompound.setInteger(ITEM_COUNT_TAG, this.storedItemCount); + } + + private void saveChanges() { + // cellItems.clean(); + int itemCount = 0; + + // add new pretty stuff... + int x = 0; + + for (final IAEItemStack v : this.cellItems) { + itemCount += v.getStackSize(); + + final NBTBase c = this.tagCompound.getTag(itemSlots[x]); + + if (c instanceof NBTTagCompound) { + v.writeToNBT((NBTTagCompound) c); + } else { + final NBTTagCompound g = new NBTTagCompound(); + v.writeToNBT(g); + this.tagCompound.setTag(itemSlots[x], g); + } + + /* + * NBTBase tagSlotCount = tagCompound.getTag( itemSlotCount[x] ); if ( tagSlotCount instanceof + * NBTTagInt ) ((NBTTagInt) tagSlotCount).data = (int) v.getStackSize(); else + */ + this.tagCompound.setInteger(itemSlotCount[x], (int) v.getStackSize()); + + x++; + } + + // NBTBase tagType = tagCompound.getTag( ITEM_TYPE_TAG ); + // NBTBase tagCount = tagCompound.getTag( ITEM_COUNT_TAG ); + final short oldStoredItems = this.storedItems; + + /* + * if ( tagType instanceof NBTTagShort ) ((NBTTagShort) tagType).data = storedItems = (short) cellItems.size(); + * else + */ + this.storedItems = (short) this.cellItems.size(); + + if (this.cellItems.isEmpty()) { + this.tagCompound.removeTag(ITEM_TYPE_TAG); + } else { + this.tagCompound.setShort(ITEM_TYPE_TAG, this.storedItems); + } + + /* + * if ( tagCount instanceof NBTTagInt ) ((NBTTagInt) tagCount).data = storedItemCount = itemCount; else + */ + this.storedItemCount = itemCount; + + if (itemCount == 0) { + this.tagCompound.removeTag(ITEM_COUNT_TAG); + } else { + this.tagCompound.setInteger(ITEM_COUNT_TAG, itemCount); + } + + // clean any old crusty stuff... + for (; x < oldStoredItems && x < this.maxItemTypes; x++) { + this.tagCompound.removeTag(itemSlots[x]); + this.tagCompound.removeTag(itemSlotCount[x]); + } + + if (this.container != null) { + this.container.saveChanges(this); + } + } + + private void loadCellItems() { + if (this.cellItems == null) { + this.cellItems = AEApi.instance().storage().createPrimitiveItemList(); + } + + this.cellItems.resetStatus(); // clears totals and stuff. + + final int types = (int) this.getStoredItemTypes(); + + for (int x = 0; x < types; x++) { + final ItemStack t = ItemStack.loadItemStackFromNBT(this.tagCompound.getCompoundTag(itemSlots[x])); + + if (t != null) { + t.stackSize = this.tagCompound.getInteger(itemSlotCount[x]); + + if (t.stackSize > 0) { + this.cellItems.add(AEItemStack.create(t)); + } + } + } + + // cellItems.clean(); + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final IAEItemStack i : this.getCellItems()) { + out.add(i); + } + + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } + + @Override + public ItemStack getItemStack() { + return this.cellItem; + } + + @Override + public double getIdleDrain() { + return this.cellType.getIdleDrain(this.cellItem); + } + + @Override + public FuzzyMode getFuzzyMode() { + return this.cellType.getFuzzyMode(this.cellItem); + } + + @Override + public String getOreFilter() { + return this.cellType.getOreFilter(this.cellItem); + } + + @Override + public IInventory getConfigInventory() { + return this.cellType.getConfigInventory(this.cellItem); + } + + @Override + public IInventory getUpgradesInventory() { + return this.cellType.getUpgradesInventory(this.cellItem); + } + + @Override + public int getBytesPerType() { + return this.cellType.getBytesPerType(this.cellItem); + } + + @Override + public boolean canHoldNewItem() { + final long bytesFree = this.getFreeBytes(); + + return (bytesFree > this.getBytesPerType() + || (bytesFree == this.getBytesPerType() && this.getUnusedItemCount() > 0)) + && this.getRemainingItemTypes() > 0; + } + + @Override + public long getTotalBytes() { + return this.cellType.getBytes(this.cellItem); + } + + @Override + public long getFreeBytes() { + return this.getTotalBytes() - this.getUsedBytes(); + } + + @Override + public long getUsedBytes() { + final long bytesForItemCount = (this.getStoredItemCount() + this.getUnusedItemCount()) / 8; + + return this.getStoredItemTypes() * this.getBytesPerType() + bytesForItemCount; + } + + @Override + public long getTotalItemTypes() { + return this.maxItemTypes; + } + + @Override + public long getStoredItemCount() { + return this.storedItemCount; + } + + @Override + public long getStoredItemTypes() { + return this.storedItems; + } + + @Override + public long getRemainingItemTypes() { + final long basedOnStorage = this.getFreeBytes() / this.getBytesPerType(); + final long baseOnTotal = this.getTotalItemTypes() - this.getStoredItemTypes(); + + return basedOnStorage > baseOnTotal ? baseOnTotal : basedOnStorage; + } + + @Override + public long getRemainingItemCount() { + final long remaining = this.getFreeBytes() * 8 + this.getUnusedItemCount(); + + return remaining > 0 ? remaining : 0; + } + + @Override + public int getUnusedItemCount() { + final int div = (int) (this.getStoredItemCount() % 8); + + if (div == 0) { + return 0; + } + + return 8 - div; + } + + @Override + public int getStatusForCell() { + if (this.canHoldNewItem()) { + return 1; + } + if (this.getRemainingItemCount() > 0) { + return 2; + } + return 3; + } } diff --git a/src/main/java/appeng/me/storage/CellInventoryHandler.java b/src/main/java/appeng/me/storage/CellInventoryHandler.java index ac2478cba7b..ee109b5ef45 100644 --- a/src/main/java/appeng/me/storage/CellInventoryHandler.java +++ b/src/main/java/appeng/me/storage/CellInventoryHandler.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.AEApi; import appeng.api.config.FuzzyMode; import appeng.api.config.IncludeExclude; @@ -37,115 +36,100 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - -public class CellInventoryHandler extends MEInventoryHandler implements ICellInventoryHandler -{ - - CellInventoryHandler( final IMEInventory c ) - { - super( c, StorageChannel.ITEMS ); - - final ICellInventory ci = this.getCellInv(); - - if( ci != null ) - { - final IInventory upgrades = ci.getUpgradesInventory(); - final IInventory config = ci.getConfigInventory(); - final FuzzyMode fzMode = ci.getFuzzyMode(); - final String filter = ci.getOreFilter(); - - boolean hasInverter = false; - boolean hasFuzzy = false; - boolean hasOreFilter = false; - - for( int x = 0; x < upgrades.getSizeInventory(); x++ ) - { - final ItemStack is = upgrades.getStackInSlot( x ); - if( is != null && is.getItem() instanceof IUpgradeModule ) - { - final Upgrades u = ( (IUpgradeModule) is.getItem() ).getType( is ); - if( u != null ) - { - switch( u ) - { - case FUZZY: - hasFuzzy = true; - break; - case INVERTER: - hasInverter = true; - break; - case ORE_FILTER: - hasOreFilter = true; - break; - default: - } - } - } - } - this.setWhitelist(hasInverter ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST); - if (hasOreFilter && !filter.isEmpty()) { - this.setPartitionList(new OreFilteredList(filter)); - } - else { - final IItemList priorityList = AEApi.instance().storage().createItemList(); - for (int x = 0; x < config.getSizeInventory(); x++) { - final ItemStack is = config.getStackInSlot(x); - if (is != null) { - priorityList.add(AEItemStack.create(is)); - } - } - - if (!priorityList.isEmpty()) { - if (hasFuzzy) { - this.setPartitionList(new FuzzyPriorityList(priorityList, fzMode)); - } else { - this.setPartitionList(new PrecisePriorityList(priorityList)); - } - } - } - } - } - - @Override - public ICellInventory getCellInv() - { - Object o = this.getInternal(); - - if( o instanceof MEPassThrough ) - { - o = ( (MEPassThrough) o ).getInternal(); - } - - return (ICellInventory) ( o instanceof ICellInventory ? o : null ); - } - - @Override - public boolean isPreformatted() - { - return !this.getPartitionList().isEmpty(); - } - - @Override - public boolean isFuzzy() - { - return this.getPartitionList() instanceof FuzzyPriorityList; - } - - @Override - public IncludeExclude getIncludeExcludeMode() - { - return this.getWhitelist(); - } - - public int getStatusForCell() - { - int val = this.getCellInv().getStatusForCell(); - - if( val == 1 && this.isPreformatted() ) - { - val = 2; - } - - return val; - } +public class CellInventoryHandler extends MEInventoryHandler implements ICellInventoryHandler { + + CellInventoryHandler(final IMEInventory c) { + super(c, StorageChannel.ITEMS); + + final ICellInventory ci = this.getCellInv(); + + if (ci != null) { + final IInventory upgrades = ci.getUpgradesInventory(); + final IInventory config = ci.getConfigInventory(); + final FuzzyMode fzMode = ci.getFuzzyMode(); + final String filter = ci.getOreFilter(); + + boolean hasInverter = false; + boolean hasFuzzy = false; + boolean hasOreFilter = false; + + for (int x = 0; x < upgrades.getSizeInventory(); x++) { + final ItemStack is = upgrades.getStackInSlot(x); + if (is != null && is.getItem() instanceof IUpgradeModule) { + final Upgrades u = ((IUpgradeModule) is.getItem()).getType(is); + if (u != null) { + switch (u) { + case FUZZY: + hasFuzzy = true; + break; + case INVERTER: + hasInverter = true; + break; + case ORE_FILTER: + hasOreFilter = true; + break; + default: + } + } + } + } + this.setWhitelist(hasInverter ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST); + if (hasOreFilter && !filter.isEmpty()) { + this.setPartitionList(new OreFilteredList(filter)); + } else { + final IItemList priorityList = + AEApi.instance().storage().createItemList(); + for (int x = 0; x < config.getSizeInventory(); x++) { + final ItemStack is = config.getStackInSlot(x); + if (is != null) { + priorityList.add(AEItemStack.create(is)); + } + } + + if (!priorityList.isEmpty()) { + if (hasFuzzy) { + this.setPartitionList(new FuzzyPriorityList(priorityList, fzMode)); + } else { + this.setPartitionList(new PrecisePriorityList(priorityList)); + } + } + } + } + } + + @Override + public ICellInventory getCellInv() { + Object o = this.getInternal(); + + if (o instanceof MEPassThrough) { + o = ((MEPassThrough) o).getInternal(); + } + + return (ICellInventory) (o instanceof ICellInventory ? o : null); + } + + @Override + public boolean isPreformatted() { + return !this.getPartitionList().isEmpty(); + } + + @Override + public boolean isFuzzy() { + return this.getPartitionList() instanceof FuzzyPriorityList; + } + + @Override + public IncludeExclude getIncludeExcludeMode() { + return this.getWhitelist(); + } + + public int getStatusForCell() { + int val = this.getCellInv().getStatusForCell(); + + if (val == 1 && this.isPreformatted()) { + val = 2; + } + + return val; + } } diff --git a/src/main/java/appeng/me/storage/CreativeCellInventory.java b/src/main/java/appeng/me/storage/CreativeCellInventory.java index 0dc41277e48..db38df4df16 100644 --- a/src/main/java/appeng/me/storage/CreativeCellInventory.java +++ b/src/main/java/appeng/me/storage/CreativeCellInventory.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -31,104 +30,86 @@ import appeng.util.item.AEItemStack; import net.minecraft.item.ItemStack; - -public class CreativeCellInventory implements IMEInventoryHandler -{ - - private final IItemList itemListCache = AEApi.instance().storage().createItemList(); - - protected CreativeCellInventory( final ItemStack o ) - { - final CellConfig cc = new CellConfig( o ); - for( final ItemStack is : cc ) - { - if( is != null ) - { - final IAEItemStack i = AEItemStack.create( is ); - i.setStackSize( Integer.MAX_VALUE ); - this.itemListCache.add( i ); - } - } - } - - public static IMEInventoryHandler getCell( final ItemStack o ) - { - return new CellInventoryHandler( new CreativeCellInventory( o ) ); - } - - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - final IAEItemStack local = this.itemListCache.findPrecise( input ); - if( local == null ) - { - return input; - } - - return null; - } - - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - final IAEItemStack local = this.itemListCache.findPrecise( request ); - if( local == null ) - { - return null; - } - - return request.copy(); - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final IAEItemStack ais : this.itemListCache ) - { - out.add( ais ); - } - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } - - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - return this.itemListCache.findPrecise( input ) != null; - } - - @Override - public boolean canAccept( final IAEItemStack input ) - { - return this.itemListCache.findPrecise( input ) != null; - } - - @Override - public int getPriority() - { - return 0; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return true; - } +public class CreativeCellInventory implements IMEInventoryHandler { + + private final IItemList itemListCache = + AEApi.instance().storage().createItemList(); + + protected CreativeCellInventory(final ItemStack o) { + final CellConfig cc = new CellConfig(o); + for (final ItemStack is : cc) { + if (is != null) { + final IAEItemStack i = AEItemStack.create(is); + i.setStackSize(Integer.MAX_VALUE); + this.itemListCache.add(i); + } + } + } + + public static IMEInventoryHandler getCell(final ItemStack o) { + return new CellInventoryHandler(new CreativeCellInventory(o)); + } + + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode, final BaseActionSource src) { + final IAEItemStack local = this.itemListCache.findPrecise(input); + if (local == null) { + return input; + } + + return null; + } + + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final BaseActionSource src) { + final IAEItemStack local = this.itemListCache.findPrecise(request); + if (local == null) { + return null; + } + + return request.copy(); + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final IAEItemStack ais : this.itemListCache) { + out.add(ais); + } + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } + + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } + + @Override + public boolean isPrioritized(final IAEItemStack input) { + return this.itemListCache.findPrecise(input) != null; + } + + @Override + public boolean canAccept(final IAEItemStack input) { + return this.itemListCache.findPrecise(input) != null; + } + + @Override + public int getPriority() { + return 0; + } + + @Override + public int getSlot() { + return 0; + } + + @Override + public boolean validForPass(final int i) { + return true; + } } diff --git a/src/main/java/appeng/me/storage/DriveWatcher.java b/src/main/java/appeng/me/storage/DriveWatcher.java index 108f096d06f..9cc73a31d75 100644 --- a/src/main/java/appeng/me/storage/DriveWatcher.java +++ b/src/main/java/appeng/me/storage/DriveWatcher.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.config.Actionable; import appeng.api.implementations.tiles.IChestOrDrive; import appeng.api.networking.security.BaseActionSource; @@ -27,58 +26,49 @@ import appeng.api.storage.data.IAEStack; import net.minecraft.item.ItemStack; +public class DriveWatcher> extends MEInventoryHandler { -public class DriveWatcher> extends MEInventoryHandler -{ - - private final int oldStatus = 0; - private final ItemStack is; - private final ICellHandler handler; - private final IChestOrDrive cord; + private final int oldStatus = 0; + private final ItemStack is; + private final ICellHandler handler; + private final IChestOrDrive cord; - public DriveWatcher( final IMEInventory i, final ItemStack is, final ICellHandler han, final IChestOrDrive cod ) - { - super( i, i.getChannel() ); - this.is = is; - this.handler = han; - this.cord = cod; - } + public DriveWatcher(final IMEInventory i, final ItemStack is, final ICellHandler han, final IChestOrDrive cod) { + super(i, i.getChannel()); + this.is = is; + this.handler = han; + this.cord = cod; + } - @Override - public T injectItems( final T input, final Actionable type, final BaseActionSource src ) - { - final long size = input.getStackSize(); + @Override + public T injectItems(final T input, final Actionable type, final BaseActionSource src) { + final long size = input.getStackSize(); - final T a = super.injectItems( input, type, src ); + final T a = super.injectItems(input, type, src); - if( a == null || a.getStackSize() != size ) - { - final int newStatus = this.handler.getStatusForCell( this.is, this.getInternal() ); + if (a == null || a.getStackSize() != size) { + final int newStatus = this.handler.getStatusForCell(this.is, this.getInternal()); - if( newStatus != this.oldStatus ) - { - this.cord.blinkCell( this.getSlot() ); - } - } + if (newStatus != this.oldStatus) { + this.cord.blinkCell(this.getSlot()); + } + } - return a; - } + return a; + } - @Override - public T extractItems( final T request, final Actionable type, final BaseActionSource src ) - { - final T a = super.extractItems( request, type, src ); + @Override + public T extractItems(final T request, final Actionable type, final BaseActionSource src) { + final T a = super.extractItems(request, type, src); - if( a != null ) - { - final int newStatus = this.handler.getStatusForCell( this.is, this.getInternal() ); + if (a != null) { + final int newStatus = this.handler.getStatusForCell(this.is, this.getInternal()); - if( newStatus != this.oldStatus ) - { - this.cord.blinkCell( this.getSlot() ); - } - } + if (newStatus != this.oldStatus) { + this.cord.blinkCell(this.getSlot()); + } + } - return a; - } + return a; + } } diff --git a/src/main/java/appeng/me/storage/ItemWatcher.java b/src/main/java/appeng/me/storage/ItemWatcher.java index 7788167fad9..3864830cfb0 100644 --- a/src/main/java/appeng/me/storage/ItemWatcher.java +++ b/src/main/java/appeng/me/storage/ItemWatcher.java @@ -18,180 +18,150 @@ package appeng.me.storage; - import appeng.api.networking.storage.IStackWatcher; import appeng.api.networking.storage.IStackWatcherHost; import appeng.api.storage.data.IAEStack; import appeng.me.cache.GridStorageCache; - import java.util.Collection; import java.util.HashSet; import java.util.Iterator; - /** * Maintain my interests, and a global watch list, they should always be fully synchronized. */ -public class ItemWatcher implements IStackWatcher -{ - - private final GridStorageCache gsc; - private final IStackWatcherHost myObject; - private final HashSet myInterests = new HashSet(); - - public ItemWatcher( final GridStorageCache cache, final IStackWatcherHost host ) - { - this.gsc = cache; - this.myObject = host; - } - - public IStackWatcherHost getHost() - { - return this.myObject; - } - - @Override - public int size() - { - return this.myInterests.size(); - } - - @Override - public boolean isEmpty() - { - return this.myInterests.isEmpty(); - } - - @Override - public boolean contains( final Object o ) - { - return this.myInterests.contains( o ); - } - - @Override - public Iterator iterator() - { - return new ItemWatcherIterator( this, this.myInterests.iterator() ); - } - - @Override - public Object[] toArray() - { - return this.myInterests.toArray(); - } - - @Override - public T[] toArray( final T[] a ) - { - return this.myInterests.toArray( a ); - } - - @Override - public boolean add( final IAEStack e ) - { - if( this.myInterests.contains( e ) ) - { - return false; - } - - return this.myInterests.add( e.copy() ) && this.gsc.getInterestManager().put( e, this ); - } - - @Override - public boolean remove( final Object o ) - { - return this.myInterests.remove( o ) && this.gsc.getInterestManager().remove( (IAEStack) o, this ); - } - - @Override - public boolean containsAll( final Collection c ) - { - return this.myInterests.containsAll( c ); - } - - @Override - public boolean addAll( final Collection c ) - { - boolean didChange = false; - - for( final IAEStack o : c ) - { - didChange = this.add( o ) || didChange; - } - - return didChange; - } - - @Override - public boolean removeAll( final Collection c ) - { - boolean didSomething = false; - for( final Object o : c ) - { - didSomething = this.remove( o ) || didSomething; - } - return didSomething; - } - - @Override - public boolean retainAll( final Collection c ) - { - boolean changed = false; - final Iterator i = this.iterator(); - - while( i.hasNext() ) - { - if( !c.contains( i.next() ) ) - { - i.remove(); - changed = true; - } - } - - return changed; - } - - @Override - public void clear() - { - final Iterator i = this.myInterests.iterator(); - while( i.hasNext() ) - { - this.gsc.getInterestManager().remove( i.next(), this ); - i.remove(); - } - } - - private class ItemWatcherIterator implements Iterator - { - - private final ItemWatcher watcher; - private final Iterator interestIterator; - private IAEStack myLast; - - public ItemWatcherIterator( final ItemWatcher parent, final Iterator i ) - { - this.watcher = parent; - this.interestIterator = i; - } - - @Override - public boolean hasNext() - { - return this.interestIterator.hasNext(); - } - - @Override - public IAEStack next() - { - return this.myLast = this.interestIterator.next(); - } - - @Override - public void remove() - { - ItemWatcher.this.gsc.getInterestManager().remove( this.myLast, this.watcher ); - this.interestIterator.remove(); - } - } +public class ItemWatcher implements IStackWatcher { + + private final GridStorageCache gsc; + private final IStackWatcherHost myObject; + private final HashSet myInterests = new HashSet(); + + public ItemWatcher(final GridStorageCache cache, final IStackWatcherHost host) { + this.gsc = cache; + this.myObject = host; + } + + public IStackWatcherHost getHost() { + return this.myObject; + } + + @Override + public int size() { + return this.myInterests.size(); + } + + @Override + public boolean isEmpty() { + return this.myInterests.isEmpty(); + } + + @Override + public boolean contains(final Object o) { + return this.myInterests.contains(o); + } + + @Override + public Iterator iterator() { + return new ItemWatcherIterator(this, this.myInterests.iterator()); + } + + @Override + public Object[] toArray() { + return this.myInterests.toArray(); + } + + @Override + public T[] toArray(final T[] a) { + return this.myInterests.toArray(a); + } + + @Override + public boolean add(final IAEStack e) { + if (this.myInterests.contains(e)) { + return false; + } + + return this.myInterests.add(e.copy()) && this.gsc.getInterestManager().put(e, this); + } + + @Override + public boolean remove(final Object o) { + return this.myInterests.remove(o) && this.gsc.getInterestManager().remove((IAEStack) o, this); + } + + @Override + public boolean containsAll(final Collection c) { + return this.myInterests.containsAll(c); + } + + @Override + public boolean addAll(final Collection c) { + boolean didChange = false; + + for (final IAEStack o : c) { + didChange = this.add(o) || didChange; + } + + return didChange; + } + + @Override + public boolean removeAll(final Collection c) { + boolean didSomething = false; + for (final Object o : c) { + didSomething = this.remove(o) || didSomething; + } + return didSomething; + } + + @Override + public boolean retainAll(final Collection c) { + boolean changed = false; + final Iterator i = this.iterator(); + + while (i.hasNext()) { + if (!c.contains(i.next())) { + i.remove(); + changed = true; + } + } + + return changed; + } + + @Override + public void clear() { + final Iterator i = this.myInterests.iterator(); + while (i.hasNext()) { + this.gsc.getInterestManager().remove(i.next(), this); + i.remove(); + } + } + + private class ItemWatcherIterator implements Iterator { + + private final ItemWatcher watcher; + private final Iterator interestIterator; + private IAEStack myLast; + + public ItemWatcherIterator(final ItemWatcher parent, final Iterator i) { + this.watcher = parent; + this.interestIterator = i; + } + + @Override + public boolean hasNext() { + return this.interestIterator.hasNext(); + } + + @Override + public IAEStack next() { + return this.myLast = this.interestIterator.next(); + } + + @Override + public void remove() { + ItemWatcher.this.gsc.getInterestManager().remove(this.myLast, this.watcher); + this.interestIterator.remove(); + } + } } diff --git a/src/main/java/appeng/me/storage/MEIInventoryWrapper.java b/src/main/java/appeng/me/storage/MEIInventoryWrapper.java index 5177d5207f0..f1f150bafd3 100644 --- a/src/main/java/appeng/me/storage/MEIInventoryWrapper.java +++ b/src/main/java/appeng/me/storage/MEIInventoryWrapper.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IMEInventory; @@ -31,194 +30,159 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public class MEIInventoryWrapper implements IMEInventory { + + private final IInventory target; + private final InventoryAdaptor adaptor; + + public MEIInventoryWrapper(final IInventory m, final InventoryAdaptor ia) { + this.target = m; + this.adaptor = ia; + } + + @Override + public IAEItemStack injectItems(final IAEItemStack iox, final Actionable mode, final BaseActionSource src) { + final ItemStack input = iox.getItemStack(); + + if (this.adaptor != null) { + final ItemStack is = + mode == Actionable.SIMULATE ? this.adaptor.simulateAdd(input) : this.adaptor.addItems(input); + if (is == null) { + return null; + } + return AEItemStack.create(is); + } + + final ItemStack out = Platform.cloneItemStack(input); + + if (mode == Actionable.MODULATE) // absolutely no need for a first run in simulate mode. + { + for (int x = 0; x < this.target.getSizeInventory(); x++) { + final ItemStack t = this.target.getStackInSlot(x); + + if (Platform.isSameItem(t, input)) { + final int oriStack = t.stackSize; + t.stackSize += out.stackSize; -public class MEIInventoryWrapper implements IMEInventory -{ - - private final IInventory target; - private final InventoryAdaptor adaptor; - - public MEIInventoryWrapper( final IInventory m, final InventoryAdaptor ia ) - { - this.target = m; - this.adaptor = ia; - } - - @Override - public IAEItemStack injectItems( final IAEItemStack iox, final Actionable mode, final BaseActionSource src ) - { - final ItemStack input = iox.getItemStack(); - - if( this.adaptor != null ) - { - final ItemStack is = mode == Actionable.SIMULATE ? this.adaptor.simulateAdd( input ) : this.adaptor.addItems( input ); - if( is == null ) - { - return null; - } - return AEItemStack.create( is ); - } - - final ItemStack out = Platform.cloneItemStack( input ); - - if( mode == Actionable.MODULATE ) // absolutely no need for a first run in simulate mode. - { - for( int x = 0; x < this.target.getSizeInventory(); x++ ) - { - final ItemStack t = this.target.getStackInSlot( x ); - - if( Platform.isSameItem( t, input ) ) - { - final int oriStack = t.stackSize; - t.stackSize += out.stackSize; - - this.target.setInventorySlotContents( x, t ); - - if( t.stackSize > this.target.getInventoryStackLimit() ) - { - t.stackSize = this.target.getInventoryStackLimit(); - } - - if( t.stackSize > t.getMaxStackSize() ) - { - t.stackSize = t.getMaxStackSize(); - } - - out.stackSize -= t.stackSize - oriStack; - - if( out.stackSize <= 0 ) - { - return null; - } - } - } - } - - for( int x = 0; x < this.target.getSizeInventory(); x++ ) - { - ItemStack t = this.target.getStackInSlot( x ); - - if( t == null ) - { - t = Platform.cloneItemStack( input ); - t.stackSize = out.stackSize; - - if( t.stackSize > this.target.getInventoryStackLimit() ) - { - t.stackSize = this.target.getInventoryStackLimit(); - } - - out.stackSize -= t.stackSize; - if( mode == Actionable.MODULATE ) - { - this.target.setInventorySlotContents( x, t ); - } - - if( out.stackSize <= 0 ) - { - return null; - } - } - } - - return AEItemStack.create( out ); - } - - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - final ItemStack Req = request.getItemStack(); - - int request_stackSize = Req.stackSize; - - if( request_stackSize > Req.getMaxStackSize() ) - { - request_stackSize = Req.getMaxStackSize(); - } - - Req.stackSize = request_stackSize; - - ItemStack Gathered = null; - if( this.adaptor != null ) - { - Gathered = this.adaptor.removeItems( Req.stackSize, Req, null ); - } - else - { - Gathered = request.getItemStack(); - Gathered.stackSize = 0; - - // try to find matching inventories that already have it... - for( int x = 0; x < this.target.getSizeInventory(); x++ ) - { - final ItemStack sub = this.target.getStackInSlot( x ); - - if( Platform.isSameItem( sub, Req ) ) - { - int reqNum = Req.stackSize; - - if( reqNum > sub.stackSize ) - { - reqNum = Req.stackSize; - } - - ItemStack retrieved = null; - - if( sub.stackSize < Req.stackSize ) - { - retrieved = Platform.cloneItemStack( sub ); - sub.stackSize = 0; - } - else - { - retrieved = sub.splitStack( Req.stackSize ); - } - - if( sub.stackSize <= 0 ) - { - this.target.setInventorySlotContents( x, null ); - } - else - { - this.target.setInventorySlotContents( x, sub ); - } - - if( retrieved != null ) - { - Gathered.stackSize += retrieved.stackSize; - Req.stackSize -= retrieved.stackSize; - } - - if( request_stackSize == Gathered.stackSize ) - { - return AEItemStack.create( Gathered ); - } - } - } - - if( Gathered.stackSize == 0 ) - { - return null; - } - } - - return AEItemStack.create( Gathered ); - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( int x = 0; x < this.target.getSizeInventory(); x++ ) - { - out.addStorage( AEItemStack.create( this.target.getStackInSlot( x ) ) ); - } - - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + this.target.setInventorySlotContents(x, t); + + if (t.stackSize > this.target.getInventoryStackLimit()) { + t.stackSize = this.target.getInventoryStackLimit(); + } + + if (t.stackSize > t.getMaxStackSize()) { + t.stackSize = t.getMaxStackSize(); + } + + out.stackSize -= t.stackSize - oriStack; + + if (out.stackSize <= 0) { + return null; + } + } + } + } + + for (int x = 0; x < this.target.getSizeInventory(); x++) { + ItemStack t = this.target.getStackInSlot(x); + + if (t == null) { + t = Platform.cloneItemStack(input); + t.stackSize = out.stackSize; + + if (t.stackSize > this.target.getInventoryStackLimit()) { + t.stackSize = this.target.getInventoryStackLimit(); + } + + out.stackSize -= t.stackSize; + if (mode == Actionable.MODULATE) { + this.target.setInventorySlotContents(x, t); + } + + if (out.stackSize <= 0) { + return null; + } + } + } + + return AEItemStack.create(out); + } + + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final BaseActionSource src) { + final ItemStack Req = request.getItemStack(); + + int request_stackSize = Req.stackSize; + + if (request_stackSize > Req.getMaxStackSize()) { + request_stackSize = Req.getMaxStackSize(); + } + + Req.stackSize = request_stackSize; + + ItemStack Gathered = null; + if (this.adaptor != null) { + Gathered = this.adaptor.removeItems(Req.stackSize, Req, null); + } else { + Gathered = request.getItemStack(); + Gathered.stackSize = 0; + + // try to find matching inventories that already have it... + for (int x = 0; x < this.target.getSizeInventory(); x++) { + final ItemStack sub = this.target.getStackInSlot(x); + + if (Platform.isSameItem(sub, Req)) { + int reqNum = Req.stackSize; + + if (reqNum > sub.stackSize) { + reqNum = Req.stackSize; + } + + ItemStack retrieved = null; + + if (sub.stackSize < Req.stackSize) { + retrieved = Platform.cloneItemStack(sub); + sub.stackSize = 0; + } else { + retrieved = sub.splitStack(Req.stackSize); + } + + if (sub.stackSize <= 0) { + this.target.setInventorySlotContents(x, null); + } else { + this.target.setInventorySlotContents(x, sub); + } + + if (retrieved != null) { + Gathered.stackSize += retrieved.stackSize; + Req.stackSize -= retrieved.stackSize; + } + + if (request_stackSize == Gathered.stackSize) { + return AEItemStack.create(Gathered); + } + } + } + + if (Gathered.stackSize == 0) { + return null; + } + } + + return AEItemStack.create(Gathered); + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + for (int x = 0; x < this.target.getSizeInventory(); x++) { + out.addStorage(AEItemStack.create(this.target.getStackInSlot(x))); + } + + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } } diff --git a/src/main/java/appeng/me/storage/MEInventoryHandler.java b/src/main/java/appeng/me/storage/MEInventoryHandler.java index 062f02c315f..7b8113e95cf 100644 --- a/src/main/java/appeng/me/storage/MEInventoryHandler.java +++ b/src/main/java/appeng/me/storage/MEInventoryHandler.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.IncludeExclude; @@ -31,169 +30,138 @@ import appeng.util.prioitylist.DefaultPriorityList; import appeng.util.prioitylist.IPartitionList; - -public class MEInventoryHandler> implements IMEInventoryHandler -{ - - private final IMEInventoryHandler internal; - private int myPriority; - private IncludeExclude myWhitelist; - private AccessRestriction myAccess; - private IPartitionList myPartitionList; - - private AccessRestriction cachedAccessRestriction; - private boolean hasReadAccess; - private boolean hasWriteAccess; - - public MEInventoryHandler( final IMEInventory i, final StorageChannel channel ) - { - if( i instanceof IMEInventoryHandler ) - { - this.internal = (IMEInventoryHandler) i; - } - else - { - this.internal = new MEPassThrough( i, channel ); - } - - this.myPriority = 0; - this.myWhitelist = IncludeExclude.WHITELIST; - this.setBaseAccess( AccessRestriction.READ_WRITE ); - this.myPartitionList = new DefaultPriorityList(); - } - - IncludeExclude getWhitelist() - { - return this.myWhitelist; - } - - public void setWhitelist( final IncludeExclude myWhitelist ) - { - this.myWhitelist = myWhitelist; - } - - public AccessRestriction getBaseAccess() - { - return this.myAccess; - } - - public void setBaseAccess( final AccessRestriction myAccess ) - { - this.myAccess = myAccess; - this.cachedAccessRestriction = this.myAccess.restrictPermissions( this.internal.getAccess() ); - this.hasReadAccess = this.cachedAccessRestriction.hasPermission( AccessRestriction.READ ); - this.hasWriteAccess = this.cachedAccessRestriction.hasPermission( AccessRestriction.WRITE ); - } - - IPartitionList getPartitionList() - { - return this.myPartitionList; - } - - public void setPartitionList( final IPartitionList myPartitionList ) - { - this.myPartitionList = myPartitionList; - } - - @Override - public T injectItems( final T input, final Actionable type, final BaseActionSource src ) - { - if( !this.canAccept( input ) ) - { - return input; - } - - return this.internal.injectItems( input, type, src ); - } - - @Override - public T extractItems( final T request, final Actionable type, final BaseActionSource src ) - { - if( !this.hasReadAccess ) - { - return null; - } - - return this.internal.extractItems( request, type, src ); - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - if( !this.hasReadAccess ) - { - return out; - } - - return this.internal.getAvailableItems( out ); - } - - @Override - public StorageChannel getChannel() - { - return this.internal.getChannel(); - } - - @Override - public AccessRestriction getAccess() - { - return this.cachedAccessRestriction; - } - - @Override - public boolean isPrioritized( final T input ) - { - if( this.myWhitelist == IncludeExclude.WHITELIST ) - { - return this.myPartitionList.isListed( input ) || this.internal.isPrioritized( input ); - } - return false; - } - - @Override - public boolean canAccept( final T input ) - { - if( !this.hasWriteAccess ) - { - return false; - } - - if( this.myWhitelist == IncludeExclude.BLACKLIST && this.myPartitionList.isListed( input ) ) - { - return false; - } - if( this.myPartitionList.isEmpty() || this.myWhitelist == IncludeExclude.BLACKLIST ) - { - return this.internal.canAccept( input ); - } - return this.myPartitionList.isListed( input ) && this.internal.canAccept( input ); - } - - @Override - public int getPriority() - { - return this.myPriority; - } - - public void setPriority( final int myPriority ) - { - this.myPriority = myPriority; - } - - @Override - public int getSlot() - { - return this.internal.getSlot(); - } - - @Override - public boolean validForPass( final int i ) - { - return true; - } - - public IMEInventory getInternal() - { - return this.internal; - } +public class MEInventoryHandler> implements IMEInventoryHandler { + + private final IMEInventoryHandler internal; + private int myPriority; + private IncludeExclude myWhitelist; + private AccessRestriction myAccess; + private IPartitionList myPartitionList; + + private AccessRestriction cachedAccessRestriction; + private boolean hasReadAccess; + private boolean hasWriteAccess; + + public MEInventoryHandler(final IMEInventory i, final StorageChannel channel) { + if (i instanceof IMEInventoryHandler) { + this.internal = (IMEInventoryHandler) i; + } else { + this.internal = new MEPassThrough(i, channel); + } + + this.myPriority = 0; + this.myWhitelist = IncludeExclude.WHITELIST; + this.setBaseAccess(AccessRestriction.READ_WRITE); + this.myPartitionList = new DefaultPriorityList(); + } + + IncludeExclude getWhitelist() { + return this.myWhitelist; + } + + public void setWhitelist(final IncludeExclude myWhitelist) { + this.myWhitelist = myWhitelist; + } + + public AccessRestriction getBaseAccess() { + return this.myAccess; + } + + public void setBaseAccess(final AccessRestriction myAccess) { + this.myAccess = myAccess; + this.cachedAccessRestriction = this.myAccess.restrictPermissions(this.internal.getAccess()); + this.hasReadAccess = this.cachedAccessRestriction.hasPermission(AccessRestriction.READ); + this.hasWriteAccess = this.cachedAccessRestriction.hasPermission(AccessRestriction.WRITE); + } + + IPartitionList getPartitionList() { + return this.myPartitionList; + } + + public void setPartitionList(final IPartitionList myPartitionList) { + this.myPartitionList = myPartitionList; + } + + @Override + public T injectItems(final T input, final Actionable type, final BaseActionSource src) { + if (!this.canAccept(input)) { + return input; + } + + return this.internal.injectItems(input, type, src); + } + + @Override + public T extractItems(final T request, final Actionable type, final BaseActionSource src) { + if (!this.hasReadAccess) { + return null; + } + + return this.internal.extractItems(request, type, src); + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + if (!this.hasReadAccess) { + return out; + } + + return this.internal.getAvailableItems(out); + } + + @Override + public StorageChannel getChannel() { + return this.internal.getChannel(); + } + + @Override + public AccessRestriction getAccess() { + return this.cachedAccessRestriction; + } + + @Override + public boolean isPrioritized(final T input) { + if (this.myWhitelist == IncludeExclude.WHITELIST) { + return this.myPartitionList.isListed(input) || this.internal.isPrioritized(input); + } + return false; + } + + @Override + public boolean canAccept(final T input) { + if (!this.hasWriteAccess) { + return false; + } + + if (this.myWhitelist == IncludeExclude.BLACKLIST && this.myPartitionList.isListed(input)) { + return false; + } + if (this.myPartitionList.isEmpty() || this.myWhitelist == IncludeExclude.BLACKLIST) { + return this.internal.canAccept(input); + } + return this.myPartitionList.isListed(input) && this.internal.canAccept(input); + } + + @Override + public int getPriority() { + return this.myPriority; + } + + public void setPriority(final int myPriority) { + this.myPriority = myPriority; + } + + @Override + public int getSlot() { + return this.internal.getSlot(); + } + + @Override + public boolean validForPass(final int i) { + return true; + } + + public IMEInventory getInternal() { + return this.internal; + } } diff --git a/src/main/java/appeng/me/storage/MEMonitorIInventory.java b/src/main/java/appeng/me/storage/MEMonitorIInventory.java index 6d645c5e530..3498313de79 100644 --- a/src/main/java/appeng/me/storage/MEMonitorIInventory.java +++ b/src/main/java/appeng/me/storage/MEMonitorIInventory.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -33,325 +32,271 @@ import appeng.util.InventoryAdaptor; import appeng.util.Platform; import appeng.util.inv.ItemSlot; -import net.minecraft.item.ItemStack; - import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.concurrent.ConcurrentSkipListMap; +import net.minecraft.item.ItemStack; - -public class MEMonitorIInventory implements IMEMonitor -{ - - private final InventoryAdaptor adaptor; - private final IItemList list = AEApi.instance().storage().createItemList(); - private final HashMap, Object> listeners = new HashMap, Object>(); - private final NavigableMap memory; - private BaseActionSource mySource; - private StorageFilter mode = StorageFilter.EXTRACTABLE_ONLY; - - public MEMonitorIInventory( final InventoryAdaptor adaptor ) - { - this.adaptor = adaptor; - this.memory = new ConcurrentSkipListMap(); - } - - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } - - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } - - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final BaseActionSource src ) - { - ItemStack out = null; - - if( type == Actionable.SIMULATE ) - { - out = this.adaptor.simulateAdd( input.getItemStack() ); - } - else - { - out = this.adaptor.addItems( input.getItemStack() ); - } - - if( type == Actionable.MODULATE ) - { - this.onTick(); - } - - if( out == null ) - { - return null; - } - - // better then doing construction from scratch :3 - final IAEItemStack o = input.copy(); - o.setStackSize( out.stackSize ); - return o; - } - - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable type, final BaseActionSource src ) - { - ItemStack out = null; - int toExtract = (int)Math.min(Integer.MAX_VALUE, request.getStackSize()); - - if( type == Actionable.SIMULATE ) - { - out = this.adaptor.simulateRemove( toExtract, request.getItemStack(), null ); - } - else - { - out = this.adaptor.removeItems( toExtract, request.getItemStack(), null ); - } - - if( out == null ) - { - return null; - } - - // better then doing construction from scratch :3 - final IAEItemStack o = request.copy(); - o.setStackSize( out.stackSize ); - - if( type == Actionable.MODULATE ) - { - this.onTick(); - } - - return o; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - public TickRateModulation onTick() - { - - final LinkedList changes = new LinkedList(); - - this.list.resetStatus(); - int high = 0; - boolean changed = false; - for( final ItemSlot is : this.adaptor ) - { - final CachedItemStack old = this.memory.get( is.getSlot() ); - high = Math.max( high, is.getSlot() ); - - final ItemStack newIS = !is.isExtractable() && this.getMode() == StorageFilter.EXTRACTABLE_ONLY ? null : is.getItemStack(); - final ItemStack oldIS = old == null ? null : old.itemStack; - - if( this.isDifferent( newIS, oldIS ) ) - { - final CachedItemStack cis = new CachedItemStack( is.getItemStack() ); - this.memory.put( is.getSlot(), cis ); - - if( old != null && old.aeStack != null ) - { - old.aeStack.setStackSize( -old.aeStack.getStackSize() ); - changes.add( old.aeStack ); - } - - if( cis.aeStack != null ) - { - changes.add( cis.aeStack ); - this.list.add( cis.aeStack ); - } - - changed = true; - } - else - { - final int newSize = ( newIS == null ? 0 : newIS.stackSize ); - final int diff = newSize - ( oldIS == null ? 0 : oldIS.stackSize ); - - final IAEItemStack stack = ( old == null || old.aeStack == null ? AEApi.instance().storage().createItemStack( newIS ) : old.aeStack.copy() ); - if( stack != null ) - { - stack.setStackSize( newSize ); - this.list.add( stack ); - } - - if( diff != 0 && stack != null ) - { - final CachedItemStack cis = new CachedItemStack( is.getItemStack() ); - this.memory.put( is.getSlot(), cis ); - - final IAEItemStack a = stack.copy(); - a.setStackSize( diff ); - changes.add( a ); - changed = true; - } - } - } - - // detect dropped items; should fix non IISided Inventory Changes. - final NavigableMap end = this.memory.tailMap( high, false ); - if( !end.isEmpty() ) - { - for( final CachedItemStack cis : end.values() ) - { - if( cis != null && cis.aeStack != null ) - { - final IAEItemStack a = cis.aeStack.copy(); - a.setStackSize( -a.getStackSize() ); - changes.add( a ); - changed = true; - } - } - end.clear(); - } - - if( !changes.isEmpty() ) - { - this.postDifference( changes ); - } - - return changed ? TickRateModulation.URGENT : TickRateModulation.SLOWER; - } - - private boolean isDifferent( final ItemStack a, final ItemStack b ) - { - if( a == b && b == null ) - { - return false; - } - - if( ( a == null && b != null ) || ( a != null && b == null ) ) - { - return true; - } - - return !Platform.isSameItemPrecise( a, b ); - } - - private void postDifference( final Iterable a ) - { - // AELog.info( a.getItemStack().getUnlocalizedName() + " @ " + a.getStackSize() ); - if( a != null ) - { - final Iterator, Object>> i = this.listeners.entrySet().iterator(); - while( i.hasNext() ) - { - final Entry, Object> l = i.next(); - final IMEMonitorHandlerReceiver key = l.getKey(); - if( key.isValid( l.getValue() ) ) - { - key.postChange( this, a, this.getActionSource() ); - } - else - { - i.remove(); - } - } - } - } - - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } - - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - return false; - } - - @Override - public boolean canAccept( final IAEItemStack input ) - { - return true; - } - - @Override - public int getPriority() - { - return 0; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return true; - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final CachedItemStack is : this.memory.values() ) - { - out.addStorage( is.aeStack ); - } - - return out; - } - - @Override - public IItemList getStorageList() - { - return this.list; - } - - private StorageFilter getMode() - { - return this.mode; - } - - public void setMode( final StorageFilter mode ) - { - this.mode = mode; - } - - private BaseActionSource getActionSource() - { - return this.mySource; - } - - public void setActionSource( final BaseActionSource mySource ) - { - this.mySource = mySource; - } - - private static class CachedItemStack - { - - private final ItemStack itemStack; - private final IAEItemStack aeStack; - - public CachedItemStack( final ItemStack is ) - { - if( is == null ) - { - this.itemStack = null; - this.aeStack = null; - } - else - { - this.itemStack = is.copy(); - this.aeStack = AEApi.instance().storage().createItemStack( is ); - } - } - } +public class MEMonitorIInventory implements IMEMonitor { + + private final InventoryAdaptor adaptor; + private final IItemList list = AEApi.instance().storage().createItemList(); + private final HashMap, Object> listeners = + new HashMap, Object>(); + private final NavigableMap memory; + private BaseActionSource mySource; + private StorageFilter mode = StorageFilter.EXTRACTABLE_ONLY; + + public MEMonitorIInventory(final InventoryAdaptor adaptor) { + this.adaptor = adaptor; + this.memory = new ConcurrentSkipListMap(); + } + + @Override + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + this.listeners.put(l, verificationToken); + } + + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } + + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable type, final BaseActionSource src) { + ItemStack out = null; + + if (type == Actionable.SIMULATE) { + out = this.adaptor.simulateAdd(input.getItemStack()); + } else { + out = this.adaptor.addItems(input.getItemStack()); + } + + if (type == Actionable.MODULATE) { + this.onTick(); + } + + if (out == null) { + return null; + } + + // better then doing construction from scratch :3 + final IAEItemStack o = input.copy(); + o.setStackSize(out.stackSize); + return o; + } + + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable type, final BaseActionSource src) { + ItemStack out = null; + int toExtract = (int) Math.min(Integer.MAX_VALUE, request.getStackSize()); + + if (type == Actionable.SIMULATE) { + out = this.adaptor.simulateRemove(toExtract, request.getItemStack(), null); + } else { + out = this.adaptor.removeItems(toExtract, request.getItemStack(), null); + } + + if (out == null) { + return null; + } + + // better then doing construction from scratch :3 + final IAEItemStack o = request.copy(); + o.setStackSize(out.stackSize); + + if (type == Actionable.MODULATE) { + this.onTick(); + } + + return o; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } + + public TickRateModulation onTick() { + + final LinkedList changes = new LinkedList(); + + this.list.resetStatus(); + int high = 0; + boolean changed = false; + for (final ItemSlot is : this.adaptor) { + final CachedItemStack old = this.memory.get(is.getSlot()); + high = Math.max(high, is.getSlot()); + + final ItemStack newIS = + !is.isExtractable() && this.getMode() == StorageFilter.EXTRACTABLE_ONLY ? null : is.getItemStack(); + final ItemStack oldIS = old == null ? null : old.itemStack; + + if (this.isDifferent(newIS, oldIS)) { + final CachedItemStack cis = new CachedItemStack(is.getItemStack()); + this.memory.put(is.getSlot(), cis); + + if (old != null && old.aeStack != null) { + old.aeStack.setStackSize(-old.aeStack.getStackSize()); + changes.add(old.aeStack); + } + + if (cis.aeStack != null) { + changes.add(cis.aeStack); + this.list.add(cis.aeStack); + } + + changed = true; + } else { + final int newSize = (newIS == null ? 0 : newIS.stackSize); + final int diff = newSize - (oldIS == null ? 0 : oldIS.stackSize); + + final IAEItemStack stack = (old == null || old.aeStack == null + ? AEApi.instance().storage().createItemStack(newIS) + : old.aeStack.copy()); + if (stack != null) { + stack.setStackSize(newSize); + this.list.add(stack); + } + + if (diff != 0 && stack != null) { + final CachedItemStack cis = new CachedItemStack(is.getItemStack()); + this.memory.put(is.getSlot(), cis); + + final IAEItemStack a = stack.copy(); + a.setStackSize(diff); + changes.add(a); + changed = true; + } + } + } + + // detect dropped items; should fix non IISided Inventory Changes. + final NavigableMap end = this.memory.tailMap(high, false); + if (!end.isEmpty()) { + for (final CachedItemStack cis : end.values()) { + if (cis != null && cis.aeStack != null) { + final IAEItemStack a = cis.aeStack.copy(); + a.setStackSize(-a.getStackSize()); + changes.add(a); + changed = true; + } + } + end.clear(); + } + + if (!changes.isEmpty()) { + this.postDifference(changes); + } + + return changed ? TickRateModulation.URGENT : TickRateModulation.SLOWER; + } + + private boolean isDifferent(final ItemStack a, final ItemStack b) { + if (a == b && b == null) { + return false; + } + + if ((a == null && b != null) || (a != null && b == null)) { + return true; + } + + return !Platform.isSameItemPrecise(a, b); + } + + private void postDifference(final Iterable a) { + // AELog.info( a.getItemStack().getUnlocalizedName() + " @ " + a.getStackSize() ); + if (a != null) { + final Iterator, Object>> i = + this.listeners.entrySet().iterator(); + while (i.hasNext()) { + final Entry, Object> l = i.next(); + final IMEMonitorHandlerReceiver key = l.getKey(); + if (key.isValid(l.getValue())) { + key.postChange(this, a, this.getActionSource()); + } else { + i.remove(); + } + } + } + } + + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } + + @Override + public boolean isPrioritized(final IAEItemStack input) { + return false; + } + + @Override + public boolean canAccept(final IAEItemStack input) { + return true; + } + + @Override + public int getPriority() { + return 0; + } + + @Override + public int getSlot() { + return 0; + } + + @Override + public boolean validForPass(final int i) { + return true; + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final CachedItemStack is : this.memory.values()) { + out.addStorage(is.aeStack); + } + + return out; + } + + @Override + public IItemList getStorageList() { + return this.list; + } + + private StorageFilter getMode() { + return this.mode; + } + + public void setMode(final StorageFilter mode) { + this.mode = mode; + } + + private BaseActionSource getActionSource() { + return this.mySource; + } + + public void setActionSource(final BaseActionSource mySource) { + this.mySource = mySource; + } + + private static class CachedItemStack { + + private final ItemStack itemStack; + private final IAEItemStack aeStack; + + public CachedItemStack(final ItemStack is) { + if (is == null) { + this.itemStack = null; + this.aeStack = null; + } else { + this.itemStack = is.copy(); + this.aeStack = AEApi.instance().storage().createItemStack(is); + } + } + } } diff --git a/src/main/java/appeng/me/storage/MEMonitorPassThrough.java b/src/main/java/appeng/me/storage/MEMonitorPassThrough.java index cdef158fa8d..bed4a498020 100644 --- a/src/main/java/appeng/me/storage/MEMonitorPassThrough.java +++ b/src/main/java/appeng/me/storage/MEMonitorPassThrough.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.networking.security.BaseActionSource; import appeng.api.networking.storage.IBaseMonitor; import appeng.api.storage.IMEInventory; @@ -29,137 +28,122 @@ import appeng.api.storage.data.IItemList; import appeng.util.Platform; import appeng.util.inv.ItemListIgnoreCrafting; - import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; - -public class MEMonitorPassThrough> extends MEPassThrough implements IMEMonitor, IMEMonitorHandlerReceiver -{ - - private final HashMap, Object> listeners = new HashMap, Object>(); - private BaseActionSource changeSource; - private IMEMonitor monitor; - - public MEMonitorPassThrough( final IMEInventory i, final StorageChannel channel ) - { - super( i, channel ); - if( i instanceof IMEMonitor ) - { - this.monitor = (IMEMonitor) i; - } - } - - @Override - public void setInternal( final IMEInventory i ) - { - if( this.monitor != null ) - { - this.monitor.removeListener( this ); - } - - this.monitor = null; - final IItemList before = this.getInternal() == null ? this.getWrappedChannel().createList() : this.getInternal().getAvailableItems( new ItemListIgnoreCrafting( this.getWrappedChannel().createList() ) ); - - super.setInternal( i ); - if( i instanceof IMEMonitor ) - { - this.monitor = (IMEMonitor) i; - } - - final IItemList after = this.getInternal() == null ? this.getWrappedChannel().createList() : this.getInternal().getAvailableItems( new ItemListIgnoreCrafting( this.getWrappedChannel().createList() ) ); - - if( this.monitor != null ) - { - this.monitor.addListener( this, this.monitor ); - } - - Platform.postListChanges( before, after, this, this.getChangeSource() ); - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - super.getAvailableItems( new ItemListIgnoreCrafting( out ) ); - return out; - } - - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } - - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } - - @Override - public IItemList getStorageList() - { - if( this.monitor == null ) - { - final IItemList out = this.getWrappedChannel().createList(); - this.getInternal().getAvailableItems( new ItemListIgnoreCrafting( out ) ); - return out; - } - return this.monitor.getStorageList(); - } - - @Override - public boolean isValid( final Object verificationToken ) - { - return verificationToken == this.monitor; - } - - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final BaseActionSource source ) - { - final Iterator, Object>> i = this.listeners.entrySet().iterator(); - while( i.hasNext() ) - { - final Entry, Object> e = i.next(); - final IMEMonitorHandlerReceiver receiver = e.getKey(); - if( receiver.isValid( e.getValue() ) ) - { - receiver.postChange( this, change, source ); - } - else - { - i.remove(); - } - } - } - - @Override - public void onListUpdate() - { - final Iterator, Object>> i = this.listeners.entrySet().iterator(); - while( i.hasNext() ) - { - final Entry, Object> e = i.next(); - final IMEMonitorHandlerReceiver receiver = e.getKey(); - if( receiver.isValid( e.getValue() ) ) - { - receiver.onListUpdate(); - } - else - { - i.remove(); - } - } - } - - private BaseActionSource getChangeSource() - { - return this.changeSource; - } - - public void setChangeSource( final BaseActionSource changeSource ) - { - this.changeSource = changeSource; - } +public class MEMonitorPassThrough> extends MEPassThrough + implements IMEMonitor, IMEMonitorHandlerReceiver { + + private final HashMap, Object> listeners = + new HashMap, Object>(); + private BaseActionSource changeSource; + private IMEMonitor monitor; + + public MEMonitorPassThrough(final IMEInventory i, final StorageChannel channel) { + super(i, channel); + if (i instanceof IMEMonitor) { + this.monitor = (IMEMonitor) i; + } + } + + @Override + public void setInternal(final IMEInventory i) { + if (this.monitor != null) { + this.monitor.removeListener(this); + } + + this.monitor = null; + final IItemList before = this.getInternal() == null + ? this.getWrappedChannel().createList() + : this.getInternal() + .getAvailableItems(new ItemListIgnoreCrafting( + this.getWrappedChannel().createList())); + + super.setInternal(i); + if (i instanceof IMEMonitor) { + this.monitor = (IMEMonitor) i; + } + + final IItemList after = this.getInternal() == null + ? this.getWrappedChannel().createList() + : this.getInternal() + .getAvailableItems(new ItemListIgnoreCrafting( + this.getWrappedChannel().createList())); + + if (this.monitor != null) { + this.monitor.addListener(this, this.monitor); + } + + Platform.postListChanges(before, after, this, this.getChangeSource()); + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + super.getAvailableItems(new ItemListIgnoreCrafting(out)); + return out; + } + + @Override + public void addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + this.listeners.put(l, verificationToken); + } + + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } + + @Override + public IItemList getStorageList() { + if (this.monitor == null) { + final IItemList out = this.getWrappedChannel().createList(); + this.getInternal().getAvailableItems(new ItemListIgnoreCrafting(out)); + return out; + } + return this.monitor.getStorageList(); + } + + @Override + public boolean isValid(final Object verificationToken) { + return verificationToken == this.monitor; + } + + @Override + public void postChange(final IBaseMonitor monitor, final Iterable change, final BaseActionSource source) { + final Iterator, Object>> i = + this.listeners.entrySet().iterator(); + while (i.hasNext()) { + final Entry, Object> e = i.next(); + final IMEMonitorHandlerReceiver receiver = e.getKey(); + if (receiver.isValid(e.getValue())) { + receiver.postChange(this, change, source); + } else { + i.remove(); + } + } + } + + @Override + public void onListUpdate() { + final Iterator, Object>> i = + this.listeners.entrySet().iterator(); + while (i.hasNext()) { + final Entry, Object> e = i.next(); + final IMEMonitorHandlerReceiver receiver = e.getKey(); + if (receiver.isValid(e.getValue())) { + receiver.onListUpdate(); + } else { + i.remove(); + } + } + } + + private BaseActionSource getChangeSource() { + return this.changeSource; + } + + public void setChangeSource(final BaseActionSource changeSource) { + this.changeSource = changeSource; + } } diff --git a/src/main/java/appeng/me/storage/MEPassThrough.java b/src/main/java/appeng/me/storage/MEPassThrough.java index b6c3cdfbbfe..edac2f4ae96 100644 --- a/src/main/java/appeng/me/storage/MEPassThrough.java +++ b/src/main/java/appeng/me/storage/MEPassThrough.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -28,91 +27,75 @@ import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; - -public class MEPassThrough> implements IMEInventoryHandler -{ - - private final StorageChannel wrappedChannel; - private IMEInventory internal; - - public MEPassThrough( final IMEInventory i, final StorageChannel channel ) - { - this.wrappedChannel = channel; - this.setInternal( i ); - } - - protected IMEInventory getInternal() - { - return this.internal; - } - - public void setInternal( final IMEInventory i ) - { - this.internal = i; - } - - @Override - public T injectItems( final T input, final Actionable type, final BaseActionSource src ) - { - return this.internal.injectItems( input, type, src ); - } - - @Override - public T extractItems( final T request, final Actionable type, final BaseActionSource src ) - { - return this.internal.extractItems( request, type, src ); - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return this.internal.getAvailableItems( out ); - } - - @Override - public StorageChannel getChannel() - { - return this.internal.getChannel(); - } - - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } - - @Override - public boolean isPrioritized( final T input ) - { - return false; - } - - @Override - public boolean canAccept( final T input ) - { - return true; - } - - @Override - public int getPriority() - { - return 0; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return true; - } - - StorageChannel getWrappedChannel() - { - return this.wrappedChannel; - } +public class MEPassThrough> implements IMEInventoryHandler { + + private final StorageChannel wrappedChannel; + private IMEInventory internal; + + public MEPassThrough(final IMEInventory i, final StorageChannel channel) { + this.wrappedChannel = channel; + this.setInternal(i); + } + + protected IMEInventory getInternal() { + return this.internal; + } + + public void setInternal(final IMEInventory i) { + this.internal = i; + } + + @Override + public T injectItems(final T input, final Actionable type, final BaseActionSource src) { + return this.internal.injectItems(input, type, src); + } + + @Override + public T extractItems(final T request, final Actionable type, final BaseActionSource src) { + return this.internal.extractItems(request, type, src); + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + return this.internal.getAvailableItems(out); + } + + @Override + public StorageChannel getChannel() { + return this.internal.getChannel(); + } + + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } + + @Override + public boolean isPrioritized(final T input) { + return false; + } + + @Override + public boolean canAccept(final T input) { + return true; + } + + @Override + public int getPriority() { + return 0; + } + + @Override + public int getSlot() { + return 0; + } + + @Override + public boolean validForPass(final int i) { + return true; + } + + StorageChannel getWrappedChannel() { + return this.wrappedChannel; + } } diff --git a/src/main/java/appeng/me/storage/NetworkInventoryHandler.java b/src/main/java/appeng/me/storage/NetworkInventoryHandler.java index 7e939c41202..5b3f50f5392 100644 --- a/src/main/java/appeng/me/storage/NetworkInventoryHandler.java +++ b/src/main/java/appeng/me/storage/NetworkInventoryHandler.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.SecurityPermissions; @@ -34,301 +33,252 @@ import appeng.api.storage.data.IItemList; import appeng.me.cache.SecurityCache; import appeng.util.ItemSorters; - import java.util.*; - -public class NetworkInventoryHandler> implements IMEInventoryHandler -{ - - private static final ThreadLocal DEPTH_MOD = new ThreadLocal(); - private static final ThreadLocal DEPTH_SIM = new ThreadLocal(); - private static final Comparator PRIORITY_SORTER = new Comparator() - { - - @Override - public int compare( final Integer o1, final Integer o2 ) - { - return ItemSorters.compareInt( o2, o1 ); - } - }; - private static int currentPass = 0; - private final StorageChannel myChannel; - private final SecurityCache security; - // final TreeMultimap> priorityInventory; - private final NavigableMap>> priorityInventory; - private int myPass = 0; - - public NetworkInventoryHandler( final StorageChannel chan, final SecurityCache security ) - { - this.myChannel = chan; - this.security = security; - this.priorityInventory = new TreeMap>>( PRIORITY_SORTER ); // TreeMultimap.create( - // prioritySorter, - // hashSorter ); - } - - public void addNewStorage( final IMEInventoryHandler h ) - { - final int priority = h.getPriority(); - List> list = this.priorityInventory.get( priority ); - if( list == null ) - { - this.priorityInventory.put( priority, list = new ArrayList>() ); - } - - list.add( h ); - } - - @Override - public T injectItems( T input, final Actionable type, final BaseActionSource src ) - { - if( this.diveList( this, type ) ) - { - return input; - } - - if( this.testPermission( src, SecurityPermissions.INJECT ) ) - { - this.surface( this, type ); - return input; - } - - for( final List> invList : this.priorityInventory.values() ) - { - Iterator> ii = invList.iterator(); - while( ii.hasNext() && input != null ) - { - final IMEInventoryHandler inv = ii.next(); - - if( inv.validForPass( 1 ) && inv.canAccept( input ) && ( inv.isPrioritized( input ) || inv.extractItems( input, Actionable.SIMULATE, src ) != null ) ) - { - input = inv.injectItems( input, type, src ); - } - } - - // We need to ignore prioritized inventories in the second pass. If they were not able to store everything - // during the first pass, they will do so in the second, but as this is stateless we will just report twice - // the amount of storable items. - // ignores craftingcache on the second pass. - ii = invList.iterator(); - while( ii.hasNext() && input != null ) - { - final IMEInventoryHandler inv = ii.next(); - - if( inv.validForPass( 2 ) && inv.canAccept( input ) && !inv.isPrioritized( input ) ) - { - input = inv.injectItems( input, type, src ); - } - } - } - - this.surface( this, type ); - - return input; - } - - private boolean diveList( final NetworkInventoryHandler networkInventoryHandler, final Actionable type ) - { - final LinkedList cDepth = this.getDepth( type ); - if( cDepth.contains( networkInventoryHandler ) ) - { - return true; - } - - cDepth.push( this ); - return false; - } - - private boolean testPermission( final BaseActionSource src, final SecurityPermissions permission ) - { - if( src.isPlayer() ) - { - if( !this.security.hasPermission( ( (PlayerSource) src ).player, permission ) ) - { - return true; - } - } - else if( src.isMachine() ) - { - if( this.security.isAvailable() ) - { - final IGridNode n = ( (MachineSource) src ).via.getActionableNode(); - if( n == null ) - { - return true; - } - - final IGrid gn = n.getGrid(); - if( gn != this.security.getGrid() ) - { - - final ISecurityGrid sg = gn.getCache( ISecurityGrid.class ); - final int playerID = sg.isAvailable() ? sg.getOwner() : n.getPlayerID(); - - if( !this.security.hasPermission( playerID, permission ) ) - { - return true; - } - } - } - } - - return false; - } - - private void surface( final NetworkInventoryHandler networkInventoryHandler, final Actionable type ) - { - if( this.getDepth( type ).pop() != this ) - { - throw new IllegalStateException( "Invalid Access to Networked Storage API detected." ); - } - } - - private LinkedList getDepth( final Actionable type ) - { - final ThreadLocal depth = type == Actionable.MODULATE ? DEPTH_MOD : DEPTH_SIM; - - LinkedList s = depth.get(); - - if( s == null ) - { - depth.set( s = new LinkedList() ); - } - - return s; - } - - @Override - public T extractItems( T request, final Actionable mode, final BaseActionSource src ) - { - if( this.diveList( this, mode ) ) - { - return null; - } - - if( this.testPermission( src, SecurityPermissions.EXTRACT ) ) - { - this.surface( this, mode ); - return null; - } - - final Iterator>> i = this.priorityInventory.descendingMap().values().iterator();// priorityInventory.asMap().descendingMap().entrySet().iterator(); - - final T output = request.copy(); - request = request.copy(); - output.setStackSize( 0 ); - final long req = request.getStackSize(); - - while( i.hasNext() ) - { - final List> invList = i.next(); - - final Iterator> ii = invList.iterator(); - while( ii.hasNext() && output.getStackSize() < req ) - { - final IMEInventoryHandler inv = ii.next(); - - request.setStackSize( req - output.getStackSize() ); - output.add( inv.extractItems( request, mode, src ) ); - } - } - - this.surface( this, mode ); - - if( output.getStackSize() <= 0 ) - { - return null; - } - - return output; - } - - @Override - public IItemList getAvailableItems( IItemList out ) - { - if( this.diveIteration( this, Actionable.SIMULATE ) ) - { - return out; - } - - // for (Entry> h : priorityInventory.entries()) - for( final List> i : this.priorityInventory.values() ) - { - for( final IMEInventoryHandler j : i ) - { - out = j.getAvailableItems( out ); - } - } - - this.surface( this, Actionable.SIMULATE ); - - return out; - } - - private boolean diveIteration( final NetworkInventoryHandler networkInventoryHandler, final Actionable type ) - { - final LinkedList cDepth = this.getDepth( type ); - if( cDepth.isEmpty() ) - { - currentPass++; - this.myPass = currentPass; - } - else - { - if( currentPass == this.myPass ) - { - return true; - } - else - { - this.myPass = currentPass; - } - } - - cDepth.push( this ); - return false; - } - - @Override - public StorageChannel getChannel() - { - return this.myChannel; - } - - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } - - @Override - public boolean isPrioritized( final T input ) - { - return false; - } - - @Override - public boolean canAccept( final T input ) - { - return true; - } - - @Override - public int getPriority() - { - return 0; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return true; - } +public class NetworkInventoryHandler> implements IMEInventoryHandler { + + private static final ThreadLocal DEPTH_MOD = new ThreadLocal(); + private static final ThreadLocal DEPTH_SIM = new ThreadLocal(); + private static final Comparator PRIORITY_SORTER = new Comparator() { + + @Override + public int compare(final Integer o1, final Integer o2) { + return ItemSorters.compareInt(o2, o1); + } + }; + private static int currentPass = 0; + private final StorageChannel myChannel; + private final SecurityCache security; + // final TreeMultimap> priorityInventory; + private final NavigableMap>> priorityInventory; + private int myPass = 0; + + public NetworkInventoryHandler(final StorageChannel chan, final SecurityCache security) { + this.myChannel = chan; + this.security = security; + this.priorityInventory = + new TreeMap>>(PRIORITY_SORTER); // TreeMultimap.create( + // prioritySorter, + // hashSorter ); + } + + public void addNewStorage(final IMEInventoryHandler h) { + final int priority = h.getPriority(); + List> list = this.priorityInventory.get(priority); + if (list == null) { + this.priorityInventory.put(priority, list = new ArrayList>()); + } + + list.add(h); + } + + @Override + public T injectItems(T input, final Actionable type, final BaseActionSource src) { + if (this.diveList(this, type)) { + return input; + } + + if (this.testPermission(src, SecurityPermissions.INJECT)) { + this.surface(this, type); + return input; + } + + for (final List> invList : this.priorityInventory.values()) { + Iterator> ii = invList.iterator(); + while (ii.hasNext() && input != null) { + final IMEInventoryHandler inv = ii.next(); + + if (inv.validForPass(1) + && inv.canAccept(input) + && (inv.isPrioritized(input) || inv.extractItems(input, Actionable.SIMULATE, src) != null)) { + input = inv.injectItems(input, type, src); + } + } + + // We need to ignore prioritized inventories in the second pass. If they were not able to store everything + // during the first pass, they will do so in the second, but as this is stateless we will just report twice + // the amount of storable items. + // ignores craftingcache on the second pass. + ii = invList.iterator(); + while (ii.hasNext() && input != null) { + final IMEInventoryHandler inv = ii.next(); + + if (inv.validForPass(2) && inv.canAccept(input) && !inv.isPrioritized(input)) { + input = inv.injectItems(input, type, src); + } + } + } + + this.surface(this, type); + + return input; + } + + private boolean diveList(final NetworkInventoryHandler networkInventoryHandler, final Actionable type) { + final LinkedList cDepth = this.getDepth(type); + if (cDepth.contains(networkInventoryHandler)) { + return true; + } + + cDepth.push(this); + return false; + } + + private boolean testPermission(final BaseActionSource src, final SecurityPermissions permission) { + if (src.isPlayer()) { + if (!this.security.hasPermission(((PlayerSource) src).player, permission)) { + return true; + } + } else if (src.isMachine()) { + if (this.security.isAvailable()) { + final IGridNode n = ((MachineSource) src).via.getActionableNode(); + if (n == null) { + return true; + } + + final IGrid gn = n.getGrid(); + if (gn != this.security.getGrid()) { + + final ISecurityGrid sg = gn.getCache(ISecurityGrid.class); + final int playerID = sg.isAvailable() ? sg.getOwner() : n.getPlayerID(); + + if (!this.security.hasPermission(playerID, permission)) { + return true; + } + } + } + } + + return false; + } + + private void surface(final NetworkInventoryHandler networkInventoryHandler, final Actionable type) { + if (this.getDepth(type).pop() != this) { + throw new IllegalStateException("Invalid Access to Networked Storage API detected."); + } + } + + private LinkedList getDepth(final Actionable type) { + final ThreadLocal depth = type == Actionable.MODULATE ? DEPTH_MOD : DEPTH_SIM; + + LinkedList s = depth.get(); + + if (s == null) { + depth.set(s = new LinkedList()); + } + + return s; + } + + @Override + public T extractItems(T request, final Actionable mode, final BaseActionSource src) { + if (this.diveList(this, mode)) { + return null; + } + + if (this.testPermission(src, SecurityPermissions.EXTRACT)) { + this.surface(this, mode); + return null; + } + + final Iterator>> i = this.priorityInventory + .descendingMap() + .values() + .iterator(); // priorityInventory.asMap().descendingMap().entrySet().iterator(); + + final T output = request.copy(); + request = request.copy(); + output.setStackSize(0); + final long req = request.getStackSize(); + + while (i.hasNext()) { + final List> invList = i.next(); + + final Iterator> ii = invList.iterator(); + while (ii.hasNext() && output.getStackSize() < req) { + final IMEInventoryHandler inv = ii.next(); + + request.setStackSize(req - output.getStackSize()); + output.add(inv.extractItems(request, mode, src)); + } + } + + this.surface(this, mode); + + if (output.getStackSize() <= 0) { + return null; + } + + return output; + } + + @Override + public IItemList getAvailableItems(IItemList out) { + if (this.diveIteration(this, Actionable.SIMULATE)) { + return out; + } + + // for (Entry> h : priorityInventory.entries()) + for (final List> i : this.priorityInventory.values()) { + for (final IMEInventoryHandler j : i) { + out = j.getAvailableItems(out); + } + } + + this.surface(this, Actionable.SIMULATE); + + return out; + } + + private boolean diveIteration(final NetworkInventoryHandler networkInventoryHandler, final Actionable type) { + final LinkedList cDepth = this.getDepth(type); + if (cDepth.isEmpty()) { + currentPass++; + this.myPass = currentPass; + } else { + if (currentPass == this.myPass) { + return true; + } else { + this.myPass = currentPass; + } + } + + cDepth.push(this); + return false; + } + + @Override + public StorageChannel getChannel() { + return this.myChannel; + } + + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } + + @Override + public boolean isPrioritized(final T input) { + return false; + } + + @Override + public boolean canAccept(final T input) { + return true; + } + + @Override + public int getPriority() { + return 0; + } + + @Override + public int getSlot() { + return 0; + } + + @Override + public boolean validForPass(final int i) { + return true; + } } diff --git a/src/main/java/appeng/me/storage/NullInventory.java b/src/main/java/appeng/me/storage/NullInventory.java index f674a192124..03c52c05510 100644 --- a/src/main/java/appeng/me/storage/NullInventory.java +++ b/src/main/java/appeng/me/storage/NullInventory.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -27,67 +26,55 @@ import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; +public class NullInventory> implements IMEInventoryHandler { -public class NullInventory> implements IMEInventoryHandler -{ - - @Override - public T injectItems( final T input, final Actionable mode, final BaseActionSource src ) - { - return input; - } + @Override + public T injectItems(final T input, final Actionable mode, final BaseActionSource src) { + return input; + } - @Override - public T extractItems( final T request, final Actionable mode, final BaseActionSource src ) - { - return null; - } + @Override + public T extractItems(final T request, final Actionable mode, final BaseActionSource src) { + return null; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return out; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + return out; + } - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ; + } - @Override - public boolean isPrioritized( final T input ) - { - return false; - } + @Override + public boolean isPrioritized(final T input) { + return false; + } - @Override - public boolean canAccept( final T input ) - { - return false; - } + @Override + public boolean canAccept(final T input) { + return false; + } - @Override - public int getPriority() - { - return 0; - } + @Override + public int getPriority() { + return 0; + } - @Override - public int getSlot() - { - return 0; - } + @Override + public int getSlot() { + return 0; + } - @Override - public boolean validForPass( final int i ) - { - return i == 2; - } + @Override + public boolean validForPass(final int i) { + return i == 2; + } } diff --git a/src/main/java/appeng/me/storage/SecurityInventory.java b/src/main/java/appeng/me/storage/SecurityInventory.java index 2471e674714..58d603b7e14 100644 --- a/src/main/java/appeng/me/storage/SecurityInventory.java +++ b/src/main/java/appeng/me/storage/SecurityInventory.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -34,165 +33,136 @@ import appeng.tile.misc.TileSecurity; import com.mojang.authlib.GameProfile; - -public class SecurityInventory implements IMEInventoryHandler -{ - - private final IItemList storedItems = AEApi.instance().storage().createItemList(); - private final TileSecurity securityTile; - - public SecurityInventory( final TileSecurity ts ) - { - this.securityTile = ts; - } - - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final BaseActionSource src ) - { - if( this.hasPermission( src ) ) - { - if( AEApi.instance().definitions().items().biometricCard().isSameAs( input.getItemStack() ) ) - { - if( this.canAccept( input ) ) - { - if( type == Actionable.SIMULATE ) - { - return null; - } - - this.getStoredItems().add( input ); - this.securityTile.inventoryChanged(); - return null; - } - } - } - return input; - } - - private boolean hasPermission( final BaseActionSource src ) - { - if( src.isPlayer() ) - { - try - { - return this.securityTile.getProxy().getSecurity().hasPermission( ( (PlayerSource) src ).player, SecurityPermissions.SECURITY ); - } - catch( final GridAccessException e ) - { - // :P - } - } - return false; - } - - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - if( this.hasPermission( src ) ) - { - final IAEItemStack target = this.getStoredItems().findPrecise( request ); - if( target != null ) - { - final IAEItemStack output = target.copy(); - - if( mode == Actionable.SIMULATE ) - { - return output; - } - - target.setStackSize( 0 ); - this.securityTile.inventoryChanged(); - return output; - } - } - return null; - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final IAEItemStack ais : this.getStoredItems() ) - { - out.add( ais ); - } - - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } - - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - return false; - } - - @Override - public boolean canAccept( final IAEItemStack input ) - { - if( input.getItem() instanceof IBiometricCard ) - { - final IBiometricCard tbc = (IBiometricCard) input.getItem(); - final GameProfile newUser = tbc.getProfile( input.getItemStack() ); - - final int PlayerID = AEApi.instance().registries().players().getID( newUser ); - if( this.securityTile.getOwner() == PlayerID ) - { - return false; - } - - for( final IAEItemStack ais : this.getStoredItems() ) - { - if( ais.isMeaningful() ) - { - final GameProfile thisUser = tbc.getProfile( ais.getItemStack() ); - if( thisUser == newUser ) - { - return false; - } - - if( thisUser != null && thisUser.equals( newUser ) ) - { - return false; - } - } - } - - return true; - } - return false; - } - - @Override - public int getPriority() - { - return 0; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return true; - } - - public IItemList getStoredItems() - { - return this.storedItems; - } +public class SecurityInventory implements IMEInventoryHandler { + + private final IItemList storedItems = + AEApi.instance().storage().createItemList(); + private final TileSecurity securityTile; + + public SecurityInventory(final TileSecurity ts) { + this.securityTile = ts; + } + + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable type, final BaseActionSource src) { + if (this.hasPermission(src)) { + if (AEApi.instance().definitions().items().biometricCard().isSameAs(input.getItemStack())) { + if (this.canAccept(input)) { + if (type == Actionable.SIMULATE) { + return null; + } + + this.getStoredItems().add(input); + this.securityTile.inventoryChanged(); + return null; + } + } + } + return input; + } + + private boolean hasPermission(final BaseActionSource src) { + if (src.isPlayer()) { + try { + return this.securityTile + .getProxy() + .getSecurity() + .hasPermission(((PlayerSource) src).player, SecurityPermissions.SECURITY); + } catch (final GridAccessException e) { + // :P + } + } + return false; + } + + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final BaseActionSource src) { + if (this.hasPermission(src)) { + final IAEItemStack target = this.getStoredItems().findPrecise(request); + if (target != null) { + final IAEItemStack output = target.copy(); + + if (mode == Actionable.SIMULATE) { + return output; + } + + target.setStackSize(0); + this.securityTile.inventoryChanged(); + return output; + } + } + return null; + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final IAEItemStack ais : this.getStoredItems()) { + out.add(ais); + } + + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } + + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } + + @Override + public boolean isPrioritized(final IAEItemStack input) { + return false; + } + + @Override + public boolean canAccept(final IAEItemStack input) { + if (input.getItem() instanceof IBiometricCard) { + final IBiometricCard tbc = (IBiometricCard) input.getItem(); + final GameProfile newUser = tbc.getProfile(input.getItemStack()); + + final int PlayerID = AEApi.instance().registries().players().getID(newUser); + if (this.securityTile.getOwner() == PlayerID) { + return false; + } + + for (final IAEItemStack ais : this.getStoredItems()) { + if (ais.isMeaningful()) { + final GameProfile thisUser = tbc.getProfile(ais.getItemStack()); + if (thisUser == newUser) { + return false; + } + + if (thisUser != null && thisUser.equals(newUser)) { + return false; + } + } + } + + return true; + } + return false; + } + + @Override + public int getPriority() { + return 0; + } + + @Override + public int getSlot() { + return 0; + } + + @Override + public boolean validForPass(final int i) { + return true; + } + + public IItemList getStoredItems() { + return this.storedItems; + } } diff --git a/src/main/java/appeng/me/storage/VoidFluidInventory.java b/src/main/java/appeng/me/storage/VoidFluidInventory.java index af98dc6e3aa..b2aea5e1ccb 100644 --- a/src/main/java/appeng/me/storage/VoidFluidInventory.java +++ b/src/main/java/appeng/me/storage/VoidFluidInventory.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -28,83 +27,68 @@ import appeng.api.storage.data.IItemList; import appeng.tile.misc.TileCondenser; - -public class VoidFluidInventory implements IMEInventoryHandler -{ - - private final TileCondenser target; - - public VoidFluidInventory( final TileCondenser te ) - { - this.target = te; - } - - @Override - public IAEFluidStack injectItems( final IAEFluidStack input, final Actionable mode, final BaseActionSource src ) - { - if( mode == Actionable.SIMULATE ) - { - return null; - } - - if( input != null ) - { - this.target.addPower( input.getStackSize() / 1000.0 ); - } - return null; - } - - @Override - public IAEFluidStack extractItems( final IAEFluidStack request, final Actionable mode, final BaseActionSource src ) - { - return null; - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.FLUIDS; - } - - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.WRITE; - } - - @Override - public boolean isPrioritized( final IAEFluidStack input ) - { - return false; - } - - @Override - public boolean canAccept( final IAEFluidStack input ) - { - return true; - } - - @Override - public int getPriority() - { - return 0; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return i == 2; - } +public class VoidFluidInventory implements IMEInventoryHandler { + + private final TileCondenser target; + + public VoidFluidInventory(final TileCondenser te) { + this.target = te; + } + + @Override + public IAEFluidStack injectItems(final IAEFluidStack input, final Actionable mode, final BaseActionSource src) { + if (mode == Actionable.SIMULATE) { + return null; + } + + if (input != null) { + this.target.addPower(input.getStackSize() / 1000.0); + } + return null; + } + + @Override + public IAEFluidStack extractItems(final IAEFluidStack request, final Actionable mode, final BaseActionSource src) { + return null; + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.FLUIDS; + } + + @Override + public AccessRestriction getAccess() { + return AccessRestriction.WRITE; + } + + @Override + public boolean isPrioritized(final IAEFluidStack input) { + return false; + } + + @Override + public boolean canAccept(final IAEFluidStack input) { + return true; + } + + @Override + public int getPriority() { + return 0; + } + + @Override + public int getSlot() { + return 0; + } + + @Override + public boolean validForPass(final int i) { + return i == 2; + } } diff --git a/src/main/java/appeng/me/storage/VoidItemInventory.java b/src/main/java/appeng/me/storage/VoidItemInventory.java index 57ed06fce1d..53f6a0bfef2 100644 --- a/src/main/java/appeng/me/storage/VoidItemInventory.java +++ b/src/main/java/appeng/me/storage/VoidItemInventory.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -28,83 +27,68 @@ import appeng.api.storage.data.IItemList; import appeng.tile.misc.TileCondenser; - -public class VoidItemInventory implements IMEInventoryHandler -{ - - private final TileCondenser target; - - public VoidItemInventory( final TileCondenser te ) - { - this.target = te; - } - - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - if( mode == Actionable.SIMULATE ) - { - return null; - } - - if( input != null ) - { - this.target.addPower( input.getStackSize() ); - } - return null; - } - - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - return null; - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.WRITE; - } - - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - return false; - } - - @Override - public boolean canAccept( final IAEItemStack input ) - { - return true; - } - - @Override - public int getPriority() - { - return 0; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return i == 2; - } +public class VoidItemInventory implements IMEInventoryHandler { + + private final TileCondenser target; + + public VoidItemInventory(final TileCondenser te) { + this.target = te; + } + + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode, final BaseActionSource src) { + if (mode == Actionable.SIMULATE) { + return null; + } + + if (input != null) { + this.target.addPower(input.getStackSize()); + } + return null; + } + + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final BaseActionSource src) { + return null; + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } + + @Override + public AccessRestriction getAccess() { + return AccessRestriction.WRITE; + } + + @Override + public boolean isPrioritized(final IAEItemStack input) { + return false; + } + + @Override + public boolean canAccept(final IAEItemStack input) { + return true; + } + + @Override + public int getPriority() { + return 0; + } + + @Override + public int getSlot() { + return 0; + } + + @Override + public boolean validForPass(final int i) { + return i == 2; + } } diff --git a/src/main/java/appeng/parts/AEBasePart.java b/src/main/java/appeng/parts/AEBasePart.java index e16d373b81e..13610ef5ce9 100644 --- a/src/main/java/appeng/parts/AEBasePart.java +++ b/src/main/java/appeng/parts/AEBasePart.java @@ -18,7 +18,6 @@ package appeng.parts; - import appeng.api.AEApi; import appeng.api.config.Upgrades; import appeng.api.definitions.IDefinitions; @@ -46,6 +45,11 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.IOException; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.crash.CrashReportCategory; import net.minecraft.entity.Entity; @@ -62,536 +66,430 @@ import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import java.io.IOException; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; - - -public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, IUpgradeableHost, ICustomNameObject -{ - - private final AENetworkProxy proxy; - private final ItemStack is; - private ISimplifiedBundle renderCache = null; - private TileEntity tile = null; - private IPartHost host = null; - private ForgeDirection side = null; - - public AEBasePart( final ItemStack is ) - { - Preconditions.checkNotNull( is ); - - this.is = is; - this.proxy = new AENetworkProxy( this, "part", is, this instanceof PartCable ); - this.proxy.setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - } - - public IPartHost getHost() - { - return this.host; - } - - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - return this.proxy.getNode(); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.GLASS; - } - - @Override - public void securityBreak() - { - if( this.getItemStack().stackSize > 0 ) - { - final List items = new ArrayList(); - items.add( this.getItemStack().copy() ); - this.host.removePart( this.getSide(), false ); - Platform.spawnDrops( this.tile.getWorldObj(), this.tile.xCoord, this.tile.yCoord, this.tile.zCoord, items ); - this.getItemStack().stackSize = 0; - } - } - - protected AEColor getColor() - { - if( this.host == null ) - { - return AEColor.Transparent; - } - return this.host.getColor(); - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return 0; - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setBounds( 1, 1, 1, 15, 15, 15 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 1, 1, 1, 15, 15, 15 ); - rh.renderInventoryBox( renderer ); - } - - @Override - public TileEntity getTile() - { - return this.tile; - } - - @Override - public AENetworkProxy getProxy() - { - return this.proxy; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this.tile ); - } - - @Override - public void gridChanged() - { - - } - - @Override - public IGridNode getActionableNode() - { - return this.proxy.getNode(); - } - - public void saveChanges() - { - this.host.markForSave(); - } - - @Override - public String getCustomName() - { - return this.getItemStack().getDisplayName(); - } - - @Override - public void setCustomName(String name) { - this.getItemStack().setStackDisplayName(name); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setBounds( 1, 1, 1, 15, 15, 15 ); - rh.renderBlock( x, y, z, renderer ); - } - - @Override - public boolean hasCustomName() - { - return this.getItemStack().hasDisplayName(); - } - - public void addEntityCrashInfo( final CrashReportCategory crashreportcategory ) - { - crashreportcategory.addCrashSection( "Part Side", this.getSide() ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderDynamic( final double x, final double y, final double z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - - } - - @Override - public ItemStack getItemStack( final PartItemStack type ) - { - if( type == PartItemStack.Network ) - { - final ItemStack copy = this.is.copy(); - copy.setTagCompound( null ); - return copy; - } - return this.is; - } - - @Override - public boolean isSolid() - { - return false; - } - - @Override - public void onNeighborChanged() - { - - } - - @Override - public boolean canConnectRedstone() - { - return false; - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - this.proxy.readFromNBT( data ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - this.proxy.writeToNBT( data ); - } - - @Override - public int isProvidingStrongPower() - { - return 0; - } - - @Override - public int isProvidingWeakPower() - { - return 0; - } - - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - - } - - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - return false; - } - - @Override - public IGridNode getGridNode() - { - return this.proxy.getNode(); - } - - @Override - public void onEntityCollision( final Entity entity ) - { - - } - - @Override - public void removeFromWorld() - { - this.proxy.invalidate(); - } - - @Override - public void addToWorld() - { - this.proxy.onReady(); - } - - @Override - public void setPartHostInfo( final ForgeDirection side, final IPartHost host, final TileEntity tile ) - { - this.setSide( side ); - this.tile = tile; - this.host = host; - } - - @Override - public IGridNode getExternalFacingNode() - { - return null; - } - - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World world, final int x, final int y, final int z, final Random r ) - { - - } - - @Override - public int getLightLevel() - { - return 0; - } - - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - - } - - @Override - public int cableConnectionRenderTo() - { - return 3; - } - - @Override - public boolean isLadder( final EntityLivingBase entity ) - { - return false; - } - - @Override - public IConfigManager getConfigManager() - { - return null; - } - - @Override - public IInventory getInventoryByName( final String name ) - { - return null; - } - - /** - * depending on the from, different settings will be accepted, don't call this with null - * - * @param from source of settings - * @param compound compound of source - */ - private void uploadSettings( final SettingsFrom from, final NBTTagCompound compound ) - { - if( compound != null ) - { - final IConfigManager cm = this.getConfigManager(); - if( cm != null ) - { - cm.readFromNBT( compound ); - } - } - - if( this instanceof IPriorityHost ) - { - final IPriorityHost pHost = (IPriorityHost) this; - pHost.setPriority( compound.getInteger( "priority" ) ); - } - - final IInventory inv = this.getInventoryByName( "config" ); - if( inv instanceof AppEngInternalAEInventory ) - { - final AppEngInternalAEInventory target = (AppEngInternalAEInventory) inv; - final AppEngInternalAEInventory tmp = new AppEngInternalAEInventory( null, target.getSizeInventory() ); - tmp.readFromNBT( compound, "config" ); - for( int x = 0; x < tmp.getSizeInventory(); x++ ) - { - target.setInventorySlotContents( x, tmp.getStackInSlot( x ) ); - } - } - } - - /** - * null means nothing to store... - * - * @param from source of settings - * @return compound of source - */ - private NBTTagCompound downloadSettings( final SettingsFrom from ) - { - final NBTTagCompound output = new NBTTagCompound(); - - final IConfigManager cm = this.getConfigManager(); - if( cm != null ) - { - cm.writeToNBT( output ); - } - - if( this instanceof IPriorityHost ) - { - final IPriorityHost pHost = (IPriorityHost) this; - output.setInteger( "priority", pHost.getPriority() ); - } - - final IInventory inv = this.getInventoryByName( "config" ); - if( inv instanceof AppEngInternalAEInventory ) - { - ( (AppEngInternalAEInventory) inv ).writeToNBT( output, "config" ); - } - - return output.hasNoTags() ? null : output; - } - - public boolean useStandardMemoryCard() - { - return true; - } - - private boolean useMemoryCard( final EntityPlayer player ) - { - final ItemStack memCardIS = player.inventory.getCurrentItem(); - if( memCardIS != null && this.useStandardMemoryCard() && memCardIS.getItem() instanceof IMemoryCard ) - { - if( ForgeEventFactory.onItemUseStart( player, memCardIS, 1 ) <= 0 ) - return false; - final IMemoryCard memoryCard = (IMemoryCard) memCardIS.getItem(); - - ItemStack is = this.getItemStack( PartItemStack.Network ); - - // Blocks and parts share the same soul! - final IDefinitions definitions = AEApi.instance().definitions(); - if( definitions.parts().iface().isSameAs( is ) ) - { - for( final ItemStack iface : definitions.blocks().iface().maybeStack( 1 ).asSet() ) - { - is = iface; - } - } - - final String name = is.getUnlocalizedName(); - - if( player.isSneaking() ) - { - final NBTTagCompound data = this.downloadSettings( SettingsFrom.MEMORY_CARD ); - if( data != null ) - { - memoryCard.setMemoryCardContents( memCardIS, name, data ); - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_SAVED ); - } - } - else - { - final String storedName = memoryCard.getSettingsName( memCardIS ); - final NBTTagCompound data = memoryCard.getData( memCardIS ); - if( name.equals( storedName ) ) - { - this.uploadSettings( SettingsFrom.MEMORY_CARD, data ); - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_LOADED ); - } - else - { - memoryCard.notifyUser( player, MemoryCardMessages.INVALID_MACHINE ); - } - } - return true; - } - return false; - } - private boolean useRenamer( final EntityPlayer player ) - { - final ItemStack is = player.inventory.getCurrentItem(); - if( is != null && is.getItem() instanceof ToolQuartzCuttingKnife) { - if (ForgeEventFactory.onItemUseStart(player, is, 1) <= 0) - return false; - Platform.openGUI( player, tile, side, GuiBridge.GUI_RENAMER ); - return true; - } - return false; - } - - @Override - public final boolean onActivate( final EntityPlayer player, final Vec3 pos ) - { - // int x = (int) pos.xCoord, y = (int) pos.yCoord, z = (int) pos.zCoord; - int x = this.tile.xCoord, y = this.tile.yCoord, z = this.tile.zCoord; - PlayerInteractEvent event = ForgeEventFactory.onPlayerInteract( player, PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, x, y, z, this.side.flag, player.getEntityWorld() ); - if( event.isCanceled() ) - return false; - - if (this.useMemoryCard( player ) || useRenamer(player)) - return true; - - return onPartActivate( player, pos ); - } - - @Override - public final boolean onShiftActivate( final EntityPlayer player, final Vec3 pos ) - { - // int x = (int) pos.xCoord, y = (int) pos.yCoord, z = (int) pos.zCoord; - int x = this.tile.xCoord, y = this.tile.yCoord, z = this.tile.zCoord; - PlayerInteractEvent event = ForgeEventFactory.onPlayerInteract( player, PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, x, y, z, this.side.flag, player.getEntityWorld() ); - if( event.isCanceled() ) - return false; - - if( this.useMemoryCard( player ) ) - { - return true; - } - - return this.onPartShiftActivate( player, pos ); - } - - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - return false; - } - - public boolean onPartShiftActivate( final EntityPlayer player, final Vec3 pos ) - { - return false; - } - - @Override - public void onPlacement( final EntityPlayer player, final ItemStack held, final ForgeDirection side ) - { - this.proxy.setOwner( player ); - } - - @Override - public boolean canBePlacedOn( final BusSupport what ) - { - return what == BusSupport.CABLE; - } - - @Override - public boolean requireDynamicRender() - { - return false; - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getBreakingTexture() - { - return null; - } - - public ForgeDirection getSide() - { - return this.side; - } - - private void setSide( final ForgeDirection side ) - { - this.side = side; - } - - public ItemStack getItemStack() - { - return this.is; - } - - public ISimplifiedBundle getRenderCache() - { - return this.renderCache; - } - - public void setRenderCache( final ISimplifiedBundle renderCache ) - { - this.renderCache = renderCache; - } -} \ No newline at end of file +public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, IUpgradeableHost, ICustomNameObject { + + private final AENetworkProxy proxy; + private final ItemStack is; + private ISimplifiedBundle renderCache = null; + private TileEntity tile = null; + private IPartHost host = null; + private ForgeDirection side = null; + + public AEBasePart(final ItemStack is) { + Preconditions.checkNotNull(is); + + this.is = is; + this.proxy = new AENetworkProxy(this, "part", is, this instanceof PartCable); + this.proxy.setValidSides(EnumSet.noneOf(ForgeDirection.class)); + } + + public IPartHost getHost() { + return this.host; + } + + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + return this.proxy.getNode(); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.GLASS; + } + + @Override + public void securityBreak() { + if (this.getItemStack().stackSize > 0) { + final List items = new ArrayList(); + items.add(this.getItemStack().copy()); + this.host.removePart(this.getSide(), false); + Platform.spawnDrops(this.tile.getWorldObj(), this.tile.xCoord, this.tile.yCoord, this.tile.zCoord, items); + this.getItemStack().stackSize = 0; + } + } + + protected AEColor getColor() { + if (this.host == null) { + return AEColor.Transparent; + } + return this.host.getColor(); + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) {} + + @Override + public int getInstalledUpgrades(final Upgrades u) { + return 0; + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setBounds(1, 1, 1, 15, 15, 15); + rh.renderInventoryBox(renderer); + + rh.setBounds(1, 1, 1, 15, 15, 15); + rh.renderInventoryBox(renderer); + } + + @Override + public TileEntity getTile() { + return this.tile; + } + + @Override + public AENetworkProxy getProxy() { + return this.proxy; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this.tile); + } + + @Override + public void gridChanged() {} + + @Override + public IGridNode getActionableNode() { + return this.proxy.getNode(); + } + + public void saveChanges() { + this.host.markForSave(); + } + + @Override + public String getCustomName() { + return this.getItemStack().getDisplayName(); + } + + @Override + public void setCustomName(String name) { + this.getItemStack().setStackDisplayName(name); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setBounds(1, 1, 1, 15, 15, 15); + rh.renderBlock(x, y, z, renderer); + } + + @Override + public boolean hasCustomName() { + return this.getItemStack().hasDisplayName(); + } + + public void addEntityCrashInfo(final CrashReportCategory crashreportcategory) { + crashreportcategory.addCrashSection("Part Side", this.getSide()); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderDynamic( + final double x, final double y, final double z, final IPartRenderHelper rh, final RenderBlocks renderer) {} + + @Override + public ItemStack getItemStack(final PartItemStack type) { + if (type == PartItemStack.Network) { + final ItemStack copy = this.is.copy(); + copy.setTagCompound(null); + return copy; + } + return this.is; + } + + @Override + public boolean isSolid() { + return false; + } + + @Override + public void onNeighborChanged() {} + + @Override + public boolean canConnectRedstone() { + return false; + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + this.proxy.readFromNBT(data); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + this.proxy.writeToNBT(data); + } + + @Override + public int isProvidingStrongPower() { + return 0; + } + + @Override + public int isProvidingWeakPower() { + return 0; + } + + @Override + public void writeToStream(final ByteBuf data) throws IOException {} + + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + return false; + } + + @Override + public IGridNode getGridNode() { + return this.proxy.getNode(); + } + + @Override + public void onEntityCollision(final Entity entity) {} + + @Override + public void removeFromWorld() { + this.proxy.invalidate(); + } + + @Override + public void addToWorld() { + this.proxy.onReady(); + } + + @Override + public void setPartHostInfo(final ForgeDirection side, final IPartHost host, final TileEntity tile) { + this.setSide(side); + this.tile = tile; + this.host = host; + } + + @Override + public IGridNode getExternalFacingNode() { + return null; + } + + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(final World world, final int x, final int y, final int z, final Random r) {} + + @Override + public int getLightLevel() { + return 0; + } + + @Override + public void getDrops(final List drops, final boolean wrenched) {} + + @Override + public int cableConnectionRenderTo() { + return 3; + } + + @Override + public boolean isLadder(final EntityLivingBase entity) { + return false; + } + + @Override + public IConfigManager getConfigManager() { + return null; + } + + @Override + public IInventory getInventoryByName(final String name) { + return null; + } + + /** + * depending on the from, different settings will be accepted, don't call this with null + * + * @param from source of settings + * @param compound compound of source + */ + private void uploadSettings(final SettingsFrom from, final NBTTagCompound compound) { + if (compound != null) { + final IConfigManager cm = this.getConfigManager(); + if (cm != null) { + cm.readFromNBT(compound); + } + } + + if (this instanceof IPriorityHost) { + final IPriorityHost pHost = (IPriorityHost) this; + pHost.setPriority(compound.getInteger("priority")); + } + + final IInventory inv = this.getInventoryByName("config"); + if (inv instanceof AppEngInternalAEInventory) { + final AppEngInternalAEInventory target = (AppEngInternalAEInventory) inv; + final AppEngInternalAEInventory tmp = new AppEngInternalAEInventory(null, target.getSizeInventory()); + tmp.readFromNBT(compound, "config"); + for (int x = 0; x < tmp.getSizeInventory(); x++) { + target.setInventorySlotContents(x, tmp.getStackInSlot(x)); + } + } + } + + /** + * null means nothing to store... + * + * @param from source of settings + * @return compound of source + */ + private NBTTagCompound downloadSettings(final SettingsFrom from) { + final NBTTagCompound output = new NBTTagCompound(); + + final IConfigManager cm = this.getConfigManager(); + if (cm != null) { + cm.writeToNBT(output); + } + + if (this instanceof IPriorityHost) { + final IPriorityHost pHost = (IPriorityHost) this; + output.setInteger("priority", pHost.getPriority()); + } + + final IInventory inv = this.getInventoryByName("config"); + if (inv instanceof AppEngInternalAEInventory) { + ((AppEngInternalAEInventory) inv).writeToNBT(output, "config"); + } + + return output.hasNoTags() ? null : output; + } + + public boolean useStandardMemoryCard() { + return true; + } + + private boolean useMemoryCard(final EntityPlayer player) { + final ItemStack memCardIS = player.inventory.getCurrentItem(); + if (memCardIS != null && this.useStandardMemoryCard() && memCardIS.getItem() instanceof IMemoryCard) { + if (ForgeEventFactory.onItemUseStart(player, memCardIS, 1) <= 0) return false; + final IMemoryCard memoryCard = (IMemoryCard) memCardIS.getItem(); + + ItemStack is = this.getItemStack(PartItemStack.Network); + + // Blocks and parts share the same soul! + final IDefinitions definitions = AEApi.instance().definitions(); + if (definitions.parts().iface().isSameAs(is)) { + for (final ItemStack iface : + definitions.blocks().iface().maybeStack(1).asSet()) { + is = iface; + } + } + + final String name = is.getUnlocalizedName(); + + if (player.isSneaking()) { + final NBTTagCompound data = this.downloadSettings(SettingsFrom.MEMORY_CARD); + if (data != null) { + memoryCard.setMemoryCardContents(memCardIS, name, data); + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_SAVED); + } + } else { + final String storedName = memoryCard.getSettingsName(memCardIS); + final NBTTagCompound data = memoryCard.getData(memCardIS); + if (name.equals(storedName)) { + this.uploadSettings(SettingsFrom.MEMORY_CARD, data); + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_LOADED); + } else { + memoryCard.notifyUser(player, MemoryCardMessages.INVALID_MACHINE); + } + } + return true; + } + return false; + } + + private boolean useRenamer(final EntityPlayer player) { + final ItemStack is = player.inventory.getCurrentItem(); + if (is != null && is.getItem() instanceof ToolQuartzCuttingKnife) { + if (ForgeEventFactory.onItemUseStart(player, is, 1) <= 0) return false; + Platform.openGUI(player, tile, side, GuiBridge.GUI_RENAMER); + return true; + } + return false; + } + + @Override + public final boolean onActivate(final EntityPlayer player, final Vec3 pos) { + // int x = (int) pos.xCoord, y = (int) pos.yCoord, z = (int) pos.zCoord; + int x = this.tile.xCoord, y = this.tile.yCoord, z = this.tile.zCoord; + PlayerInteractEvent event = ForgeEventFactory.onPlayerInteract( + player, PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, x, y, z, this.side.flag, player.getEntityWorld()); + if (event.isCanceled()) return false; + + if (this.useMemoryCard(player) || useRenamer(player)) return true; + + return onPartActivate(player, pos); + } + + @Override + public final boolean onShiftActivate(final EntityPlayer player, final Vec3 pos) { + // int x = (int) pos.xCoord, y = (int) pos.yCoord, z = (int) pos.zCoord; + int x = this.tile.xCoord, y = this.tile.yCoord, z = this.tile.zCoord; + PlayerInteractEvent event = ForgeEventFactory.onPlayerInteract( + player, PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, x, y, z, this.side.flag, player.getEntityWorld()); + if (event.isCanceled()) return false; + + if (this.useMemoryCard(player)) { + return true; + } + + return this.onPartShiftActivate(player, pos); + } + + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + return false; + } + + public boolean onPartShiftActivate(final EntityPlayer player, final Vec3 pos) { + return false; + } + + @Override + public void onPlacement(final EntityPlayer player, final ItemStack held, final ForgeDirection side) { + this.proxy.setOwner(player); + } + + @Override + public boolean canBePlacedOn(final BusSupport what) { + return what == BusSupport.CABLE; + } + + @Override + public boolean requireDynamicRender() { + return false; + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getBreakingTexture() { + return null; + } + + public ForgeDirection getSide() { + return this.side; + } + + private void setSide(final ForgeDirection side) { + this.side = side; + } + + public ItemStack getItemStack() { + return this.is; + } + + public ISimplifiedBundle getRenderCache() { + return this.renderCache; + } + + public void setRenderCache(final ISimplifiedBundle renderCache) { + this.renderCache = renderCache; + } +} diff --git a/src/main/java/appeng/parts/BusCollisionHelper.java b/src/main/java/appeng/parts/BusCollisionHelper.java index 32c6c90771a..0e4fedf707b 100644 --- a/src/main/java/appeng/parts/BusCollisionHelper.java +++ b/src/main/java/appeng/parts/BusCollisionHelper.java @@ -18,159 +18,150 @@ package appeng.parts; - import appeng.api.parts.IPartCollisionHelper; +import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.util.AxisAlignedBB; import net.minecraftforge.common.util.ForgeDirection; -import java.util.List; - - -public class BusCollisionHelper implements IPartCollisionHelper -{ - - private final List boxes; - - private final ForgeDirection x; - private final ForgeDirection y; - private final ForgeDirection z; - - private final Entity entity; - private final boolean isVisual; - - public BusCollisionHelper( final List boxes, final ForgeDirection x, final ForgeDirection y, final ForgeDirection z, final Entity e, final boolean visual ) - { - this.boxes = boxes; - this.x = x; - this.y = y; - this.z = z; - this.entity = e; - this.isVisual = visual; - } - - public BusCollisionHelper( final List boxes, final ForgeDirection s, final Entity e, final boolean visual ) - { - this.boxes = boxes; - this.entity = e; - this.isVisual = visual; - - switch( s ) - { - case DOWN: - this.x = ForgeDirection.EAST; - this.y = ForgeDirection.NORTH; - this.z = ForgeDirection.DOWN; - break; - case UP: - this.x = ForgeDirection.EAST; - this.y = ForgeDirection.SOUTH; - this.z = ForgeDirection.UP; - break; - case EAST: - this.x = ForgeDirection.SOUTH; - this.y = ForgeDirection.UP; - this.z = ForgeDirection.EAST; - break; - case WEST: - this.x = ForgeDirection.NORTH; - this.y = ForgeDirection.UP; - this.z = ForgeDirection.WEST; - break; - case NORTH: - this.x = ForgeDirection.WEST; - this.y = ForgeDirection.UP; - this.z = ForgeDirection.NORTH; - break; - case SOUTH: - this.x = ForgeDirection.EAST; - this.y = ForgeDirection.UP; - this.z = ForgeDirection.SOUTH; - break; - case UNKNOWN: - default: - this.x = ForgeDirection.EAST; - this.y = ForgeDirection.UP; - this.z = ForgeDirection.SOUTH; - break; - } - } - - /** - * pretty much useless... - */ - public Entity getEntity() - { - return this.entity; - } - - @Override - public void addBox( double minX, double minY, double minZ, double maxX, double maxY, double maxZ ) - { - minX /= 16.0; - minY /= 16.0; - minZ /= 16.0; - maxX /= 16.0; - maxY /= 16.0; - maxZ /= 16.0; - - double aX = minX * this.x.offsetX + minY * this.y.offsetX + minZ * this.z.offsetX; - double aY = minX * this.x.offsetY + minY * this.y.offsetY + minZ * this.z.offsetY; - double aZ = minX * this.x.offsetZ + minY * this.y.offsetZ + minZ * this.z.offsetZ; - - double bX = maxX * this.x.offsetX + maxY * this.y.offsetX + maxZ * this.z.offsetX; - double bY = maxX * this.x.offsetY + maxY * this.y.offsetY + maxZ * this.z.offsetY; - double bZ = maxX * this.x.offsetZ + maxY * this.y.offsetZ + maxZ * this.z.offsetZ; - - if( this.x.offsetX + this.y.offsetX + this.z.offsetX < 0 ) - { - aX += 1; - bX += 1; - } - - if( this.x.offsetY + this.y.offsetY + this.z.offsetY < 0 ) - { - aY += 1; - bY += 1; - } - - if( this.x.offsetZ + this.y.offsetZ + this.z.offsetZ < 0 ) - { - aZ += 1; - bZ += 1; - } - - minX = Math.min( aX, bX ); - minY = Math.min( aY, bY ); - minZ = Math.min( aZ, bZ ); - maxX = Math.max( aX, bX ); - maxY = Math.max( aY, bY ); - maxZ = Math.max( aZ, bZ ); - - this.boxes.add( AxisAlignedBB.getBoundingBox( minX, minY, minZ, maxX, maxY, maxZ ) ); - } - - @Override - public ForgeDirection getWorldX() - { - return this.x; - } - - @Override - public ForgeDirection getWorldY() - { - return this.y; - } - - @Override - public ForgeDirection getWorldZ() - { - return this.z; - } - - @Override - public boolean isBBCollision() - { - return !this.isVisual; - } +public class BusCollisionHelper implements IPartCollisionHelper { + + private final List boxes; + + private final ForgeDirection x; + private final ForgeDirection y; + private final ForgeDirection z; + + private final Entity entity; + private final boolean isVisual; + + public BusCollisionHelper( + final List boxes, + final ForgeDirection x, + final ForgeDirection y, + final ForgeDirection z, + final Entity e, + final boolean visual) { + this.boxes = boxes; + this.x = x; + this.y = y; + this.z = z; + this.entity = e; + this.isVisual = visual; + } + + public BusCollisionHelper( + final List boxes, final ForgeDirection s, final Entity e, final boolean visual) { + this.boxes = boxes; + this.entity = e; + this.isVisual = visual; + + switch (s) { + case DOWN: + this.x = ForgeDirection.EAST; + this.y = ForgeDirection.NORTH; + this.z = ForgeDirection.DOWN; + break; + case UP: + this.x = ForgeDirection.EAST; + this.y = ForgeDirection.SOUTH; + this.z = ForgeDirection.UP; + break; + case EAST: + this.x = ForgeDirection.SOUTH; + this.y = ForgeDirection.UP; + this.z = ForgeDirection.EAST; + break; + case WEST: + this.x = ForgeDirection.NORTH; + this.y = ForgeDirection.UP; + this.z = ForgeDirection.WEST; + break; + case NORTH: + this.x = ForgeDirection.WEST; + this.y = ForgeDirection.UP; + this.z = ForgeDirection.NORTH; + break; + case SOUTH: + this.x = ForgeDirection.EAST; + this.y = ForgeDirection.UP; + this.z = ForgeDirection.SOUTH; + break; + case UNKNOWN: + default: + this.x = ForgeDirection.EAST; + this.y = ForgeDirection.UP; + this.z = ForgeDirection.SOUTH; + break; + } + } + + /** + * pretty much useless... + */ + public Entity getEntity() { + return this.entity; + } + + @Override + public void addBox(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + minX /= 16.0; + minY /= 16.0; + minZ /= 16.0; + maxX /= 16.0; + maxY /= 16.0; + maxZ /= 16.0; + + double aX = minX * this.x.offsetX + minY * this.y.offsetX + minZ * this.z.offsetX; + double aY = minX * this.x.offsetY + minY * this.y.offsetY + minZ * this.z.offsetY; + double aZ = minX * this.x.offsetZ + minY * this.y.offsetZ + minZ * this.z.offsetZ; + + double bX = maxX * this.x.offsetX + maxY * this.y.offsetX + maxZ * this.z.offsetX; + double bY = maxX * this.x.offsetY + maxY * this.y.offsetY + maxZ * this.z.offsetY; + double bZ = maxX * this.x.offsetZ + maxY * this.y.offsetZ + maxZ * this.z.offsetZ; + + if (this.x.offsetX + this.y.offsetX + this.z.offsetX < 0) { + aX += 1; + bX += 1; + } + + if (this.x.offsetY + this.y.offsetY + this.z.offsetY < 0) { + aY += 1; + bY += 1; + } + + if (this.x.offsetZ + this.y.offsetZ + this.z.offsetZ < 0) { + aZ += 1; + bZ += 1; + } + + minX = Math.min(aX, bX); + minY = Math.min(aY, bY); + minZ = Math.min(aZ, bZ); + maxX = Math.max(aX, bX); + maxY = Math.max(aY, bY); + maxZ = Math.max(aZ, bZ); + + this.boxes.add(AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ)); + } + + @Override + public ForgeDirection getWorldX() { + return this.x; + } + + @Override + public ForgeDirection getWorldY() { + return this.y; + } + + @Override + public ForgeDirection getWorldZ() { + return this.z; + } + + @Override + public boolean isBBCollision() { + return !this.isVisual; + } } diff --git a/src/main/java/appeng/parts/CableBusContainer.java b/src/main/java/appeng/parts/CableBusContainer.java index 8a44d1ffd05..e3757d9aed4 100644 --- a/src/main/java/appeng/parts/CableBusContainer.java +++ b/src/main/java/appeng/parts/CableBusContainer.java @@ -18,7 +18,6 @@ package appeng.parts; - import appeng.api.AEApi; import appeng.api.config.YesNo; import appeng.api.exceptions.FailedConnection; @@ -41,6 +40,8 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.IOException; +import java.util.*; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -53,1082 +54,872 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; -import java.util.*; - - -public class CableBusContainer extends CableBusStorage implements AEMultiTile, ICableBusContainer -{ - - private static final ThreadLocal IS_LOADING = new ThreadLocal(); - private final EnumSet myLayerFlags = EnumSet.noneOf( LayerFlags.class ); - private YesNo hasRedstone = YesNo.UNDECIDED; - private IPartHost tcb; - private boolean requiresDynamicRender = false; - private boolean inWorld = false; - - public CableBusContainer( final IPartHost host ) - { - this.tcb = host; - } - - public static boolean isLoading() - { - final Boolean is = IS_LOADING.get(); - return is != null && is; - } - - public void setHost( final IPartHost host ) - { - this.tcb.clearContainer(); - this.tcb = host; - } - - public void rotateLeft() - { - final IPart[] newSides = new IPart[6]; - - newSides[ForgeDirection.UP.ordinal()] = this.getSide( ForgeDirection.UP ); - newSides[ForgeDirection.DOWN.ordinal()] = this.getSide( ForgeDirection.DOWN ); - - newSides[ForgeDirection.EAST.ordinal()] = this.getSide( ForgeDirection.NORTH ); - newSides[ForgeDirection.SOUTH.ordinal()] = this.getSide( ForgeDirection.EAST ); - newSides[ForgeDirection.WEST.ordinal()] = this.getSide( ForgeDirection.SOUTH ); - newSides[ForgeDirection.NORTH.ordinal()] = this.getSide( ForgeDirection.WEST ); - - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - this.setSide( dir, newSides[dir.ordinal()] ); - } - - this.getFacadeContainer().rotateLeft(); - } - - @Override - public IFacadeContainer getFacadeContainer() - { - return new FacadeContainer( this ); - } - - @Override - public boolean canAddPart( ItemStack is, final ForgeDirection side ) - { - if( PartPlacement.isFacade( is, side ) != null ) - { - return true; - } - - if( is.getItem() instanceof IPartItem ) - { - final IPartItem bi = (IPartItem) is.getItem(); - - is = is.copy(); - is.stackSize = 1; - - final IPart bp = bi.createPartFromItemStack( is ); - if( bp != null ) - { - if( bp instanceof IPartCable ) - { - boolean canPlace = true; - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.getPart( d ) != null && !this.getPart( d ).canBePlacedOn( ( (IPartCable) bp ).supportsBuses() ) ) - { - canPlace = false; - } - } - - if( !canPlace ) - { - return false; - } - - return this.getPart( ForgeDirection.UNKNOWN ) == null; - } - else if( !( bp instanceof IPartCable ) && side != ForgeDirection.UNKNOWN ) - { - final IPart cable = this.getPart( ForgeDirection.UNKNOWN ); - if( cable != null && !bp.canBePlacedOn( ( (IPartCable) cable ).supportsBuses() ) ) - { - return false; - } - - return this.getPart( side ) == null; - } - } - } - return false; - } - - @Override - public ForgeDirection addPart( ItemStack is, final ForgeDirection side, final EntityPlayer player ) - { - if( this.canAddPart( is, side ) ) - { - if( is.getItem() instanceof IPartItem ) - { - final IPartItem bi = (IPartItem) is.getItem(); - - is = is.copy(); - is.stackSize = 1; - - final IPart bp = bi.createPartFromItemStack( is ); - if( bp instanceof IPartCable ) - { - boolean canPlace = true; - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.getPart( d ) != null && !this.getPart( d ).canBePlacedOn( ( (IPartCable) bp ).supportsBuses() ) ) - { - canPlace = false; - } - } - - if( !canPlace ) - { - return null; - } - - if( this.getPart( ForgeDirection.UNKNOWN ) != null ) - { - return null; - } - - this.setCenter( (IPartCable) bp ); - bp.setPartHostInfo( ForgeDirection.UNKNOWN, this, this.tcb.getTile() ); - - if( player != null ) - { - bp.onPlacement( player, is, side ); - } - - if( this.inWorld ) - { - bp.addToWorld(); - } - - final IGridNode cn = this.getCenter().getGridNode(); - if( cn != null ) - { - for( final ForgeDirection ins : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart sbp = this.getPart( ins ); - if( sbp != null ) - { - final IGridNode sn = sbp.getGridNode(); - if( sn != null ) - { - try - { - new GridConnection( cn, sn, ForgeDirection.UNKNOWN ); - } - catch( final FailedConnection e ) - { - // ekk! - - bp.removeFromWorld(); - this.setCenter( null ); - return null; - } - } - } - } - } - - this.updateConnections(); - this.markForUpdate(); - this.markForSave(); - this.partChanged(); - return ForgeDirection.UNKNOWN; - } - else if( bp != null && !( bp instanceof IPartCable ) && side != ForgeDirection.UNKNOWN ) - { - final IPart cable = this.getPart( ForgeDirection.UNKNOWN ); - if( cable != null && !bp.canBePlacedOn( ( (IPartCable) cable ).supportsBuses() ) ) - { - return null; - } - - this.setSide( side, bp ); - bp.setPartHostInfo( side, this, this.getTile() ); - - if( player != null ) - { - bp.onPlacement( player, is, side ); - } - - if( this.inWorld ) - { - bp.addToWorld(); - } - - if( this.getCenter() != null ) - { - final IGridNode cn = this.getCenter().getGridNode(); - final IGridNode sn = bp.getGridNode(); - - if( cn != null && sn != null ) - { - try - { - new GridConnection( cn, sn, ForgeDirection.UNKNOWN ); - } - catch( final FailedConnection e ) - { - // ekk! - - bp.removeFromWorld(); - this.setSide( side, null ); - return null; - } - } - } - - this.updateDynamicRender(); - this.updateConnections(); - this.markForUpdate(); - this.markForSave(); - this.partChanged(); - return side; - } - } - } - return null; - } - - @Override - public IPart getPart( final ForgeDirection side ) - { - if( side == ForgeDirection.UNKNOWN ) - { - return this.getCenter(); - } - return this.getSide( side ); - } - - @Override - public void removePart( final ForgeDirection side, final boolean suppressUpdate ) - { - if( side == ForgeDirection.UNKNOWN ) - { - if( this.getCenter() != null ) - { - this.getCenter().removeFromWorld(); - } - this.setCenter( null ); - } - else - { - if( this.getSide( side ) != null ) - { - this.getSide( side ).removeFromWorld(); - } - this.setSide( side, null ); - } - - if( !suppressUpdate ) - { - this.updateDynamicRender(); - this.updateConnections(); - this.markForUpdate(); - this.markForSave(); - this.partChanged(); - } - } - - @Override - public void markForUpdate() - { - this.tcb.markForUpdate(); - } - - @Override - public DimensionalCoord getLocation() - { - return this.tcb.getLocation(); - } - - @Override - public TileEntity getTile() - { - return this.tcb.getTile(); - } - - @Override - public AEColor getColor() - { - if( this.getCenter() != null ) - { - final IPartCable c = this.getCenter(); - return c.getCableColor(); - } - return AEColor.Transparent; - } - - @Override - public void clearContainer() - { - throw new UnsupportedOperationException( "Now that is silly!" ); - } - - @Override - public boolean isBlocked( final ForgeDirection side ) - { - return this.tcb.isBlocked( side ); - } - - @Override - public SelectedPart selectPart( final Vec3 pos ) - { - for( final ForgeDirection side : ForgeDirection.values() ) - { - final IPart p = this.getPart( side ); - if( p != null ) - { - final List boxes = new LinkedList(); - - final IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); - p.getBoxes( bch ); - for( AxisAlignedBB bb : boxes ) - { - bb = bb.expand( 0.002, 0.002, 0.002 ); - if( bb.isVecInside( pos ) ) - { - return new SelectedPart( p, side ); - } - } - } - } - - if( AEApi.instance().partHelper().getCableRenderMode().opaqueFacades ) - { - final IFacadeContainer fc = this.getFacadeContainer(); - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - final IFacadePart p = fc.getFacade( side ); - if( p != null ) - { - final List boxes = new LinkedList(); - - final IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); - p.getBoxes( bch, null ); - for( AxisAlignedBB bb : boxes ) - { - bb = bb.expand( 0.01, 0.01, 0.01 ); - if( bb.isVecInside( pos ) ) - { - return new SelectedPart( p, side ); - } - } - } - } - } - - return new SelectedPart(); - } - - @Override - public void markForSave() - { - this.tcb.markForSave(); - } - - @Override - public void partChanged() - { - if( this.getCenter() == null ) - { - final List facades = new LinkedList(); - - final IFacadeContainer fc = this.getFacadeContainer(); - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - final IFacadePart fp = fc.getFacade( d ); - if( fp != null ) - { - facades.add( fp.getItemStack() ); - fc.removeFacade( this.tcb, d ); - } - } - - if( !facades.isEmpty() ) - { - final TileEntity te = this.tcb.getTile(); - Platform.spawnDrops( te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord, facades ); - } - } - - this.tcb.partChanged(); - } - - @Override - public boolean hasRedstone( final ForgeDirection side ) - { - if( this.hasRedstone == YesNo.UNDECIDED ) - { - this.updateRedstone(); - } - - return this.hasRedstone == YesNo.YES; - } - - @Override - public boolean isEmpty() - { - final IFacadeContainer fc = this.getFacadeContainer(); - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - return false; - } - - if( s != ForgeDirection.UNKNOWN ) - { - final IFacadePart fp = fc.getFacade( s ); - if( fp != null ) - { - return false; - } - } - } - return true; - } - - @Override - public Set getLayerFlags() - { - return this.myLayerFlags; - } - - @Override - public void cleanup() - { - this.tcb.cleanup(); - } - - @Override - public void notifyNeighbors() - { - this.tcb.notifyNeighbors(); - } - - @Override - public boolean isInWorld() - { - return this.inWorld; - } - - private void updateRedstone() - { - final TileEntity te = this.getTile(); - this.hasRedstone = te.getWorldObj().isBlockIndirectlyGettingPowered( te.xCoord, te.yCoord, te.zCoord ) ? YesNo.YES : YesNo.NO; - } - - private void updateDynamicRender() - { - this.setRequiresDynamicRender( false ); - for( final ForgeDirection s : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart p = this.getPart( s ); - if( p != null ) - { - this.setRequiresDynamicRender( this.isRequiresDynamicRender() || p.requireDynamicRender() ); - } - } - } - - /** - * use for FMP - */ - public void updateConnections() - { - if( this.getCenter() != null ) - { - final EnumSet sides = EnumSet.allOf( ForgeDirection.class ); - - for( final ForgeDirection s : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.getPart( s ) != null || this.isBlocked( s ) ) - { - sides.remove( s ); - } - } - - this.getCenter().setValidSides( sides ); - final IGridNode n = this.getCenter().getGridNode(); - if( n != null ) - { - n.updateState(); - } - } - } - - public void addToWorld() - { - if( this.inWorld ) - { - return; - } - - this.inWorld = true; - IS_LOADING.set( true ); - - final TileEntity te = this.getTile(); - - // start with the center, then install the side parts into the grid. - for( int x = 6; x >= 0; x-- ) - { - final ForgeDirection s = ForgeDirection.getOrientation( x ); - final IPart part = this.getPart( s ); - - if( part != null ) - { - part.setPartHostInfo( s, this, te ); - part.addToWorld(); - - if( s != ForgeDirection.UNKNOWN ) - { - final IGridNode sn = part.getGridNode(); - if( sn != null ) - { - // this is a really stupid if statement, why was this - // here? - // if ( !sn.getConnections().iterator().hasNext() ) - - final IPart center = this.getPart( ForgeDirection.UNKNOWN ); - if( center != null ) - { - final IGridNode cn = center.getGridNode(); - if( cn != null ) - { - try - { - AEApi.instance().createGridConnection( cn, sn ); - } - catch( final FailedConnection e ) - { - // ekk - } - } - } - } - } - } - } - - this.partChanged(); - - IS_LOADING.set( false ); - } - - public void removeFromWorld() - { - if( !this.inWorld ) - { - return; - } - - this.inWorld = false; - - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - part.removeFromWorld(); - } - } - - this.partChanged(); - } - - @Override - public IGridNode getGridNode( final ForgeDirection side ) - { - final IPart part = this.getPart( side ); - if( part != null ) - { - final IGridNode n = part.getExternalFacingNode(); - if( n != null ) - { - return n; - } - } - - if( this.getCenter() != null ) - { - return this.getCenter().getGridNode(); - } - - return null; - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IGridHost ) - { - final AECableType t = ( (IGridHost) part ).getCableConnectionType( dir ); - if( t != null && t != AECableType.NONE ) - { - return t; - } - } - - if( this.getCenter() != null ) - { - final IPartCable c = this.getCenter(); - return c.getCableConnectionType(); - } - return AECableType.NONE; - } - - @Override - public void securityBreak() - { - for( final ForgeDirection d : ForgeDirection.values() ) - { - final IPart p = this.getPart( d ); - if( p instanceof IGridHost ) - { - ( (IGridHost) p ).securityBreak(); - } - } - } - - public Iterable getSelectedBoundingBoxesFromPool( final boolean ignoreConnections, final boolean includeFacades, final Entity e, final boolean visual ) - { - final List boxes = new LinkedList(); - - final IFacadeContainer fc = this.getFacadeContainer(); - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPartCollisionHelper bch = new BusCollisionHelper( boxes, s, e, visual ); - - final IPart part = this.getPart( s ); - if( part != null ) - { - if( ignoreConnections && part instanceof IPartCable ) - { - bch.addBox( 6.0, 6.0, 6.0, 10.0, 10.0, 10.0 ); - } - else - { - part.getBoxes( bch ); - } - } - - if( AEApi.instance().partHelper().getCableRenderMode().opaqueFacades || !visual ) - { - if( includeFacades && s != null && s != ForgeDirection.UNKNOWN ) - { - final IFacadePart fp = fc.getFacade( s ); - if( fp != null ) - { - fp.getBoxes( bch, e ); - } - } - } - } - - return boxes; - } - - @Override - public int isProvidingStrongPower( final ForgeDirection side ) - { - final IPart part = this.getPart( side ); - return part != null ? part.isProvidingStrongPower() : 0; - } - - @Override - public int isProvidingWeakPower( final ForgeDirection side ) - { - final IPart part = this.getPart( side ); - return part != null ? part.isProvidingWeakPower() : 0; - } - - @Override - public boolean canConnectRedstone( final EnumSet enumSet ) - { - for( final ForgeDirection dir : enumSet ) - { - final IPart part = this.getPart( dir ); - if( part != null && part.canConnectRedstone() ) - { - return true; - } - } - return false; - } - - @Override - public void onEntityCollision( final Entity entity ) - { - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - part.onEntityCollision( entity ); - } - } - } - - @Override - public boolean activate( final EntityPlayer player, final Vec3 pos ) - { - final SelectedPart p = this.selectPart( pos ); - if( p != null && p.part != null ) - { - return p.part.onActivate( player, pos ); - } - return false; - } - - @Override - public void onNeighborChanged() - { - this.hasRedstone = YesNo.UNDECIDED; - - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - part.onNeighborChanged(); - } - } - } - - @Override - public boolean isSolidOnSide( final ForgeDirection side ) - { - if( side == null || side == ForgeDirection.UNKNOWN ) - { - return false; - } - - // facades are solid.. - final IFacadePart fp = this.getFacadeContainer().getFacade( side ); - if( fp != null ) - { - return true; - } - - // buses can be too. - final IPart part = this.getPart( side ); - return part != null && part.isSolid(); - } - - @Override - public boolean isLadder( final EntityLivingBase entity ) - { - for( final ForgeDirection side : ForgeDirection.values() ) - { - final IPart p = this.getPart( side ); - if( p != null ) - { - if( p.isLadder( entity ) ) - { - return true; - } - } - } - - return false; - } - - @Override - public void randomDisplayTick( final World world, final int x, final int y, final int z, final Random r ) - { - for( final ForgeDirection side : ForgeDirection.values() ) - { - final IPart p = this.getPart( side ); - if( p != null ) - { - p.randomDisplayTick( world, x, y, z, r ); - } - } - } - - @Override - public int getLightValue() - { - int light = 0; - - for( final ForgeDirection d : ForgeDirection.values() ) - { - final IPart p = this.getPart( d ); - if( p != null ) - { - light = Math.max( p.getLightLevel(), light ); - } - } - - if( light > 0 && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.CLApi ) ) - { - return ( (ICLApi) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.CLApi ) ).colorLight( this.getColor(), light ); - } - - return light; - } - - @SideOnly( Side.CLIENT ) - public void renderStatic( final double x, final double y, final double z ) - { - CableRenderHelper.getInstance().renderStatic( this, this.getFacadeContainer() ); - } - - @SideOnly( Side.CLIENT ) - public void renderDynamic( final double x, final double y, final double z ) - { - CableRenderHelper.getInstance().renderDynamic( this, x, y, z ); - } - - public void writeToStream( final ByteBuf data ) throws IOException - { - int sides = 0; - for( int x = 0; x < 7; x++ ) - { - final IPart p = this.getPart( ForgeDirection.getOrientation( x ) ); - if( p != null ) - { - sides |= ( 1 << x ); - } - } - - data.writeByte( (byte) sides ); - - for( int x = 0; x < 7; x++ ) - { - final IPart p = this.getPart( ForgeDirection.getOrientation( x ) ); - if( p != null ) - { - final ItemStack is = p.getItemStack( PartItemStack.Network ); - - data.writeShort( Item.getIdFromItem( is.getItem() ) ); - data.writeShort( is.getItemDamage() ); - - p.writeToStream( data ); - } - } - - this.getFacadeContainer().writeToStream( data ); - } - - public boolean readFromStream( final ByteBuf data ) throws IOException - { - final byte sides = data.readByte(); - - boolean updateBlock = false; - - for( int x = 0; x < 7; x++ ) - { - ForgeDirection side = ForgeDirection.getOrientation( x ); - if( ( ( sides & ( 1 << x ) ) == ( 1 << x ) ) ) - { - IPart p = this.getPart( side ); - - final short itemID = data.readShort(); - final short dmgValue = data.readShort(); - - final Item myItem = Item.getItemById( itemID ); - - final ItemStack current = p != null ? p.getItemStack( PartItemStack.Network ) : null; - if( current != null && current.getItem() == myItem && current.getItemDamage() == dmgValue ) - { - if( p.readFromStream( data ) ) - { - updateBlock = true; - } - } - else - { - this.removePart( side, false ); - side = this.addPart( new ItemStack( myItem, 1, dmgValue ), side, null ); - if( side != null ) - { - p = this.getPart( side ); - p.readFromStream( data ); - } - else - { - throw new IllegalStateException( "Invalid Stream For CableBus Container." ); - } - } - } - else if( this.getPart( side ) != null ) - { - this.removePart( side, false ); - } - } - - if( this.getFacadeContainer().readFromStream( data ) ) - { - return true; - } - - return updateBlock; - } - - public void writeToNBT( final NBTTagCompound data ) - { - data.setInteger( "hasRedstone", this.hasRedstone.ordinal() ); - - final IFacadeContainer fc = this.getFacadeContainer(); - for( final ForgeDirection s : ForgeDirection.values() ) - { - fc.writeToNBT( data ); - - final IPart part = this.getPart( s ); - if( part != null ) - { - final NBTTagCompound def = new NBTTagCompound(); - part.getItemStack( PartItemStack.World ).writeToNBT( def ); - - final NBTTagCompound extra = new NBTTagCompound(); - part.writeToNBT( extra ); - - data.setTag( "def:" + this.getSide( part ).ordinal(), def ); - data.setTag( "extra:" + this.getSide( part ).ordinal(), extra ); - } - } - } - - private ForgeDirection getSide( final IPart part ) - { - if( this.getCenter() == part ) - { - return ForgeDirection.UNKNOWN; - } - else - { - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.getSide( side ) == part ) - { - return side; - } - } - } - - throw new IllegalStateException( "Uhh Bad Part (" + part + ") on Side." ); - } - - public void readFromNBT( final NBTTagCompound data ) - { - if( data.hasKey( "hasRedstone" ) ) - { - this.hasRedstone = YesNo.values()[data.getInteger( "hasRedstone" )]; - } - - for( int x = 0; x < 7; x++ ) - { - ForgeDirection side = ForgeDirection.getOrientation( x ); - - final NBTTagCompound def = data.getCompoundTag( "def:" + side.ordinal() ); - final NBTTagCompound extra = data.getCompoundTag( "extra:" + side.ordinal() ); - if( def != null && extra != null ) - { - IPart p = this.getPart( side ); - final ItemStack iss = ItemStack.loadItemStackFromNBT( def ); - if( iss == null ) - { - continue; - } - - final ItemStack current = p == null ? null : p.getItemStack( PartItemStack.World ); - - if( Platform.isSameItemType( iss, current ) ) - { - p.readFromNBT( extra ); - } - else - { - this.removePart( side, true ); - side = this.addPart( iss, side, null ); - if( side != null ) - { - p = this.getPart( side ); - p.readFromNBT( extra ); - } - else - { - AELog.warn( "Invalid NBT For CableBus Container: " + iss.getItem().getClass().getName() + " is not a valid part; it was ignored." ); - } - } - } - else - { - this.removePart( side, false ); - } - } - - this.getFacadeContainer().readFromNBT( data ); - } - - public List getDrops( final List drops ) - { - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - drops.add( part.getItemStack( PartItemStack.Break ) ); - part.getDrops( drops, false ); - } - - if( s != ForgeDirection.UNKNOWN ) - { - final IFacadePart fp = this.getFacadeContainer().getFacade( s ); - if( fp != null ) - { - drops.add( fp.getItemStack() ); - } - } - } - - return drops; - } - - public List getNoDrops( final List drops ) - { - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - part.getDrops( drops, false ); - } - } - - return drops; - } - - @Override - public boolean recolourBlock( final ForgeDirection side, final AEColor colour, final EntityPlayer who ) - { - final IPart cable = this.getPart( ForgeDirection.UNKNOWN ); - if( cable != null ) - { - final IPartCable pc = (IPartCable) cable; - return pc.changeColor( colour, who ); - } - return false; - } - - public boolean isRequiresDynamicRender() - { - return this.requiresDynamicRender; - } - - private void setRequiresDynamicRender( final boolean requiresDynamicRender ) - { - this.requiresDynamicRender = requiresDynamicRender; - } +public class CableBusContainer extends CableBusStorage implements AEMultiTile, ICableBusContainer { + + private static final ThreadLocal IS_LOADING = new ThreadLocal(); + private final EnumSet myLayerFlags = EnumSet.noneOf(LayerFlags.class); + private YesNo hasRedstone = YesNo.UNDECIDED; + private IPartHost tcb; + private boolean requiresDynamicRender = false; + private boolean inWorld = false; + + public CableBusContainer(final IPartHost host) { + this.tcb = host; + } + + public static boolean isLoading() { + final Boolean is = IS_LOADING.get(); + return is != null && is; + } + + public void setHost(final IPartHost host) { + this.tcb.clearContainer(); + this.tcb = host; + } + + public void rotateLeft() { + final IPart[] newSides = new IPart[6]; + + newSides[ForgeDirection.UP.ordinal()] = this.getSide(ForgeDirection.UP); + newSides[ForgeDirection.DOWN.ordinal()] = this.getSide(ForgeDirection.DOWN); + + newSides[ForgeDirection.EAST.ordinal()] = this.getSide(ForgeDirection.NORTH); + newSides[ForgeDirection.SOUTH.ordinal()] = this.getSide(ForgeDirection.EAST); + newSides[ForgeDirection.WEST.ordinal()] = this.getSide(ForgeDirection.SOUTH); + newSides[ForgeDirection.NORTH.ordinal()] = this.getSide(ForgeDirection.WEST); + + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + this.setSide(dir, newSides[dir.ordinal()]); + } + + this.getFacadeContainer().rotateLeft(); + } + + @Override + public IFacadeContainer getFacadeContainer() { + return new FacadeContainer(this); + } + + @Override + public boolean canAddPart(ItemStack is, final ForgeDirection side) { + if (PartPlacement.isFacade(is, side) != null) { + return true; + } + + if (is.getItem() instanceof IPartItem) { + final IPartItem bi = (IPartItem) is.getItem(); + + is = is.copy(); + is.stackSize = 1; + + final IPart bp = bi.createPartFromItemStack(is); + if (bp != null) { + if (bp instanceof IPartCable) { + boolean canPlace = true; + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + if (this.getPart(d) != null + && !this.getPart(d).canBePlacedOn(((IPartCable) bp).supportsBuses())) { + canPlace = false; + } + } + + if (!canPlace) { + return false; + } + + return this.getPart(ForgeDirection.UNKNOWN) == null; + } else if (!(bp instanceof IPartCable) && side != ForgeDirection.UNKNOWN) { + final IPart cable = this.getPart(ForgeDirection.UNKNOWN); + if (cable != null && !bp.canBePlacedOn(((IPartCable) cable).supportsBuses())) { + return false; + } + + return this.getPart(side) == null; + } + } + } + return false; + } + + @Override + public ForgeDirection addPart(ItemStack is, final ForgeDirection side, final EntityPlayer player) { + if (this.canAddPart(is, side)) { + if (is.getItem() instanceof IPartItem) { + final IPartItem bi = (IPartItem) is.getItem(); + + is = is.copy(); + is.stackSize = 1; + + final IPart bp = bi.createPartFromItemStack(is); + if (bp instanceof IPartCable) { + boolean canPlace = true; + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + if (this.getPart(d) != null + && !this.getPart(d).canBePlacedOn(((IPartCable) bp).supportsBuses())) { + canPlace = false; + } + } + + if (!canPlace) { + return null; + } + + if (this.getPart(ForgeDirection.UNKNOWN) != null) { + return null; + } + + this.setCenter((IPartCable) bp); + bp.setPartHostInfo(ForgeDirection.UNKNOWN, this, this.tcb.getTile()); + + if (player != null) { + bp.onPlacement(player, is, side); + } + + if (this.inWorld) { + bp.addToWorld(); + } + + final IGridNode cn = this.getCenter().getGridNode(); + if (cn != null) { + for (final ForgeDirection ins : ForgeDirection.VALID_DIRECTIONS) { + final IPart sbp = this.getPart(ins); + if (sbp != null) { + final IGridNode sn = sbp.getGridNode(); + if (sn != null) { + try { + new GridConnection(cn, sn, ForgeDirection.UNKNOWN); + } catch (final FailedConnection e) { + // ekk! + + bp.removeFromWorld(); + this.setCenter(null); + return null; + } + } + } + } + } + + this.updateConnections(); + this.markForUpdate(); + this.markForSave(); + this.partChanged(); + return ForgeDirection.UNKNOWN; + } else if (bp != null && !(bp instanceof IPartCable) && side != ForgeDirection.UNKNOWN) { + final IPart cable = this.getPart(ForgeDirection.UNKNOWN); + if (cable != null && !bp.canBePlacedOn(((IPartCable) cable).supportsBuses())) { + return null; + } + + this.setSide(side, bp); + bp.setPartHostInfo(side, this, this.getTile()); + + if (player != null) { + bp.onPlacement(player, is, side); + } + + if (this.inWorld) { + bp.addToWorld(); + } + + if (this.getCenter() != null) { + final IGridNode cn = this.getCenter().getGridNode(); + final IGridNode sn = bp.getGridNode(); + + if (cn != null && sn != null) { + try { + new GridConnection(cn, sn, ForgeDirection.UNKNOWN); + } catch (final FailedConnection e) { + // ekk! + + bp.removeFromWorld(); + this.setSide(side, null); + return null; + } + } + } + + this.updateDynamicRender(); + this.updateConnections(); + this.markForUpdate(); + this.markForSave(); + this.partChanged(); + return side; + } + } + } + return null; + } + + @Override + public IPart getPart(final ForgeDirection side) { + if (side == ForgeDirection.UNKNOWN) { + return this.getCenter(); + } + return this.getSide(side); + } + + @Override + public void removePart(final ForgeDirection side, final boolean suppressUpdate) { + if (side == ForgeDirection.UNKNOWN) { + if (this.getCenter() != null) { + this.getCenter().removeFromWorld(); + } + this.setCenter(null); + } else { + if (this.getSide(side) != null) { + this.getSide(side).removeFromWorld(); + } + this.setSide(side, null); + } + + if (!suppressUpdate) { + this.updateDynamicRender(); + this.updateConnections(); + this.markForUpdate(); + this.markForSave(); + this.partChanged(); + } + } + + @Override + public void markForUpdate() { + this.tcb.markForUpdate(); + } + + @Override + public DimensionalCoord getLocation() { + return this.tcb.getLocation(); + } + + @Override + public TileEntity getTile() { + return this.tcb.getTile(); + } + + @Override + public AEColor getColor() { + if (this.getCenter() != null) { + final IPartCable c = this.getCenter(); + return c.getCableColor(); + } + return AEColor.Transparent; + } + + @Override + public void clearContainer() { + throw new UnsupportedOperationException("Now that is silly!"); + } + + @Override + public boolean isBlocked(final ForgeDirection side) { + return this.tcb.isBlocked(side); + } + + @Override + public SelectedPart selectPart(final Vec3 pos) { + for (final ForgeDirection side : ForgeDirection.values()) { + final IPart p = this.getPart(side); + if (p != null) { + final List boxes = new LinkedList(); + + final IPartCollisionHelper bch = new BusCollisionHelper(boxes, side, null, true); + p.getBoxes(bch); + for (AxisAlignedBB bb : boxes) { + bb = bb.expand(0.002, 0.002, 0.002); + if (bb.isVecInside(pos)) { + return new SelectedPart(p, side); + } + } + } + } + + if (AEApi.instance().partHelper().getCableRenderMode().opaqueFacades) { + final IFacadeContainer fc = this.getFacadeContainer(); + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + final IFacadePart p = fc.getFacade(side); + if (p != null) { + final List boxes = new LinkedList(); + + final IPartCollisionHelper bch = new BusCollisionHelper(boxes, side, null, true); + p.getBoxes(bch, null); + for (AxisAlignedBB bb : boxes) { + bb = bb.expand(0.01, 0.01, 0.01); + if (bb.isVecInside(pos)) { + return new SelectedPart(p, side); + } + } + } + } + } + + return new SelectedPart(); + } + + @Override + public void markForSave() { + this.tcb.markForSave(); + } + + @Override + public void partChanged() { + if (this.getCenter() == null) { + final List facades = new LinkedList(); + + final IFacadeContainer fc = this.getFacadeContainer(); + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + final IFacadePart fp = fc.getFacade(d); + if (fp != null) { + facades.add(fp.getItemStack()); + fc.removeFacade(this.tcb, d); + } + } + + if (!facades.isEmpty()) { + final TileEntity te = this.tcb.getTile(); + Platform.spawnDrops(te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord, facades); + } + } + + this.tcb.partChanged(); + } + + @Override + public boolean hasRedstone(final ForgeDirection side) { + if (this.hasRedstone == YesNo.UNDECIDED) { + this.updateRedstone(); + } + + return this.hasRedstone == YesNo.YES; + } + + @Override + public boolean isEmpty() { + final IFacadeContainer fc = this.getFacadeContainer(); + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = this.getPart(s); + if (part != null) { + return false; + } + + if (s != ForgeDirection.UNKNOWN) { + final IFacadePart fp = fc.getFacade(s); + if (fp != null) { + return false; + } + } + } + return true; + } + + @Override + public Set getLayerFlags() { + return this.myLayerFlags; + } + + @Override + public void cleanup() { + this.tcb.cleanup(); + } + + @Override + public void notifyNeighbors() { + this.tcb.notifyNeighbors(); + } + + @Override + public boolean isInWorld() { + return this.inWorld; + } + + private void updateRedstone() { + final TileEntity te = this.getTile(); + this.hasRedstone = te.getWorldObj().isBlockIndirectlyGettingPowered(te.xCoord, te.yCoord, te.zCoord) + ? YesNo.YES + : YesNo.NO; + } + + private void updateDynamicRender() { + this.setRequiresDynamicRender(false); + for (final ForgeDirection s : ForgeDirection.VALID_DIRECTIONS) { + final IPart p = this.getPart(s); + if (p != null) { + this.setRequiresDynamicRender(this.isRequiresDynamicRender() || p.requireDynamicRender()); + } + } + } + + /** + * use for FMP + */ + public void updateConnections() { + if (this.getCenter() != null) { + final EnumSet sides = EnumSet.allOf(ForgeDirection.class); + + for (final ForgeDirection s : ForgeDirection.VALID_DIRECTIONS) { + if (this.getPart(s) != null || this.isBlocked(s)) { + sides.remove(s); + } + } + + this.getCenter().setValidSides(sides); + final IGridNode n = this.getCenter().getGridNode(); + if (n != null) { + n.updateState(); + } + } + } + + public void addToWorld() { + if (this.inWorld) { + return; + } + + this.inWorld = true; + IS_LOADING.set(true); + + final TileEntity te = this.getTile(); + + // start with the center, then install the side parts into the grid. + for (int x = 6; x >= 0; x--) { + final ForgeDirection s = ForgeDirection.getOrientation(x); + final IPart part = this.getPart(s); + + if (part != null) { + part.setPartHostInfo(s, this, te); + part.addToWorld(); + + if (s != ForgeDirection.UNKNOWN) { + final IGridNode sn = part.getGridNode(); + if (sn != null) { + // this is a really stupid if statement, why was this + // here? + // if ( !sn.getConnections().iterator().hasNext() ) + + final IPart center = this.getPart(ForgeDirection.UNKNOWN); + if (center != null) { + final IGridNode cn = center.getGridNode(); + if (cn != null) { + try { + AEApi.instance().createGridConnection(cn, sn); + } catch (final FailedConnection e) { + // ekk + } + } + } + } + } + } + } + + this.partChanged(); + + IS_LOADING.set(false); + } + + public void removeFromWorld() { + if (!this.inWorld) { + return; + } + + this.inWorld = false; + + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = this.getPart(s); + if (part != null) { + part.removeFromWorld(); + } + } + + this.partChanged(); + } + + @Override + public IGridNode getGridNode(final ForgeDirection side) { + final IPart part = this.getPart(side); + if (part != null) { + final IGridNode n = part.getExternalFacingNode(); + if (n != null) { + return n; + } + } + + if (this.getCenter() != null) { + return this.getCenter().getGridNode(); + } + + return null; + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + final IPart part = this.getPart(dir); + if (part instanceof IGridHost) { + final AECableType t = ((IGridHost) part).getCableConnectionType(dir); + if (t != null && t != AECableType.NONE) { + return t; + } + } + + if (this.getCenter() != null) { + final IPartCable c = this.getCenter(); + return c.getCableConnectionType(); + } + return AECableType.NONE; + } + + @Override + public void securityBreak() { + for (final ForgeDirection d : ForgeDirection.values()) { + final IPart p = this.getPart(d); + if (p instanceof IGridHost) { + ((IGridHost) p).securityBreak(); + } + } + } + + public Iterable getSelectedBoundingBoxesFromPool( + final boolean ignoreConnections, final boolean includeFacades, final Entity e, final boolean visual) { + final List boxes = new LinkedList(); + + final IFacadeContainer fc = this.getFacadeContainer(); + for (final ForgeDirection s : ForgeDirection.values()) { + final IPartCollisionHelper bch = new BusCollisionHelper(boxes, s, e, visual); + + final IPart part = this.getPart(s); + if (part != null) { + if (ignoreConnections && part instanceof IPartCable) { + bch.addBox(6.0, 6.0, 6.0, 10.0, 10.0, 10.0); + } else { + part.getBoxes(bch); + } + } + + if (AEApi.instance().partHelper().getCableRenderMode().opaqueFacades || !visual) { + if (includeFacades && s != null && s != ForgeDirection.UNKNOWN) { + final IFacadePart fp = fc.getFacade(s); + if (fp != null) { + fp.getBoxes(bch, e); + } + } + } + } + + return boxes; + } + + @Override + public int isProvidingStrongPower(final ForgeDirection side) { + final IPart part = this.getPart(side); + return part != null ? part.isProvidingStrongPower() : 0; + } + + @Override + public int isProvidingWeakPower(final ForgeDirection side) { + final IPart part = this.getPart(side); + return part != null ? part.isProvidingWeakPower() : 0; + } + + @Override + public boolean canConnectRedstone(final EnumSet enumSet) { + for (final ForgeDirection dir : enumSet) { + final IPart part = this.getPart(dir); + if (part != null && part.canConnectRedstone()) { + return true; + } + } + return false; + } + + @Override + public void onEntityCollision(final Entity entity) { + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = this.getPart(s); + if (part != null) { + part.onEntityCollision(entity); + } + } + } + + @Override + public boolean activate(final EntityPlayer player, final Vec3 pos) { + final SelectedPart p = this.selectPart(pos); + if (p != null && p.part != null) { + return p.part.onActivate(player, pos); + } + return false; + } + + @Override + public void onNeighborChanged() { + this.hasRedstone = YesNo.UNDECIDED; + + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = this.getPart(s); + if (part != null) { + part.onNeighborChanged(); + } + } + } + + @Override + public boolean isSolidOnSide(final ForgeDirection side) { + if (side == null || side == ForgeDirection.UNKNOWN) { + return false; + } + + // facades are solid.. + final IFacadePart fp = this.getFacadeContainer().getFacade(side); + if (fp != null) { + return true; + } + + // buses can be too. + final IPart part = this.getPart(side); + return part != null && part.isSolid(); + } + + @Override + public boolean isLadder(final EntityLivingBase entity) { + for (final ForgeDirection side : ForgeDirection.values()) { + final IPart p = this.getPart(side); + if (p != null) { + if (p.isLadder(entity)) { + return true; + } + } + } + + return false; + } + + @Override + public void randomDisplayTick(final World world, final int x, final int y, final int z, final Random r) { + for (final ForgeDirection side : ForgeDirection.values()) { + final IPart p = this.getPart(side); + if (p != null) { + p.randomDisplayTick(world, x, y, z, r); + } + } + } + + @Override + public int getLightValue() { + int light = 0; + + for (final ForgeDirection d : ForgeDirection.values()) { + final IPart p = this.getPart(d); + if (p != null) { + light = Math.max(p.getLightLevel(), light); + } + } + + if (light > 0 && IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.CLApi)) { + return ((ICLApi) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.CLApi)) + .colorLight(this.getColor(), light); + } + + return light; + } + + @SideOnly(Side.CLIENT) + public void renderStatic(final double x, final double y, final double z) { + CableRenderHelper.getInstance().renderStatic(this, this.getFacadeContainer()); + } + + @SideOnly(Side.CLIENT) + public void renderDynamic(final double x, final double y, final double z) { + CableRenderHelper.getInstance().renderDynamic(this, x, y, z); + } + + public void writeToStream(final ByteBuf data) throws IOException { + int sides = 0; + for (int x = 0; x < 7; x++) { + final IPart p = this.getPart(ForgeDirection.getOrientation(x)); + if (p != null) { + sides |= (1 << x); + } + } + + data.writeByte((byte) sides); + + for (int x = 0; x < 7; x++) { + final IPart p = this.getPart(ForgeDirection.getOrientation(x)); + if (p != null) { + final ItemStack is = p.getItemStack(PartItemStack.Network); + + data.writeShort(Item.getIdFromItem(is.getItem())); + data.writeShort(is.getItemDamage()); + + p.writeToStream(data); + } + } + + this.getFacadeContainer().writeToStream(data); + } + + public boolean readFromStream(final ByteBuf data) throws IOException { + final byte sides = data.readByte(); + + boolean updateBlock = false; + + for (int x = 0; x < 7; x++) { + ForgeDirection side = ForgeDirection.getOrientation(x); + if (((sides & (1 << x)) == (1 << x))) { + IPart p = this.getPart(side); + + final short itemID = data.readShort(); + final short dmgValue = data.readShort(); + + final Item myItem = Item.getItemById(itemID); + + final ItemStack current = p != null ? p.getItemStack(PartItemStack.Network) : null; + if (current != null && current.getItem() == myItem && current.getItemDamage() == dmgValue) { + if (p.readFromStream(data)) { + updateBlock = true; + } + } else { + this.removePart(side, false); + side = this.addPart(new ItemStack(myItem, 1, dmgValue), side, null); + if (side != null) { + p = this.getPart(side); + p.readFromStream(data); + } else { + throw new IllegalStateException("Invalid Stream For CableBus Container."); + } + } + } else if (this.getPart(side) != null) { + this.removePart(side, false); + } + } + + if (this.getFacadeContainer().readFromStream(data)) { + return true; + } + + return updateBlock; + } + + public void writeToNBT(final NBTTagCompound data) { + data.setInteger("hasRedstone", this.hasRedstone.ordinal()); + + final IFacadeContainer fc = this.getFacadeContainer(); + for (final ForgeDirection s : ForgeDirection.values()) { + fc.writeToNBT(data); + + final IPart part = this.getPart(s); + if (part != null) { + final NBTTagCompound def = new NBTTagCompound(); + part.getItemStack(PartItemStack.World).writeToNBT(def); + + final NBTTagCompound extra = new NBTTagCompound(); + part.writeToNBT(extra); + + data.setTag("def:" + this.getSide(part).ordinal(), def); + data.setTag("extra:" + this.getSide(part).ordinal(), extra); + } + } + } + + private ForgeDirection getSide(final IPart part) { + if (this.getCenter() == part) { + return ForgeDirection.UNKNOWN; + } else { + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + if (this.getSide(side) == part) { + return side; + } + } + } + + throw new IllegalStateException("Uhh Bad Part (" + part + ") on Side."); + } + + public void readFromNBT(final NBTTagCompound data) { + if (data.hasKey("hasRedstone")) { + this.hasRedstone = YesNo.values()[data.getInteger("hasRedstone")]; + } + + for (int x = 0; x < 7; x++) { + ForgeDirection side = ForgeDirection.getOrientation(x); + + final NBTTagCompound def = data.getCompoundTag("def:" + side.ordinal()); + final NBTTagCompound extra = data.getCompoundTag("extra:" + side.ordinal()); + if (def != null && extra != null) { + IPart p = this.getPart(side); + final ItemStack iss = ItemStack.loadItemStackFromNBT(def); + if (iss == null) { + continue; + } + + final ItemStack current = p == null ? null : p.getItemStack(PartItemStack.World); + + if (Platform.isSameItemType(iss, current)) { + p.readFromNBT(extra); + } else { + this.removePart(side, true); + side = this.addPart(iss, side, null); + if (side != null) { + p = this.getPart(side); + p.readFromNBT(extra); + } else { + AELog.warn("Invalid NBT For CableBus Container: " + + iss.getItem().getClass().getName() + " is not a valid part; it was ignored."); + } + } + } else { + this.removePart(side, false); + } + } + + this.getFacadeContainer().readFromNBT(data); + } + + public List getDrops(final List drops) { + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = this.getPart(s); + if (part != null) { + drops.add(part.getItemStack(PartItemStack.Break)); + part.getDrops(drops, false); + } + + if (s != ForgeDirection.UNKNOWN) { + final IFacadePart fp = this.getFacadeContainer().getFacade(s); + if (fp != null) { + drops.add(fp.getItemStack()); + } + } + } + + return drops; + } + + public List getNoDrops(final List drops) { + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = this.getPart(s); + if (part != null) { + part.getDrops(drops, false); + } + } + + return drops; + } + + @Override + public boolean recolourBlock(final ForgeDirection side, final AEColor colour, final EntityPlayer who) { + final IPart cable = this.getPart(ForgeDirection.UNKNOWN); + if (cable != null) { + final IPartCable pc = (IPartCable) cable; + return pc.changeColor(colour, who); + } + return false; + } + + public boolean isRequiresDynamicRender() { + return this.requiresDynamicRender; + } + + private void setRequiresDynamicRender(final boolean requiresDynamicRender) { + this.requiresDynamicRender = requiresDynamicRender; + } } diff --git a/src/main/java/appeng/parts/CableBusStorage.java b/src/main/java/appeng/parts/CableBusStorage.java index cbed6da0b3e..5ae8625823b 100644 --- a/src/main/java/appeng/parts/CableBusStorage.java +++ b/src/main/java/appeng/parts/CableBusStorage.java @@ -18,129 +18,103 @@ package appeng.parts; - import appeng.api.implementations.parts.IPartCable; import appeng.api.parts.IFacadePart; import appeng.api.parts.IPart; -import net.minecraftforge.common.util.ForgeDirection; - import javax.annotation.Nullable; - +import net.minecraftforge.common.util.ForgeDirection; /** * Thin data storage to optimize memory usage for cables. */ -public class CableBusStorage -{ - - private IPartCable center; - private IPart[] sides; - private IFacadePart[] facades; - - protected IPartCable getCenter() - { - return this.center; - } - - protected void setCenter( final IPartCable center ) - { - this.center = center; - } - - protected IPart getSide( final ForgeDirection side ) - { - final int x = side.ordinal(); - if( this.sides != null && this.sides.length > x ) - { - return this.sides[x]; - } - - return null; - } - - protected void setSide( final ForgeDirection side, final IPart part ) - { - final int x = side.ordinal(); - - if( this.sides != null && this.sides.length > x && part == null ) - { - this.sides[x] = null; - this.sides = this.shrink( this.sides, true ); - } - else if( part != null ) - { - this.sides = this.grow( this.sides, x, true ); - this.sides[x] = part; - } - } - - private T[] shrink( final T[] in, final boolean parts ) - { - int newSize = -1; - for( int x = 0; x < in.length; x++ ) - { - if( in[x] != null ) - { - newSize = x; - } - } - - if( newSize == -1 ) - { - return null; - } - - newSize++; - if( newSize == in.length ) - { - return in; - } - - final T[] newArray = (T[]) ( parts ? new IPart[newSize] : new IFacadePart[newSize] ); - System.arraycopy( in, 0, newArray, 0, newSize ); - - return newArray; - } - - private T[] grow( final T[] in, final int newValue, final boolean parts ) - { - if( in != null && in.length > newValue ) - { - return in; - } - - final int newSize = newValue + 1; - - final T[] newArray = (T[]) ( parts ? new IPart[newSize] : new IFacadePart[newSize] ); - if( in != null ) - { - System.arraycopy( in, 0, newArray, 0, in.length ); - } - - return newArray; - } - - public IFacadePart getFacade( final int x ) - { - if( this.facades != null && this.facades.length > x ) - { - return this.facades[x]; - } - - return null; - } - - public void setFacade( final int x, @Nullable final IFacadePart facade ) - { - if( this.facades != null && this.facades.length > x && facade == null ) - { - this.facades[x] = null; - this.facades = this.shrink( this.facades, false ); - } - else - { - this.facades = this.grow( this.facades, x, false ); - this.facades[x] = facade; - } - } +public class CableBusStorage { + + private IPartCable center; + private IPart[] sides; + private IFacadePart[] facades; + + protected IPartCable getCenter() { + return this.center; + } + + protected void setCenter(final IPartCable center) { + this.center = center; + } + + protected IPart getSide(final ForgeDirection side) { + final int x = side.ordinal(); + if (this.sides != null && this.sides.length > x) { + return this.sides[x]; + } + + return null; + } + + protected void setSide(final ForgeDirection side, final IPart part) { + final int x = side.ordinal(); + + if (this.sides != null && this.sides.length > x && part == null) { + this.sides[x] = null; + this.sides = this.shrink(this.sides, true); + } else if (part != null) { + this.sides = this.grow(this.sides, x, true); + this.sides[x] = part; + } + } + + private T[] shrink(final T[] in, final boolean parts) { + int newSize = -1; + for (int x = 0; x < in.length; x++) { + if (in[x] != null) { + newSize = x; + } + } + + if (newSize == -1) { + return null; + } + + newSize++; + if (newSize == in.length) { + return in; + } + + final T[] newArray = (T[]) (parts ? new IPart[newSize] : new IFacadePart[newSize]); + System.arraycopy(in, 0, newArray, 0, newSize); + + return newArray; + } + + private T[] grow(final T[] in, final int newValue, final boolean parts) { + if (in != null && in.length > newValue) { + return in; + } + + final int newSize = newValue + 1; + + final T[] newArray = (T[]) (parts ? new IPart[newSize] : new IFacadePart[newSize]); + if (in != null) { + System.arraycopy(in, 0, newArray, 0, in.length); + } + + return newArray; + } + + public IFacadePart getFacade(final int x) { + if (this.facades != null && this.facades.length > x) { + return this.facades[x]; + } + + return null; + } + + public void setFacade(final int x, @Nullable final IFacadePart facade) { + if (this.facades != null && this.facades.length > x && facade == null) { + this.facades[x] = null; + this.facades = this.shrink(this.facades, false); + } else { + this.facades = this.grow(this.facades, x, false); + this.facades[x] = facade; + } + } } diff --git a/src/main/java/appeng/parts/ICableBusContainer.java b/src/main/java/appeng/parts/ICableBusContainer.java index 1384afc9da9..1ef494e43e4 100644 --- a/src/main/java/appeng/parts/ICableBusContainer.java +++ b/src/main/java/appeng/parts/ICableBusContainer.java @@ -18,11 +18,12 @@ package appeng.parts; - import appeng.api.parts.SelectedPart; import appeng.api.util.AEColor; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import java.util.Random; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -30,37 +31,32 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.Random; - - -public interface ICableBusContainer -{ +public interface ICableBusContainer { - int isProvidingStrongPower( ForgeDirection opposite ); + int isProvidingStrongPower(ForgeDirection opposite); - int isProvidingWeakPower( ForgeDirection opposite ); + int isProvidingWeakPower(ForgeDirection opposite); - boolean canConnectRedstone( EnumSet of ); + boolean canConnectRedstone(EnumSet of); - void onEntityCollision( Entity e ); + void onEntityCollision(Entity e); - boolean activate( EntityPlayer player, Vec3 vecFromPool ); + boolean activate(EntityPlayer player, Vec3 vecFromPool); - void onNeighborChanged(); + void onNeighborChanged(); - boolean isSolidOnSide( ForgeDirection side ); + boolean isSolidOnSide(ForgeDirection side); - boolean isEmpty(); + boolean isEmpty(); - SelectedPart selectPart( Vec3 v3 ); + SelectedPart selectPart(Vec3 v3); - boolean recolourBlock( ForgeDirection side, AEColor colour, EntityPlayer who ); + boolean recolourBlock(ForgeDirection side, AEColor colour, EntityPlayer who); - boolean isLadder( EntityLivingBase entity ); + boolean isLadder(EntityLivingBase entity); - @SideOnly( Side.CLIENT ) - void randomDisplayTick( World world, int x, int y, int z, Random r ); + @SideOnly(Side.CLIENT) + void randomDisplayTick(World world, int x, int y, int z, Random r); - int getLightValue(); + int getLightValue(); } diff --git a/src/main/java/appeng/parts/NullCableBusContainer.java b/src/main/java/appeng/parts/NullCableBusContainer.java index 42a02a5fab6..c8bf124ac13 100644 --- a/src/main/java/appeng/parts/NullCableBusContainer.java +++ b/src/main/java/appeng/parts/NullCableBusContainer.java @@ -18,9 +18,10 @@ package appeng.parts; - import appeng.api.parts.SelectedPart; import appeng.api.util.AEColor; +import java.util.EnumSet; +import java.util.Random; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -28,88 +29,64 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.Random; - - -public class NullCableBusContainer implements ICableBusContainer -{ - - @Override - public int isProvidingStrongPower( final ForgeDirection opposite ) - { - return 0; - } - - @Override - public int isProvidingWeakPower( final ForgeDirection opposite ) - { - return 0; - } - - @Override - public boolean canConnectRedstone( final EnumSet of ) - { - return false; - } - - @Override - public void onEntityCollision( final Entity e ) - { - - } - - @Override - public boolean activate( final EntityPlayer player, final Vec3 vecFromPool ) - { - return false; - } - - @Override - public void onNeighborChanged() - { - - } - - @Override - public boolean isSolidOnSide( final ForgeDirection side ) - { - return false; - } - - @Override - public boolean isEmpty() - { - return true; - } - - @Override - public SelectedPart selectPart( final Vec3 v3 ) - { - return new SelectedPart(); - } - - @Override - public boolean recolourBlock( final ForgeDirection side, final AEColor colour, final EntityPlayer who ) - { - return false; - } - - @Override - public boolean isLadder( final EntityLivingBase entity ) - { - return false; - } - - @Override - public void randomDisplayTick( final World world, final int x, final int y, final int z, final Random r ) - { - - } - - @Override - public int getLightValue() - { - return 0; - } +public class NullCableBusContainer implements ICableBusContainer { + + @Override + public int isProvidingStrongPower(final ForgeDirection opposite) { + return 0; + } + + @Override + public int isProvidingWeakPower(final ForgeDirection opposite) { + return 0; + } + + @Override + public boolean canConnectRedstone(final EnumSet of) { + return false; + } + + @Override + public void onEntityCollision(final Entity e) {} + + @Override + public boolean activate(final EntityPlayer player, final Vec3 vecFromPool) { + return false; + } + + @Override + public void onNeighborChanged() {} + + @Override + public boolean isSolidOnSide(final ForgeDirection side) { + return false; + } + + @Override + public boolean isEmpty() { + return true; + } + + @Override + public SelectedPart selectPart(final Vec3 v3) { + return new SelectedPart(); + } + + @Override + public boolean recolourBlock(final ForgeDirection side, final AEColor colour, final EntityPlayer who) { + return false; + } + + @Override + public boolean isLadder(final EntityLivingBase entity) { + return false; + } + + @Override + public void randomDisplayTick(final World world, final int x, final int y, final int z, final Random r) {} + + @Override + public int getLightValue() { + return 0; + } } diff --git a/src/main/java/appeng/parts/PartBasicState.java b/src/main/java/appeng/parts/PartBasicState.java index 2fe3126e883..33cbb89ac7f 100644 --- a/src/main/java/appeng/parts/PartBasicState.java +++ b/src/main/java/appeng/parts/PartBasicState.java @@ -18,7 +18,6 @@ package appeng.parts; - import appeng.api.implementations.IPowerChannelState; import appeng.api.networking.GridFlags; import appeng.api.networking.events.MENetworkChannelsChanged; @@ -30,156 +29,131 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.IOException; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; - - -public abstract class PartBasicState extends AEBasePart implements IPowerChannelState -{ - - protected static final int POWERED_FLAG = 1; - protected static final int CHANNEL_FLAG = 2; - protected static final int BOOTING_FLAG = 4; - - private int clientFlags = 0; // sent as byte. - - public PartBasicState( final ItemStack is ) - { - super( is ); - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - } - - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged c ) - { - this.getHost().markForUpdate(); - } - - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } - - @SideOnly( Side.CLIENT ) - public void renderLights( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.normalRendering(); - this.setColors( ( this.getClientFlags() & ( POWERED_FLAG | CHANNEL_FLAG ) ) == ( POWERED_FLAG | CHANNEL_FLAG ), ( this.getClientFlags() & POWERED_FLAG ) == POWERED_FLAG ); - rh.renderFace( x, y, z, CableBusTextures.PartMonitorSidesStatusLights.getIcon(), ForgeDirection.EAST, renderer ); - rh.renderFace( x, y, z, CableBusTextures.PartMonitorSidesStatusLights.getIcon(), ForgeDirection.WEST, renderer ); - rh.renderFace( x, y, z, CableBusTextures.PartMonitorSidesStatusLights.getIcon(), ForgeDirection.UP, renderer ); - rh.renderFace( x, y, z, CableBusTextures.PartMonitorSidesStatusLights.getIcon(), ForgeDirection.DOWN, renderer ); - } - - public void setColors( final boolean hasChan, final boolean hasPower ) - { - if( hasChan ) - { - final int l = 14; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - Tessellator.instance.setColorOpaque_I( this.getColor().blackVariant ); - } - else if( hasPower ) - { - final int l = 9; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - Tessellator.instance.setColorOpaque_I( this.getColor().whiteVariant ); - } - else - { - Tessellator.instance.setBrightness( 0 ); - Tessellator.instance.setColorOpaque_I( 0x000000 ); - } - } - - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - - this.setClientFlags( 0 ); - - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - this.setClientFlags( this.getClientFlags() | POWERED_FLAG ); - } - - if( this.getProxy().getNode().meetsChannelRequirements() ) - { - this.setClientFlags( this.getClientFlags() | CHANNEL_FLAG ); - } - - if( this.getProxy().getPath().isNetworkBooting() ) - { - this.setClientFlags( this.getClientFlags() | BOOTING_FLAG ); - } - - this.setClientFlags( this.populateFlags( this.getClientFlags() ) ); - } - catch( final GridAccessException e ) - { - // meh - } - - data.writeByte( (byte) this.getClientFlags() ); - } - - protected int populateFlags( final int cf ) - { - return cf; - } - - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean eh = super.readFromStream( data ); - - final int old = this.getClientFlags(); - this.setClientFlags( data.readByte() ); - - return eh || old != this.getClientFlags(); - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getBreakingTexture() - { - return CableBusTextures.PartTransitionPlaneBack.getIcon(); - } - - @Override - public boolean isPowered() - { - return ( this.getClientFlags() & POWERED_FLAG ) == POWERED_FLAG; - } - - @Override - public boolean isActive() - { - return ( this.getClientFlags() & CHANNEL_FLAG ) == CHANNEL_FLAG; - } - - @Override - public boolean isBooting() - { - return ( this.getClientFlags() & BOOTING_FLAG ) == BOOTING_FLAG; - } - - public int getClientFlags() - { - return this.clientFlags; - } - - private void setClientFlags( final int clientFlags ) - { - this.clientFlags = clientFlags; - } +public abstract class PartBasicState extends AEBasePart implements IPowerChannelState { + + protected static final int POWERED_FLAG = 1; + protected static final int CHANNEL_FLAG = 2; + protected static final int BOOTING_FLAG = 4; + + private int clientFlags = 0; // sent as byte. + + public PartBasicState(final ItemStack is) { + super(is); + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + } + + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged c) { + this.getHost().markForUpdate(); + } + + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } + + @SideOnly(Side.CLIENT) + public void renderLights( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.normalRendering(); + this.setColors( + (this.getClientFlags() & (POWERED_FLAG | CHANNEL_FLAG)) == (POWERED_FLAG | CHANNEL_FLAG), + (this.getClientFlags() & POWERED_FLAG) == POWERED_FLAG); + rh.renderFace(x, y, z, CableBusTextures.PartMonitorSidesStatusLights.getIcon(), ForgeDirection.EAST, renderer); + rh.renderFace(x, y, z, CableBusTextures.PartMonitorSidesStatusLights.getIcon(), ForgeDirection.WEST, renderer); + rh.renderFace(x, y, z, CableBusTextures.PartMonitorSidesStatusLights.getIcon(), ForgeDirection.UP, renderer); + rh.renderFace(x, y, z, CableBusTextures.PartMonitorSidesStatusLights.getIcon(), ForgeDirection.DOWN, renderer); + } + + public void setColors(final boolean hasChan, final boolean hasPower) { + if (hasChan) { + final int l = 14; + Tessellator.instance.setBrightness(l << 20 | l << 4); + Tessellator.instance.setColorOpaque_I(this.getColor().blackVariant); + } else if (hasPower) { + final int l = 9; + Tessellator.instance.setBrightness(l << 20 | l << 4); + Tessellator.instance.setColorOpaque_I(this.getColor().whiteVariant); + } else { + Tessellator.instance.setBrightness(0); + Tessellator.instance.setColorOpaque_I(0x000000); + } + } + + @Override + public void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + + this.setClientFlags(0); + + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + this.setClientFlags(this.getClientFlags() | POWERED_FLAG); + } + + if (this.getProxy().getNode().meetsChannelRequirements()) { + this.setClientFlags(this.getClientFlags() | CHANNEL_FLAG); + } + + if (this.getProxy().getPath().isNetworkBooting()) { + this.setClientFlags(this.getClientFlags() | BOOTING_FLAG); + } + + this.setClientFlags(this.populateFlags(this.getClientFlags())); + } catch (final GridAccessException e) { + // meh + } + + data.writeByte((byte) this.getClientFlags()); + } + + protected int populateFlags(final int cf) { + return cf; + } + + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + final boolean eh = super.readFromStream(data); + + final int old = this.getClientFlags(); + this.setClientFlags(data.readByte()); + + return eh || old != this.getClientFlags(); + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getBreakingTexture() { + return CableBusTextures.PartTransitionPlaneBack.getIcon(); + } + + @Override + public boolean isPowered() { + return (this.getClientFlags() & POWERED_FLAG) == POWERED_FLAG; + } + + @Override + public boolean isActive() { + return (this.getClientFlags() & CHANNEL_FLAG) == CHANNEL_FLAG; + } + + @Override + public boolean isBooting() { + return (this.getClientFlags() & BOOTING_FLAG) == BOOTING_FLAG; + } + + public int getClientFlags() { + return this.clientFlags; + } + + private void setClientFlags(final int clientFlags) { + this.clientFlags = clientFlags; + } } diff --git a/src/main/java/appeng/parts/PartPlacement.java b/src/main/java/appeng/parts/PartPlacement.java index ecc77ede505..82ceecd04a9 100644 --- a/src/main/java/appeng/parts/PartPlacement.java +++ b/src/main/java/appeng/parts/PartPlacement.java @@ -18,7 +18,6 @@ package appeng.parts; - import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IItems; @@ -39,6 +38,8 @@ import com.google.common.base.Optional; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; +import java.util.LinkedList; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.Block.SoundType; import net.minecraft.client.Minecraft; @@ -57,461 +58,441 @@ import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; import net.minecraftforge.event.world.BlockEvent; -import java.util.LinkedList; -import java.util.List; - - -public class PartPlacement -{ - - private static float eyeHeight = 0.0f; - private final ThreadLocal placing = new ThreadLocal(); - private boolean wasCanceled = false; - - public static boolean place( final ItemStack held, final int x, final int y, final int z, final int face, final EntityPlayer player, final World world, PlaceType pass, final int depth ) - { - if( depth > 3 ) - { - return false; - } - - ForgeDirection side = ForgeDirection.getOrientation( face ); - - if( held != null && Platform.isWrench( player, held, x, y, z ) && player.isSneaking() ) - { - if( !Platform.hasPermissions( new DimensionalCoord( world, x, y, z ), player ) ) - { - return false; - } - - final Block block = world.getBlock( x, y, z ); - final TileEntity tile = world.getTileEntity( x, y, z ); - IPartHost host = null; - - if( tile instanceof IPartHost ) - { - host = (IPartHost) tile; - } - - if( host != null ) - { - if( !world.isRemote ) - { - final LookDirection dir = Platform.getPlayerRay( player, getEyeOffset( player ) ); - final MovingObjectPosition mop = block.collisionRayTrace( world, x, y, z, dir.getA(), dir.getB() ); - if( mop != null ) - { - final List is = new LinkedList(); - final SelectedPart sp = selectPart( player, host, mop.hitVec.addVector( -mop.blockX, -mop.blockY, -mop.blockZ ) ); - - BlockEvent.BreakEvent event = new BlockEvent.BreakEvent( x, y, z, world, block, world.getBlockMetadata( x, y, z ), player ); - MinecraftForge.EVENT_BUS.post( event ); - if( event.isCanceled() ) - { - return false; - } - - if( sp.part != null ) - { - is.add( sp.part.getItemStack( PartItemStack.Wrench ) ); - sp.part.getDrops( is, true ); - host.removePart( sp.side, false ); - } - - if( sp.facade != null ) - { - is.add( sp.facade.getItemStack() ); - host.getFacadeContainer().removeFacade( host, sp.side ); - Platform.notifyBlocksOfNeighbors( world, x, y, z ); - } - - if( host.isEmpty() ) - { - host.cleanup(); - } - - if( !is.isEmpty() ) - { - Platform.spawnDrops( world, x, y, z, is ); - } - } - } - else - { - player.swingItem(); - NetworkHandler.instance.sendToServer( new PacketPartPlacement( x, y, z, face, getEyeOffset( player ) ) ); - } - return true; - } - - return false; - } - - TileEntity tile = world.getTileEntity( x, y, z ); - IPartHost host = null; - - if( tile instanceof IPartHost ) - { - host = (IPartHost) tile; - } - - if( held != null ) - { - final IFacadePart fp = isFacade( held, side ); - if( fp != null ) - { - if( host != null ) - { - if( !world.isRemote ) - { - if( host.getPart( ForgeDirection.UNKNOWN ) == null ) - { - return false; - } - - if( host.canAddPart( held, side ) ) - { - if( host.getFacadeContainer().addFacade( fp ) ) - { - host.markForUpdate(); - if( !player.capabilities.isCreativeMode ) - { - held.stackSize--; - if( held.stackSize == 0 ) - { - player.inventory.mainInventory[player.inventory.currentItem] = null; - MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( player, held ) ); - } - } - return true; - } - } - } - else - { - player.swingItem(); - NetworkHandler.instance.sendToServer( new PacketPartPlacement( x, y, z, face, getEyeOffset( player ) ) ); - return true; - } - } - return false; - } - } - - if( host == null && tile != null && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.FMP ) ) - { - host = ( (IFMP) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.FMP ) ).getOrCreateHost( tile ); - } - - if( host == null && tile != null && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.ImmibisMicroblocks ) ) - { - host = ( (IImmibisMicroblocks) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.ImmibisMicroblocks ) ).getOrCreateHost( player, face, tile ); - } - - // if ( held == null ) - { - final Block block = world.getBlock( x, y, z ); - if( host != null && player.isSneaking() && block != null ) - { - final LookDirection dir = Platform.getPlayerRay( player, getEyeOffset( player ) ); - final MovingObjectPosition mop = block.collisionRayTrace( world, x, y, z, dir.getA(), dir.getB() ); - if( mop != null ) - { - mop.hitVec = mop.hitVec.addVector( -mop.blockX, -mop.blockY, -mop.blockZ ); - final SelectedPart sPart = selectPart( player, host, mop.hitVec ); - if( sPart != null && sPart.part != null ) - { - if( sPart.part.onShiftActivate( player, mop.hitVec ) ) - { - if( world.isRemote ) - { - NetworkHandler.instance.sendToServer( new PacketPartPlacement( x, y, z, face, getEyeOffset( player ) ) ); - } - return true; - } - } - } - } - } - - if( held == null || !( held.getItem() instanceof IPartItem ) ) - { - return false; - } - - int te_x = x; - int te_y = y; - int te_z = z; - - final IBlockDefinition multiPart = AEApi.instance().definitions().blocks().multiPart(); - if( host == null && pass == PlaceType.PLACE_ITEM ) - { - ForgeDirection offset = ForgeDirection.UNKNOWN; - - final Block blkID = world.getBlock( x, y, z ); - if( blkID != null && !blkID.isReplaceable( world, x, y, z ) ) - { - offset = side; - if( Platform.isServer() ) - { - side = side.getOpposite(); - } - } - - te_x = x + offset.offsetX; - te_y = y + offset.offsetY; - te_z = z + offset.offsetZ; - - tile = world.getTileEntity( te_x, te_y, te_z ); - if( tile instanceof IPartHost ) - { - host = (IPartHost) tile; - } - - if( host == null && tile != null && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.FMP ) ) - { - host = ( (IFMP) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.FMP ) ).getOrCreateHost( tile ); - } - - if( host == null && tile != null && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.ImmibisMicroblocks ) ) - { - host = ( (IImmibisMicroblocks) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.ImmibisMicroblocks ) ).getOrCreateHost( player, face, tile ); - } - - final Optional maybeMultiPartStack = multiPart.maybeStack( 1 ); - final Optional maybeMultiPartBlock = multiPart.maybeBlock(); - final Optional maybeMultiPartItemBlock = multiPart.maybeItemBlock(); - - final boolean hostIsNotPresent = host == null; - final boolean multiPartPresent = maybeMultiPartBlock.isPresent() && maybeMultiPartStack.isPresent() && maybeMultiPartItemBlock.isPresent(); - final boolean canMultiPartBePlaced = maybeMultiPartBlock.get().canPlaceBlockAt( world, te_x, te_y, te_z ); - - if( hostIsNotPresent && multiPartPresent && canMultiPartBePlaced && maybeMultiPartItemBlock.get().placeBlockAt( maybeMultiPartStack.get(), player, world, te_x, te_y, te_z, side.ordinal(), 0.5f, 0.5f, 0.5f, 0 ) ) - { - if( !world.isRemote ) - { - tile = world.getTileEntity( te_x, te_y, te_z ); - - if( tile instanceof IPartHost ) - { - host = (IPartHost) tile; - } - - pass = PlaceType.INTERACT_SECOND_PASS; - } - else - { - player.swingItem(); - NetworkHandler.instance.sendToServer( new PacketPartPlacement( x, y, z, face, getEyeOffset( player ) ) ); - return true; - } - } - else if( host != null && !host.canAddPart( held, side ) ) - { - return false; - } - } - - if( host == null ) - { - return false; - } - - if( !host.canAddPart( held, side ) ) - { - if( pass == PlaceType.INTERACT_FIRST_PASS || pass == PlaceType.PLACE_ITEM ) - { - te_x = x + side.offsetX; - te_y = y + side.offsetY; - te_z = z + side.offsetZ; - - final Block blkID = world.getBlock( te_x, te_y, te_z ); - tile = world.getTileEntity( te_x, te_y, te_z ); - - if( tile != null && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.FMP ) ) - { - host = ( (IFMP) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.FMP ) ).getOrCreateHost( tile ); - } - - if( ( blkID == null || blkID.isReplaceable( world, te_x, te_y, te_z ) || host != null ) && side != ForgeDirection.UNKNOWN ) - { - return place( held, te_x, te_y, te_z, side.getOpposite().ordinal(), player, world, pass == PlaceType.INTERACT_FIRST_PASS ? PlaceType.INTERACT_SECOND_PASS : PlaceType.PLACE_ITEM, depth + 1 ); - } - } - return false; - } - - if( !world.isRemote ) - { - final Block block = world.getBlock( x, y, z ); - final LookDirection dir = Platform.getPlayerRay( player, getEyeOffset( player ) ); - final MovingObjectPosition mop = block.collisionRayTrace( world, x, y, z, dir.getA(), dir.getB() ); - if( mop != null ) - { - final SelectedPart sp = selectPart( player, host, mop.hitVec.addVector( -mop.blockX, -mop.blockY, -mop.blockZ ) ); - - if( sp.part != null ) - { - if( !player.isSneaking() && sp.part.onActivate( player, mop.hitVec ) ) - { - return false; - } - } - } - - final DimensionalCoord dc = host.getLocation(); - if( !Platform.hasPermissions( dc, player ) ) - { - return false; - } - - BlockEvent.PlaceEvent event = new BlockEvent.PlaceEvent( BlockSnapshot.getBlockSnapshot( world, x, y, z ), world.getBlock( x, y, z ), player ); - MinecraftForge.EVENT_BUS.post( event ); - if( event.isCanceled() ) - { - return false; - } - final ForgeDirection mySide = host.addPart( held, side, player ); - if( mySide != null ) - { - for( final Block multiPartBlock : multiPart.maybeBlock().asSet() ) - { - final SoundType ss = multiPartBlock.stepSound; - - world.playSoundEffect( 0.5 + x, 0.5 + y, 0.5 + z, ss.func_150496_b(), ( ss.getVolume() + 1.0F ) / 2.0F, ss.getPitch() * 0.8F ); - } - - if( !player.capabilities.isCreativeMode ) - { - held.stackSize--; - if( held.stackSize == 0 ) - { - player.inventory.mainInventory[player.inventory.currentItem] = null; - MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( player, held ) ); - } - } - } - } - else - { - player.swingItem(); - NetworkHandler.instance.sendToServer( new PacketPartPlacement( x, y, z, face, getEyeOffset( player ) ) ); - } - return true; - } - - private static float getEyeOffset( final EntityPlayer p ) - { - if( p.worldObj.isRemote ) - { - return Platform.getEyeOffset( p ); - } - - return getEyeHeight(); - } - - private static SelectedPart selectPart( final EntityPlayer player, final IPartHost host, final Vec3 pos ) - { - CommonHelper.proxy.updateRenderMode( player ); - final SelectedPart sp = host.selectPart( pos ); - CommonHelper.proxy.updateRenderMode( null ); - - return sp; - } - - public static IFacadePart isFacade( final ItemStack held, final ForgeDirection side ) - { - if( held.getItem() instanceof IFacadeItem ) - { - return ( (IFacadeItem) held.getItem() ).createPartFromItemStack( held, side ); - } - - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport bc = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - if( bc.isFacade( held ) ) - { - return bc.createFacadePart( held, side ); - } - } - - return null; - } - - private static float getEyeHeight() - { - return eyeHeight; - } - - public static void setEyeHeight( final float eyeHeight ) - { - PartPlacement.eyeHeight = eyeHeight; - } - - @SubscribeEvent - public void playerInteract( final TickEvent.ClientTickEvent event ) - { - this.wasCanceled = false; - } - - @SubscribeEvent - public void playerInteract( final PlayerInteractEvent event ) - { - if( event.action == Action.RIGHT_CLICK_AIR && event.entityPlayer.worldObj.isRemote ) - { - // re-check to see if this event was already channeled, cause these two events are really stupid... - final MovingObjectPosition mop = Platform.rayTrace( event.entityPlayer, true, false ); - final Minecraft mc = Minecraft.getMinecraft(); - - final float f = 1.0F; - final double d0 = mc.playerController.getBlockReachDistance(); - final Vec3 vec3 = mc.renderViewEntity.getPosition( f ); - - if( mop != null && mop.hitVec.distanceTo( vec3 ) < d0 ) - { - final World w = event.entity.worldObj; - final TileEntity te = w.getTileEntity( mop.blockX, mop.blockY, mop.blockZ ); - if( te instanceof IPartHost && this.wasCanceled ) - { - event.setCanceled( true ); - } - } - else - { - final ItemStack held = event.entityPlayer.getHeldItem(); - final IItems items = AEApi.instance().definitions().items(); - - boolean supportedItem = items.memoryCard().isSameAs( held ); - supportedItem |= items.colorApplicator().isSameAs( held ); - - if( event.entityPlayer.isSneaking() && held != null && supportedItem ) - { - NetworkHandler.instance.sendToServer( new PacketClick( event.x, event.y, event.z, event.face, 0, 0, 0 ) ); - } - } - } - else if( event.action == Action.RIGHT_CLICK_BLOCK && event.entityPlayer.worldObj.isRemote ) - { - if( this.placing.get() != null ) - { - return; - } - - this.placing.set( event ); - - final ItemStack held = event.entityPlayer.getHeldItem(); - if( place( held, event.x, event.y, event.z, event.face, event.entityPlayer, event.entityPlayer.worldObj, PlaceType.INTERACT_FIRST_PASS, 0 ) ) - { - event.setCanceled( true ); - this.wasCanceled = true; - } - - this.placing.set( null ); - } - } - - public enum PlaceType - { - PLACE_ITEM, INTERACT_FIRST_PASS, INTERACT_SECOND_PASS - } -} \ No newline at end of file +public class PartPlacement { + + private static float eyeHeight = 0.0f; + private final ThreadLocal placing = new ThreadLocal(); + private boolean wasCanceled = false; + + public static boolean place( + final ItemStack held, + final int x, + final int y, + final int z, + final int face, + final EntityPlayer player, + final World world, + PlaceType pass, + final int depth) { + if (depth > 3) { + return false; + } + + ForgeDirection side = ForgeDirection.getOrientation(face); + + if (held != null && Platform.isWrench(player, held, x, y, z) && player.isSneaking()) { + if (!Platform.hasPermissions(new DimensionalCoord(world, x, y, z), player)) { + return false; + } + + final Block block = world.getBlock(x, y, z); + final TileEntity tile = world.getTileEntity(x, y, z); + IPartHost host = null; + + if (tile instanceof IPartHost) { + host = (IPartHost) tile; + } + + if (host != null) { + if (!world.isRemote) { + final LookDirection dir = Platform.getPlayerRay(player, getEyeOffset(player)); + final MovingObjectPosition mop = block.collisionRayTrace(world, x, y, z, dir.getA(), dir.getB()); + if (mop != null) { + final List is = new LinkedList(); + final SelectedPart sp = + selectPart(player, host, mop.hitVec.addVector(-mop.blockX, -mop.blockY, -mop.blockZ)); + + BlockEvent.BreakEvent event = new BlockEvent.BreakEvent( + x, y, z, world, block, world.getBlockMetadata(x, y, z), player); + MinecraftForge.EVENT_BUS.post(event); + if (event.isCanceled()) { + return false; + } + + if (sp.part != null) { + is.add(sp.part.getItemStack(PartItemStack.Wrench)); + sp.part.getDrops(is, true); + host.removePart(sp.side, false); + } + + if (sp.facade != null) { + is.add(sp.facade.getItemStack()); + host.getFacadeContainer().removeFacade(host, sp.side); + Platform.notifyBlocksOfNeighbors(world, x, y, z); + } + + if (host.isEmpty()) { + host.cleanup(); + } + + if (!is.isEmpty()) { + Platform.spawnDrops(world, x, y, z, is); + } + } + } else { + player.swingItem(); + NetworkHandler.instance.sendToServer(new PacketPartPlacement(x, y, z, face, getEyeOffset(player))); + } + return true; + } + + return false; + } + + TileEntity tile = world.getTileEntity(x, y, z); + IPartHost host = null; + + if (tile instanceof IPartHost) { + host = (IPartHost) tile; + } + + if (held != null) { + final IFacadePart fp = isFacade(held, side); + if (fp != null) { + if (host != null) { + if (!world.isRemote) { + if (host.getPart(ForgeDirection.UNKNOWN) == null) { + return false; + } + + if (host.canAddPart(held, side)) { + if (host.getFacadeContainer().addFacade(fp)) { + host.markForUpdate(); + if (!player.capabilities.isCreativeMode) { + held.stackSize--; + if (held.stackSize == 0) { + player.inventory.mainInventory[player.inventory.currentItem] = null; + MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(player, held)); + } + } + return true; + } + } + } else { + player.swingItem(); + NetworkHandler.instance.sendToServer( + new PacketPartPlacement(x, y, z, face, getEyeOffset(player))); + return true; + } + } + return false; + } + } + + if (host == null && tile != null && IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.FMP)) { + host = ((IFMP) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.FMP)).getOrCreateHost(tile); + } + + if (host == null + && tile != null + && IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.ImmibisMicroblocks)) { + host = ((IImmibisMicroblocks) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.ImmibisMicroblocks)) + .getOrCreateHost(player, face, tile); + } + + // if ( held == null ) + { + final Block block = world.getBlock(x, y, z); + if (host != null && player.isSneaking() && block != null) { + final LookDirection dir = Platform.getPlayerRay(player, getEyeOffset(player)); + final MovingObjectPosition mop = block.collisionRayTrace(world, x, y, z, dir.getA(), dir.getB()); + if (mop != null) { + mop.hitVec = mop.hitVec.addVector(-mop.blockX, -mop.blockY, -mop.blockZ); + final SelectedPart sPart = selectPart(player, host, mop.hitVec); + if (sPart != null && sPart.part != null) { + if (sPart.part.onShiftActivate(player, mop.hitVec)) { + if (world.isRemote) { + NetworkHandler.instance.sendToServer( + new PacketPartPlacement(x, y, z, face, getEyeOffset(player))); + } + return true; + } + } + } + } + } + + if (held == null || !(held.getItem() instanceof IPartItem)) { + return false; + } + + int te_x = x; + int te_y = y; + int te_z = z; + + final IBlockDefinition multiPart = + AEApi.instance().definitions().blocks().multiPart(); + if (host == null && pass == PlaceType.PLACE_ITEM) { + ForgeDirection offset = ForgeDirection.UNKNOWN; + + final Block blkID = world.getBlock(x, y, z); + if (blkID != null && !blkID.isReplaceable(world, x, y, z)) { + offset = side; + if (Platform.isServer()) { + side = side.getOpposite(); + } + } + + te_x = x + offset.offsetX; + te_y = y + offset.offsetY; + te_z = z + offset.offsetZ; + + tile = world.getTileEntity(te_x, te_y, te_z); + if (tile instanceof IPartHost) { + host = (IPartHost) tile; + } + + if (host == null && tile != null && IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.FMP)) { + host = ((IFMP) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.FMP)).getOrCreateHost(tile); + } + + if (host == null + && tile != null + && IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.ImmibisMicroblocks)) { + host = ((IImmibisMicroblocks) + IntegrationRegistry.INSTANCE.getInstance(IntegrationType.ImmibisMicroblocks)) + .getOrCreateHost(player, face, tile); + } + + final Optional maybeMultiPartStack = multiPart.maybeStack(1); + final Optional maybeMultiPartBlock = multiPart.maybeBlock(); + final Optional maybeMultiPartItemBlock = multiPart.maybeItemBlock(); + + final boolean hostIsNotPresent = host == null; + final boolean multiPartPresent = maybeMultiPartBlock.isPresent() + && maybeMultiPartStack.isPresent() + && maybeMultiPartItemBlock.isPresent(); + final boolean canMultiPartBePlaced = maybeMultiPartBlock.get().canPlaceBlockAt(world, te_x, te_y, te_z); + + if (hostIsNotPresent + && multiPartPresent + && canMultiPartBePlaced + && maybeMultiPartItemBlock + .get() + .placeBlockAt( + maybeMultiPartStack.get(), + player, + world, + te_x, + te_y, + te_z, + side.ordinal(), + 0.5f, + 0.5f, + 0.5f, + 0)) { + if (!world.isRemote) { + tile = world.getTileEntity(te_x, te_y, te_z); + + if (tile instanceof IPartHost) { + host = (IPartHost) tile; + } + + pass = PlaceType.INTERACT_SECOND_PASS; + } else { + player.swingItem(); + NetworkHandler.instance.sendToServer(new PacketPartPlacement(x, y, z, face, getEyeOffset(player))); + return true; + } + } else if (host != null && !host.canAddPart(held, side)) { + return false; + } + } + + if (host == null) { + return false; + } + + if (!host.canAddPart(held, side)) { + if (pass == PlaceType.INTERACT_FIRST_PASS || pass == PlaceType.PLACE_ITEM) { + te_x = x + side.offsetX; + te_y = y + side.offsetY; + te_z = z + side.offsetZ; + + final Block blkID = world.getBlock(te_x, te_y, te_z); + tile = world.getTileEntity(te_x, te_y, te_z); + + if (tile != null && IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.FMP)) { + host = ((IFMP) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.FMP)).getOrCreateHost(tile); + } + + if ((blkID == null || blkID.isReplaceable(world, te_x, te_y, te_z) || host != null) + && side != ForgeDirection.UNKNOWN) { + return place( + held, + te_x, + te_y, + te_z, + side.getOpposite().ordinal(), + player, + world, + pass == PlaceType.INTERACT_FIRST_PASS + ? PlaceType.INTERACT_SECOND_PASS + : PlaceType.PLACE_ITEM, + depth + 1); + } + } + return false; + } + + if (!world.isRemote) { + final Block block = world.getBlock(x, y, z); + final LookDirection dir = Platform.getPlayerRay(player, getEyeOffset(player)); + final MovingObjectPosition mop = block.collisionRayTrace(world, x, y, z, dir.getA(), dir.getB()); + if (mop != null) { + final SelectedPart sp = + selectPart(player, host, mop.hitVec.addVector(-mop.blockX, -mop.blockY, -mop.blockZ)); + + if (sp.part != null) { + if (!player.isSneaking() && sp.part.onActivate(player, mop.hitVec)) { + return false; + } + } + } + + final DimensionalCoord dc = host.getLocation(); + if (!Platform.hasPermissions(dc, player)) { + return false; + } + + BlockEvent.PlaceEvent event = new BlockEvent.PlaceEvent( + BlockSnapshot.getBlockSnapshot(world, x, y, z), world.getBlock(x, y, z), player); + MinecraftForge.EVENT_BUS.post(event); + if (event.isCanceled()) { + return false; + } + final ForgeDirection mySide = host.addPart(held, side, player); + if (mySide != null) { + for (final Block multiPartBlock : multiPart.maybeBlock().asSet()) { + final SoundType ss = multiPartBlock.stepSound; + + world.playSoundEffect( + 0.5 + x, + 0.5 + y, + 0.5 + z, + ss.func_150496_b(), + (ss.getVolume() + 1.0F) / 2.0F, + ss.getPitch() * 0.8F); + } + + if (!player.capabilities.isCreativeMode) { + held.stackSize--; + if (held.stackSize == 0) { + player.inventory.mainInventory[player.inventory.currentItem] = null; + MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(player, held)); + } + } + } + } else { + player.swingItem(); + NetworkHandler.instance.sendToServer(new PacketPartPlacement(x, y, z, face, getEyeOffset(player))); + } + return true; + } + + private static float getEyeOffset(final EntityPlayer p) { + if (p.worldObj.isRemote) { + return Platform.getEyeOffset(p); + } + + return getEyeHeight(); + } + + private static SelectedPart selectPart(final EntityPlayer player, final IPartHost host, final Vec3 pos) { + CommonHelper.proxy.updateRenderMode(player); + final SelectedPart sp = host.selectPart(pos); + CommonHelper.proxy.updateRenderMode(null); + + return sp; + } + + public static IFacadePart isFacade(final ItemStack held, final ForgeDirection side) { + if (held.getItem() instanceof IFacadeItem) { + return ((IFacadeItem) held.getItem()).createPartFromItemStack(held, side); + } + + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport)) { + final IBuildCraftTransport bc = (IBuildCraftTransport) + IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport); + if (bc.isFacade(held)) { + return bc.createFacadePart(held, side); + } + } + + return null; + } + + private static float getEyeHeight() { + return eyeHeight; + } + + public static void setEyeHeight(final float eyeHeight) { + PartPlacement.eyeHeight = eyeHeight; + } + + @SubscribeEvent + public void playerInteract(final TickEvent.ClientTickEvent event) { + this.wasCanceled = false; + } + + @SubscribeEvent + public void playerInteract(final PlayerInteractEvent event) { + if (event.action == Action.RIGHT_CLICK_AIR && event.entityPlayer.worldObj.isRemote) { + // re-check to see if this event was already channeled, cause these two events are really stupid... + final MovingObjectPosition mop = Platform.rayTrace(event.entityPlayer, true, false); + final Minecraft mc = Minecraft.getMinecraft(); + + final float f = 1.0F; + final double d0 = mc.playerController.getBlockReachDistance(); + final Vec3 vec3 = mc.renderViewEntity.getPosition(f); + + if (mop != null && mop.hitVec.distanceTo(vec3) < d0) { + final World w = event.entity.worldObj; + final TileEntity te = w.getTileEntity(mop.blockX, mop.blockY, mop.blockZ); + if (te instanceof IPartHost && this.wasCanceled) { + event.setCanceled(true); + } + } else { + final ItemStack held = event.entityPlayer.getHeldItem(); + final IItems items = AEApi.instance().definitions().items(); + + boolean supportedItem = items.memoryCard().isSameAs(held); + supportedItem |= items.colorApplicator().isSameAs(held); + + if (event.entityPlayer.isSneaking() && held != null && supportedItem) { + NetworkHandler.instance.sendToServer( + new PacketClick(event.x, event.y, event.z, event.face, 0, 0, 0)); + } + } + } else if (event.action == Action.RIGHT_CLICK_BLOCK && event.entityPlayer.worldObj.isRemote) { + if (this.placing.get() != null) { + return; + } + + this.placing.set(event); + + final ItemStack held = event.entityPlayer.getHeldItem(); + if (place( + held, + event.x, + event.y, + event.z, + event.face, + event.entityPlayer, + event.entityPlayer.worldObj, + PlaceType.INTERACT_FIRST_PASS, + 0)) { + event.setCanceled(true); + this.wasCanceled = true; + } + + this.placing.set(null); + } + } + + public enum PlaceType { + PLACE_ITEM, + INTERACT_FIRST_PASS, + INTERACT_SECOND_PASS + } +} diff --git a/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java b/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java index 6504026e29a..a3c11b59b2a 100644 --- a/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java @@ -1,6 +1,5 @@ package appeng.parts.automation; - import appeng.api.config.Upgrades; import appeng.tile.inventory.IAEAppEngInventory; import net.minecraft.block.Block; @@ -8,33 +7,27 @@ import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; +public class BlockUpgradeInventory extends UpgradeInventory { + private final Block block; -public class BlockUpgradeInventory extends UpgradeInventory -{ - private final Block block; - - public BlockUpgradeInventory( final Block block, final IAEAppEngInventory parent, final int s ) - { - super( parent, s ); - this.block = block; - } + public BlockUpgradeInventory(final Block block, final IAEAppEngInventory parent, final int s) { + super(parent, s); + this.block = block; + } - @Override - public int getMaxInstalled( final Upgrades upgrades ) - { - int max = 0; + @Override + public int getMaxInstalled(final Upgrades upgrades) { + int max = 0; - for( final ItemStack is : upgrades.getSupported().keySet() ) - { - final Item encodedItem = is.getItem(); + for (final ItemStack is : upgrades.getSupported().keySet()) { + final Item encodedItem = is.getItem(); - if( encodedItem instanceof ItemBlock && Block.getBlockFromItem( encodedItem ) == this.block ) - { - max = upgrades.getSupported().get( is ); - break; - } - } + if (encodedItem instanceof ItemBlock && Block.getBlockFromItem(encodedItem) == this.block) { + max = upgrades.getSupported().get(is); + break; + } + } - return max; - } + return max; + } } diff --git a/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java b/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java index ba5436d28ef..23ad6ee6f71 100644 --- a/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java @@ -1,37 +1,30 @@ package appeng.parts.automation; - import appeng.api.config.Upgrades; import appeng.api.definitions.IItemDefinition; import appeng.tile.inventory.IAEAppEngInventory; import net.minecraft.item.ItemStack; +public final class DefinitionUpgradeInventory extends UpgradeInventory { + private final IItemDefinition definition; -public final class DefinitionUpgradeInventory extends UpgradeInventory -{ - private final IItemDefinition definition; - - public DefinitionUpgradeInventory( final IItemDefinition definition, final IAEAppEngInventory parent, final int s ) - { - super( parent, s ); + public DefinitionUpgradeInventory(final IItemDefinition definition, final IAEAppEngInventory parent, final int s) { + super(parent, s); - this.definition = definition; - } + this.definition = definition; + } - @Override - public int getMaxInstalled( final Upgrades upgrades ) - { - int max = 0; + @Override + public int getMaxInstalled(final Upgrades upgrades) { + int max = 0; - for( final ItemStack stack : upgrades.getSupported().keySet() ) - { - if( this.definition.isSameAs( stack ) ) - { - max = upgrades.getSupported().get( stack ); - break; - } - } + for (final ItemStack stack : upgrades.getSupported().keySet()) { + if (this.definition.isSameAs(stack)) { + max = upgrades.getSupported().get(stack); + break; + } + } - return max; - } + return max; + } } diff --git a/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java b/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java index 1011c9ef390..5f1f8b67422 100644 --- a/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java +++ b/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java @@ -18,7 +18,6 @@ package appeng.parts.automation; - import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; import appeng.api.config.YesNo; @@ -51,6 +50,7 @@ import com.google.common.collect.Lists; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.RenderBlocks; @@ -59,7 +59,6 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; -import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.IIcon; @@ -69,533 +68,517 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.world.BlockEvent; -import java.util.List; - - -public class PartAnnihilationPlane extends PartBasicState implements IGridTickable, IWorldCallable -{ - private static final IIcon SIDE_ICON = CableBusTextures.PartPlaneSides.getIcon(); - private static final IIcon BACK_ICON = CableBusTextures.PartTransitionPlaneBack.getIcon(); - private static final IIcon STATUS_ICON = CableBusTextures.PartMonitorSidesStatus.getIcon(); - private static final IIcon ACTIVE_ICON = CableBusTextures.BlockAnnihilationPlaneOn.getIcon(); - private static final int MAX_CACHE_TIME = 60; - - private final BaseActionSource mySrc = new MachineSource( this ); - private EntityPlayer owner = null; - private boolean isAccepting = true; - private boolean breaking = false; - private YesNo permissionCache = YesNo.UNDECIDED; - private int cacheTime = 0; - - public PartAnnihilationPlane( final ItemStack is ) - { - super( is ); - } - - @Override - public void onPlacement( EntityPlayer player, ItemStack held, ForgeDirection side ) - { - super.onPlacement( player, held, side ); - this.owner = player; - } - - @Override - public TickRateModulation call( final World world ) throws Exception - { - this.breaking = false; - return this.breakBlock( true ); - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - int minX = 1; - int minY = 1; - int maxX = 15; - int maxY = 15; - - final IPartHost host = this.getHost(); - if( host != null ) - { - final TileEntity te = host.getTile(); - - final int x = te.xCoord; - final int y = te.yCoord; - final int z = te.zCoord; - - final ForgeDirection e = bch.getWorldX(); - final ForgeDirection u = bch.getWorldY(); - - if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x - e.offsetX, y - e.offsetY, z - e.offsetZ ), this.getSide() ) ) - { - minX = 0; - } - - if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.getSide() ) ) - { - maxX = 16; - } - - if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.getSide() ) ) - { - minY = 0; - } - - if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.getSide() ) ) - { - maxY = 16; - } - } - - bch.addBox( 5, 5, 14, 11, 11, 15 ); - bch.addBox( minX, minY, 15, maxX, maxY, bch.isBBCollision() ? 15 : 16 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( SIDE_ICON, SIDE_ICON, BACK_ICON, this.getItemStack().getIconIndex(), SIDE_ICON, SIDE_ICON ); - - rh.setBounds( 1, 1, 15, 15, 15, 16 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 5, 5, 14, 11, 11, 15 ); - rh.renderInventoryBox( renderer ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.renderStaticWithIcon( x, y, z, rh, renderer, ACTIVE_ICON ); - } - - protected void renderStaticWithIcon( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer, final IIcon activeIcon ) - { - int minX = 1; - - final ForgeDirection e = rh.getWorldX(); - final ForgeDirection u = rh.getWorldY(); - - final TileEntity te = this.getHost().getTile(); - - if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x - e.offsetX, y - e.offsetY, z - e.offsetZ ), this.getSide() ) ) - { - minX = 0; - } - - int maxX = 15; - if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.getSide() ) ) - { - maxX = 16; - } - - int minY = 1; - if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.getSide() ) ) - { - minY = 0; - } - - int maxY = 15; - if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.getSide() ) ) - { - maxY = 16; - } - - final boolean isActive = ( this.getClientFlags() & ( PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG ) ) == ( PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG ); - - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( SIDE_ICON, SIDE_ICON, BACK_ICON, isActive ? activeIcon : this.getItemStack().getIconIndex(), SIDE_ICON, SIDE_ICON ); - - rh.setBounds( minX, minY, 15, maxX, maxY, 16 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( STATUS_ICON, STATUS_ICON, BACK_ICON, isActive ? activeIcon : this.getItemStack().getIconIndex(), STATUS_ICON, STATUS_ICON ); - - rh.setBounds( 5, 5, 14, 11, 11, 15 ); - rh.renderBlock( x, y, z, renderer ); - - this.renderLights( x, y, z, rh, renderer ); - } - - @Override - public void onNeighborChanged() - { - this.isAccepting = true; - try - { - this.getProxy().getTick().alertDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - @Override - public void onEntityCollision( final Entity entity ) - { - if( this.isAccepting && entity instanceof EntityItem && !entity.isDead && Platform.isServer() && this.getProxy().isActive() ) - { - boolean capture = false; - - switch( this.getSide() ) - { - case DOWN: - case UP: - if( entity.posX > this.getTile().xCoord && entity.posX < this.getTile().xCoord + 1 ) - { - if( entity.posZ > this.getTile().zCoord && entity.posZ < this.getTile().zCoord + 1 ) - { - if( ( entity.posY > this.getTile().yCoord + 0.9 && this.getSide() == ForgeDirection.UP ) || ( entity.posY < this.getTile().yCoord + 0.1 && this.getSide() == ForgeDirection.DOWN ) ) - { - capture = true; - } - } - } - break; - case SOUTH: - case NORTH: - if( entity.posX > this.getTile().xCoord && entity.posX < this.getTile().xCoord + 1 ) - { - if( entity.posY > this.getTile().yCoord && entity.posY < this.getTile().yCoord + 1 ) - { - if( ( entity.posZ > this.getTile().zCoord + 0.9 && this.getSide() == ForgeDirection.SOUTH ) || ( entity.posZ < this.getTile().zCoord + 0.1 && this.getSide() == ForgeDirection.NORTH ) ) - { - capture = true; - } - } - } - break; - case EAST: - case WEST: - if( entity.posZ > this.getTile().zCoord && entity.posZ < this.getTile().zCoord + 1 ) - { - if( entity.posY > this.getTile().yCoord && entity.posY < this.getTile().yCoord + 1 ) - { - if( ( entity.posX > this.getTile().xCoord + 0.9 && this.getSide() == ForgeDirection.EAST ) || ( entity.posX < this.getTile().xCoord + 0.1 && this.getSide() == ForgeDirection.WEST ) ) - { - capture = true; - } - } - } - break; - default: - // umm? - break; - } - - if( capture ) - { - final boolean changed = this.storeEntityItem( (EntityItem) entity ); - - if( changed ) - { - ServerHelper.proxy.sendToAllNearExcept( null, this.getTile().xCoord, this.getTile().yCoord, this.getTile().zCoord, 64, this.getTile().getWorldObj(), new PacketTransitionEffect( entity.posX, entity.posY, entity.posZ, this.getSide(), false ) ); - } - } - } - } - - @Override - public int cableConnectionRenderTo() - { - return 1; - } - - /** - * Stores an {@link EntityItem} inside the network and either marks it as dead or sets it to the leftover stackSize. - * - * @param entityItem {@link EntityItem} to store - */ - private boolean storeEntityItem( final EntityItem entityItem ) - { - if( !entityItem.isDead ) - { - final IAEItemStack overflow = this.storeItemStack( entityItem.getEntityItem() ); - - return this.handleOverflow( entityItem, overflow ); - } - - return false; - } - - /** - * Stores an {@link ItemStack} inside the network. - * - * @param item {@link ItemStack} to store - * @return the leftover items, which could not be stored inside the network - */ - private IAEItemStack storeItemStack( final ItemStack item ) - { - final IAEItemStack itemToStore = AEItemStack.create( item ); - try - { - final IStorageGrid storage = this.getProxy().getStorage(); - final IEnergyGrid energy = this.getProxy().getEnergy(); - final IAEItemStack overflow = Platform.poweredInsert( energy, storage.getItemInventory(), itemToStore, this.mySrc ); - - this.isAccepting = overflow == null; - - return overflow; - } - catch( final GridAccessException e1 ) - { - // :P - } - - return null; - } - - /** - * Handles a possible overflow or none at all. - * It will update the entity to match the leftover stack size as well as mark it as dead without any leftover - * amount. - * - * @param entityItem the entity to update or destroy - * @param overflow the leftover {@link IAEItemStack} - * @return true, if the entity was changed otherwise false. - */ - private boolean handleOverflow( final EntityItem entityItem, final IAEItemStack overflow ) - { - if( overflow == null || overflow.getStackSize() == 0 ) - { - entityItem.setDead(); - return true; - } - - final int oldStackSize = entityItem.getEntityItem().stackSize; - final int newStackSize = (int) overflow.getStackSize(); - final boolean changed = oldStackSize != newStackSize; - - entityItem.getEntityItem().stackSize = newStackSize; - - return changed; - } - - /** - * Spawns an overflow item as new {@link EntityItem} into the {@link World} - * - * @param overflow the item to spawn - */ - private void spawnOverflow( final IAEItemStack overflow ) - { - if( overflow == null ) - { - return; - } - - final TileEntity te = this.getTile(); - final WorldServer w = (WorldServer) te.getWorldObj(); - final double x = te.xCoord + this.getSide().offsetX + .5d; - final double y = te.yCoord + this.getSide().offsetY + .5d; - final double z = te.zCoord + this.getSide().offsetZ + .5d; - - final EntityItem overflowEntity = new EntityItem( w, x, y, z, overflow.getItemStack() ); - overflowEntity.motionX = 0; - overflowEntity.motionY = 0; - overflowEntity.motionZ = 0; - - w.spawnEntityInWorld( overflowEntity ); - } - - protected boolean isAnnihilationPlane( final TileEntity blockTileEntity, final ForgeDirection side ) - { - if( blockTileEntity instanceof IPartHost ) - { - final IPart p = ( (IPartHost) blockTileEntity ).getPart( side ); - return p != null && p.getClass() == this.getClass(); - } - return false; - } - - @Override - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged c ) - { - this.onNeighborChanged(); - this.getHost().markForUpdate(); - } - - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.onNeighborChanged(); - this.getHost().markForUpdate(); - } - - private TickRateModulation breakBlock( final boolean modulate ) - { - if( this.isAccepting && this.getProxy().isActive() ) - { - try - { - final TileEntity te = this.getTile(); - final WorldServer w = (WorldServer) te.getWorldObj(); - - final int x = te.xCoord + this.getSide().offsetX; - final int y = te.yCoord + this.getSide().offsetY; - final int z = te.zCoord + this.getSide().offsetZ; - - final IEnergyGrid energy = this.getProxy().getEnergy(); - - if( this.canHandleBlock( w, x, y, z ) ) - { - final List items = this.obtainBlockDrops( w, x, y, z ); - final float requiredPower = this.calculateEnergyUsage( w, x, y, z, items ); - - final boolean hasPower = energy.extractAEPower( requiredPower, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > requiredPower - 0.1; - final boolean canStore = this.canStoreItemStacks( items ); - - if( hasPower && canStore ) - { - if( modulate ) - { - energy.extractAEPower( requiredPower, Actionable.MODULATE, PowerMultiplier.CONFIG ); - this.breakBlockAndStoreItems( w, x, y, z, items ); - ServerHelper.proxy.sendToAllNearExcept( null, x, y, z, 64, w, new PacketTransitionEffect( x, y, z, this.getSide(), true ) ); - } - else - { - this.breaking = true; - TickHandler.INSTANCE.addCallable( this.getTile().getWorldObj(), this ); - } - return TickRateModulation.URGENT; - } - } - } - catch( final GridAccessException e1 ) - { - // :P - } - } - - // nothing to do here :) - return TickRateModulation.IDLE; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.AnnihilationPlane.getMin(), TickRates.AnnihilationPlane.getMax(), false, true ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( this.breaking ) - { - return TickRateModulation.URGENT; - } - - if( ticksSinceLastCall == 120 || cacheTime >= MAX_CACHE_TIME ) - { - cacheTime = 0; - permissionCache = YesNo.UNDECIDED; - } - cacheTime += ticksSinceLastCall - 120; - this.isAccepting = true; - return this.breakBlock( false ); - } - - /** - * Checks if this plane can handle the block at the specific coordinates. - */ - private boolean canHandleBlock( final WorldServer w, final int x, final int y, final int z ) - { - final Block block = w.getBlock( x, y, z ); - final Material material = block.getMaterial(); - final float hardness = block.getBlockHardness( w, x, y, z ); - final boolean ignoreMaterials = material == Material.air || material == Material.lava || material == Material.water || material.isLiquid(); - final boolean ignoreBlocks = block == Blocks.bedrock || block == Blocks.end_portal || block == Blocks.end_portal_frame || block == Blocks.command_block; - final EntityPlayer player = owner == null ? Platform.getPlayer( w ) : owner; - if( permissionCache == YesNo.UNDECIDED ) - { - BlockEvent.BreakEvent event = new BlockEvent.BreakEvent( x, y, z, w, block, w.getBlockMetadata( x, y, z ), player ); - MinecraftForge.EVENT_BUS.post( event ); - permissionCache = ( event.isCanceled() ) ? YesNo.NO : YesNo.YES; - } - return permissionCache == YesNo.YES && !ignoreMaterials && !ignoreBlocks && !w.isAirBlock( x, y, z ) && w.blockExists( x, y, z ) && w.canMineBlock( player , x, y, z ) && hardness >= 0f; - } - - protected List obtainBlockDrops( final WorldServer w, final int x, final int y, final int z ) - { - final ItemStack[] out = Platform.getBlockDrops( w, x, y, z ); - return Lists.newArrayList( out ); - } - - /** - * Checks if this plane can handle the block at the specific coordinates. - */ - protected float calculateEnergyUsage( final WorldServer w, final int x, final int y, final int z, final List items ) - { - final Block block = w.getBlock( x, y, z ); - final float hardness = block.getBlockHardness( w, x, y, z ); - - float requiredEnergy = 1 + hardness; - for( final ItemStack is : items ) - { - requiredEnergy += is.stackSize; - } - - return requiredEnergy; - } - - /** - * Checks if the network can store the possible drops. - *

- * It also sets isAccepting to false, if the item can not be stored. - * - * @param itemStacks an array of {@link ItemStack} to test - * @return true, if the network can store at least a single item of all drops or no drops are reported - */ - private boolean canStoreItemStacks( final List itemStacks ) - { - boolean canStore = itemStacks.isEmpty(); - - try - { - final IStorageGrid storage = this.getProxy().getStorage(); - - for( final ItemStack itemStack : itemStacks ) - { - final IAEItemStack itemToTest = AEItemStack.create( itemStack ); - final IAEItemStack overflow = storage.getItemInventory().injectItems( itemToTest, Actionable.SIMULATE, this.mySrc ); - if( overflow == null || itemToTest.getStackSize() > overflow.getStackSize() ) - { - canStore = true; - } - } - } - catch( final GridAccessException e ) - { - // :P - } - - this.isAccepting = canStore; - return canStore; - } - - private void breakBlockAndStoreItems( final WorldServer w, final int x, final int y, final int z, final List items ) - { - w.setBlock( x, y, z, Platform.AIR_BLOCK, 0, 3 ); - - final AxisAlignedBB box = AxisAlignedBB.getBoundingBox( x - 0.2, y - 0.2, z - 0.2, x + 1.2, y + 1.2, z + 1.2 ); - for( final Object ei : w.getEntitiesWithinAABB( EntityItem.class, box ) ) - { - if( ei instanceof EntityItem ) - { - final EntityItem entityItem = (EntityItem) ei; - this.storeEntityItem( entityItem ); - } - } - - for( final ItemStack snaggedItem : items ) - { - final IAEItemStack overflow = this.storeItemStack( snaggedItem ); - this.spawnOverflow( overflow ); - } - } +public class PartAnnihilationPlane extends PartBasicState implements IGridTickable, IWorldCallable { + private static final IIcon SIDE_ICON = CableBusTextures.PartPlaneSides.getIcon(); + private static final IIcon BACK_ICON = CableBusTextures.PartTransitionPlaneBack.getIcon(); + private static final IIcon STATUS_ICON = CableBusTextures.PartMonitorSidesStatus.getIcon(); + private static final IIcon ACTIVE_ICON = CableBusTextures.BlockAnnihilationPlaneOn.getIcon(); + private static final int MAX_CACHE_TIME = 60; + + private final BaseActionSource mySrc = new MachineSource(this); + private EntityPlayer owner = null; + private boolean isAccepting = true; + private boolean breaking = false; + private YesNo permissionCache = YesNo.UNDECIDED; + private int cacheTime = 0; + + public PartAnnihilationPlane(final ItemStack is) { + super(is); + } + + @Override + public void onPlacement(EntityPlayer player, ItemStack held, ForgeDirection side) { + super.onPlacement(player, held, side); + this.owner = player; + } + + @Override + public TickRateModulation call(final World world) throws Exception { + this.breaking = false; + return this.breakBlock(true); + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + int minX = 1; + int minY = 1; + int maxX = 15; + int maxY = 15; + + final IPartHost host = this.getHost(); + if (host != null) { + final TileEntity te = host.getTile(); + + final int x = te.xCoord; + final int y = te.yCoord; + final int z = te.zCoord; + + final ForgeDirection e = bch.getWorldX(); + final ForgeDirection u = bch.getWorldY(); + + if (this.isAnnihilationPlane( + te.getWorldObj().getTileEntity(x - e.offsetX, y - e.offsetY, z - e.offsetZ), this.getSide())) { + minX = 0; + } + + if (this.isAnnihilationPlane( + te.getWorldObj().getTileEntity(x + e.offsetX, y + e.offsetY, z + e.offsetZ), this.getSide())) { + maxX = 16; + } + + if (this.isAnnihilationPlane( + te.getWorldObj().getTileEntity(x - u.offsetX, y - u.offsetY, z - u.offsetZ), this.getSide())) { + minY = 0; + } + + if (this.isAnnihilationPlane( + te.getWorldObj().getTileEntity(x + u.offsetX, y + u.offsetY, z + u.offsetZ), this.getSide())) { + maxY = 16; + } + } + + bch.addBox(5, 5, 14, 11, 11, 15); + bch.addBox(minX, minY, 15, maxX, maxY, bch.isBBCollision() ? 15 : 16); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture(SIDE_ICON, SIDE_ICON, BACK_ICON, this.getItemStack().getIconIndex(), SIDE_ICON, SIDE_ICON); + + rh.setBounds(1, 1, 15, 15, 15, 16); + rh.renderInventoryBox(renderer); + + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderInventoryBox(renderer); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + this.renderStaticWithIcon(x, y, z, rh, renderer, ACTIVE_ICON); + } + + protected void renderStaticWithIcon( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer, + final IIcon activeIcon) { + int minX = 1; + + final ForgeDirection e = rh.getWorldX(); + final ForgeDirection u = rh.getWorldY(); + + final TileEntity te = this.getHost().getTile(); + + if (this.isAnnihilationPlane( + te.getWorldObj().getTileEntity(x - e.offsetX, y - e.offsetY, z - e.offsetZ), this.getSide())) { + minX = 0; + } + + int maxX = 15; + if (this.isAnnihilationPlane( + te.getWorldObj().getTileEntity(x + e.offsetX, y + e.offsetY, z + e.offsetZ), this.getSide())) { + maxX = 16; + } + + int minY = 1; + if (this.isAnnihilationPlane( + te.getWorldObj().getTileEntity(x - u.offsetX, y - u.offsetY, z - u.offsetZ), this.getSide())) { + minY = 0; + } + + int maxY = 15; + if (this.isAnnihilationPlane( + te.getWorldObj().getTileEntity(x + u.offsetX, y + u.offsetY, z + u.offsetZ), this.getSide())) { + maxY = 16; + } + + final boolean isActive = (this.getClientFlags() & (PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG)) + == (PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG); + + this.setRenderCache(rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache())); + rh.setTexture( + SIDE_ICON, + SIDE_ICON, + BACK_ICON, + isActive ? activeIcon : this.getItemStack().getIconIndex(), + SIDE_ICON, + SIDE_ICON); + + rh.setBounds(minX, minY, 15, maxX, maxY, 16); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture( + STATUS_ICON, + STATUS_ICON, + BACK_ICON, + isActive ? activeIcon : this.getItemStack().getIconIndex(), + STATUS_ICON, + STATUS_ICON); + + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderBlock(x, y, z, renderer); + + this.renderLights(x, y, z, rh, renderer); + } + + @Override + public void onNeighborChanged() { + this.isAccepting = true; + try { + this.getProxy().getTick().alertDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // :P + } + } + + @Override + public void onEntityCollision(final Entity entity) { + if (this.isAccepting + && entity instanceof EntityItem + && !entity.isDead + && Platform.isServer() + && this.getProxy().isActive()) { + boolean capture = false; + + switch (this.getSide()) { + case DOWN: + case UP: + if (entity.posX > this.getTile().xCoord && entity.posX < this.getTile().xCoord + 1) { + if (entity.posZ > this.getTile().zCoord && entity.posZ < this.getTile().zCoord + 1) { + if ((entity.posY > this.getTile().yCoord + 0.9 && this.getSide() == ForgeDirection.UP) + || (entity.posY < this.getTile().yCoord + 0.1 + && this.getSide() == ForgeDirection.DOWN)) { + capture = true; + } + } + } + break; + case SOUTH: + case NORTH: + if (entity.posX > this.getTile().xCoord && entity.posX < this.getTile().xCoord + 1) { + if (entity.posY > this.getTile().yCoord && entity.posY < this.getTile().yCoord + 1) { + if ((entity.posZ > this.getTile().zCoord + 0.9 && this.getSide() == ForgeDirection.SOUTH) + || (entity.posZ < this.getTile().zCoord + 0.1 + && this.getSide() == ForgeDirection.NORTH)) { + capture = true; + } + } + } + break; + case EAST: + case WEST: + if (entity.posZ > this.getTile().zCoord && entity.posZ < this.getTile().zCoord + 1) { + if (entity.posY > this.getTile().yCoord && entity.posY < this.getTile().yCoord + 1) { + if ((entity.posX > this.getTile().xCoord + 0.9 && this.getSide() == ForgeDirection.EAST) + || (entity.posX < this.getTile().xCoord + 0.1 + && this.getSide() == ForgeDirection.WEST)) { + capture = true; + } + } + } + break; + default: + // umm? + break; + } + + if (capture) { + final boolean changed = this.storeEntityItem((EntityItem) entity); + + if (changed) { + ServerHelper.proxy.sendToAllNearExcept( + null, + this.getTile().xCoord, + this.getTile().yCoord, + this.getTile().zCoord, + 64, + this.getTile().getWorldObj(), + new PacketTransitionEffect(entity.posX, entity.posY, entity.posZ, this.getSide(), false)); + } + } + } + } + + @Override + public int cableConnectionRenderTo() { + return 1; + } + + /** + * Stores an {@link EntityItem} inside the network and either marks it as dead or sets it to the leftover stackSize. + * + * @param entityItem {@link EntityItem} to store + */ + private boolean storeEntityItem(final EntityItem entityItem) { + if (!entityItem.isDead) { + final IAEItemStack overflow = this.storeItemStack(entityItem.getEntityItem()); + + return this.handleOverflow(entityItem, overflow); + } + + return false; + } + + /** + * Stores an {@link ItemStack} inside the network. + * + * @param item {@link ItemStack} to store + * @return the leftover items, which could not be stored inside the network + */ + private IAEItemStack storeItemStack(final ItemStack item) { + final IAEItemStack itemToStore = AEItemStack.create(item); + try { + final IStorageGrid storage = this.getProxy().getStorage(); + final IEnergyGrid energy = this.getProxy().getEnergy(); + final IAEItemStack overflow = + Platform.poweredInsert(energy, storage.getItemInventory(), itemToStore, this.mySrc); + + this.isAccepting = overflow == null; + + return overflow; + } catch (final GridAccessException e1) { + // :P + } + + return null; + } + + /** + * Handles a possible overflow or none at all. + * It will update the entity to match the leftover stack size as well as mark it as dead without any leftover + * amount. + * + * @param entityItem the entity to update or destroy + * @param overflow the leftover {@link IAEItemStack} + * @return true, if the entity was changed otherwise false. + */ + private boolean handleOverflow(final EntityItem entityItem, final IAEItemStack overflow) { + if (overflow == null || overflow.getStackSize() == 0) { + entityItem.setDead(); + return true; + } + + final int oldStackSize = entityItem.getEntityItem().stackSize; + final int newStackSize = (int) overflow.getStackSize(); + final boolean changed = oldStackSize != newStackSize; + + entityItem.getEntityItem().stackSize = newStackSize; + + return changed; + } + + /** + * Spawns an overflow item as new {@link EntityItem} into the {@link World} + * + * @param overflow the item to spawn + */ + private void spawnOverflow(final IAEItemStack overflow) { + if (overflow == null) { + return; + } + + final TileEntity te = this.getTile(); + final WorldServer w = (WorldServer) te.getWorldObj(); + final double x = te.xCoord + this.getSide().offsetX + .5d; + final double y = te.yCoord + this.getSide().offsetY + .5d; + final double z = te.zCoord + this.getSide().offsetZ + .5d; + + final EntityItem overflowEntity = new EntityItem(w, x, y, z, overflow.getItemStack()); + overflowEntity.motionX = 0; + overflowEntity.motionY = 0; + overflowEntity.motionZ = 0; + + w.spawnEntityInWorld(overflowEntity); + } + + protected boolean isAnnihilationPlane(final TileEntity blockTileEntity, final ForgeDirection side) { + if (blockTileEntity instanceof IPartHost) { + final IPart p = ((IPartHost) blockTileEntity).getPart(side); + return p != null && p.getClass() == this.getClass(); + } + return false; + } + + @Override + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged c) { + this.onNeighborChanged(); + this.getHost().markForUpdate(); + } + + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.onNeighborChanged(); + this.getHost().markForUpdate(); + } + + private TickRateModulation breakBlock(final boolean modulate) { + if (this.isAccepting && this.getProxy().isActive()) { + try { + final TileEntity te = this.getTile(); + final WorldServer w = (WorldServer) te.getWorldObj(); + + final int x = te.xCoord + this.getSide().offsetX; + final int y = te.yCoord + this.getSide().offsetY; + final int z = te.zCoord + this.getSide().offsetZ; + + final IEnergyGrid energy = this.getProxy().getEnergy(); + + if (this.canHandleBlock(w, x, y, z)) { + final List items = this.obtainBlockDrops(w, x, y, z); + final float requiredPower = this.calculateEnergyUsage(w, x, y, z, items); + + final boolean hasPower = + energy.extractAEPower(requiredPower, Actionable.SIMULATE, PowerMultiplier.CONFIG) + > requiredPower - 0.1; + final boolean canStore = this.canStoreItemStacks(items); + + if (hasPower && canStore) { + if (modulate) { + energy.extractAEPower(requiredPower, Actionable.MODULATE, PowerMultiplier.CONFIG); + this.breakBlockAndStoreItems(w, x, y, z, items); + ServerHelper.proxy.sendToAllNearExcept( + null, x, y, z, 64, w, new PacketTransitionEffect(x, y, z, this.getSide(), true)); + } else { + this.breaking = true; + TickHandler.INSTANCE.addCallable(this.getTile().getWorldObj(), this); + } + return TickRateModulation.URGENT; + } + } + } catch (final GridAccessException e1) { + // :P + } + } + + // nothing to do here :) + return TickRateModulation.IDLE; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest( + TickRates.AnnihilationPlane.getMin(), TickRates.AnnihilationPlane.getMax(), false, true); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (this.breaking) { + return TickRateModulation.URGENT; + } + + if (ticksSinceLastCall == 120 || cacheTime >= MAX_CACHE_TIME) { + cacheTime = 0; + permissionCache = YesNo.UNDECIDED; + } + cacheTime += ticksSinceLastCall - 120; + this.isAccepting = true; + return this.breakBlock(false); + } + + /** + * Checks if this plane can handle the block at the specific coordinates. + */ + private boolean canHandleBlock(final WorldServer w, final int x, final int y, final int z) { + final Block block = w.getBlock(x, y, z); + final Material material = block.getMaterial(); + final float hardness = block.getBlockHardness(w, x, y, z); + final boolean ignoreMaterials = material == Material.air + || material == Material.lava + || material == Material.water + || material.isLiquid(); + final boolean ignoreBlocks = block == Blocks.bedrock + || block == Blocks.end_portal + || block == Blocks.end_portal_frame + || block == Blocks.command_block; + final EntityPlayer player = owner == null ? Platform.getPlayer(w) : owner; + if (permissionCache == YesNo.UNDECIDED) { + BlockEvent.BreakEvent event = + new BlockEvent.BreakEvent(x, y, z, w, block, w.getBlockMetadata(x, y, z), player); + MinecraftForge.EVENT_BUS.post(event); + permissionCache = (event.isCanceled()) ? YesNo.NO : YesNo.YES; + } + return permissionCache == YesNo.YES + && !ignoreMaterials + && !ignoreBlocks + && !w.isAirBlock(x, y, z) + && w.blockExists(x, y, z) + && w.canMineBlock(player, x, y, z) + && hardness >= 0f; + } + + protected List obtainBlockDrops(final WorldServer w, final int x, final int y, final int z) { + final ItemStack[] out = Platform.getBlockDrops(w, x, y, z); + return Lists.newArrayList(out); + } + + /** + * Checks if this plane can handle the block at the specific coordinates. + */ + protected float calculateEnergyUsage( + final WorldServer w, final int x, final int y, final int z, final List items) { + final Block block = w.getBlock(x, y, z); + final float hardness = block.getBlockHardness(w, x, y, z); + + float requiredEnergy = 1 + hardness; + for (final ItemStack is : items) { + requiredEnergy += is.stackSize; + } + + return requiredEnergy; + } + + /** + * Checks if the network can store the possible drops. + *

+ * It also sets isAccepting to false, if the item can not be stored. + * + * @param itemStacks an array of {@link ItemStack} to test + * @return true, if the network can store at least a single item of all drops or no drops are reported + */ + private boolean canStoreItemStacks(final List itemStacks) { + boolean canStore = itemStacks.isEmpty(); + + try { + final IStorageGrid storage = this.getProxy().getStorage(); + + for (final ItemStack itemStack : itemStacks) { + final IAEItemStack itemToTest = AEItemStack.create(itemStack); + final IAEItemStack overflow = + storage.getItemInventory().injectItems(itemToTest, Actionable.SIMULATE, this.mySrc); + if (overflow == null || itemToTest.getStackSize() > overflow.getStackSize()) { + canStore = true; + } + } + } catch (final GridAccessException e) { + // :P + } + + this.isAccepting = canStore; + return canStore; + } + + private void breakBlockAndStoreItems( + final WorldServer w, final int x, final int y, final int z, final List items) { + w.setBlock(x, y, z, Platform.AIR_BLOCK, 0, 3); + + final AxisAlignedBB box = AxisAlignedBB.getBoundingBox(x - 0.2, y - 0.2, z - 0.2, x + 1.2, y + 1.2, z + 1.2); + for (final Object ei : w.getEntitiesWithinAABB(EntityItem.class, box)) { + if (ei instanceof EntityItem) { + final EntityItem entityItem = (EntityItem) ei; + this.storeEntityItem(entityItem); + } + } + + for (final ItemStack snaggedItem : items) { + final IAEItemStack overflow = this.storeItemStack(snaggedItem); + this.spawnOverflow(overflow); + } + } } diff --git a/src/main/java/appeng/parts/automation/PartExportBus.java b/src/main/java/appeng/parts/automation/PartExportBus.java index bc51eabb123..3510d2385b9 100644 --- a/src/main/java/appeng/parts/automation/PartExportBus.java +++ b/src/main/java/appeng/parts/automation/PartExportBus.java @@ -18,7 +18,6 @@ package appeng.parts.automation; - import appeng.api.config.*; import appeng.api.networking.IGridNode; import appeng.api.networking.crafting.ICraftingGrid; @@ -55,326 +54,319 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; -public class PartExportBus extends PartSharedItemBus implements ICraftingRequester -{ - private final MultiCraftingTracker craftingTracker = new MultiCraftingTracker( this, 9 ); - private final BaseActionSource mySrc; - private long itemToSend = 1; - private boolean didSomething = false; - private int nextSlot = 0; - - @Reflected - public PartExportBus( final ItemStack is ) - { - super( is ); - - this.getConfigManager().registerSetting( Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.getConfigManager().registerSetting( Settings.CRAFT_ONLY, YesNo.NO ); - this.getConfigManager().registerSetting( Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT ); - this.mySrc = new MachineSource( this ); - } - - @Override - public void readFromNBT( final NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.craftingTracker.readFromNBT( extra ); - this.nextSlot = extra.getInteger( "nextSlot" ); - } - - @Override - public void writeToNBT( final NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.craftingTracker.writeToNBT( extra ); - extra.setInteger( "nextSlot", this.nextSlot ); - } - - @Override - protected TickRateModulation doBusWork() - { - if( !this.getProxy().isActive() || !this.canDoBusWork() ) - { - return TickRateModulation.IDLE; - } - - this.itemToSend = this.calculateItemsToSend(); - this.didSomething = false; - - try - { - final InventoryAdaptor destination = this.getHandler(); - final IMEMonitor inv = this.getProxy().getStorage().getItemInventory(); - final IEnergyGrid energy = this.getProxy().getEnergy(); - final ICraftingGrid cg = this.getProxy().getCrafting(); - final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ); - final SchedulingMode schedulingMode = (SchedulingMode) this.getConfigManager().getSetting( Settings.SCHEDULING_MODE ); - - if( destination != null ) - { - if (this.getInstalledUpgrades( Upgrades.ORE_FILTER ) == 0) { - int x = 0; - - for (x = 0; x < this.availableSlots() && this.itemToSend > 0; x++) { - final int slotToExport = this.getStartingSlot(schedulingMode, x); - - final IAEItemStack ais = this.getConfig().getAEStackInSlot(slotToExport); - - if (ais == null || this.itemToSend <= 0 || this.craftOnly()) { - if (this.isCraftingEnabled()) { - this.didSomething = this.craftingTracker.handleCrafting(slotToExport, this.itemToSend, ais, destination, this.getTile().getWorldObj(), this.getProxy().getGrid(), cg, this.mySrc) || this.didSomething; - } - continue; - } - - final long before = this.itemToSend; - - if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { - for (final IAEItemStack o : ImmutableList.copyOf(inv.getStorageList().findFuzzy(ais, fzMode))) { - this.pushItemIntoTarget(destination, energy, inv, o); - if (this.itemToSend <= 0) { - break; - } - } - } else { - this.pushItemIntoTarget(destination, energy, inv, ais); - } - - if (this.itemToSend == before && this.isCraftingEnabled()) { - this.didSomething = this.craftingTracker.handleCrafting(slotToExport, this.itemToSend, ais, destination, this.getTile().getWorldObj(), this.getProxy().getGrid(), cg, this.mySrc) || this.didSomething; - } - } - - this.updateSchedulingMode(schedulingMode, x); - } - else if (!oreFilterString.isEmpty()) - { - if (filterPredicate == null) - filterPredicate = OreFilteredList.makeFilter(oreFilterString); - - for (IAEItemStack stack : inv.getStorageList()) { - if (stack == null || filterPredicate == null || !this.filterPredicate.test(stack)) - continue; - this.pushItemIntoTarget(destination, energy, inv, stack); - if (this.itemToSend <= 0) - break; - } - } - } - else - { - return TickRateModulation.SLEEP; - } - } - catch( final GridAccessException e ) - { - // :P - } - - return this.didSomething ? TickRateModulation.FASTER : TickRateModulation.SLOWER; - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 4, 4, 12, 12, 12, 14 ); - bch.addBox( 5, 5, 14, 11, 11, 15 ); - bch.addBox( 6, 6, 15, 10, 10, 16 ); - bch.addBox( 6, 6, 11, 10, 10, 12 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( CableBusTextures.PartExportSides.getIcon(), CableBusTextures.PartExportSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartExportSides.getIcon(), CableBusTextures.PartExportSides.getIcon() ); - - rh.setBounds( 4, 4, 12, 12, 12, 14 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 5, 5, 14, 11, 11, 15 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 6, 6, 15, 10, 10, 16 ); - rh.renderInventoryBox( renderer ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( CableBusTextures.PartExportSides.getIcon(), CableBusTextures.PartExportSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartExportSides.getIcon(), CableBusTextures.PartExportSides.getIcon() ); - - rh.setBounds( 4, 4, 12, 12, 12, 14 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setBounds( 5, 5, 14, 11, 11, 15 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setBounds( 6, 6, 15, 10, 10, 16 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon() ); - - rh.setBounds( 6, 6, 11, 10, 10, 12 ); - rh.renderBlock( x, y, z, renderer ); - - this.renderLights( x, y, z, rh, renderer ); - } - - @Override - public int cableConnectionRenderTo() - { - return 5; - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( !player.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } - - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_BUS ); - return true; - } - - return false; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.ExportBus.getMin(), TickRates.ExportBus.getMax(), this.isSleeping(), false ); - } - - @Override - public RedstoneMode getRSMode() - { - return (RedstoneMode) this.getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.doBusWork(); - } - - @Override - public ImmutableSet getRequestedJobs() - { - return this.craftingTracker.getRequestedJobs(); - } - - @Override - public IAEItemStack injectCraftedItems( final ICraftingLink link, final IAEItemStack items, final Actionable mode ) - { - final InventoryAdaptor d = this.getHandler(); - - try - { - if( d != null && this.getProxy().isActive() ) - { - final IEnergyGrid energy = this.getProxy().getEnergy(); - final double power = items.getStackSize(); - - if( energy.extractAEPower( power, mode, PowerMultiplier.CONFIG ) > power - 0.01 ) - { - if( mode == Actionable.MODULATE ) - { - return AEItemStack.create( d.addItems( items.getItemStack() ) ); - } - return AEItemStack.create( d.simulateAdd( items.getItemStack() ) ); - } - } - } - catch( final GridAccessException e ) - { - AELog.debug( e ); - } - - return items; - } - - @Override - public void jobStateChange( final ICraftingLink link ) - { - this.craftingTracker.jobStateChange( link ); - } - - @Override - protected boolean isSleeping() - { - return this.getHandler() == null || super.isSleeping(); - } - - private boolean craftOnly() - { - return this.getConfigManager().getSetting( Settings.CRAFT_ONLY ) == YesNo.YES; - } - - private boolean isCraftingEnabled() - { - return this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0; - } - - private void pushItemIntoTarget( final InventoryAdaptor d, final IEnergyGrid energy, final IMEInventory inv, IAEItemStack ais ) - { - final ItemStack is = ais.getItemStack(); - is.stackSize = (int) this.itemToSend; - - final ItemStack o = d.simulateAdd( is ); - final long canFit = o == null ? this.itemToSend : this.itemToSend - o.stackSize; - - if( canFit > 0 ) - { - ais = ais.copy(); - ais.setStackSize( canFit ); - final IAEItemStack itemsToAdd = Platform.poweredExtraction( energy, inv, ais, this.mySrc ); - - if( itemsToAdd != null ) - { - this.itemToSend -= itemsToAdd.getStackSize(); - - final ItemStack failed = d.addItems( itemsToAdd.getItemStack() ); - if( failed != null ) - { - ais.setStackSize( failed.stackSize ); - inv.injectItems( ais, Actionable.MODULATE, this.mySrc ); - } - else - { - this.didSomething = true; - } - } - } - } - - private int getStartingSlot( final SchedulingMode schedulingMode, final int x ) - { - if( schedulingMode == SchedulingMode.RANDOM ) - { - return Platform.getRandom().nextInt( this.availableSlots() ); - } - - if( schedulingMode == SchedulingMode.ROUNDROBIN ) - { - return ( this.nextSlot + x ) % this.availableSlots(); - } - - return x; - } - - private void updateSchedulingMode( final SchedulingMode schedulingMode, final int x ) - { - if( schedulingMode == SchedulingMode.ROUNDROBIN ) - { - this.nextSlot = ( this.nextSlot + x ) % this.availableSlots(); - } - } +public class PartExportBus extends PartSharedItemBus implements ICraftingRequester { + private final MultiCraftingTracker craftingTracker = new MultiCraftingTracker(this, 9); + private final BaseActionSource mySrc; + private long itemToSend = 1; + private boolean didSomething = false; + private int nextSlot = 0; + + @Reflected + public PartExportBus(final ItemStack is) { + super(is); + + this.getConfigManager().registerSetting(Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.getConfigManager().registerSetting(Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.getConfigManager().registerSetting(Settings.CRAFT_ONLY, YesNo.NO); + this.getConfigManager().registerSetting(Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT); + this.mySrc = new MachineSource(this); + } + + @Override + public void readFromNBT(final NBTTagCompound extra) { + super.readFromNBT(extra); + this.craftingTracker.readFromNBT(extra); + this.nextSlot = extra.getInteger("nextSlot"); + } + + @Override + public void writeToNBT(final NBTTagCompound extra) { + super.writeToNBT(extra); + this.craftingTracker.writeToNBT(extra); + extra.setInteger("nextSlot", this.nextSlot); + } + + @Override + protected TickRateModulation doBusWork() { + if (!this.getProxy().isActive() || !this.canDoBusWork()) { + return TickRateModulation.IDLE; + } + + this.itemToSend = this.calculateItemsToSend(); + this.didSomething = false; + + try { + final InventoryAdaptor destination = this.getHandler(); + final IMEMonitor inv = this.getProxy().getStorage().getItemInventory(); + final IEnergyGrid energy = this.getProxy().getEnergy(); + final ICraftingGrid cg = this.getProxy().getCrafting(); + final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting(Settings.FUZZY_MODE); + final SchedulingMode schedulingMode = + (SchedulingMode) this.getConfigManager().getSetting(Settings.SCHEDULING_MODE); + + if (destination != null) { + if (this.getInstalledUpgrades(Upgrades.ORE_FILTER) == 0) { + int x = 0; + + for (x = 0; x < this.availableSlots() && this.itemToSend > 0; x++) { + final int slotToExport = this.getStartingSlot(schedulingMode, x); + + final IAEItemStack ais = this.getConfig().getAEStackInSlot(slotToExport); + + if (ais == null || this.itemToSend <= 0 || this.craftOnly()) { + if (this.isCraftingEnabled()) { + this.didSomething = this.craftingTracker.handleCrafting( + slotToExport, + this.itemToSend, + ais, + destination, + this.getTile().getWorldObj(), + this.getProxy().getGrid(), + cg, + this.mySrc) + || this.didSomething; + } + continue; + } + + final long before = this.itemToSend; + + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + for (final IAEItemStack o : + ImmutableList.copyOf(inv.getStorageList().findFuzzy(ais, fzMode))) { + this.pushItemIntoTarget(destination, energy, inv, o); + if (this.itemToSend <= 0) { + break; + } + } + } else { + this.pushItemIntoTarget(destination, energy, inv, ais); + } + + if (this.itemToSend == before && this.isCraftingEnabled()) { + this.didSomething = this.craftingTracker.handleCrafting( + slotToExport, + this.itemToSend, + ais, + destination, + this.getTile().getWorldObj(), + this.getProxy().getGrid(), + cg, + this.mySrc) + || this.didSomething; + } + } + + this.updateSchedulingMode(schedulingMode, x); + } else if (!oreFilterString.isEmpty()) { + if (filterPredicate == null) filterPredicate = OreFilteredList.makeFilter(oreFilterString); + + for (IAEItemStack stack : inv.getStorageList()) { + if (stack == null || filterPredicate == null || !this.filterPredicate.test(stack)) continue; + this.pushItemIntoTarget(destination, energy, inv, stack); + if (this.itemToSend <= 0) break; + } + } + } else { + return TickRateModulation.SLEEP; + } + } catch (final GridAccessException e) { + // :P + } + + return this.didSomething ? TickRateModulation.FASTER : TickRateModulation.SLOWER; + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(4, 4, 12, 12, 12, 14); + bch.addBox(5, 5, 14, 11, 11, 15); + bch.addBox(6, 6, 15, 10, 10, 16); + bch.addBox(6, 6, 11, 10, 10, 12); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture( + CableBusTextures.PartExportSides.getIcon(), + CableBusTextures.PartExportSides.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartExportSides.getIcon(), + CableBusTextures.PartExportSides.getIcon()); + + rh.setBounds(4, 4, 12, 12, 12, 14); + rh.renderInventoryBox(renderer); + + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderInventoryBox(renderer); + + rh.setBounds(6, 6, 15, 10, 10, 16); + rh.renderInventoryBox(renderer); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + this.setRenderCache(rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache())); + rh.setTexture( + CableBusTextures.PartExportSides.getIcon(), + CableBusTextures.PartExportSides.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartExportSides.getIcon(), + CableBusTextures.PartExportSides.getIcon()); + + rh.setBounds(4, 4, 12, 12, 12, 14); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(6, 6, 15, 10, 10, 16); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture( + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon()); + + rh.setBounds(6, 6, 11, 10, 10, 12); + rh.renderBlock(x, y, z, renderer); + + this.renderLights(x, y, z, rh, renderer); + } + + @Override + public int cableConnectionRenderTo() { + return 5; + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (!player.isSneaking()) { + if (Platform.isClient()) { + return true; + } + + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_BUS); + return true; + } + + return false; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.ExportBus.getMin(), TickRates.ExportBus.getMax(), this.isSleeping(), false); + } + + @Override + public RedstoneMode getRSMode() { + return (RedstoneMode) this.getConfigManager().getSetting(Settings.REDSTONE_CONTROLLED); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.doBusWork(); + } + + @Override + public ImmutableSet getRequestedJobs() { + return this.craftingTracker.getRequestedJobs(); + } + + @Override + public IAEItemStack injectCraftedItems(final ICraftingLink link, final IAEItemStack items, final Actionable mode) { + final InventoryAdaptor d = this.getHandler(); + + try { + if (d != null && this.getProxy().isActive()) { + final IEnergyGrid energy = this.getProxy().getEnergy(); + final double power = items.getStackSize(); + + if (energy.extractAEPower(power, mode, PowerMultiplier.CONFIG) > power - 0.01) { + if (mode == Actionable.MODULATE) { + return AEItemStack.create(d.addItems(items.getItemStack())); + } + return AEItemStack.create(d.simulateAdd(items.getItemStack())); + } + } + } catch (final GridAccessException e) { + AELog.debug(e); + } + + return items; + } + + @Override + public void jobStateChange(final ICraftingLink link) { + this.craftingTracker.jobStateChange(link); + } + + @Override + protected boolean isSleeping() { + return this.getHandler() == null || super.isSleeping(); + } + + private boolean craftOnly() { + return this.getConfigManager().getSetting(Settings.CRAFT_ONLY) == YesNo.YES; + } + + private boolean isCraftingEnabled() { + return this.getInstalledUpgrades(Upgrades.CRAFTING) > 0; + } + + private void pushItemIntoTarget( + final InventoryAdaptor d, + final IEnergyGrid energy, + final IMEInventory inv, + IAEItemStack ais) { + final ItemStack is = ais.getItemStack(); + is.stackSize = (int) this.itemToSend; + + final ItemStack o = d.simulateAdd(is); + final long canFit = o == null ? this.itemToSend : this.itemToSend - o.stackSize; + + if (canFit > 0) { + ais = ais.copy(); + ais.setStackSize(canFit); + final IAEItemStack itemsToAdd = Platform.poweredExtraction(energy, inv, ais, this.mySrc); + + if (itemsToAdd != null) { + this.itemToSend -= itemsToAdd.getStackSize(); + + final ItemStack failed = d.addItems(itemsToAdd.getItemStack()); + if (failed != null) { + ais.setStackSize(failed.stackSize); + inv.injectItems(ais, Actionable.MODULATE, this.mySrc); + } else { + this.didSomething = true; + } + } + } + } + + private int getStartingSlot(final SchedulingMode schedulingMode, final int x) { + if (schedulingMode == SchedulingMode.RANDOM) { + return Platform.getRandom().nextInt(this.availableSlots()); + } + + if (schedulingMode == SchedulingMode.ROUNDROBIN) { + return (this.nextSlot + x) % this.availableSlots(); + } + + return x; + } + + private void updateSchedulingMode(final SchedulingMode schedulingMode, final int x) { + if (schedulingMode == SchedulingMode.ROUNDROBIN) { + this.nextSlot = (this.nextSlot + x) % this.availableSlots(); + } + } } diff --git a/src/main/java/appeng/parts/automation/PartFormationPlane.java b/src/main/java/appeng/parts/automation/PartFormationPlane.java index 362c8d39912..b3e0ba33ffe 100644 --- a/src/main/java/appeng/parts/automation/PartFormationPlane.java +++ b/src/main/java/appeng/parts/automation/PartFormationPlane.java @@ -18,7 +18,6 @@ package appeng.parts.automation; - import appeng.api.AEApi; import appeng.api.config.*; import appeng.api.networking.events.MENetworkCellArrayUpdate; @@ -48,6 +47,8 @@ import appeng.util.prioitylist.PrecisePriorityList; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.List; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; @@ -67,538 +68,565 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.world.BlockEvent; -import java.util.ArrayList; -import java.util.List; - - -public class PartFormationPlane extends PartUpgradeable implements ICellContainer, IPriorityHost, IMEInventory -{ - private final MEInventoryHandler myHandler = new MEInventoryHandler( this, StorageChannel.ITEMS ); - private final AppEngInternalAEInventory Config = new AppEngInternalAEInventory( this, 63 ); - private EntityPlayer owner = null; - private int priority = 0; - private boolean wasActive = false; - private boolean blocked = false; - public PartFormationPlane( final ItemStack is ) - { - super( is ); - - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.getConfigManager().registerSetting( Settings.PLACE_BLOCK, YesNo.YES ); - this.updateHandler(); - } - - @Override - public void onPlacement( EntityPlayer player, ItemStack held, ForgeDirection side ) - { - super.onPlacement( player, held, side ); - this.owner = player; - } - - private void updateHandler() - { - this.myHandler.setBaseAccess( AccessRestriction.WRITE ); - this.myHandler.setWhitelist( this.getInstalledUpgrades( Upgrades.INVERTER ) > 0 ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST ); - this.myHandler.setPriority( this.priority ); - - final IItemList priorityList = AEApi.instance().storage().createItemList(); - - final int slotsToUse = 18 + this.getInstalledUpgrades( Upgrades.CAPACITY ) * 9; - for( int x = 0; x < this.Config.getSizeInventory() && x < slotsToUse; x++ ) - { - final IAEItemStack is = this.Config.getAEStackInSlot( x ); - if( is != null ) - { - priorityList.add( is ); - } - } - - if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) - { - this.myHandler.setPartitionList( new FuzzyPriorityList( priorityList, (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ) ) ); - } - else - { - this.myHandler.setPartitionList( new PrecisePriorityList( priorityList ) ); - } - - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - @Override - protected int getUpgradeSlots() - { - return 5; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - this.updateHandler(); - this.getHost().markForSave(); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - super.onChangeInventory( inv, slot, mc, removedStack, newStack ); - - if( inv == this.Config ) - { - this.updateHandler(); - } - } - - @Override - public void upgradesChanged() - { - this.updateHandler(); - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.Config.readFromNBT( data, "config" ); - this.priority = data.getInteger( "priority" ); - this.updateHandler(); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.Config.writeToNBT( data, "config" ); - data.setInteger( "priority", this.priority ); - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "config" ) ) - { - return this.Config; - } - - return super.getInventoryByName( name ); - } - - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - final boolean currentActive = this.getProxy().isActive(); - if( this.wasActive != currentActive ) - { - this.wasActive = currentActive; - this.updateHandler();// proxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); - this.getHost().markForUpdate(); - } - } - - @MENetworkEventSubscribe - public void updateChannels( final MENetworkChannelsChanged changedChannels ) - { - final boolean currentActive = this.getProxy().isActive(); - if( this.wasActive != currentActive ) - { - this.wasActive = currentActive; - this.updateHandler();// proxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); - this.getHost().markForUpdate(); - } - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - int minX = 1; - int minY = 1; - int maxX = 15; - int maxY = 15; - - final IPartHost host = this.getHost(); - if( host != null ) - { - final TileEntity te = host.getTile(); - - final int x = te.xCoord; - final int y = te.yCoord; - final int z = te.zCoord; - - final ForgeDirection e = bch.getWorldX(); - final ForgeDirection u = bch.getWorldY(); - - if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x - e.offsetX, y - e.offsetY, z - e.offsetZ ), this.getSide() ) ) - { - minX = 0; - } - - if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.getSide() ) ) - { - maxX = 16; - } - - if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.getSide() ) ) - { - minY = 0; - } - - if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.getSide() ) ) - { - maxY = 16; - } - } - - bch.addBox( 5, 5, 14, 11, 11, 15 ); - bch.addBox( minX, minY, 15, maxX, maxY, 16 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( CableBusTextures.PartPlaneSides.getIcon(), CableBusTextures.PartPlaneSides.getIcon(), CableBusTextures.PartTransitionPlaneBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartPlaneSides.getIcon(), CableBusTextures.PartPlaneSides.getIcon() ); - - rh.setBounds( 1, 1, 15, 15, 15, 16 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 5, 5, 14, 11, 11, 15 ); - rh.renderInventoryBox( renderer ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - int minX = 1; - - final ForgeDirection e = rh.getWorldX(); - final ForgeDirection u = rh.getWorldY(); - - final TileEntity te = this.getHost().getTile(); - - if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x - e.offsetX, y - e.offsetY, z - e.offsetZ ), this.getSide() ) ) - { - minX = 0; - } - - int maxX = 15; - if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.getSide() ) ) - { - maxX = 16; - } - - int minY = 1; - if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.getSide() ) ) - { - minY = 0; - } - - int maxY = 15; - if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.getSide() ) ) - { - maxY = 16; - } - - final boolean isActive = ( this.getClientFlags() & ( PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG ) ) == ( PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG ); - - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( CableBusTextures.PartPlaneSides.getIcon(), CableBusTextures.PartPlaneSides.getIcon(), CableBusTextures.PartTransitionPlaneBack.getIcon(), isActive ? CableBusTextures.BlockFormPlaneOn.getIcon() : this.getItemStack().getIconIndex(), CableBusTextures.PartPlaneSides.getIcon(), CableBusTextures.PartPlaneSides.getIcon() ); - - rh.setBounds( minX, minY, 15, maxX, maxY, 16 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartTransitionPlaneBack.getIcon(), isActive ? CableBusTextures.BlockFormPlaneOn.getIcon() : this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon() ); - - rh.setBounds( 5, 5, 14, 11, 11, 15 ); - rh.renderBlock( x, y, z, renderer ); - - this.renderLights( x, y, z, rh, renderer ); - } - - @Override - public void onNeighborChanged() - { - final TileEntity te = this.getHost().getTile(); - final World w = te.getWorldObj(); - final ForgeDirection side = this.getSide(); - - final int x = te.xCoord + side.offsetX; - final int y = te.yCoord + side.offsetY; - final int z = te.zCoord + side.offsetZ; - - this.blocked = !w.getBlock( x, y, z ).isReplaceable( w, x, y, z ); - } - - @Override - public int cableConnectionRenderTo() - { - return 1; - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( !player.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } - - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_FORMATION_PLANE ); - return true; - } - - return false; - } - - private boolean isTransitionPlane( final TileEntity blockTileEntity, final ForgeDirection side ) - { - if( blockTileEntity instanceof IPartHost ) - { - final IPart p = ( (IPartHost) blockTileEntity ).getPart( side ); - return p instanceof PartFormationPlane; - } - return false; - } - - @Override - public List getCellArray( final StorageChannel channel ) - { - if( this.getProxy().isActive() && channel == StorageChannel.ITEMS ) - { - final List Handler = new ArrayList( 1 ); - Handler.add( this.myHandler ); - return Handler; - } - return new ArrayList(); - } - - @Override - public int getPriority() - { - return this.priority; - } - - @Override - public void setPriority( final int newValue ) - { - this.priority = newValue; - this.getHost().markForSave(); - this.updateHandler(); - } - - @Override - public void blinkCell( final int slot ) - { - // :P - } - - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final BaseActionSource src ) - { - if( this.blocked || input == null || input.getStackSize() <= 0 ) - { - return input; - } - - final YesNo placeBlock = (YesNo) this.getConfigManager().getSetting( Settings.PLACE_BLOCK ); - - final ItemStack is = input.getItemStack(); - final Item i = is.getItem(); - - long maxStorage = Math.min( input.getStackSize(), is.getMaxStackSize() ); - boolean worked = false; - - final TileEntity te = this.getHost().getTile(); - final World w = te.getWorldObj(); - final ForgeDirection side = this.getSide(); - - final int x = te.xCoord + side.offsetX; - final int y = te.yCoord + side.offsetY; - final int z = te.zCoord + side.offsetZ; - - if( w.getBlock( x, y, z ).isReplaceable( w, x, y, z ) ) - { - if( placeBlock == YesNo.YES && ( i instanceof ItemBlock || i instanceof IPlantable || i instanceof ItemSkull || i instanceof ItemFirework || i instanceof ItemReed ) ) - { - final EntityPlayer player = Platform.getPlayer( (WorldServer) w ); - Platform.configurePlayer( player, side, this.getTile() ); - - if( i instanceof ItemFirework ) - { - final Chunk c = w.getChunkFromBlockCoords( x, z ); - int sum = 0; - for( final List Z : c.entityLists ) - { - sum += Z.size(); - } - if( sum > 32 ) - { - return input; - } - } - maxStorage = is.stackSize; - worked = true; - if( type == Actionable.MODULATE ) - { - if( i instanceof IPlantable || i instanceof ItemSkull || i instanceof ItemReed ) - { - boolean Worked = false; - - if( side.offsetX == 0 && side.offsetZ == 0 ) - { - Worked = i.onItemUse( is, player, w, x + side.offsetX, y + side.offsetY, z + side.offsetZ, side.getOpposite().ordinal(), side.offsetX, side.offsetY, side.offsetZ ); - } - - if( !Worked && side.offsetX == 0 && side.offsetZ == 0 ) - { - Worked = i.onItemUse( is, player, w, x - side.offsetX, y - side.offsetY, z - side.offsetZ, side.ordinal(), side.offsetX, side.offsetY, side.offsetZ ); - } - - if( !Worked && side.offsetY == 0 ) - { - Worked = i.onItemUse( is, player, w, x, y - 1, z, ForgeDirection.UP.ordinal(), side.offsetX, side.offsetY, side.offsetZ ); - } - - if( !Worked ) - { - i.onItemUse( is, player, w, x, y, z, side.getOpposite().ordinal(), side.offsetX, side.offsetY, side.offsetZ ); - } - - maxStorage -= is.stackSize; - } - else if (i instanceof ItemFirework) - { - i.onItemUse( is, player, w, x, y, z, side.getOpposite().ordinal(), side.offsetX, side.offsetY, side.offsetZ ); - maxStorage -= is.stackSize; - } - else - { - player.setCurrentItemOrArmor( 0, is.copy() ); - BlockSnapshot blockSnapshot = new BlockSnapshot( w, x, y, z, ( (ItemBlock) i ).field_150939_a, i.getMetadata( is.getItemDamage() ) ); - BlockEvent.PlaceEvent event = new BlockEvent.PlaceEvent( blockSnapshot, w.getBlock( x, y, z ), owner == null ? player : owner ); - MinecraftForge.EVENT_BUS.post( event ); - if( !event.isCanceled() ) - { - i.onItemUse( is, player, w, x, y, z, side.getOpposite().ordinal(), side.offsetX, side.offsetY, side.offsetZ ); - maxStorage -= is.stackSize; - } - } - } - else - { - maxStorage = 1; - } - } - else - { - worked = true; - final Chunk c = w.getChunkFromBlockCoords( x, z ); - int sum = 0; - for( final List Z : c.entityLists ) - { - sum += Z.size(); - } - - if( sum < AEConfig.instance.formationPlaneEntityLimit ) - { - if( type == Actionable.MODULATE ) - { - - is.stackSize = (int) maxStorage; - final EntityItem ei = new EntityItem( w, - ( ( side.offsetX != 0 ? 0.0 : 0.7 ) * ( Platform.getRandomFloat() - 0.5f ) ) + 0.5 + side.offsetX * -0.3 + x, - ( ( side.offsetY != 0 ? 0.0 : 0.7 ) * ( Platform.getRandomFloat() - 0.5f ) ) + 0.5 + side.offsetY * -0.3 + y, - ( ( side.offsetZ != 0 ? 0.0 : 0.7 ) * ( Platform.getRandomFloat() - 0.5f ) ) + 0.5 + side.offsetZ * -0.3 + z, - is.copy() ); - - Entity result = ei; - - ei.motionX = side.offsetX * 0.2; - ei.motionY = side.offsetY * 0.2; - ei.motionZ = side.offsetZ * 0.2; - - if( is.getItem().hasCustomEntity( is ) ) - { - result = is.getItem().createEntity( w, ei, is ); - if( result != null ) - { - ei.setDead(); - } - else - { - result = ei; - } - } - - if( !w.spawnEntityInWorld( result ) ) - { - if (((EntityItem)result).getEntityItem().getItem() == Item.getItemFromBlock(Blocks.dragon_egg)) - { // Ducttape fix for HEE replacing the Dragon Egg - // HEE does cancel the event but does not mark passed entity as dead - worked = true; - } - else { - // e.g. ExU item collector cancels item spawn, but takes the item inside - worked = result.isDead; - result.setDead(); - } - } - } - } - else - { - worked = false; - } - } - } - - this.blocked = !w.getBlock( x, y, z ).isReplaceable( w, x, y, z ); - - if( worked ) - { - final IAEItemStack out = input.copy(); - out.decStackSize( maxStorage ); - if( out.getStackSize() == 0 ) - { - return null; - } - return out; - } - - return input; - } - - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - return null; - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public void saveChanges( final IMEInventory cellInventory ) - { - // nope! - } +public class PartFormationPlane extends PartUpgradeable + implements ICellContainer, IPriorityHost, IMEInventory { + private final MEInventoryHandler myHandler = new MEInventoryHandler(this, StorageChannel.ITEMS); + private final AppEngInternalAEInventory Config = new AppEngInternalAEInventory(this, 63); + private EntityPlayer owner = null; + private int priority = 0; + private boolean wasActive = false; + private boolean blocked = false; + + public PartFormationPlane(final ItemStack is) { + super(is); + + this.getConfigManager().registerSetting(Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.getConfigManager().registerSetting(Settings.PLACE_BLOCK, YesNo.YES); + this.updateHandler(); + } + + @Override + public void onPlacement(EntityPlayer player, ItemStack held, ForgeDirection side) { + super.onPlacement(player, held, side); + this.owner = player; + } + + private void updateHandler() { + this.myHandler.setBaseAccess(AccessRestriction.WRITE); + this.myHandler.setWhitelist( + this.getInstalledUpgrades(Upgrades.INVERTER) > 0 ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST); + this.myHandler.setPriority(this.priority); + + final IItemList priorityList = AEApi.instance().storage().createItemList(); + + final int slotsToUse = 18 + this.getInstalledUpgrades(Upgrades.CAPACITY) * 9; + for (int x = 0; x < this.Config.getSizeInventory() && x < slotsToUse; x++) { + final IAEItemStack is = this.Config.getAEStackInSlot(x); + if (is != null) { + priorityList.add(is); + } + } + + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + this.myHandler.setPartitionList(new FuzzyPriorityList( + priorityList, (FuzzyMode) this.getConfigManager().getSetting(Settings.FUZZY_MODE))); + } else { + this.myHandler.setPartitionList(new PrecisePriorityList(priorityList)); + } + + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } + + @Override + protected int getUpgradeSlots() { + return 5; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + this.updateHandler(); + this.getHost().markForSave(); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) { + super.onChangeInventory(inv, slot, mc, removedStack, newStack); + + if (inv == this.Config) { + this.updateHandler(); + } + } + + @Override + public void upgradesChanged() { + this.updateHandler(); + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.Config.readFromNBT(data, "config"); + this.priority = data.getInteger("priority"); + this.updateHandler(); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.Config.writeToNBT(data, "config"); + data.setInteger("priority", this.priority); + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("config")) { + return this.Config; + } + + return super.getInventoryByName(name); + } + + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + final boolean currentActive = this.getProxy().isActive(); + if (this.wasActive != currentActive) { + this.wasActive = currentActive; + this.updateHandler(); // proxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); + this.getHost().markForUpdate(); + } + } + + @MENetworkEventSubscribe + public void updateChannels(final MENetworkChannelsChanged changedChannels) { + final boolean currentActive = this.getProxy().isActive(); + if (this.wasActive != currentActive) { + this.wasActive = currentActive; + this.updateHandler(); // proxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); + this.getHost().markForUpdate(); + } + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + int minX = 1; + int minY = 1; + int maxX = 15; + int maxY = 15; + + final IPartHost host = this.getHost(); + if (host != null) { + final TileEntity te = host.getTile(); + + final int x = te.xCoord; + final int y = te.yCoord; + final int z = te.zCoord; + + final ForgeDirection e = bch.getWorldX(); + final ForgeDirection u = bch.getWorldY(); + + if (this.isTransitionPlane( + te.getWorldObj().getTileEntity(x - e.offsetX, y - e.offsetY, z - e.offsetZ), this.getSide())) { + minX = 0; + } + + if (this.isTransitionPlane( + te.getWorldObj().getTileEntity(x + e.offsetX, y + e.offsetY, z + e.offsetZ), this.getSide())) { + maxX = 16; + } + + if (this.isTransitionPlane( + te.getWorldObj().getTileEntity(x - u.offsetX, y - u.offsetY, z - u.offsetZ), this.getSide())) { + minY = 0; + } + + if (this.isTransitionPlane( + te.getWorldObj().getTileEntity(x + u.offsetX, y + u.offsetY, z + u.offsetZ), this.getSide())) { + maxY = 16; + } + } + + bch.addBox(5, 5, 14, 11, 11, 15); + bch.addBox(minX, minY, 15, maxX, maxY, 16); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture( + CableBusTextures.PartPlaneSides.getIcon(), + CableBusTextures.PartPlaneSides.getIcon(), + CableBusTextures.PartTransitionPlaneBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartPlaneSides.getIcon(), + CableBusTextures.PartPlaneSides.getIcon()); + + rh.setBounds(1, 1, 15, 15, 15, 16); + rh.renderInventoryBox(renderer); + + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderInventoryBox(renderer); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + int minX = 1; + + final ForgeDirection e = rh.getWorldX(); + final ForgeDirection u = rh.getWorldY(); + + final TileEntity te = this.getHost().getTile(); + + if (this.isTransitionPlane( + te.getWorldObj().getTileEntity(x - e.offsetX, y - e.offsetY, z - e.offsetZ), this.getSide())) { + minX = 0; + } + + int maxX = 15; + if (this.isTransitionPlane( + te.getWorldObj().getTileEntity(x + e.offsetX, y + e.offsetY, z + e.offsetZ), this.getSide())) { + maxX = 16; + } + + int minY = 1; + if (this.isTransitionPlane( + te.getWorldObj().getTileEntity(x - u.offsetX, y - u.offsetY, z - u.offsetZ), this.getSide())) { + minY = 0; + } + + int maxY = 15; + if (this.isTransitionPlane( + te.getWorldObj().getTileEntity(x + u.offsetX, y + u.offsetY, z + u.offsetZ), this.getSide())) { + maxY = 16; + } + + final boolean isActive = (this.getClientFlags() & (PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG)) + == (PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG); + + this.setRenderCache(rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache())); + rh.setTexture( + CableBusTextures.PartPlaneSides.getIcon(), + CableBusTextures.PartPlaneSides.getIcon(), + CableBusTextures.PartTransitionPlaneBack.getIcon(), + isActive + ? CableBusTextures.BlockFormPlaneOn.getIcon() + : this.getItemStack().getIconIndex(), + CableBusTextures.PartPlaneSides.getIcon(), + CableBusTextures.PartPlaneSides.getIcon()); + + rh.setBounds(minX, minY, 15, maxX, maxY, 16); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture( + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartTransitionPlaneBack.getIcon(), + isActive + ? CableBusTextures.BlockFormPlaneOn.getIcon() + : this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon()); + + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderBlock(x, y, z, renderer); + + this.renderLights(x, y, z, rh, renderer); + } + + @Override + public void onNeighborChanged() { + final TileEntity te = this.getHost().getTile(); + final World w = te.getWorldObj(); + final ForgeDirection side = this.getSide(); + + final int x = te.xCoord + side.offsetX; + final int y = te.yCoord + side.offsetY; + final int z = te.zCoord + side.offsetZ; + + this.blocked = !w.getBlock(x, y, z).isReplaceable(w, x, y, z); + } + + @Override + public int cableConnectionRenderTo() { + return 1; + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (!player.isSneaking()) { + if (Platform.isClient()) { + return true; + } + + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_FORMATION_PLANE); + return true; + } + + return false; + } + + private boolean isTransitionPlane(final TileEntity blockTileEntity, final ForgeDirection side) { + if (blockTileEntity instanceof IPartHost) { + final IPart p = ((IPartHost) blockTileEntity).getPart(side); + return p instanceof PartFormationPlane; + } + return false; + } + + @Override + public List getCellArray(final StorageChannel channel) { + if (this.getProxy().isActive() && channel == StorageChannel.ITEMS) { + final List Handler = new ArrayList(1); + Handler.add(this.myHandler); + return Handler; + } + return new ArrayList(); + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public void setPriority(final int newValue) { + this.priority = newValue; + this.getHost().markForSave(); + this.updateHandler(); + } + + @Override + public void blinkCell(final int slot) { + // :P + } + + @Override + public IAEItemStack injectItems(final IAEItemStack input, final Actionable type, final BaseActionSource src) { + if (this.blocked || input == null || input.getStackSize() <= 0) { + return input; + } + + final YesNo placeBlock = (YesNo) this.getConfigManager().getSetting(Settings.PLACE_BLOCK); + + final ItemStack is = input.getItemStack(); + final Item i = is.getItem(); + + long maxStorage = Math.min(input.getStackSize(), is.getMaxStackSize()); + boolean worked = false; + + final TileEntity te = this.getHost().getTile(); + final World w = te.getWorldObj(); + final ForgeDirection side = this.getSide(); + + final int x = te.xCoord + side.offsetX; + final int y = te.yCoord + side.offsetY; + final int z = te.zCoord + side.offsetZ; + + if (w.getBlock(x, y, z).isReplaceable(w, x, y, z)) { + if (placeBlock == YesNo.YES + && (i instanceof ItemBlock + || i instanceof IPlantable + || i instanceof ItemSkull + || i instanceof ItemFirework + || i instanceof ItemReed)) { + final EntityPlayer player = Platform.getPlayer((WorldServer) w); + Platform.configurePlayer(player, side, this.getTile()); + + if (i instanceof ItemFirework) { + final Chunk c = w.getChunkFromBlockCoords(x, z); + int sum = 0; + for (final List Z : c.entityLists) { + sum += Z.size(); + } + if (sum > 32) { + return input; + } + } + maxStorage = is.stackSize; + worked = true; + if (type == Actionable.MODULATE) { + if (i instanceof IPlantable || i instanceof ItemSkull || i instanceof ItemReed) { + boolean Worked = false; + + if (side.offsetX == 0 && side.offsetZ == 0) { + Worked = i.onItemUse( + is, + player, + w, + x + side.offsetX, + y + side.offsetY, + z + side.offsetZ, + side.getOpposite().ordinal(), + side.offsetX, + side.offsetY, + side.offsetZ); + } + + if (!Worked && side.offsetX == 0 && side.offsetZ == 0) { + Worked = i.onItemUse( + is, + player, + w, + x - side.offsetX, + y - side.offsetY, + z - side.offsetZ, + side.ordinal(), + side.offsetX, + side.offsetY, + side.offsetZ); + } + + if (!Worked && side.offsetY == 0) { + Worked = i.onItemUse( + is, + player, + w, + x, + y - 1, + z, + ForgeDirection.UP.ordinal(), + side.offsetX, + side.offsetY, + side.offsetZ); + } + + if (!Worked) { + i.onItemUse( + is, + player, + w, + x, + y, + z, + side.getOpposite().ordinal(), + side.offsetX, + side.offsetY, + side.offsetZ); + } + + maxStorage -= is.stackSize; + } else if (i instanceof ItemFirework) { + i.onItemUse( + is, + player, + w, + x, + y, + z, + side.getOpposite().ordinal(), + side.offsetX, + side.offsetY, + side.offsetZ); + maxStorage -= is.stackSize; + } else { + player.setCurrentItemOrArmor(0, is.copy()); + BlockSnapshot blockSnapshot = new BlockSnapshot( + w, x, y, z, ((ItemBlock) i).field_150939_a, i.getMetadata(is.getItemDamage())); + BlockEvent.PlaceEvent event = new BlockEvent.PlaceEvent( + blockSnapshot, w.getBlock(x, y, z), owner == null ? player : owner); + MinecraftForge.EVENT_BUS.post(event); + if (!event.isCanceled()) { + i.onItemUse( + is, + player, + w, + x, + y, + z, + side.getOpposite().ordinal(), + side.offsetX, + side.offsetY, + side.offsetZ); + maxStorage -= is.stackSize; + } + } + } else { + maxStorage = 1; + } + } else { + worked = true; + final Chunk c = w.getChunkFromBlockCoords(x, z); + int sum = 0; + for (final List Z : c.entityLists) { + sum += Z.size(); + } + + if (sum < AEConfig.instance.formationPlaneEntityLimit) { + if (type == Actionable.MODULATE) { + + is.stackSize = (int) maxStorage; + final EntityItem ei = new EntityItem( + w, + ((side.offsetX != 0 ? 0.0 : 0.7) * (Platform.getRandomFloat() - 0.5f)) + + 0.5 + + side.offsetX * -0.3 + + x, + ((side.offsetY != 0 ? 0.0 : 0.7) * (Platform.getRandomFloat() - 0.5f)) + + 0.5 + + side.offsetY * -0.3 + + y, + ((side.offsetZ != 0 ? 0.0 : 0.7) * (Platform.getRandomFloat() - 0.5f)) + + 0.5 + + side.offsetZ * -0.3 + + z, + is.copy()); + + Entity result = ei; + + ei.motionX = side.offsetX * 0.2; + ei.motionY = side.offsetY * 0.2; + ei.motionZ = side.offsetZ * 0.2; + + if (is.getItem().hasCustomEntity(is)) { + result = is.getItem().createEntity(w, ei, is); + if (result != null) { + ei.setDead(); + } else { + result = ei; + } + } + + if (!w.spawnEntityInWorld(result)) { + if (((EntityItem) result).getEntityItem().getItem() + == Item.getItemFromBlock( + Blocks.dragon_egg)) { // Ducttape fix for HEE replacing the Dragon Egg + // HEE does cancel the event but does not mark passed entity as dead + worked = true; + } else { + // e.g. ExU item collector cancels item spawn, but takes the item inside + worked = result.isDead; + result.setDead(); + } + } + } + } else { + worked = false; + } + } + } + + this.blocked = !w.getBlock(x, y, z).isReplaceable(w, x, y, z); + + if (worked) { + final IAEItemStack out = input.copy(); + out.decStackSize(maxStorage); + if (out.getStackSize() == 0) { + return null; + } + return out; + } + + return input; + } + + @Override + public IAEItemStack extractItems(final IAEItemStack request, final Actionable mode, final BaseActionSource src) { + return null; + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } + + @Override + public void saveChanges(final IMEInventory cellInventory) { + // nope! + } } diff --git a/src/main/java/appeng/parts/automation/PartIdentityAnnihilationPlane.java b/src/main/java/appeng/parts/automation/PartIdentityAnnihilationPlane.java index a9883786c48..0bbd5a28017 100644 --- a/src/main/java/appeng/parts/automation/PartIdentityAnnihilationPlane.java +++ b/src/main/java/appeng/parts/automation/PartIdentityAnnihilationPlane.java @@ -18,7 +18,6 @@ package appeng.parts.automation; - import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import appeng.api.parts.IPartRenderHelper; @@ -26,6 +25,8 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.entity.player.EntityPlayer; @@ -36,74 +37,60 @@ import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.List; - - -public class PartIdentityAnnihilationPlane extends PartAnnihilationPlane -{ - private static final IIcon ACTIVE_ICON = CableBusTextures.BlockIdentityAnnihilationPlaneOn.getIcon(); +public class PartIdentityAnnihilationPlane extends PartAnnihilationPlane { + private static final IIcon ACTIVE_ICON = CableBusTextures.BlockIdentityAnnihilationPlaneOn.getIcon(); - private static final float SILK_TOUCH_FACTOR = 16; + private static final float SILK_TOUCH_FACTOR = 16; - public PartIdentityAnnihilationPlane( final ItemStack is ) - { - super( is ); - } + public PartIdentityAnnihilationPlane(final ItemStack is) { + super(is); + } - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.renderStaticWithIcon( x, y, z, rh, renderer, ACTIVE_ICON ); - } + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + this.renderStaticWithIcon(x, y, z, rh, renderer, ACTIVE_ICON); + } - @Override - protected boolean isAnnihilationPlane( final TileEntity blockTileEntity, final ForgeDirection side ) - { - if( blockTileEntity instanceof IPartHost ) - { - final IPart p = ( (IPartHost) blockTileEntity ).getPart( side ); - return p != null && p.getClass() == this.getClass(); - } - return false; - } + @Override + protected boolean isAnnihilationPlane(final TileEntity blockTileEntity, final ForgeDirection side) { + if (blockTileEntity instanceof IPartHost) { + final IPart p = ((IPartHost) blockTileEntity).getPart(side); + return p != null && p.getClass() == this.getClass(); + } + return false; + } - @Override - protected float calculateEnergyUsage( final WorldServer w, final int x, final int y, final int z, final List items ) - { - final float requiredEnergy = super.calculateEnergyUsage( w, x, y, z, items ); + @Override + protected float calculateEnergyUsage( + final WorldServer w, final int x, final int y, final int z, final List items) { + final float requiredEnergy = super.calculateEnergyUsage(w, x, y, z, items); - return requiredEnergy * SILK_TOUCH_FACTOR; - } + return requiredEnergy * SILK_TOUCH_FACTOR; + } - @Override - protected List obtainBlockDrops( final WorldServer w, final int x, final int y, final int z ) - { - final EntityPlayer fakePlayer = Platform.getPlayer( w ); - final Block block = w.getBlock( x, y, z ); - final int blockMeta = w.getBlockMetadata( x, y, z ); + @Override + protected List obtainBlockDrops(final WorldServer w, final int x, final int y, final int z) { + final EntityPlayer fakePlayer = Platform.getPlayer(w); + final Block block = w.getBlock(x, y, z); + final int blockMeta = w.getBlockMetadata(x, y, z); - if( block.canSilkHarvest( w, fakePlayer, x, y, z, blockMeta ) ) - { - final List out = new ArrayList( 1 ); - final Item item = Item.getItemFromBlock( block ); + if (block.canSilkHarvest(w, fakePlayer, x, y, z, blockMeta)) { + final List out = new ArrayList(1); + final Item item = Item.getItemFromBlock(block); - if( item != null ) - { - int meta = 0; - if( item.getHasSubtypes() ) - { - meta = blockMeta; - } - final ItemStack itemstack = new ItemStack( item, 1, meta ); - out.add( itemstack ); - } - return out; - } - else - { - return super.obtainBlockDrops( w, x, y, z ); - } - } + if (item != null) { + int meta = 0; + if (item.getHasSubtypes()) { + meta = blockMeta; + } + final ItemStack itemstack = new ItemStack(item, 1, meta); + out.add(itemstack); + } + return out; + } else { + return super.obtainBlockDrops(w, x, y, z); + } + } } diff --git a/src/main/java/appeng/parts/automation/PartImportBus.java b/src/main/java/appeng/parts/automation/PartImportBus.java index 5338d7b67b1..05f01712d06 100644 --- a/src/main/java/appeng/parts/automation/PartImportBus.java +++ b/src/main/java/appeng/parts/automation/PartImportBus.java @@ -18,7 +18,6 @@ package appeng.parts.automation; - import appeng.api.AEApi; import appeng.api.config.*; import appeng.api.networking.IGridNode; @@ -51,296 +50,291 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.Vec3; - -public class PartImportBus extends PartSharedItemBus implements IInventoryDestination -{ - private final BaseActionSource source; - private IMEInventory destination = null; - private IAEItemStack lastItemChecked = null; - private int itemToSend; // used in tickingRequest - private boolean worked; // used in tickingRequest - - @Reflected - public PartImportBus( final ItemStack is ) - { - super( is ); - - this.getConfigManager().registerSetting( Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.source = new MachineSource( this ); - } - - @Override - public boolean canInsert( final ItemStack stack ) - { - if( stack == null || stack.getItem() == null ) - { - return false; - } - - final IAEItemStack out = this.destination.injectItems( this.lastItemChecked = AEApi.instance().storage().createItemStack( stack ), Actionable.SIMULATE, this.source ); - if( out == null ) - { - return true; - } - return out.getStackSize() != stack.stackSize; - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 6, 6, 11, 10, 10, 13 ); - bch.addBox( 5, 5, 13, 11, 11, 14 ); - bch.addBox( 4, 4, 14, 12, 12, 16 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( CableBusTextures.PartImportSides.getIcon(), CableBusTextures.PartImportSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartImportSides.getIcon(), CableBusTextures.PartImportSides.getIcon() ); - - rh.setBounds( 3, 3, 15, 13, 13, 16 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 4, 4, 14, 12, 12, 15 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 5, 5, 13, 11, 11, 14 ); - rh.renderInventoryBox( renderer ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( CableBusTextures.PartImportSides.getIcon(), CableBusTextures.PartImportSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartImportSides.getIcon(), CableBusTextures.PartImportSides.getIcon() ); - - rh.setBounds( 4, 4, 14, 12, 12, 16 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setBounds( 5, 5, 13, 11, 11, 14 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setBounds( 6, 6, 12, 10, 10, 13 ); - rh.renderBlock( x, y, z, renderer ); - rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon() ); - - rh.setBounds( 6, 6, 11, 10, 10, 12 ); - rh.renderBlock( x, y, z, renderer ); - - this.renderLights( x, y, z, rh, renderer ); - } - - @Override - public int cableConnectionRenderTo() - { - return 5; - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( !player.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } - - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_BUS ); - return true; - } - - return false; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.ImportBus.getMin(), TickRates.ImportBus.getMax(), this.getHandler() == null, false ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.doBusWork(); - } - - @Override - protected TickRateModulation doBusWork() - { - if( !this.getProxy().isActive() || !this.canDoBusWork() ) - { - return TickRateModulation.IDLE; - } - - this.worked = false; - - final InventoryAdaptor myAdaptor = this.getHandler(); - final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ); - - if( myAdaptor != null ) - { - try - { - this.itemToSend = this.calculateItemsToSend(); - this.itemToSend = Math.min( this.itemToSend, (int) ( 0.01 + this.getProxy().getEnergy().extractAEPower( this.itemToSend, Actionable.SIMULATE, PowerMultiplier.CONFIG ) ) ); - - final IMEMonitor inv = this.getProxy().getStorage().getItemInventory(); - final IEnergyGrid energy = this.getProxy().getEnergy(); - - boolean configured = false; - if (this.getInstalledUpgrades( Upgrades.ORE_FILTER ) == 0) { - for (int x = 0; x < this.availableSlots(); x++) { - final IAEItemStack ais = this.getConfig().getAEStackInSlot(x); - if (ais != null && this.itemToSend > 0) { - configured = true; - while (this.itemToSend > 0) { - if (this.importStuff(myAdaptor, ais, inv, energy, fzMode)) { - break; - } - } - } - } - } else if (!oreFilterString.isEmpty()) { - configured = true; - if (filterPredicate == null) - filterPredicate = OreFilteredList.makeFilter(oreFilterString); - for (ItemSlot slot : myAdaptor) { - if (this.itemToSend <= 0) - break; - if (slot.isExtractable() && filterPredicate != null && filterPredicate.test(slot.getAEItemStack())) { - while (this.itemToSend > 0) { - if (this.importStuff(myAdaptor, slot.getAEItemStack(), inv, energy, fzMode)) - break; - } - } - } - } - - if( !configured ) - { - while( this.itemToSend > 0 ) - { - if( this.importStuff( myAdaptor, null, inv, energy, fzMode ) ) - { - break; - } - } - } - } - catch( final GridAccessException e ) - { - // :3 - } - } - else - { - return TickRateModulation.SLEEP; - } - - return this.worked ? TickRateModulation.FASTER : TickRateModulation.SLOWER; - } - - private boolean importStuff( final InventoryAdaptor myAdaptor, final IAEItemStack whatToImport, final IMEMonitor inv, final IEnergySource energy, final FuzzyMode fzMode ) - { - final int toSend = this.calculateMaximumAmountToImport( myAdaptor, whatToImport, inv, fzMode ); - final ItemStack newItems; - - if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) - { - newItems = myAdaptor.removeSimilarItems( toSend, whatToImport == null ? null : whatToImport.getItemStack(), fzMode, this.configDestination( inv ) ); - } - else - { - newItems = myAdaptor.removeItems( toSend, whatToImport == null ? null : whatToImport.getItemStack(), this.configDestination( inv ) ); - } - - if( newItems != null ) - { - newItems.stackSize = (int) ( Math.min( newItems.stackSize, energy.extractAEPower( newItems.stackSize, Actionable.SIMULATE, PowerMultiplier.CONFIG ) ) + 0.01 ); - this.itemToSend -= newItems.stackSize; - - if( this.lastItemChecked == null || !this.lastItemChecked.isSameType( newItems ) ) - { - this.lastItemChecked = AEApi.instance().storage().createItemStack( newItems ); - } - else - { - this.lastItemChecked.setStackSize( newItems.stackSize ); - } - - final IAEItemStack failed = Platform.poweredInsert( energy, this.destination, this.lastItemChecked, this.source ); - - if( failed != null ) - { - myAdaptor.addItems( failed.getItemStack() ); - return true; - } - else - { - this.worked = true; - } - } - else - { - return true; - } - - return false; - } - - private int calculateMaximumAmountToImport( final InventoryAdaptor myAdaptor, final IAEItemStack whatToImport, final IMEMonitor inv, final FuzzyMode fzMode ) - { - final int toSend = Math.min( this.itemToSend, 64 ); - final ItemStack itemStackToImport; - - if( whatToImport == null ) - { - itemStackToImport = null; - } - else - { - itemStackToImport = whatToImport.getItemStack(); - } - - final IAEItemStack itemAmountNotStorable; - final ItemStack simResult; - if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) - { - simResult = myAdaptor.simulateSimilarRemove( toSend, itemStackToImport, fzMode, this.configDestination( inv ) ); - } - else - { - simResult = myAdaptor.simulateRemove( toSend, itemStackToImport, this.configDestination( inv ) ); - } - itemAmountNotStorable = this.destination.injectItems( AEItemStack.create( simResult ), Actionable.SIMULATE, this.source ); - - if( itemAmountNotStorable != null ) - { - return (int) Math.min( simResult.stackSize - itemAmountNotStorable.getStackSize(), toSend ); - } - - return toSend; - } - - private IInventoryDestination configDestination( final IMEMonitor itemInventory ) - { - this.destination = itemInventory; - return this; - } - - @Override - protected boolean isSleeping() - { - return this.getHandler() == null || super.isSleeping(); - } - - @Override - public RedstoneMode getRSMode() - { - return (RedstoneMode) this.getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ); - } +public class PartImportBus extends PartSharedItemBus implements IInventoryDestination { + private final BaseActionSource source; + private IMEInventory destination = null; + private IAEItemStack lastItemChecked = null; + private int itemToSend; // used in tickingRequest + private boolean worked; // used in tickingRequest + + @Reflected + public PartImportBus(final ItemStack is) { + super(is); + + this.getConfigManager().registerSetting(Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.getConfigManager().registerSetting(Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.source = new MachineSource(this); + } + + @Override + public boolean canInsert(final ItemStack stack) { + if (stack == null || stack.getItem() == null) { + return false; + } + + final IAEItemStack out = this.destination.injectItems( + this.lastItemChecked = AEApi.instance().storage().createItemStack(stack), + Actionable.SIMULATE, + this.source); + if (out == null) { + return true; + } + return out.getStackSize() != stack.stackSize; + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(6, 6, 11, 10, 10, 13); + bch.addBox(5, 5, 13, 11, 11, 14); + bch.addBox(4, 4, 14, 12, 12, 16); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture( + CableBusTextures.PartImportSides.getIcon(), + CableBusTextures.PartImportSides.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartImportSides.getIcon(), + CableBusTextures.PartImportSides.getIcon()); + + rh.setBounds(3, 3, 15, 13, 13, 16); + rh.renderInventoryBox(renderer); + + rh.setBounds(4, 4, 14, 12, 12, 15); + rh.renderInventoryBox(renderer); + + rh.setBounds(5, 5, 13, 11, 11, 14); + rh.renderInventoryBox(renderer); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + this.setRenderCache(rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache())); + rh.setTexture( + CableBusTextures.PartImportSides.getIcon(), + CableBusTextures.PartImportSides.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartImportSides.getIcon(), + CableBusTextures.PartImportSides.getIcon()); + + rh.setBounds(4, 4, 14, 12, 12, 16); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(5, 5, 13, 11, 11, 14); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(6, 6, 12, 10, 10, 13); + rh.renderBlock(x, y, z, renderer); + rh.setTexture( + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon()); + + rh.setBounds(6, 6, 11, 10, 10, 12); + rh.renderBlock(x, y, z, renderer); + + this.renderLights(x, y, z, rh, renderer); + } + + @Override + public int cableConnectionRenderTo() { + return 5; + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (!player.isSneaking()) { + if (Platform.isClient()) { + return true; + } + + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_BUS); + return true; + } + + return false; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest( + TickRates.ImportBus.getMin(), TickRates.ImportBus.getMax(), this.getHandler() == null, false); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.doBusWork(); + } + + @Override + protected TickRateModulation doBusWork() { + if (!this.getProxy().isActive() || !this.canDoBusWork()) { + return TickRateModulation.IDLE; + } + + this.worked = false; + + final InventoryAdaptor myAdaptor = this.getHandler(); + final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting(Settings.FUZZY_MODE); + + if (myAdaptor != null) { + try { + this.itemToSend = this.calculateItemsToSend(); + this.itemToSend = Math.min(this.itemToSend, (int) (0.01 + + this.getProxy() + .getEnergy() + .extractAEPower(this.itemToSend, Actionable.SIMULATE, PowerMultiplier.CONFIG))); + + final IMEMonitor inv = + this.getProxy().getStorage().getItemInventory(); + final IEnergyGrid energy = this.getProxy().getEnergy(); + + boolean configured = false; + if (this.getInstalledUpgrades(Upgrades.ORE_FILTER) == 0) { + for (int x = 0; x < this.availableSlots(); x++) { + final IAEItemStack ais = this.getConfig().getAEStackInSlot(x); + if (ais != null && this.itemToSend > 0) { + configured = true; + while (this.itemToSend > 0) { + if (this.importStuff(myAdaptor, ais, inv, energy, fzMode)) { + break; + } + } + } + } + } else if (!oreFilterString.isEmpty()) { + configured = true; + if (filterPredicate == null) filterPredicate = OreFilteredList.makeFilter(oreFilterString); + for (ItemSlot slot : myAdaptor) { + if (this.itemToSend <= 0) break; + if (slot.isExtractable() + && filterPredicate != null + && filterPredicate.test(slot.getAEItemStack())) { + while (this.itemToSend > 0) { + if (this.importStuff(myAdaptor, slot.getAEItemStack(), inv, energy, fzMode)) break; + } + } + } + } + + if (!configured) { + while (this.itemToSend > 0) { + if (this.importStuff(myAdaptor, null, inv, energy, fzMode)) { + break; + } + } + } + } catch (final GridAccessException e) { + // :3 + } + } else { + return TickRateModulation.SLEEP; + } + + return this.worked ? TickRateModulation.FASTER : TickRateModulation.SLOWER; + } + + private boolean importStuff( + final InventoryAdaptor myAdaptor, + final IAEItemStack whatToImport, + final IMEMonitor inv, + final IEnergySource energy, + final FuzzyMode fzMode) { + final int toSend = this.calculateMaximumAmountToImport(myAdaptor, whatToImport, inv, fzMode); + final ItemStack newItems; + + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + newItems = myAdaptor.removeSimilarItems( + toSend, + whatToImport == null ? null : whatToImport.getItemStack(), + fzMode, + this.configDestination(inv)); + } else { + newItems = myAdaptor.removeItems( + toSend, whatToImport == null ? null : whatToImport.getItemStack(), this.configDestination(inv)); + } + + if (newItems != null) { + newItems.stackSize = (int) (Math.min( + newItems.stackSize, + energy.extractAEPower(newItems.stackSize, Actionable.SIMULATE, PowerMultiplier.CONFIG)) + + 0.01); + this.itemToSend -= newItems.stackSize; + + if (this.lastItemChecked == null || !this.lastItemChecked.isSameType(newItems)) { + this.lastItemChecked = AEApi.instance().storage().createItemStack(newItems); + } else { + this.lastItemChecked.setStackSize(newItems.stackSize); + } + + final IAEItemStack failed = + Platform.poweredInsert(energy, this.destination, this.lastItemChecked, this.source); + + if (failed != null) { + myAdaptor.addItems(failed.getItemStack()); + return true; + } else { + this.worked = true; + } + } else { + return true; + } + + return false; + } + + private int calculateMaximumAmountToImport( + final InventoryAdaptor myAdaptor, + final IAEItemStack whatToImport, + final IMEMonitor inv, + final FuzzyMode fzMode) { + final int toSend = Math.min(this.itemToSend, 64); + final ItemStack itemStackToImport; + + if (whatToImport == null) { + itemStackToImport = null; + } else { + itemStackToImport = whatToImport.getItemStack(); + } + + final IAEItemStack itemAmountNotStorable; + final ItemStack simResult; + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + simResult = myAdaptor.simulateSimilarRemove(toSend, itemStackToImport, fzMode, this.configDestination(inv)); + } else { + simResult = myAdaptor.simulateRemove(toSend, itemStackToImport, this.configDestination(inv)); + } + itemAmountNotStorable = + this.destination.injectItems(AEItemStack.create(simResult), Actionable.SIMULATE, this.source); + + if (itemAmountNotStorable != null) { + return (int) Math.min(simResult.stackSize - itemAmountNotStorable.getStackSize(), toSend); + } + + return toSend; + } + + private IInventoryDestination configDestination(final IMEMonitor itemInventory) { + this.destination = itemInventory; + return this; + } + + @Override + protected boolean isSleeping() { + return this.getHandler() == null || super.isSleeping(); + } + + @Override + public RedstoneMode getRSMode() { + return (RedstoneMode) this.getConfigManager().getSetting(Settings.REDSTONE_CONTROLLED); + } } diff --git a/src/main/java/appeng/parts/automation/PartLevelEmitter.java b/src/main/java/appeng/parts/automation/PartLevelEmitter.java index 9192723887c..ead3273b967 100644 --- a/src/main/java/appeng/parts/automation/PartLevelEmitter.java +++ b/src/main/java/appeng/parts/automation/PartLevelEmitter.java @@ -18,7 +18,6 @@ package appeng.parts.automation; - import appeng.api.config.*; import appeng.api.networking.IGridNode; import appeng.api.networking.crafting.*; @@ -57,6 +56,8 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Collection; +import java.util.Random; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.player.EntityPlayer; @@ -71,730 +72,690 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collection; -import java.util.Random; - - public class PartLevelEmitter extends PartUpgradeable - implements IEnergyWatcherHost, IStackWatcherHost, ICraftingWatcherHost, IMEMonitorHandlerReceiver, ICraftingProvider, IGridTickable -{ - - private static final int FLAG_ON = 8; - - private final AppEngInternalAEInventory config = new AppEngInternalAEInventory( this, 1 ); - - private boolean prevState = false; - - private long lastReportedValue = 0; - private long reportingValue = 0; - - private IStackWatcher myWatcher; - private IEnergyWatcher myEnergyWatcher; - private ICraftingWatcher myCraftingWatcher; - private double centerX; - private double centerY; - private double centerZ; - - private int lastWorkingTick = 0; - private boolean delayedUpdatesQueued = false; - - @Reflected - public PartLevelEmitter( final ItemStack is ) - { - super( is ); - - this.getConfigManager().registerSetting( Settings.REDSTONE_EMITTER, RedstoneMode.HIGH_SIGNAL ); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.getConfigManager().registerSetting( Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL ); - this.getConfigManager().registerSetting( Settings.CRAFT_VIA_REDSTONE, YesNo.NO ); - - // Workaround the emitter randomly breaking on world load - delayedUpdatesQueued = true; - lastWorkingTick = MinecraftServer.getServer().getTickCounter(); - } - - public long getReportingValue() - { - return this.reportingValue; - } - - public void setReportingValue( final long v ) - { - this.reportingValue = v; - if( this.getConfigManager().getSetting( Settings.LEVEL_TYPE ) == LevelType.ENERGY_LEVEL ) - { - this.configureWatchers(); - } - else - { - this.updateState(); - } - } - - @MENetworkEventSubscribe - public void powerChanged( final MENetworkPowerStatusChange c ) - { - this.updateState(); - } - - private void updateState() - { - final boolean isOn = this.isLevelEmitterOn(); - if( this.prevState != isOn ) - { - this.getHost().markForUpdate(); - final TileEntity te = this.getHost().getTile(); - this.prevState = isOn; - Platform.notifyBlocksOfNeighbors( te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord ); - Platform.notifyBlocksOfNeighbors( te.getWorldObj(), te.xCoord + this.getSide().offsetX, te.yCoord + this.getSide().offsetY, te.zCoord + this.getSide().offsetZ ); - } - } - - private boolean isLevelEmitterOn() - { - if( Platform.isClient() ) - { - return ( this.getClientFlags() & FLAG_ON ) == FLAG_ON; - } - - if( !this.getProxy().isActive() ) - { - return false; - } - - if( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ) - { - try - { - return this.getProxy().getCrafting().isRequesting( this.config.getAEStackInSlot( 0 ) ); - } - catch( final GridAccessException e ) - { - // :P - } - - return this.prevState; - } - - final boolean flipState = this.getConfigManager().getSetting( Settings.REDSTONE_EMITTER ) == RedstoneMode.LOW_SIGNAL; - return flipState ? this.reportingValue >= this.lastReportedValue + 1 : this.reportingValue < this.lastReportedValue + 1; - } - - @MENetworkEventSubscribe - public void channelChanged( final MENetworkChannelsChanged c ) - { - this.updateState(); - } - - @Override - protected int populateFlags( final int cf ) - { - return cf | ( this.prevState ? FLAG_ON : 0 ); - } - - @Override - public IIcon getBreakingTexture() - { - return this.getItemStack().getIconIndex(); - } - - @Override - public void updateWatcher( final ICraftingWatcher newWatcher ) - { - this.myCraftingWatcher = newWatcher; - this.configureWatchers(); - } - - @Override - public void onRequestChange( final ICraftingGrid craftingGrid, final IAEItemStack what ) - { - this.updateState(); - } - - // update the system... - private void configureWatchers() - { - final IAEItemStack myStack = this.config.getAEStackInSlot( 0 ); - - if( this.myWatcher != null ) - { - this.myWatcher.clear(); - } - - if( this.myEnergyWatcher != null ) - { - this.myEnergyWatcher.clear(); - } - - if( this.myCraftingWatcher != null ) - { - this.myCraftingWatcher.clear(); - } - - try - { - this.getProxy().getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.getProxy().getNode() ) ); - } - catch( final GridAccessException e1 ) - { - // :/ - } - - if( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ) - { - if( this.myCraftingWatcher != null && myStack != null ) - { - this.myCraftingWatcher.add( myStack ); - } - - return; - } - - if( this.getConfigManager().getSetting( Settings.LEVEL_TYPE ) == LevelType.ENERGY_LEVEL ) - { - if( this.myEnergyWatcher != null ) - { - this.myEnergyWatcher.add( (double) this.reportingValue ); - } - - try - { - // update to power... - this.lastReportedValue = (long) this.getProxy().getEnergy().getStoredPower(); - this.updateState(); - - // no more item stuff.. - this.getProxy().getStorage().getItemInventory().removeListener( this ); - } - catch( final GridAccessException e ) - { - // :P - } - - return; - } - - try - { - if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 || myStack == null ) - { - this.getProxy().getStorage().getItemInventory().addListener( this, this.getProxy().getGrid() ); - } - else - { - this.getProxy().getStorage().getItemInventory().removeListener( this ); - - if( this.myWatcher != null ) - { - this.myWatcher.add( myStack ); - } - } - - this.updateReportingValue( this.getProxy().getStorage().getItemInventory() ); - } - catch( final GridAccessException e ) - { - // >.> - } - } - - private void updateReportingValue( final IMEMonitor monitor ) - { - final IAEItemStack myStack = this.config.getAEStackInSlot( 0 ); - - if( myStack == null ) - { - this.lastReportedValue = 0; - for( final IAEItemStack st : monitor.getStorageList() ) - { - this.lastReportedValue += st.getStackSize(); - } - } - else if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) - { - this.lastReportedValue = 0; - final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ); - final Collection fuzzyList = monitor.getStorageList().findFuzzy( myStack, fzMode ); - for( final IAEItemStack st : fuzzyList ) - { - this.lastReportedValue += st.getStackSize(); - } - } - else - { - final IAEItemStack r = monitor.getStorageList().findPrecise( myStack ); - if( r == null ) - { - this.lastReportedValue = 0; - } - else - { - this.lastReportedValue = r.getStackSize(); - } - } - - this.updateState(); - } - - @Override - public void updateWatcher( final IStackWatcher newWatcher ) - { - this.myWatcher = newWatcher; - this.configureWatchers(); - } - - @Override - public void onStackChange( final IItemList o, final IAEStack fullStack, final IAEStack diffStack, final BaseActionSource src, final StorageChannel chan ) - { - if( chan == StorageChannel.ITEMS && fullStack.equals( this.config.getAEStackInSlot( 0 ) ) && this.getInstalledUpgrades( Upgrades.FUZZY ) == 0 ) - { - this.lastReportedValue = fullStack.getStackSize(); - this.updateState(); - } - } - - @Override - public void updateWatcher( final IEnergyWatcher newWatcher ) - { - this.myEnergyWatcher = newWatcher; - this.configureWatchers(); - } - - @Override - public void onThresholdPass( final IEnergyGrid energyGrid ) - { - this.lastReportedValue = (long) energyGrid.getStoredPower(); - this.updateState(); - } - - @Override - public boolean isValid( final Object effectiveGrid ) - { - try - { - return this.getProxy().getGrid() == effectiveGrid; - } - catch( final GridAccessException e ) - { - return false; - } - } - - @Override - public TickingRequest getTickingRequest( IGridNode node ) - { - return new TickingRequest( AEConfig.instance.levelEmitterDelay / 2, AEConfig.instance.levelEmitterDelay, !delayedUpdatesQueued, true ); - } - - private boolean canDoWork() - { - int currentTick = MinecraftServer.getServer().getTickCounter(); - return ( currentTick - lastWorkingTick ) > AEConfig.instance.levelEmitterDelay; - } - - @Override - public TickRateModulation tickingRequest( IGridNode node, int TicksSinceLastCall ) - { - if( delayedUpdatesQueued && canDoWork() ) - { - delayedUpdatesQueued = false; - lastWorkingTick = MinecraftServer.getServer().getTickCounter(); - this.onListUpdate(); - } - return delayedUpdatesQueued ? TickRateModulation.IDLE : TickRateModulation.SLEEP; - } - - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final BaseActionSource actionSource ) - { - if( canDoWork() ) - { - if ( delayedUpdatesQueued ) - { - delayedUpdatesQueued = false; - try - { - this.getProxy().getTick().sleepDevice( this.getProxy().getNode() ); - } catch( GridAccessException e ) - { - AELog.error( e, "Couldn't put level emitter to sleep after cancelling delayed updates" ); - } - } - lastWorkingTick = MinecraftServer.getServer().getTickCounter(); - this.updateReportingValue( (IMEMonitor) monitor ); - } else if( !delayedUpdatesQueued ) - { - delayedUpdatesQueued = true; - try - { - this.getProxy().getTick().alertDevice( this.getProxy().getNode() ); - } catch( GridAccessException e ) - { - AELog.error( e, "Couldn't wake up level emitter for delayed updates" ); - } - } - } - - @Override - public void onListUpdate() - { - try - { - this.updateReportingValue( this.getProxy().getStorage().getItemInventory() ); - } - catch( final GridAccessException e ) - { - // ;P - } - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 7, 7, 11, 9, 9, 16 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( this.getItemStack().getIconIndex() ); - Tessellator.instance.startDrawingQuads(); - this.renderTorchAtAngle( 0, -0.5, 0 ); - Tessellator.instance.draw(); - // rh.setBounds( 7, 7, 10, 9, 9, 15 ); - // rh.renderInventoryBox( renderer ); - } - - private void renderTorchAtAngle( double baseX, double baseY, double baseZ ) - { - final boolean isOn = this.isLevelEmitterOn(); - final IIcon offTexture = this.getItemStack().getIconIndex(); - final IIcon IIcon = ( isOn ? CableBusTextures.LevelEmitterTorchOn.getIcon() : offTexture ); - // - this.centerX = baseX + 0.5; - this.centerY = baseY + 0.5; - this.centerZ = baseZ + 0.5; - - baseY += 7.0 / 16.0; - - // double par11 = 0; - - /* - * double d5 = (double)IIcon.func_94209_e(); double d6 = (double)IIcon.func_94206_g(); double d7 = - * (double)IIcon.func_94212_f(); double d8 = (double)IIcon.func_94210_h(); double d9 = - * (double)IIcon.func_94214_a(7.0D); double d10 = (double)IIcon.func_94207_b(6.0D); double d11 = - * (double)IIcon.func_94214_a(9.0D); double d12 = (double)IIcon.func_94207_b(8.0D); double d13 = - * (double)IIcon.func_94214_a(7.0D); double d14 = (double)IIcon.func_94207_b(13.0D); double d15 = - * (double)IIcon.func_94214_a(9.0D); double d16 = (double)IIcon.func_94207_b(15.0D); - */ - - final float var16 = IIcon.getMinU(); - final float var17 = IIcon.getMaxU(); - final float var18 = IIcon.getMinV(); - final float var19 = IIcon.getMaxV(); - /* - * float var16 = (float)var14 / 256.0F; float var17 = ((float)var14 + 15.99F) / 256.0F; float var18 = - * (float)var15 / 256.0F; float var19 = ((float)var15 + 15.99F) / 256.0F; - */ - final double var20b = offTexture.getInterpolatedU( 7.0D ); - final double var24b = offTexture.getInterpolatedU( 9.0D ); - - final double var20 = IIcon.getInterpolatedU( 7.0D ); - final double var24 = IIcon.getInterpolatedU( 9.0D ); - final double var22 = IIcon.getInterpolatedV( 6.0D + ( isOn ? 0 : 1.0D ) ); - final double var26 = IIcon.getInterpolatedV( 8.0D + ( isOn ? 0 : 1.0D ) ); - final double var28 = IIcon.getInterpolatedU( 7.0D ); - final double var30 = IIcon.getInterpolatedV( 13.0D ); - final double var32 = IIcon.getInterpolatedU( 9.0D ); - final double var34 = IIcon.getInterpolatedV( 15.0D ); - - final double var22b = IIcon.getInterpolatedV( 9.0D ); - final double var26b = IIcon.getInterpolatedV( 11.0D ); - - baseX += 0.5D; - baseZ += 0.5D; - final double var36 = baseX - 0.5D; - final double var38 = baseX + 0.5D; - final double var40 = baseZ - 0.5D; - final double var42 = baseZ + 0.5D; - - double toff = 0.0d; - - if( !isOn ) - { - toff = 1.0d / 16.0d; - } - - final Tessellator var12 = Tessellator.instance; - if( isOn ) - { - var12.setColorOpaque_F( 1.0F, 1.0F, 1.0F ); - var12.setBrightness( 11 << 20 | 11 << 4 ); - } - - final double TorchLen = 0.625D; - final double var44 = 0.0625D; - final double Zero = 0; - final double par10 = 0; - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) - var44, baseY + TorchLen - toff, baseZ + par10 * ( 1.0D - TorchLen ) - var44, var20, var22 ); - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) - var44, baseY + TorchLen - toff, baseZ + par10 * ( 1.0D - TorchLen ) + var44, var20, var26 ); - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) + var44, baseY + TorchLen - toff, baseZ + par10 * ( 1.0D - TorchLen ) + var44, var24, var26 ); - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) + var44, baseY + TorchLen - toff, baseZ + par10 * ( 1.0D - TorchLen ) - var44, var24, var22 ); - - final double var422 = 0.1915D + 1.0 / 16.0; - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) + var44, baseY + var422, baseZ + par10 * ( 1.0D - TorchLen ) - var44, var24b, var22b ); - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) + var44, baseY + var422, baseZ + par10 * ( 1.0D - TorchLen ) + var44, var24b, var26b ); - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) - var44, baseY + var422, baseZ + par10 * ( 1.0D - TorchLen ) + var44, var20b, var26b ); - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) - var44, baseY + var422, baseZ + par10 * ( 1.0D - TorchLen ) - var44, var20b, var22b ); - - this.addVertexWithUV( baseX + var44 + Zero, baseY, baseZ - var44 + par10, var32, var30 ); - this.addVertexWithUV( baseX + var44 + Zero, baseY, baseZ + var44 + par10, var32, var34 ); - this.addVertexWithUV( baseX - var44 + Zero, baseY, baseZ + var44 + par10, var28, var34 ); - this.addVertexWithUV( baseX - var44 + Zero, baseY, baseZ - var44 + par10, var28, var30 ); - - this.addVertexWithUV( baseX - var44, baseY + 1.0D, var40, var16, var18 ); - this.addVertexWithUV( baseX - var44 + Zero, baseY + 0.0D, var40 + par10, var16, var19 ); - this.addVertexWithUV( baseX - var44 + Zero, baseY + 0.0D, var42 + par10, var17, var19 ); - this.addVertexWithUV( baseX - var44, baseY + 1.0D, var42, var17, var18 ); - - this.addVertexWithUV( baseX + var44, baseY + 1.0D, var42, var16, var18 ); - this.addVertexWithUV( baseX + Zero + var44, baseY + 0.0D, var42 + par10, var16, var19 ); - this.addVertexWithUV( baseX + Zero + var44, baseY + 0.0D, var40 + par10, var17, var19 ); - this.addVertexWithUV( baseX + var44, baseY + 1.0D, var40, var17, var18 ); - - this.addVertexWithUV( var36, baseY + 1.0D, baseZ + var44, var16, var18 ); - this.addVertexWithUV( var36 + Zero, baseY + 0.0D, baseZ + var44 + par10, var16, var19 ); - this.addVertexWithUV( var38 + Zero, baseY + 0.0D, baseZ + var44 + par10, var17, var19 ); - this.addVertexWithUV( var38, baseY + 1.0D, baseZ + var44, var17, var18 ); - - this.addVertexWithUV( var38, baseY + 1.0D, baseZ - var44, var16, var18 ); - this.addVertexWithUV( var38 + Zero, baseY + 0.0D, baseZ - var44 + par10, var16, var19 ); - this.addVertexWithUV( var36 + Zero, baseY + 0.0D, baseZ - var44 + par10, var17, var19 ); - this.addVertexWithUV( var36, baseY + 1.0D, baseZ - var44, var17, var18 ); - } - - private void addVertexWithUV( double x, double y, double z, final double u, final double v ) - { - final Tessellator var12 = Tessellator.instance; - - x -= this.centerX; - y -= this.centerY; - z -= this.centerZ; - - if( this.getSide() == ForgeDirection.DOWN ) - { - y = -y; - z = -z; - } - - if( this.getSide() == ForgeDirection.EAST ) - { - final double m = x; - x = y; - y = m; - y = -y; - } - - if( this.getSide() == ForgeDirection.WEST ) - { - final double m = x; - x = -y; - y = m; - } - - if( this.getSide() == ForgeDirection.SOUTH ) - { - final double m = z; - z = y; - y = m; - y = -y; - } - - if( this.getSide() == ForgeDirection.NORTH ) - { - final double m = z; - z = -y; - y = m; - } - - x += this.centerX;// + orientation.offsetX * 0.4; - y += this.centerY;// + orientation.offsetY * 0.4; - z += this.centerZ;// + orientation.offsetZ * 0.4; - - var12.addVertexWithUV( x, y, z, u, v ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( this.getItemStack().getIconIndex() ); - // rh.setTexture( CableBusTextures.ItemPartLevelEmitterOn.getIcon() ); - - // rh.setBounds( 2, 2, 14, 14, 14, 16 ); - // rh.renderBlock( x, y, z, renderer ); - - // rh.setBounds( 7, 7, 10, 9, 9, 15 ); - // rh.renderBlock( x, y, z, renderer ); - - renderer.renderAllFaces = true; - - final Tessellator tess = Tessellator.instance; - tess.setBrightness( rh.getBlock().getMixedBrightnessForBlock( this.getHost().getTile().getWorldObj(), x, y, z ) ); - tess.setColorOpaque_F( 1.0F, 1.0F, 1.0F ); - - this.renderTorchAtAngle( x, y, z ); - - renderer.renderAllFaces = false; - - rh.setBounds( 7, 7, 11, 9, 9, 12 ); - this.renderLights( x, y, z, rh, renderer ); - - // super.renderWorldBlock( world, x, y, z, block, modelId, renderer ); - } - - @Override - public int isProvidingStrongPower() - { - return this.prevState ? 15 : 0; - } - - @Override - public int isProvidingWeakPower() - { - return this.prevState ? 15 : 0; - } - - @Override - public void randomDisplayTick( final World world, final int x, final int y, final int z, final Random r ) - { - if( this.isLevelEmitterOn() ) - { - final ForgeDirection d = this.getSide(); - - final double d0 = d.offsetX * 0.45F + ( r.nextFloat() - 0.5F ) * 0.2D; - final double d1 = d.offsetY * 0.45F + ( r.nextFloat() - 0.5F ) * 0.2D; - final double d2 = d.offsetZ * 0.45F + ( r.nextFloat() - 0.5F ) * 0.2D; - - world.spawnParticle( "reddust", 0.5 + x + d0, 0.5 + y + d1, 0.5 + z + d2, 0.0D, 0.0D, 0.0D ); - } - } - - @Override - public int cableConnectionRenderTo() - { - return 16; - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( !player.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } - - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_LEVEL_EMITTER ); - return true; - } - - return false; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - this.configureWatchers(); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - if( inv == this.config ) - { - this.configureWatchers(); - } - - super.onChangeInventory( inv, slot, mc, removedStack, newStack ); - } - - @Override - public void upgradesChanged() - { - this.configureWatchers(); - } - - @Override - public boolean canConnectRedstone() - { - return true; - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.lastReportedValue = data.getLong( "lastReportedValue" ); - this.reportingValue = data.getLong( "reportingValue" ); - this.prevState = data.getBoolean( "prevState" ); - this.config.readFromNBT( data, "config" ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setLong( "lastReportedValue", this.lastReportedValue ); - data.setLong( "reportingValue", this.reportingValue ); - data.setBoolean( "prevState", this.prevState ); - this.config.writeToNBT( data, "config" ); - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "config" ) ) - { - return this.config; - } - - return super.getInventoryByName( name ); - } - - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table ) - { - return false; - } - - @Override - public boolean isBusy() - { - return true; - } - - @Override - public void provideCrafting( final ICraftingProviderHelper craftingTracker ) - { - if( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ) - { - if( this.getConfigManager().getSetting( Settings.CRAFT_VIA_REDSTONE ) == YesNo.YES ) - { - final IAEItemStack what = this.config.getAEStackInSlot( 0 ); - if( what != null ) - { - craftingTracker.setEmitable( what ); - } - } - } - } + implements IEnergyWatcherHost, + IStackWatcherHost, + ICraftingWatcherHost, + IMEMonitorHandlerReceiver, + ICraftingProvider, + IGridTickable { + + private static final int FLAG_ON = 8; + + private final AppEngInternalAEInventory config = new AppEngInternalAEInventory(this, 1); + + private boolean prevState = false; + + private long lastReportedValue = 0; + private long reportingValue = 0; + + private IStackWatcher myWatcher; + private IEnergyWatcher myEnergyWatcher; + private ICraftingWatcher myCraftingWatcher; + private double centerX; + private double centerY; + private double centerZ; + + private int lastWorkingTick = 0; + private boolean delayedUpdatesQueued = false; + + @Reflected + public PartLevelEmitter(final ItemStack is) { + super(is); + + this.getConfigManager().registerSetting(Settings.REDSTONE_EMITTER, RedstoneMode.HIGH_SIGNAL); + this.getConfigManager().registerSetting(Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.getConfigManager().registerSetting(Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL); + this.getConfigManager().registerSetting(Settings.CRAFT_VIA_REDSTONE, YesNo.NO); + + // Workaround the emitter randomly breaking on world load + delayedUpdatesQueued = true; + lastWorkingTick = MinecraftServer.getServer().getTickCounter(); + } + + public long getReportingValue() { + return this.reportingValue; + } + + public void setReportingValue(final long v) { + this.reportingValue = v; + if (this.getConfigManager().getSetting(Settings.LEVEL_TYPE) == LevelType.ENERGY_LEVEL) { + this.configureWatchers(); + } else { + this.updateState(); + } + } + + @MENetworkEventSubscribe + public void powerChanged(final MENetworkPowerStatusChange c) { + this.updateState(); + } + + private void updateState() { + final boolean isOn = this.isLevelEmitterOn(); + if (this.prevState != isOn) { + this.getHost().markForUpdate(); + final TileEntity te = this.getHost().getTile(); + this.prevState = isOn; + Platform.notifyBlocksOfNeighbors(te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord); + Platform.notifyBlocksOfNeighbors( + te.getWorldObj(), + te.xCoord + this.getSide().offsetX, + te.yCoord + this.getSide().offsetY, + te.zCoord + this.getSide().offsetZ); + } + } + + private boolean isLevelEmitterOn() { + if (Platform.isClient()) { + return (this.getClientFlags() & FLAG_ON) == FLAG_ON; + } + + if (!this.getProxy().isActive()) { + return false; + } + + if (this.getInstalledUpgrades(Upgrades.CRAFTING) > 0) { + try { + return this.getProxy().getCrafting().isRequesting(this.config.getAEStackInSlot(0)); + } catch (final GridAccessException e) { + // :P + } + + return this.prevState; + } + + final boolean flipState = + this.getConfigManager().getSetting(Settings.REDSTONE_EMITTER) == RedstoneMode.LOW_SIGNAL; + return flipState + ? this.reportingValue >= this.lastReportedValue + 1 + : this.reportingValue < this.lastReportedValue + 1; + } + + @MENetworkEventSubscribe + public void channelChanged(final MENetworkChannelsChanged c) { + this.updateState(); + } + + @Override + protected int populateFlags(final int cf) { + return cf | (this.prevState ? FLAG_ON : 0); + } + + @Override + public IIcon getBreakingTexture() { + return this.getItemStack().getIconIndex(); + } + + @Override + public void updateWatcher(final ICraftingWatcher newWatcher) { + this.myCraftingWatcher = newWatcher; + this.configureWatchers(); + } + + @Override + public void onRequestChange(final ICraftingGrid craftingGrid, final IAEItemStack what) { + this.updateState(); + } + + // update the system... + private void configureWatchers() { + final IAEItemStack myStack = this.config.getAEStackInSlot(0); + + if (this.myWatcher != null) { + this.myWatcher.clear(); + } + + if (this.myEnergyWatcher != null) { + this.myEnergyWatcher.clear(); + } + + if (this.myCraftingWatcher != null) { + this.myCraftingWatcher.clear(); + } + + try { + this.getProxy() + .getGrid() + .postEvent(new MENetworkCraftingPatternChange( + this, this.getProxy().getNode())); + } catch (final GridAccessException e1) { + // :/ + } + + if (this.getInstalledUpgrades(Upgrades.CRAFTING) > 0) { + if (this.myCraftingWatcher != null && myStack != null) { + this.myCraftingWatcher.add(myStack); + } + + return; + } + + if (this.getConfigManager().getSetting(Settings.LEVEL_TYPE) == LevelType.ENERGY_LEVEL) { + if (this.myEnergyWatcher != null) { + this.myEnergyWatcher.add((double) this.reportingValue); + } + + try { + // update to power... + this.lastReportedValue = (long) this.getProxy().getEnergy().getStoredPower(); + this.updateState(); + + // no more item stuff.. + this.getProxy().getStorage().getItemInventory().removeListener(this); + } catch (final GridAccessException e) { + // :P + } + + return; + } + + try { + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0 || myStack == null) { + this.getProxy() + .getStorage() + .getItemInventory() + .addListener(this, this.getProxy().getGrid()); + } else { + this.getProxy().getStorage().getItemInventory().removeListener(this); + + if (this.myWatcher != null) { + this.myWatcher.add(myStack); + } + } + + this.updateReportingValue(this.getProxy().getStorage().getItemInventory()); + } catch (final GridAccessException e) { + // >.> + } + } + + private void updateReportingValue(final IMEMonitor monitor) { + final IAEItemStack myStack = this.config.getAEStackInSlot(0); + + if (myStack == null) { + this.lastReportedValue = 0; + for (final IAEItemStack st : monitor.getStorageList()) { + this.lastReportedValue += st.getStackSize(); + } + } else if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + this.lastReportedValue = 0; + final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting(Settings.FUZZY_MODE); + final Collection fuzzyList = monitor.getStorageList().findFuzzy(myStack, fzMode); + for (final IAEItemStack st : fuzzyList) { + this.lastReportedValue += st.getStackSize(); + } + } else { + final IAEItemStack r = monitor.getStorageList().findPrecise(myStack); + if (r == null) { + this.lastReportedValue = 0; + } else { + this.lastReportedValue = r.getStackSize(); + } + } + + this.updateState(); + } + + @Override + public void updateWatcher(final IStackWatcher newWatcher) { + this.myWatcher = newWatcher; + this.configureWatchers(); + } + + @Override + public void onStackChange( + final IItemList o, + final IAEStack fullStack, + final IAEStack diffStack, + final BaseActionSource src, + final StorageChannel chan) { + if (chan == StorageChannel.ITEMS + && fullStack.equals(this.config.getAEStackInSlot(0)) + && this.getInstalledUpgrades(Upgrades.FUZZY) == 0) { + this.lastReportedValue = fullStack.getStackSize(); + this.updateState(); + } + } + + @Override + public void updateWatcher(final IEnergyWatcher newWatcher) { + this.myEnergyWatcher = newWatcher; + this.configureWatchers(); + } + + @Override + public void onThresholdPass(final IEnergyGrid energyGrid) { + this.lastReportedValue = (long) energyGrid.getStoredPower(); + this.updateState(); + } + + @Override + public boolean isValid(final Object effectiveGrid) { + try { + return this.getProxy().getGrid() == effectiveGrid; + } catch (final GridAccessException e) { + return false; + } + } + + @Override + public TickingRequest getTickingRequest(IGridNode node) { + return new TickingRequest( + AEConfig.instance.levelEmitterDelay / 2, + AEConfig.instance.levelEmitterDelay, + !delayedUpdatesQueued, + true); + } + + private boolean canDoWork() { + int currentTick = MinecraftServer.getServer().getTickCounter(); + return (currentTick - lastWorkingTick) > AEConfig.instance.levelEmitterDelay; + } + + @Override + public TickRateModulation tickingRequest(IGridNode node, int TicksSinceLastCall) { + if (delayedUpdatesQueued && canDoWork()) { + delayedUpdatesQueued = false; + lastWorkingTick = MinecraftServer.getServer().getTickCounter(); + this.onListUpdate(); + } + return delayedUpdatesQueued ? TickRateModulation.IDLE : TickRateModulation.SLEEP; + } + + @Override + public void postChange( + final IBaseMonitor monitor, + final Iterable change, + final BaseActionSource actionSource) { + if (canDoWork()) { + if (delayedUpdatesQueued) { + delayedUpdatesQueued = false; + try { + this.getProxy().getTick().sleepDevice(this.getProxy().getNode()); + } catch (GridAccessException e) { + AELog.error(e, "Couldn't put level emitter to sleep after cancelling delayed updates"); + } + } + lastWorkingTick = MinecraftServer.getServer().getTickCounter(); + this.updateReportingValue((IMEMonitor) monitor); + } else if (!delayedUpdatesQueued) { + delayedUpdatesQueued = true; + try { + this.getProxy().getTick().alertDevice(this.getProxy().getNode()); + } catch (GridAccessException e) { + AELog.error(e, "Couldn't wake up level emitter for delayed updates"); + } + } + } + + @Override + public void onListUpdate() { + try { + this.updateReportingValue(this.getProxy().getStorage().getItemInventory()); + } catch (final GridAccessException e) { + // ;P + } + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(7, 7, 11, 9, 9, 16); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture(this.getItemStack().getIconIndex()); + Tessellator.instance.startDrawingQuads(); + this.renderTorchAtAngle(0, -0.5, 0); + Tessellator.instance.draw(); + // rh.setBounds( 7, 7, 10, 9, 9, 15 ); + // rh.renderInventoryBox( renderer ); + } + + private void renderTorchAtAngle(double baseX, double baseY, double baseZ) { + final boolean isOn = this.isLevelEmitterOn(); + final IIcon offTexture = this.getItemStack().getIconIndex(); + final IIcon IIcon = (isOn ? CableBusTextures.LevelEmitterTorchOn.getIcon() : offTexture); + // + this.centerX = baseX + 0.5; + this.centerY = baseY + 0.5; + this.centerZ = baseZ + 0.5; + + baseY += 7.0 / 16.0; + + // double par11 = 0; + + /* + * double d5 = (double)IIcon.func_94209_e(); double d6 = (double)IIcon.func_94206_g(); double d7 = + * (double)IIcon.func_94212_f(); double d8 = (double)IIcon.func_94210_h(); double d9 = + * (double)IIcon.func_94214_a(7.0D); double d10 = (double)IIcon.func_94207_b(6.0D); double d11 = + * (double)IIcon.func_94214_a(9.0D); double d12 = (double)IIcon.func_94207_b(8.0D); double d13 = + * (double)IIcon.func_94214_a(7.0D); double d14 = (double)IIcon.func_94207_b(13.0D); double d15 = + * (double)IIcon.func_94214_a(9.0D); double d16 = (double)IIcon.func_94207_b(15.0D); + */ + + final float var16 = IIcon.getMinU(); + final float var17 = IIcon.getMaxU(); + final float var18 = IIcon.getMinV(); + final float var19 = IIcon.getMaxV(); + /* + * float var16 = (float)var14 / 256.0F; float var17 = ((float)var14 + 15.99F) / 256.0F; float var18 = + * (float)var15 / 256.0F; float var19 = ((float)var15 + 15.99F) / 256.0F; + */ + final double var20b = offTexture.getInterpolatedU(7.0D); + final double var24b = offTexture.getInterpolatedU(9.0D); + + final double var20 = IIcon.getInterpolatedU(7.0D); + final double var24 = IIcon.getInterpolatedU(9.0D); + final double var22 = IIcon.getInterpolatedV(6.0D + (isOn ? 0 : 1.0D)); + final double var26 = IIcon.getInterpolatedV(8.0D + (isOn ? 0 : 1.0D)); + final double var28 = IIcon.getInterpolatedU(7.0D); + final double var30 = IIcon.getInterpolatedV(13.0D); + final double var32 = IIcon.getInterpolatedU(9.0D); + final double var34 = IIcon.getInterpolatedV(15.0D); + + final double var22b = IIcon.getInterpolatedV(9.0D); + final double var26b = IIcon.getInterpolatedV(11.0D); + + baseX += 0.5D; + baseZ += 0.5D; + final double var36 = baseX - 0.5D; + final double var38 = baseX + 0.5D; + final double var40 = baseZ - 0.5D; + final double var42 = baseZ + 0.5D; + + double toff = 0.0d; + + if (!isOn) { + toff = 1.0d / 16.0d; + } + + final Tessellator var12 = Tessellator.instance; + if (isOn) { + var12.setColorOpaque_F(1.0F, 1.0F, 1.0F); + var12.setBrightness(11 << 20 | 11 << 4); + } + + final double TorchLen = 0.625D; + final double var44 = 0.0625D; + final double Zero = 0; + final double par10 = 0; + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) - var44, + baseY + TorchLen - toff, + baseZ + par10 * (1.0D - TorchLen) - var44, + var20, + var22); + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) - var44, + baseY + TorchLen - toff, + baseZ + par10 * (1.0D - TorchLen) + var44, + var20, + var26); + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) + var44, + baseY + TorchLen - toff, + baseZ + par10 * (1.0D - TorchLen) + var44, + var24, + var26); + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) + var44, + baseY + TorchLen - toff, + baseZ + par10 * (1.0D - TorchLen) - var44, + var24, + var22); + + final double var422 = 0.1915D + 1.0 / 16.0; + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) + var44, + baseY + var422, + baseZ + par10 * (1.0D - TorchLen) - var44, + var24b, + var22b); + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) + var44, + baseY + var422, + baseZ + par10 * (1.0D - TorchLen) + var44, + var24b, + var26b); + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) - var44, + baseY + var422, + baseZ + par10 * (1.0D - TorchLen) + var44, + var20b, + var26b); + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) - var44, + baseY + var422, + baseZ + par10 * (1.0D - TorchLen) - var44, + var20b, + var22b); + + this.addVertexWithUV(baseX + var44 + Zero, baseY, baseZ - var44 + par10, var32, var30); + this.addVertexWithUV(baseX + var44 + Zero, baseY, baseZ + var44 + par10, var32, var34); + this.addVertexWithUV(baseX - var44 + Zero, baseY, baseZ + var44 + par10, var28, var34); + this.addVertexWithUV(baseX - var44 + Zero, baseY, baseZ - var44 + par10, var28, var30); + + this.addVertexWithUV(baseX - var44, baseY + 1.0D, var40, var16, var18); + this.addVertexWithUV(baseX - var44 + Zero, baseY + 0.0D, var40 + par10, var16, var19); + this.addVertexWithUV(baseX - var44 + Zero, baseY + 0.0D, var42 + par10, var17, var19); + this.addVertexWithUV(baseX - var44, baseY + 1.0D, var42, var17, var18); + + this.addVertexWithUV(baseX + var44, baseY + 1.0D, var42, var16, var18); + this.addVertexWithUV(baseX + Zero + var44, baseY + 0.0D, var42 + par10, var16, var19); + this.addVertexWithUV(baseX + Zero + var44, baseY + 0.0D, var40 + par10, var17, var19); + this.addVertexWithUV(baseX + var44, baseY + 1.0D, var40, var17, var18); + + this.addVertexWithUV(var36, baseY + 1.0D, baseZ + var44, var16, var18); + this.addVertexWithUV(var36 + Zero, baseY + 0.0D, baseZ + var44 + par10, var16, var19); + this.addVertexWithUV(var38 + Zero, baseY + 0.0D, baseZ + var44 + par10, var17, var19); + this.addVertexWithUV(var38, baseY + 1.0D, baseZ + var44, var17, var18); + + this.addVertexWithUV(var38, baseY + 1.0D, baseZ - var44, var16, var18); + this.addVertexWithUV(var38 + Zero, baseY + 0.0D, baseZ - var44 + par10, var16, var19); + this.addVertexWithUV(var36 + Zero, baseY + 0.0D, baseZ - var44 + par10, var17, var19); + this.addVertexWithUV(var36, baseY + 1.0D, baseZ - var44, var17, var18); + } + + private void addVertexWithUV(double x, double y, double z, final double u, final double v) { + final Tessellator var12 = Tessellator.instance; + + x -= this.centerX; + y -= this.centerY; + z -= this.centerZ; + + if (this.getSide() == ForgeDirection.DOWN) { + y = -y; + z = -z; + } + + if (this.getSide() == ForgeDirection.EAST) { + final double m = x; + x = y; + y = m; + y = -y; + } + + if (this.getSide() == ForgeDirection.WEST) { + final double m = x; + x = -y; + y = m; + } + + if (this.getSide() == ForgeDirection.SOUTH) { + final double m = z; + z = y; + y = m; + y = -y; + } + + if (this.getSide() == ForgeDirection.NORTH) { + final double m = z; + z = -y; + y = m; + } + + x += this.centerX; // + orientation.offsetX * 0.4; + y += this.centerY; // + orientation.offsetY * 0.4; + z += this.centerZ; // + orientation.offsetZ * 0.4; + + var12.addVertexWithUV(x, y, z, u, v); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture(this.getItemStack().getIconIndex()); + // rh.setTexture( CableBusTextures.ItemPartLevelEmitterOn.getIcon() ); + + // rh.setBounds( 2, 2, 14, 14, 14, 16 ); + // rh.renderBlock( x, y, z, renderer ); + + // rh.setBounds( 7, 7, 10, 9, 9, 15 ); + // rh.renderBlock( x, y, z, renderer ); + + renderer.renderAllFaces = true; + + final Tessellator tess = Tessellator.instance; + tess.setBrightness(rh.getBlock() + .getMixedBrightnessForBlock(this.getHost().getTile().getWorldObj(), x, y, z)); + tess.setColorOpaque_F(1.0F, 1.0F, 1.0F); + + this.renderTorchAtAngle(x, y, z); + + renderer.renderAllFaces = false; + + rh.setBounds(7, 7, 11, 9, 9, 12); + this.renderLights(x, y, z, rh, renderer); + + // super.renderWorldBlock( world, x, y, z, block, modelId, renderer ); + } + + @Override + public int isProvidingStrongPower() { + return this.prevState ? 15 : 0; + } + + @Override + public int isProvidingWeakPower() { + return this.prevState ? 15 : 0; + } + + @Override + public void randomDisplayTick(final World world, final int x, final int y, final int z, final Random r) { + if (this.isLevelEmitterOn()) { + final ForgeDirection d = this.getSide(); + + final double d0 = d.offsetX * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; + final double d1 = d.offsetY * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; + final double d2 = d.offsetZ * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; + + world.spawnParticle("reddust", 0.5 + x + d0, 0.5 + y + d1, 0.5 + z + d2, 0.0D, 0.0D, 0.0D); + } + } + + @Override + public int cableConnectionRenderTo() { + return 16; + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (!player.isSneaking()) { + if (Platform.isClient()) { + return true; + } + + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_LEVEL_EMITTER); + return true; + } + + return false; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + this.configureWatchers(); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) { + if (inv == this.config) { + this.configureWatchers(); + } + + super.onChangeInventory(inv, slot, mc, removedStack, newStack); + } + + @Override + public void upgradesChanged() { + this.configureWatchers(); + } + + @Override + public boolean canConnectRedstone() { + return true; + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.lastReportedValue = data.getLong("lastReportedValue"); + this.reportingValue = data.getLong("reportingValue"); + this.prevState = data.getBoolean("prevState"); + this.config.readFromNBT(data, "config"); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setLong("lastReportedValue", this.lastReportedValue); + data.setLong("reportingValue", this.reportingValue); + data.setBoolean("prevState", this.prevState); + this.config.writeToNBT(data, "config"); + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("config")) { + return this.config; + } + + return super.getInventoryByName(name); + } + + @Override + public boolean pushPattern(final ICraftingPatternDetails patternDetails, final InventoryCrafting table) { + return false; + } + + @Override + public boolean isBusy() { + return true; + } + + @Override + public void provideCrafting(final ICraftingProviderHelper craftingTracker) { + if (this.getInstalledUpgrades(Upgrades.CRAFTING) > 0) { + if (this.getConfigManager().getSetting(Settings.CRAFT_VIA_REDSTONE) == YesNo.YES) { + final IAEItemStack what = this.config.getAEStackInSlot(0); + if (what != null) { + craftingTracker.setEmitable(what); + } + } + } + } } diff --git a/src/main/java/appeng/parts/automation/PartSharedItemBus.java b/src/main/java/appeng/parts/automation/PartSharedItemBus.java index 035dd369b02..771f67a9e1f 100644 --- a/src/main/java/appeng/parts/automation/PartSharedItemBus.java +++ b/src/main/java/appeng/parts/automation/PartSharedItemBus.java @@ -18,7 +18,6 @@ package appeng.parts.automation; - import appeng.api.config.RedstoneMode; import appeng.api.config.Upgrades; import appeng.api.networking.ticking.IGridTickable; @@ -29,183 +28,161 @@ import appeng.tile.inventory.AppEngInternalAEInventory; import appeng.util.InventoryAdaptor; import appeng.util.Platform; +import java.util.function.Predicate; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.util.function.Predicate; - - -public abstract class PartSharedItemBus extends PartUpgradeable implements IGridTickable, IOreFilterable -{ - private final AppEngInternalAEInventory config = new AppEngInternalAEInventory( this, 9 ); - private int adaptorHash = 0; - private InventoryAdaptor adaptor; - private boolean lastRedstone = false; - protected String oreFilterString = ""; - protected Predicate filterPredicate = null; - - public PartSharedItemBus( final ItemStack is ) - { - super( is ); - } - - @Override - public void upgradesChanged() - { - if (getInstalledUpgrades(Upgrades.ORE_FILTER) == 0) { - oreFilterString = ""; - filterPredicate = null; - } - this.updateState(); - } - - @Override - public void readFromNBT( final net.minecraft.nbt.NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.getConfig().readFromNBT( extra, "config" ); - this.oreFilterString = extra.getString("filter"); - } - - @Override - public void writeToNBT( final net.minecraft.nbt.NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.getConfig().writeToNBT( extra, "config" ); - extra.setString("filter", this.oreFilterString); - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "config" ) ) - { - return this.getConfig(); - } - - return super.getInventoryByName( name ); - } - - @Override - public void onNeighborChanged() - { - this.updateState(); - if( this.lastRedstone != this.getHost().hasRedstone( this.getSide() ) ) - { - this.lastRedstone = !this.lastRedstone; - if( this.lastRedstone && this.getRSMode() == RedstoneMode.SIGNAL_PULSE ) - { - this.doBusWork(); - } - } - } - - protected InventoryAdaptor getHandler() - { - final TileEntity self = this.getHost().getTile(); - final TileEntity target = this.getTileEntity( self, self.xCoord + this.getSide().offsetX, self.yCoord + this.getSide().offsetY, self.zCoord + this.getSide().offsetZ ); - - final int newAdaptorHash = Platform.generateTileHash( target ); - - if( this.adaptorHash == newAdaptorHash && newAdaptorHash != 0 ) - { - return this.adaptor; - } - - this.adaptorHash = newAdaptorHash; - this.adaptor = InventoryAdaptor.getAdaptor( target, this.getSide().getOpposite() ); - - return this.adaptor; - } - - protected int availableSlots() - { - return Math.min( 1 + this.getInstalledUpgrades( Upgrades.CAPACITY ) * 4, this.getConfig().getSizeInventory() ); - } - - protected int calculateItemsToSend() - { - switch( this.getInstalledUpgrades( Upgrades.SPEED ) ) - { - default: - case 0: - return 1; - case 1: - return 8; - case 2: - return 32; - case 3: - return 64; - case 4: - return 96; - } - } - - /** - * Checks if the bus can actually do something. - *

- * Currently this tests if the chunk for the target is actually loaded. - * - * @return true, if the the bus should do its work. - */ - protected boolean canDoBusWork() - { - final TileEntity self = this.getHost().getTile(); - final World world = self.getWorldObj(); - final int xCoordinate = self.xCoord + this.getSide().offsetX; - final int zCoordinate = self.zCoord + this.getSide().offsetZ; - - return world != null && world.getChunkProvider().chunkExists( xCoordinate >> 4, zCoordinate >> 4 ); - } - - private void updateState() - { - try - { - if( !this.isSleeping() ) - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - else - { - this.getProxy().getTick().sleepDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - - private TileEntity getTileEntity( final TileEntity self, final int x, final int y, final int z ) - { - final World w = self.getWorldObj(); - - if( w.getChunkProvider().chunkExists( x >> 4, z >> 4 ) ) - { - return w.getTileEntity( x, y, z ); - } - - return null; - } - - protected abstract TickRateModulation doBusWork(); - - AppEngInternalAEInventory getConfig() - { - return this.config; - } - - @Override - public String getFilter() { - return oreFilterString; - } - - @Override - public void setFilter(String filter) { - oreFilterString = filter; - filterPredicate = null; - } +public abstract class PartSharedItemBus extends PartUpgradeable implements IGridTickable, IOreFilterable { + private final AppEngInternalAEInventory config = new AppEngInternalAEInventory(this, 9); + private int adaptorHash = 0; + private InventoryAdaptor adaptor; + private boolean lastRedstone = false; + protected String oreFilterString = ""; + protected Predicate filterPredicate = null; + + public PartSharedItemBus(final ItemStack is) { + super(is); + } + + @Override + public void upgradesChanged() { + if (getInstalledUpgrades(Upgrades.ORE_FILTER) == 0) { + oreFilterString = ""; + filterPredicate = null; + } + this.updateState(); + } + + @Override + public void readFromNBT(final net.minecraft.nbt.NBTTagCompound extra) { + super.readFromNBT(extra); + this.getConfig().readFromNBT(extra, "config"); + this.oreFilterString = extra.getString("filter"); + } + + @Override + public void writeToNBT(final net.minecraft.nbt.NBTTagCompound extra) { + super.writeToNBT(extra); + this.getConfig().writeToNBT(extra, "config"); + extra.setString("filter", this.oreFilterString); + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("config")) { + return this.getConfig(); + } + + return super.getInventoryByName(name); + } + + @Override + public void onNeighborChanged() { + this.updateState(); + if (this.lastRedstone != this.getHost().hasRedstone(this.getSide())) { + this.lastRedstone = !this.lastRedstone; + if (this.lastRedstone && this.getRSMode() == RedstoneMode.SIGNAL_PULSE) { + this.doBusWork(); + } + } + } + + protected InventoryAdaptor getHandler() { + final TileEntity self = this.getHost().getTile(); + final TileEntity target = this.getTileEntity( + self, + self.xCoord + this.getSide().offsetX, + self.yCoord + this.getSide().offsetY, + self.zCoord + this.getSide().offsetZ); + + final int newAdaptorHash = Platform.generateTileHash(target); + + if (this.adaptorHash == newAdaptorHash && newAdaptorHash != 0) { + return this.adaptor; + } + + this.adaptorHash = newAdaptorHash; + this.adaptor = InventoryAdaptor.getAdaptor(target, this.getSide().getOpposite()); + + return this.adaptor; + } + + protected int availableSlots() { + return Math.min( + 1 + this.getInstalledUpgrades(Upgrades.CAPACITY) * 4, + this.getConfig().getSizeInventory()); + } + + protected int calculateItemsToSend() { + switch (this.getInstalledUpgrades(Upgrades.SPEED)) { + default: + case 0: + return 1; + case 1: + return 8; + case 2: + return 32; + case 3: + return 64; + case 4: + return 96; + } + } + + /** + * Checks if the bus can actually do something. + *

+ * Currently this tests if the chunk for the target is actually loaded. + * + * @return true, if the the bus should do its work. + */ + protected boolean canDoBusWork() { + final TileEntity self = this.getHost().getTile(); + final World world = self.getWorldObj(); + final int xCoordinate = self.xCoord + this.getSide().offsetX; + final int zCoordinate = self.zCoord + this.getSide().offsetZ; + + return world != null && world.getChunkProvider().chunkExists(xCoordinate >> 4, zCoordinate >> 4); + } + + private void updateState() { + try { + if (!this.isSleeping()) { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } else { + this.getProxy().getTick().sleepDevice(this.getProxy().getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } + + private TileEntity getTileEntity(final TileEntity self, final int x, final int y, final int z) { + final World w = self.getWorldObj(); + + if (w.getChunkProvider().chunkExists(x >> 4, z >> 4)) { + return w.getTileEntity(x, y, z); + } + + return null; + } + + protected abstract TickRateModulation doBusWork(); + + AppEngInternalAEInventory getConfig() { + return this.config; + } + + @Override + public String getFilter() { + return oreFilterString; + } + + @Override + public void setFilter(String filter) { + oreFilterString = filter; + filterPredicate = null; + } } diff --git a/src/main/java/appeng/parts/automation/PartUpgradeable.java b/src/main/java/appeng/parts/automation/PartUpgradeable.java index b73582af029..45634a3d856 100644 --- a/src/main/java/appeng/parts/automation/PartUpgradeable.java +++ b/src/main/java/appeng/parts/automation/PartUpgradeable.java @@ -18,7 +18,6 @@ package appeng.parts.automation; - import appeng.api.config.RedstoneMode; import appeng.api.config.Upgrades; import appeng.api.util.IConfigManager; @@ -27,145 +26,121 @@ import appeng.tile.inventory.InvOperation; import appeng.util.ConfigManager; import appeng.util.IConfigManagerHost; +import java.util.List; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.util.List; - - -public abstract class PartUpgradeable extends PartBasicState implements IAEAppEngInventory, IConfigManagerHost -{ - private final IConfigManager manager; - private final UpgradeInventory upgrades; - - public PartUpgradeable( final ItemStack is ) - { - super( is ); - this.upgrades = new StackUpgradeInventory( this.getItemStack(), this, this.getUpgradeSlots() ); - this.upgrades.setMaxStackSize( 1 ); - this.manager = new ConfigManager( this ); - } - - protected int getUpgradeSlots() - { - return 4; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - if( inv == this.upgrades ) - { - this.upgradesChanged(); - } - } - - public void upgradesChanged() - { - - } - - protected boolean isSleeping() - { - if( this.getInstalledUpgrades( Upgrades.REDSTONE ) > 0 ) - { - switch( this.getRSMode() ) - { - case IGNORE: - return false; - - case HIGH_SIGNAL: - if( this.getHost().hasRedstone( this.getSide() ) ) - { - return false; - } - - break; - - case LOW_SIGNAL: - if( !this.getHost().hasRedstone( this.getSide() ) ) - { - return false; - } - - break; - - case SIGNAL_PULSE: - default: - break; - } - - return true; - } - - return false; - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.upgrades.getInstalledUpgrades( u ); - } - - @Override - public boolean canConnectRedstone() - { - return this.upgrades.getMaxInstalled( Upgrades.REDSTONE ) > 0; - } - - @Override - public void readFromNBT( final net.minecraft.nbt.NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.manager.readFromNBT( extra ); - this.upgrades.readFromNBT( extra, "upgrades" ); - } - - @Override - public void writeToNBT( final net.minecraft.nbt.NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.manager.writeToNBT( extra ); - this.upgrades.writeToNBT( extra, "upgrades" ); - } - - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - for( final ItemStack is : this.upgrades ) - { - if( is != null ) - { - drops.add( is ); - } - } - } - - @Override - public IConfigManager getConfigManager() - { - return this.manager; - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "upgrades" ) ) - { - return this.upgrades; - } - - return null; - } - - public RedstoneMode getRSMode() - { - return null; - } +public abstract class PartUpgradeable extends PartBasicState implements IAEAppEngInventory, IConfigManagerHost { + private final IConfigManager manager; + private final UpgradeInventory upgrades; + + public PartUpgradeable(final ItemStack is) { + super(is); + this.upgrades = new StackUpgradeInventory(this.getItemStack(), this, this.getUpgradeSlots()); + this.upgrades.setMaxStackSize(1); + this.manager = new ConfigManager(this); + } + + protected int getUpgradeSlots() { + return 4; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) {} + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) { + if (inv == this.upgrades) { + this.upgradesChanged(); + } + } + + public void upgradesChanged() {} + + protected boolean isSleeping() { + if (this.getInstalledUpgrades(Upgrades.REDSTONE) > 0) { + switch (this.getRSMode()) { + case IGNORE: + return false; + + case HIGH_SIGNAL: + if (this.getHost().hasRedstone(this.getSide())) { + return false; + } + + break; + + case LOW_SIGNAL: + if (!this.getHost().hasRedstone(this.getSide())) { + return false; + } + + break; + + case SIGNAL_PULSE: + default: + break; + } + + return true; + } + + return false; + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.upgrades.getInstalledUpgrades(u); + } + + @Override + public boolean canConnectRedstone() { + return this.upgrades.getMaxInstalled(Upgrades.REDSTONE) > 0; + } + + @Override + public void readFromNBT(final net.minecraft.nbt.NBTTagCompound extra) { + super.readFromNBT(extra); + this.manager.readFromNBT(extra); + this.upgrades.readFromNBT(extra, "upgrades"); + } + + @Override + public void writeToNBT(final net.minecraft.nbt.NBTTagCompound extra) { + super.writeToNBT(extra); + this.manager.writeToNBT(extra); + this.upgrades.writeToNBT(extra, "upgrades"); + } + + @Override + public void getDrops(final List drops, final boolean wrenched) { + for (final ItemStack is : this.upgrades) { + if (is != null) { + drops.add(is); + } + } + } + + @Override + public IConfigManager getConfigManager() { + return this.manager; + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("upgrades")) { + return this.upgrades; + } + + return null; + } + + public RedstoneMode getRSMode() { + return null; + } } diff --git a/src/main/java/appeng/parts/automation/StackUpgradeInventory.java b/src/main/java/appeng/parts/automation/StackUpgradeInventory.java index 1ffebfa2849..2c49ebce6fd 100644 --- a/src/main/java/appeng/parts/automation/StackUpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/StackUpgradeInventory.java @@ -1,36 +1,29 @@ package appeng.parts.automation; - import appeng.api.config.Upgrades; import appeng.tile.inventory.IAEAppEngInventory; import appeng.util.Platform; import net.minecraft.item.ItemStack; +public class StackUpgradeInventory extends UpgradeInventory { + private final ItemStack stack; -public class StackUpgradeInventory extends UpgradeInventory -{ - private final ItemStack stack; - - public StackUpgradeInventory( final ItemStack stack, final IAEAppEngInventory inventory, final int s ) - { - super( inventory, s ); - this.stack = stack; - } + public StackUpgradeInventory(final ItemStack stack, final IAEAppEngInventory inventory, final int s) { + super(inventory, s); + this.stack = stack; + } - @Override - public int getMaxInstalled( final Upgrades upgrades ) - { - int max = 0; + @Override + public int getMaxInstalled(final Upgrades upgrades) { + int max = 0; - for( final ItemStack is : upgrades.getSupported().keySet() ) - { - if( Platform.isSameItem( this.stack, is ) ) - { - max = upgrades.getSupported().get( is ); - break; - } - } + for (final ItemStack is : upgrades.getSupported().keySet()) { + if (Platform.isSameItem(this.stack, is)) { + max = upgrades.getSupported().get(is); + break; + } + } - return max; - } + return max; + } } diff --git a/src/main/java/appeng/parts/automation/UpgradeInventory.java b/src/main/java/appeng/parts/automation/UpgradeInventory.java index 5555a9957ac..b05dd979081 100644 --- a/src/main/java/appeng/parts/automation/UpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/UpgradeInventory.java @@ -18,7 +18,6 @@ package appeng.parts.automation; - import appeng.api.config.Upgrades; import appeng.api.implementations.items.IUpgradeModule; import appeng.tile.inventory.AppEngInternalInventory; @@ -30,165 +29,152 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; - -public abstract class UpgradeInventory extends AppEngInternalInventory implements IAEAppEngInventory -{ - private final IAEAppEngInventory parent; - - private boolean cached = false; - private int fuzzyUpgrades = 0; - private int speedUpgrades = 0; - private int redstoneUpgrades = 0; - private int capacityUpgrades = 0; - private int inverterUpgrades = 0; - private int craftingUpgrades = 0; - private int oreFilterUpgrades = 0; - private int patternCapacityUpgrades = 0; - - public UpgradeInventory( final IAEAppEngInventory parent, final int s ) - { - super( null, s ); - this.setTileEntity( this ); - this.parent = parent; - } - - @Override - protected boolean eventsEnabled() - { - return true; - } - - @Override - public int getInventoryStackLimit() - { - return 1; - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - if( itemstack == null ) - { - return false; - } - final Item it = itemstack.getItem(); - if( it instanceof IUpgradeModule ) - { - final Upgrades u = ( (IUpgradeModule) it ).getType( itemstack ); - if( u != null ) - { - return this.getInstalledUpgrades( u ) < this.getMaxInstalled( u ); - } - } - return false; - } - - public int getInstalledUpgrades( final Upgrades u ) - { - if( !this.cached ) - { - this.updateUpgradeInfo(); - } - - switch( u ) - { - case PATTERN_CAPACITY: - return this.patternCapacityUpgrades; - case CAPACITY: - return this.capacityUpgrades; - case FUZZY: - return this.fuzzyUpgrades; - case REDSTONE: - return this.redstoneUpgrades; - case SPEED: - return this.speedUpgrades; - case INVERTER: - return this.inverterUpgrades; - case CRAFTING: - return this.craftingUpgrades; - case ORE_FILTER: - return this.oreFilterUpgrades; - default: - return 0; - } - } - - public abstract int getMaxInstalled( Upgrades upgrades ); - - private void updateUpgradeInfo() - { - this.cached = true; - this.patternCapacityUpgrades = this.inverterUpgrades = this.capacityUpgrades = this.redstoneUpgrades = this.speedUpgrades = this.fuzzyUpgrades = this.craftingUpgrades = this.oreFilterUpgrades = 0; - - for( final ItemStack is : this ) - { - if( is == null || is.getItem() == null || !( is.getItem() instanceof IUpgradeModule ) ) - { - continue; - } - - final Upgrades myUpgrade = ( (IUpgradeModule) is.getItem() ).getType( is ); - switch( myUpgrade ) - { - case PATTERN_CAPACITY: - this.patternCapacityUpgrades++; - break; - case CAPACITY: - this.capacityUpgrades++; - break; - case FUZZY: - this.fuzzyUpgrades++; - break; - case REDSTONE: - this.redstoneUpgrades++; - break; - case SPEED: - this.speedUpgrades++; - break; - case INVERTER: - this.inverterUpgrades++; - break; - case CRAFTING: - this.craftingUpgrades++; - break; - case ORE_FILTER: - this.oreFilterUpgrades++; - break; - default: - break; - } - } - - this.capacityUpgrades = Math.min( this.capacityUpgrades, this.getMaxInstalled( Upgrades.CAPACITY ) ); - this.fuzzyUpgrades = Math.min( this.fuzzyUpgrades, this.getMaxInstalled( Upgrades.FUZZY ) ); - this.redstoneUpgrades = Math.min( this.redstoneUpgrades, this.getMaxInstalled( Upgrades.REDSTONE ) ); - this.speedUpgrades = Math.min( this.speedUpgrades, this.getMaxInstalled( Upgrades.SPEED ) ); - this.inverterUpgrades = Math.min( this.inverterUpgrades, this.getMaxInstalled( Upgrades.INVERTER ) ); - this.craftingUpgrades = Math.min( this.craftingUpgrades, this.getMaxInstalled( Upgrades.CRAFTING ) ); - this.patternCapacityUpgrades = Math.min( this.patternCapacityUpgrades, this.getMaxInstalled( Upgrades.PATTERN_CAPACITY ) ); - this.oreFilterUpgrades = Math.min( this.oreFilterUpgrades, this.getMaxInstalled( Upgrades.ORE_FILTER ) ); - } - - @Override - public void readFromNBT( final NBTTagCompound target ) - { - super.readFromNBT( target ); - this.updateUpgradeInfo(); - } - - @Override - public void saveChanges() - { - this.parent.saveChanges(); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - this.cached = false; - if( this.parent != null && Platform.isServer() ) - { - this.parent.onChangeInventory( inv, slot, mc, removedStack, newStack ); - } - } +public abstract class UpgradeInventory extends AppEngInternalInventory implements IAEAppEngInventory { + private final IAEAppEngInventory parent; + + private boolean cached = false; + private int fuzzyUpgrades = 0; + private int speedUpgrades = 0; + private int redstoneUpgrades = 0; + private int capacityUpgrades = 0; + private int inverterUpgrades = 0; + private int craftingUpgrades = 0; + private int oreFilterUpgrades = 0; + private int patternCapacityUpgrades = 0; + + public UpgradeInventory(final IAEAppEngInventory parent, final int s) { + super(null, s); + this.setTileEntity(this); + this.parent = parent; + } + + @Override + protected boolean eventsEnabled() { + return true; + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + if (itemstack == null) { + return false; + } + final Item it = itemstack.getItem(); + if (it instanceof IUpgradeModule) { + final Upgrades u = ((IUpgradeModule) it).getType(itemstack); + if (u != null) { + return this.getInstalledUpgrades(u) < this.getMaxInstalled(u); + } + } + return false; + } + + public int getInstalledUpgrades(final Upgrades u) { + if (!this.cached) { + this.updateUpgradeInfo(); + } + + switch (u) { + case PATTERN_CAPACITY: + return this.patternCapacityUpgrades; + case CAPACITY: + return this.capacityUpgrades; + case FUZZY: + return this.fuzzyUpgrades; + case REDSTONE: + return this.redstoneUpgrades; + case SPEED: + return this.speedUpgrades; + case INVERTER: + return this.inverterUpgrades; + case CRAFTING: + return this.craftingUpgrades; + case ORE_FILTER: + return this.oreFilterUpgrades; + default: + return 0; + } + } + + public abstract int getMaxInstalled(Upgrades upgrades); + + private void updateUpgradeInfo() { + this.cached = true; + this.patternCapacityUpgrades = this.inverterUpgrades = this.capacityUpgrades = this.redstoneUpgrades = + this.speedUpgrades = this.fuzzyUpgrades = this.craftingUpgrades = this.oreFilterUpgrades = 0; + + for (final ItemStack is : this) { + if (is == null || is.getItem() == null || !(is.getItem() instanceof IUpgradeModule)) { + continue; + } + + final Upgrades myUpgrade = ((IUpgradeModule) is.getItem()).getType(is); + switch (myUpgrade) { + case PATTERN_CAPACITY: + this.patternCapacityUpgrades++; + break; + case CAPACITY: + this.capacityUpgrades++; + break; + case FUZZY: + this.fuzzyUpgrades++; + break; + case REDSTONE: + this.redstoneUpgrades++; + break; + case SPEED: + this.speedUpgrades++; + break; + case INVERTER: + this.inverterUpgrades++; + break; + case CRAFTING: + this.craftingUpgrades++; + break; + case ORE_FILTER: + this.oreFilterUpgrades++; + break; + default: + break; + } + } + + this.capacityUpgrades = Math.min(this.capacityUpgrades, this.getMaxInstalled(Upgrades.CAPACITY)); + this.fuzzyUpgrades = Math.min(this.fuzzyUpgrades, this.getMaxInstalled(Upgrades.FUZZY)); + this.redstoneUpgrades = Math.min(this.redstoneUpgrades, this.getMaxInstalled(Upgrades.REDSTONE)); + this.speedUpgrades = Math.min(this.speedUpgrades, this.getMaxInstalled(Upgrades.SPEED)); + this.inverterUpgrades = Math.min(this.inverterUpgrades, this.getMaxInstalled(Upgrades.INVERTER)); + this.craftingUpgrades = Math.min(this.craftingUpgrades, this.getMaxInstalled(Upgrades.CRAFTING)); + this.patternCapacityUpgrades = + Math.min(this.patternCapacityUpgrades, this.getMaxInstalled(Upgrades.PATTERN_CAPACITY)); + this.oreFilterUpgrades = Math.min(this.oreFilterUpgrades, this.getMaxInstalled(Upgrades.ORE_FILTER)); + } + + @Override + public void readFromNBT(final NBTTagCompound target) { + super.readFromNBT(target); + this.updateUpgradeInfo(); + } + + @Override + public void saveChanges() { + this.parent.saveChanges(); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) { + this.cached = false; + if (this.parent != null && Platform.isServer()) { + this.parent.onChangeInventory(inv, slot, mc, removedStack, newStack); + } + } } diff --git a/src/main/java/appeng/parts/layers/InvLayerData.java b/src/main/java/appeng/parts/layers/InvLayerData.java index 1ffa285ef07..86d9a3b19ad 100644 --- a/src/main/java/appeng/parts/layers/InvLayerData.java +++ b/src/main/java/appeng/parts/layers/InvLayerData.java @@ -18,128 +18,103 @@ package appeng.parts.layers; - +import java.util.List; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; -import java.util.List; - - -public class InvLayerData -{ - - // a simple empty array for empty stuff.. - private static final int[] NULL_SIDES = {}; - - // cache of inventory state. - private final int[][] sides; - private final List inventories; - private final List slots; - - public InvLayerData( final int[][] a, final List b, final List c ) - { - this.sides = a; - this.inventories = b; - this.slots = c; - } - - ItemStack decreaseStackSize( final int slot, final int amount ) - { - if( this.isSlotValid( slot ) ) - { - return this.slots.get( slot ).decreaseStackSize( amount ); - } - - return null; - } - - /** - * check if a slot index is valid, prevent crashes from bad code :) - * - * @param slot slot index - * @return true, if the slot exists. - */ - private boolean isSlotValid( final int slot ) - { - return this.slots != null && slot >= 0 && slot < this.slots.size(); - } - - int getSizeInventory() - { - if( this.slots == null ) - { - return 0; - } - - return this.slots.size(); - } - - ItemStack getStackInSlot( final int slot ) - { - if( this.isSlotValid( slot ) ) - { - return this.slots.get( slot ).getStackInSlot(); - } - - return null; - } - - boolean isItemValidForSlot( final int slot, final ItemStack itemstack ) - { - if( this.isSlotValid( slot ) ) - { - return this.slots.get( slot ).isItemValidForSlot( itemstack ); - } - - return false; - } - - void setInventorySlotContents( final int slot, final ItemStack itemstack ) - { - if( this.isSlotValid( slot ) ) - { - this.slots.get( slot ).setInventorySlotContents( itemstack ); - } - } - - boolean canExtractItem( final int slot, final ItemStack itemstack, final int side ) - { - if( this.isSlotValid( slot ) ) - { - return this.slots.get( slot ).canExtractItem( itemstack, side ); - } - - return false; - } - - boolean canInsertItem( final int slot, final ItemStack itemstack, final int side ) - { - if( this.isSlotValid( slot ) ) - { - return this.slots.get( slot ).canInsertItem( itemstack, side ); - } - - return false; - } - - void markDirty() - { - if( this.inventories != null ) - { - for( final IInventory inv : this.inventories ) - { - inv.markDirty(); - } - } - } - - int[] getAccessibleSlotsFromSide( final int side ) - { - if( this.sides == null || side < 0 || side > 5 ) - { - return NULL_SIDES; - } - return this.sides[side]; - } +public class InvLayerData { + + // a simple empty array for empty stuff.. + private static final int[] NULL_SIDES = {}; + + // cache of inventory state. + private final int[][] sides; + private final List inventories; + private final List slots; + + public InvLayerData(final int[][] a, final List b, final List c) { + this.sides = a; + this.inventories = b; + this.slots = c; + } + + ItemStack decreaseStackSize(final int slot, final int amount) { + if (this.isSlotValid(slot)) { + return this.slots.get(slot).decreaseStackSize(amount); + } + + return null; + } + + /** + * check if a slot index is valid, prevent crashes from bad code :) + * + * @param slot slot index + * @return true, if the slot exists. + */ + private boolean isSlotValid(final int slot) { + return this.slots != null && slot >= 0 && slot < this.slots.size(); + } + + int getSizeInventory() { + if (this.slots == null) { + return 0; + } + + return this.slots.size(); + } + + ItemStack getStackInSlot(final int slot) { + if (this.isSlotValid(slot)) { + return this.slots.get(slot).getStackInSlot(); + } + + return null; + } + + boolean isItemValidForSlot(final int slot, final ItemStack itemstack) { + if (this.isSlotValid(slot)) { + return this.slots.get(slot).isItemValidForSlot(itemstack); + } + + return false; + } + + void setInventorySlotContents(final int slot, final ItemStack itemstack) { + if (this.isSlotValid(slot)) { + this.slots.get(slot).setInventorySlotContents(itemstack); + } + } + + boolean canExtractItem(final int slot, final ItemStack itemstack, final int side) { + if (this.isSlotValid(slot)) { + return this.slots.get(slot).canExtractItem(itemstack, side); + } + + return false; + } + + boolean canInsertItem(final int slot, final ItemStack itemstack, final int side) { + if (this.isSlotValid(slot)) { + return this.slots.get(slot).canInsertItem(itemstack, side); + } + + return false; + } + + void markDirty() { + if (this.inventories != null) { + for (final IInventory inv : this.inventories) { + inv.markDirty(); + } + } + } + + int[] getAccessibleSlotsFromSide(final int side) { + if (this.sides == null || side < 0 || side > 5) { + return NULL_SIDES; + } + return this.sides[side]; + } } diff --git a/src/main/java/appeng/parts/layers/InvSot.java b/src/main/java/appeng/parts/layers/InvSot.java index 7cc84985325..3099c644b6d 100644 --- a/src/main/java/appeng/parts/layers/InvSot.java +++ b/src/main/java/appeng/parts/layers/InvSot.java @@ -18,50 +18,40 @@ package appeng.parts.layers; - import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; +public class InvSot { -public class InvSot -{ - - private final ISidedInventory partInv; - private final int index; + private final ISidedInventory partInv; + private final int index; - public InvSot( final ISidedInventory part, final int slot ) - { - this.partInv = part; - this.index = slot; - } + public InvSot(final ISidedInventory part, final int slot) { + this.partInv = part; + this.index = slot; + } - ItemStack decreaseStackSize( final int j ) - { - return this.partInv.decrStackSize( this.index, j ); - } + ItemStack decreaseStackSize(final int j) { + return this.partInv.decrStackSize(this.index, j); + } - ItemStack getStackInSlot() - { - return this.partInv.getStackInSlot( this.index ); - } + ItemStack getStackInSlot() { + return this.partInv.getStackInSlot(this.index); + } - boolean isItemValidForSlot( final ItemStack itemstack ) - { - return this.partInv.isItemValidForSlot( this.index, itemstack ); - } + boolean isItemValidForSlot(final ItemStack itemstack) { + return this.partInv.isItemValidForSlot(this.index, itemstack); + } - void setInventorySlotContents( final ItemStack itemstack ) - { - this.partInv.setInventorySlotContents( this.index, itemstack ); - } + void setInventorySlotContents(final ItemStack itemstack) { + this.partInv.setInventorySlotContents(this.index, itemstack); + } - boolean canExtractItem( final ItemStack itemstack, final int side ) - { - return this.partInv.canExtractItem( this.index, itemstack, side ); - } + boolean canExtractItem(final ItemStack itemstack, final int side) { + return this.partInv.canExtractItem(this.index, itemstack, side); + } - boolean canInsertItem( final ItemStack itemstack, final int side ) - { - return this.partInv.canInsertItem( this.index, itemstack, side ); - } + boolean canInsertItem(final ItemStack itemstack, final int side) { + return this.partInv.canInsertItem(this.index, itemstack, side); + } } diff --git a/src/main/java/appeng/parts/layers/LayerIEnergyConnected.java b/src/main/java/appeng/parts/layers/LayerIEnergyConnected.java index a789312311a..10317dbb589 100644 --- a/src/main/java/appeng/parts/layers/LayerIEnergyConnected.java +++ b/src/main/java/appeng/parts/layers/LayerIEnergyConnected.java @@ -19,10 +19,9 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.IFluidHandler; -@Integration.Interface( iname = IntegrationType.GT, iface = "gregtech.api.interfaces.tileentity.IEnergyConnected" ) -public class LayerIEnergyConnected extends LayerBase implements IEnergyConnected { - public LayerIEnergyConnected() { - } +@Integration.Interface(iname = IntegrationType.GT, iface = "gregtech.api.interfaces.tileentity.IEnergyConnected") +public class LayerIEnergyConnected extends LayerBase implements IEnergyConnected { + public LayerIEnergyConnected() {} public long injectEnergyUnits(byte side, long voltage, long amperage) { IPart part = this.getPart(ForgeDirection.getOrientation(side)); @@ -34,10 +33,12 @@ public long injectEnergyUnits(byte side, long voltage, long amperage) { TileEntity source = this.getTileEntityAtSide(side); if (source != null && ((IEnergySink) part).acceptsEnergyFrom(source, dir)) { long rUsedAmperes; - for (rUsedAmperes = 0L; amperage > rUsedAmperes && ((IEnergySink) part).getDemandedEnergy() > 0.0D - && ((IEnergySink) part).injectEnergy(dir, (double) voltage, (double) voltage) < (double) voltage; - ++rUsedAmperes) { - } + for (rUsedAmperes = 0L; + amperage > rUsedAmperes + && ((IEnergySink) part).getDemandedEnergy() > 0.0D + && ((IEnergySink) part).injectEnergy(dir, (double) voltage, (double) voltage) + < (double) voltage; + ++rUsedAmperes) {} return rUsedAmperes; } @@ -160,7 +161,10 @@ public final Block getBlockAtSide(byte aSide) { } public final Block getBlockAtSideAndDistance(byte aSide, int aDistance) { - return this.getBlock(this.getOffsetX(aSide, aDistance), this.getOffsetY(aSide, aDistance), this.getOffsetZ(aSide, aDistance)); + return this.getBlock( + this.getOffsetX(aSide, aDistance), + this.getOffsetY(aSide, aDistance), + this.getOffsetZ(aSide, aDistance)); } public final byte getMetaIDOffset(int aX, int aY, int aZ) { @@ -172,7 +176,10 @@ public final byte getMetaIDAtSide(byte aSide) { } public final byte getMetaIDAtSideAndDistance(byte aSide, int aDistance) { - return this.getMetaID(this.getOffsetX(aSide, aDistance), this.getOffsetY(aSide, aDistance), this.getOffsetZ(aSide, aDistance)); + return this.getMetaID( + this.getOffsetX(aSide, aDistance), + this.getOffsetY(aSide, aDistance), + this.getOffsetZ(aSide, aDistance)); } public final byte getLightLevelOffset(int aX, int aY, int aZ) { @@ -184,7 +191,10 @@ public final byte getLightLevelAtSide(byte aSide) { } public final byte getLightLevelAtSideAndDistance(byte aSide, int aDistance) { - return this.getLightLevel(this.getOffsetX(aSide, aDistance), this.getOffsetY(aSide, aDistance), this.getOffsetZ(aSide, aDistance)); + return this.getLightLevel( + this.getOffsetX(aSide, aDistance), + this.getOffsetY(aSide, aDistance), + this.getOffsetZ(aSide, aDistance)); } public final boolean getOpacityOffset(int aX, int aY, int aZ) { @@ -196,7 +206,10 @@ public final boolean getOpacityAtSide(byte aSide) { } public final boolean getOpacityAtSideAndDistance(byte aSide, int aDistance) { - return this.getOpacity(this.getOffsetX(aSide, aDistance), this.getOffsetY(aSide, aDistance), this.getOffsetZ(aSide, aDistance)); + return this.getOpacity( + this.getOffsetX(aSide, aDistance), + this.getOffsetY(aSide, aDistance), + this.getOffsetZ(aSide, aDistance)); } public final boolean getSkyOffset(int aX, int aY, int aZ) { @@ -208,7 +221,10 @@ public final boolean getSkyAtSide(byte aSide) { } public final boolean getSkyAtSideAndDistance(byte aSide, int aDistance) { - return this.getSky(this.getOffsetX(aSide, aDistance), this.getOffsetY(aSide, aDistance), this.getOffsetZ(aSide, aDistance)); + return this.getSky( + this.getOffsetX(aSide, aDistance), + this.getOffsetY(aSide, aDistance), + this.getOffsetZ(aSide, aDistance)); } public final boolean getAirOffset(int aX, int aY, int aZ) { @@ -220,7 +236,10 @@ public final boolean getAirAtSide(byte aSide) { } public final boolean getAirAtSideAndDistance(byte aSide, int aDistance) { - return this.getAir(this.getOffsetX(aSide, aDistance), this.getOffsetY(aSide, aDistance), this.getOffsetZ(aSide, aDistance)); + return this.getAir( + this.getOffsetX(aSide, aDistance), + this.getOffsetY(aSide, aDistance), + this.getOffsetZ(aSide, aDistance)); } public final TileEntity getTileEntityOffset(int aX, int aY, int aZ) { @@ -228,7 +247,12 @@ public final TileEntity getTileEntityOffset(int aX, int aY, int aZ) { } public final TileEntity getTileEntityAtSideAndDistance(byte aSide, int aDistance) { - return aDistance == 1 ? this.getTileEntityAtSide(aSide) : this.getTileEntity(this.getOffsetX(aSide, aDistance), this.getOffsetY(aSide, aDistance), this.getOffsetZ(aSide, aDistance)); + return aDistance == 1 + ? this.getTileEntityAtSide(aSide) + : this.getTileEntity( + this.getOffsetX(aSide, aDistance), + this.getOffsetY(aSide, aDistance), + this.getOffsetZ(aSide, aDistance)); } public final IInventory getIInventory(int aX, int aY, int aZ) { @@ -296,56 +320,66 @@ private boolean crossedChunkBorder(int aX, int aZ) { } public final Block getBlock(int aX, int aY, int aZ) { - return this.crossedChunkBorder(aX, aZ) && !this.worldObj.blockExists(aX, aY, aZ) ? Blocks.air : this.worldObj.getBlock(aX, aY, aZ); + return this.crossedChunkBorder(aX, aZ) && !this.worldObj.blockExists(aX, aY, aZ) + ? Blocks.air + : this.worldObj.getBlock(aX, aY, aZ); } public final byte getMetaID(int aX, int aY, int aZ) { - return this.crossedChunkBorder(aX, aZ) && !this.worldObj.blockExists(aX, aY, aZ) ? 0 : (byte) this.worldObj.getBlockMetadata(aX, aY, aZ); + return this.crossedChunkBorder(aX, aZ) && !this.worldObj.blockExists(aX, aY, aZ) + ? 0 + : (byte) this.worldObj.getBlockMetadata(aX, aY, aZ); } public final byte getLightLevel(int aX, int aY, int aZ) { - return this.crossedChunkBorder(aX, aZ) && !this.worldObj.blockExists(aX, aY, aZ) ? 0 : (byte) ((int) (this.worldObj.getLightBrightness(aX, aY, aZ) * 15.0F)); + return this.crossedChunkBorder(aX, aZ) && !this.worldObj.blockExists(aX, aY, aZ) + ? 0 + : (byte) ((int) (this.worldObj.getLightBrightness(aX, aY, aZ) * 15.0F)); } public final boolean getSky(int aX, int aY, int aZ) { - return this.crossedChunkBorder(aX, aZ) && !this.worldObj.blockExists(aX, aY, aZ) || this.worldObj.canBlockSeeTheSky(aX, aY, aZ); + return this.crossedChunkBorder(aX, aZ) && !this.worldObj.blockExists(aX, aY, aZ) + || this.worldObj.canBlockSeeTheSky(aX, aY, aZ); } public final boolean getOpacity(int aX, int aY, int aZ) { - return (!this.crossedChunkBorder(aX, aZ) || this.worldObj.blockExists(aX, aY, aZ)) && GT_Utility.isOpaqueBlock(this.worldObj, aX, aY, aZ); + return (!this.crossedChunkBorder(aX, aZ) || this.worldObj.blockExists(aX, aY, aZ)) + && GT_Utility.isOpaqueBlock(this.worldObj, aX, aY, aZ); } public final boolean getAir(int aX, int aY, int aZ) { - return this.crossedChunkBorder(aX, aZ) && !this.worldObj.blockExists(aX, aY, aZ) || GT_Utility.isBlockAir(this.worldObj, aX, aY, aZ); + return this.crossedChunkBorder(aX, aZ) && !this.worldObj.blockExists(aX, aY, aZ) + || GT_Utility.isBlockAir(this.worldObj, aX, aY, aZ); } public final TileEntity getTileEntity(int aX, int aY, int aZ) { - return this.crossedChunkBorder(aX, aZ) && !this.worldObj.blockExists(aX, aY, aZ) ? null : this.worldObj.getTileEntity(aX, aY, aZ); + return this.crossedChunkBorder(aX, aZ) && !this.worldObj.blockExists(aX, aY, aZ) + ? null + : this.worldObj.getTileEntity(aX, aY, aZ); } public final TileEntity getTileEntityAtSide(byte aSide) { int tX = this.getOffsetX(aSide, 1); int tY = this.getOffsetY(aSide, 1); int tZ = this.getOffsetZ(aSide, 1); - return this.crossedChunkBorder(tX, tZ) && !this.worldObj.blockExists(tX, tY, tZ) ? null : this.worldObj.getTileEntity(tX, tY, tZ); + return this.crossedChunkBorder(tX, tZ) && !this.worldObj.blockExists(tX, tY, tZ) + ? null + : this.worldObj.getTileEntity(tX, tY, tZ); } public boolean isDead() { return this.isInvalidTileEntity(); } - public void sendBlockEvent(byte b, byte b1) { - } + public void sendBlockEvent(byte b, byte b1) {} public long getTimer() { return 0L; } - public void setLightValue(byte b) { - } + public void setLightValue(byte b) {} public boolean isInvalidTileEntity() { return this.isInvalid(); } - } diff --git a/src/main/java/appeng/parts/layers/LayerIEnergyHandler.java b/src/main/java/appeng/parts/layers/LayerIEnergyHandler.java index 7f512027d14..ffc1080b754 100644 --- a/src/main/java/appeng/parts/layers/LayerIEnergyHandler.java +++ b/src/main/java/appeng/parts/layers/LayerIEnergyHandler.java @@ -18,7 +18,6 @@ package appeng.parts.layers; - import appeng.api.parts.IPart; import appeng.api.parts.LayerBase; import cofh.api.energy.IEnergyConnection; @@ -27,67 +26,55 @@ import cofh.api.energy.IEnergyReceiver; import net.minecraftforge.common.util.ForgeDirection; +public class LayerIEnergyHandler extends LayerBase implements IEnergyHandler { -public class LayerIEnergyHandler extends LayerBase implements IEnergyHandler -{ - - @Override - public int receiveEnergy( final ForgeDirection from, final int maxReceive, final boolean simulate ) - { - final IPart part = this.getPart( from ); - if( part instanceof IEnergyReceiver ) - { - return ( (IEnergyReceiver) part ).receiveEnergy( from, maxReceive, simulate ); - } + @Override + public int receiveEnergy(final ForgeDirection from, final int maxReceive, final boolean simulate) { + final IPart part = this.getPart(from); + if (part instanceof IEnergyReceiver) { + return ((IEnergyReceiver) part).receiveEnergy(from, maxReceive, simulate); + } - return 0; - } + return 0; + } - @Override - public int extractEnergy( final ForgeDirection from, final int maxExtract, final boolean simulate ) - { - final IPart part = this.getPart( from ); - if( part instanceof IEnergyProvider ) - { - return ( (IEnergyProvider) part ).extractEnergy( from, maxExtract, simulate ); - } + @Override + public int extractEnergy(final ForgeDirection from, final int maxExtract, final boolean simulate) { + final IPart part = this.getPart(from); + if (part instanceof IEnergyProvider) { + return ((IEnergyProvider) part).extractEnergy(from, maxExtract, simulate); + } - return 0; - } + return 0; + } - @Override - public int getEnergyStored( final ForgeDirection from ) - { - final IPart part = this.getPart( from ); - if( part instanceof IEnergyProvider ) - { - return ( (IEnergyProvider) part ).getEnergyStored( from ); - } + @Override + public int getEnergyStored(final ForgeDirection from) { + final IPart part = this.getPart(from); + if (part instanceof IEnergyProvider) { + return ((IEnergyProvider) part).getEnergyStored(from); + } - return 0; - } + return 0; + } - @Override - public int getMaxEnergyStored( final ForgeDirection from ) - { - final IPart part = this.getPart( from ); - if( part instanceof IEnergyProvider ) - { - return ( (IEnergyProvider) part ).getMaxEnergyStored( from ); - } + @Override + public int getMaxEnergyStored(final ForgeDirection from) { + final IPart part = this.getPart(from); + if (part instanceof IEnergyProvider) { + return ((IEnergyProvider) part).getMaxEnergyStored(from); + } - return 0; - } + return 0; + } - @Override - public boolean canConnectEnergy( final ForgeDirection from ) - { - final IPart part = this.getPart( from ); - if( part instanceof IEnergyConnection ) - { - return ( (IEnergyConnection) part ).canConnectEnergy( from ); - } + @Override + public boolean canConnectEnergy(final ForgeDirection from) { + final IPart part = this.getPart(from); + if (part instanceof IEnergyConnection) { + return ((IEnergyConnection) part).canConnectEnergy(from); + } - return false; - } + return false; + } } diff --git a/src/main/java/appeng/parts/layers/LayerIEnergySink.java b/src/main/java/appeng/parts/layers/LayerIEnergySink.java index 5e9bf45e35d..4ca4aa529d4 100644 --- a/src/main/java/appeng/parts/layers/LayerIEnergySink.java +++ b/src/main/java/appeng/parts/layers/LayerIEnergySink.java @@ -18,7 +18,6 @@ package appeng.parts.layers; - import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import appeng.api.parts.LayerBase; @@ -32,170 +31,138 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.ForgeDirection; - -public class LayerIEnergySink extends LayerBase implements IEnergySink -{ - - private TileEntity getEnergySinkTile() - { - final IPartHost host = (IPartHost) this; - return host.getTile(); - } - - private World getEnergySinkWorld() - { - if( this.getEnergySinkTile() == null ) - { - return null; - } - - return this.getEnergySinkTile().getWorldObj(); - } - - private boolean isTileValid() - { - final TileEntity te = this.getEnergySinkTile(); - - if( te == null ) - { - return false; - } - - return !te.isInvalid() && te.getWorldObj().blockExists( te.xCoord, te.yCoord, te.zCoord ); - } - - private void addToENet() - { - if( this.getEnergySinkWorld() == null ) - { - return; - } - - // re-add - this.removeFromENet(); - - if( !this.isInIC2() && Platform.isServer() && this.isTileValid() ) - { - this.getLayerFlags().add( LayerFlags.IC2_ENET ); - MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileLoadEvent( (IEnergyTile) this.getEnergySinkTile() ) ); - } - } - - private void removeFromENet() - { - if( this.getEnergySinkWorld() == null ) - { - return; - } - - if( this.isInIC2() && Platform.isServer() ) - { - this.getLayerFlags().remove( LayerFlags.IC2_ENET ); - MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileUnloadEvent( (IEnergyTile) this.getEnergySinkTile() ) ); - } - } - - private boolean interestedInIC2() - { - if( !( (IPartHost) this ).isInWorld() ) - { - return false; - } - - int interested = 0; - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IEnergyTile ) - { - interested++; - } - } - return interested == 1;// if more then one tile is interested we need to abandon... - } - - @Override - public void partChanged() - { - super.partChanged(); - - if( this.interestedInIC2() ) - { - this.addToENet(); - } - else - { - this.removeFromENet(); - } - } - - @Override - public boolean acceptsEnergyFrom( final TileEntity emitter, final ForgeDirection direction ) - { - if( !this.isInIC2() ) - { - return false; - } - - final IPart part = this.getPart( direction ); - if( part instanceof IEnergySink ) - { - return ( (IEnergyAcceptor) part ).acceptsEnergyFrom( emitter, direction ); - } - return false; - } - - private boolean isInIC2() - { - return this.getLayerFlags().contains( LayerFlags.IC2_ENET ); - } - - @Override - public double getDemandedEnergy() - { - if( !this.isInIC2() ) - { - return 0; - } - - // this is a flawed implementation, that requires a change to the IC2 API. - - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IEnergySink ) - { - // use lower number cause ic2 deletes power it sends that isn't received. - return ( (IEnergySink) part ).getDemandedEnergy(); - } - } - - return 0; - } - - @Override - public int getSinkTier() - { - return Integer.MAX_VALUE; // no real options here... - } - - @Override - public double injectEnergy( final ForgeDirection directionFrom, final double amount, final double voltage ) - { - if( !this.isInIC2() ) - { - return amount; - } - - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IEnergySink ) - { - return ( (IEnergySink) part ).injectEnergy( directionFrom, amount, voltage ); - } - } - - return amount; - } +public class LayerIEnergySink extends LayerBase implements IEnergySink { + + private TileEntity getEnergySinkTile() { + final IPartHost host = (IPartHost) this; + return host.getTile(); + } + + private World getEnergySinkWorld() { + if (this.getEnergySinkTile() == null) { + return null; + } + + return this.getEnergySinkTile().getWorldObj(); + } + + private boolean isTileValid() { + final TileEntity te = this.getEnergySinkTile(); + + if (te == null) { + return false; + } + + return !te.isInvalid() && te.getWorldObj().blockExists(te.xCoord, te.yCoord, te.zCoord); + } + + private void addToENet() { + if (this.getEnergySinkWorld() == null) { + return; + } + + // re-add + this.removeFromENet(); + + if (!this.isInIC2() && Platform.isServer() && this.isTileValid()) { + this.getLayerFlags().add(LayerFlags.IC2_ENET); + MinecraftForge.EVENT_BUS.post( + new ic2.api.energy.event.EnergyTileLoadEvent((IEnergyTile) this.getEnergySinkTile())); + } + } + + private void removeFromENet() { + if (this.getEnergySinkWorld() == null) { + return; + } + + if (this.isInIC2() && Platform.isServer()) { + this.getLayerFlags().remove(LayerFlags.IC2_ENET); + MinecraftForge.EVENT_BUS.post( + new ic2.api.energy.event.EnergyTileUnloadEvent((IEnergyTile) this.getEnergySinkTile())); + } + } + + private boolean interestedInIC2() { + if (!((IPartHost) this).isInWorld()) { + return false; + } + + int interested = 0; + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getPart(dir); + if (part instanceof IEnergyTile) { + interested++; + } + } + return interested == 1; // if more then one tile is interested we need to abandon... + } + + @Override + public void partChanged() { + super.partChanged(); + + if (this.interestedInIC2()) { + this.addToENet(); + } else { + this.removeFromENet(); + } + } + + @Override + public boolean acceptsEnergyFrom(final TileEntity emitter, final ForgeDirection direction) { + if (!this.isInIC2()) { + return false; + } + + final IPart part = this.getPart(direction); + if (part instanceof IEnergySink) { + return ((IEnergyAcceptor) part).acceptsEnergyFrom(emitter, direction); + } + return false; + } + + private boolean isInIC2() { + return this.getLayerFlags().contains(LayerFlags.IC2_ENET); + } + + @Override + public double getDemandedEnergy() { + if (!this.isInIC2()) { + return 0; + } + + // this is a flawed implementation, that requires a change to the IC2 API. + + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getPart(dir); + if (part instanceof IEnergySink) { + // use lower number cause ic2 deletes power it sends that isn't received. + return ((IEnergySink) part).getDemandedEnergy(); + } + } + + return 0; + } + + @Override + public int getSinkTier() { + return Integer.MAX_VALUE; // no real options here... + } + + @Override + public double injectEnergy(final ForgeDirection directionFrom, final double amount, final double voltage) { + if (!this.isInIC2()) { + return amount; + } + + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getPart(dir); + if (part instanceof IEnergySink) { + return ((IEnergySink) part).injectEnergy(directionFrom, amount, voltage); + } + } + + return amount; + } } diff --git a/src/main/java/appeng/parts/layers/LayerIEnergySource.java b/src/main/java/appeng/parts/layers/LayerIEnergySource.java index face5309278..1d992896bac 100644 --- a/src/main/java/appeng/parts/layers/LayerIEnergySource.java +++ b/src/main/java/appeng/parts/layers/LayerIEnergySource.java @@ -18,7 +18,6 @@ package appeng.parts.layers; - import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import appeng.api.parts.LayerBase; @@ -33,174 +32,141 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.ForgeDirection; - -public class LayerIEnergySource extends LayerBase implements IEnergySource -{ - - private TileEntity getEnergySourceTile() - { - final IPartHost host = (IPartHost) this; - return host.getTile(); - } - - private World getEnergySourceWorld() - { - if( this.getEnergySourceTile() == null ) - { - return null; - } - return this.getEnergySourceTile().getWorldObj(); - } - - private boolean isTileValid() - { - final TileEntity te = this.getEnergySourceTile(); - if( te == null ) - { - return false; - } - return !te.isInvalid(); - } - - private void addToENet() - { - if( this.getEnergySourceWorld() == null ) - { - return; - } - - // re-add - this.removeFromENet(); - - if( !this.isInIC2() && Platform.isServer() && this.isTileValid() ) - { - this.getLayerFlags().add( LayerFlags.IC2_ENET ); - MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileLoadEvent( (IEnergyTile) this.getEnergySourceTile() ) ); - } - } - - private void removeFromENet() - { - if( this.getEnergySourceWorld() == null ) - { - return; - } - - if( this.isInIC2() && Platform.isServer() ) - { - this.getLayerFlags().remove( LayerFlags.IC2_ENET ); - MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileUnloadEvent( (IEnergyTile) this.getEnergySourceTile() ) ); - } - } - - private boolean interestedInIC2() - { - if( !( (IPartHost) this ).isInWorld() ) - { - return false; - } - - int interested = 0; - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IEnergyTile ) - { - interested++; - } - } - return interested == 1;// if more then one tile is interested we need to abandon... - } - - @Override - public void partChanged() - { - super.partChanged(); - - if( this.interestedInIC2() ) - { - this.addToENet(); - } - else - { - this.removeFromENet(); - } - } - - @Override - public boolean emitsEnergyTo( final TileEntity receiver, final ForgeDirection direction ) - { - if( !this.isInIC2() ) - { - return false; - } - - final IPart part = this.getPart( direction ); - if( part instanceof IEnergySink ) - { - return ( (IEnergyEmitter) part ).emitsEnergyTo( receiver, direction ); - } - return false; - } - - private boolean isInIC2() - { - return this.getLayerFlags().contains( LayerFlags.IC2_ENET ); - } - - @Override - public double getOfferedEnergy() - { - if( !this.isInIC2() ) - { - return 0; - } - - // this is a flawed implementation, that requires a change to the IC2 API. - - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IEnergySource ) - { - // use lower number cause ic2 deletes power it sends that isn't received. - return ( (IEnergySource) part ).getOfferedEnergy(); - } - } - - return 0; - } - - @Override - public void drawEnergy( final double amount ) - { - // this is a flawed implementation, that requires a change to the IC2 API. - - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IEnergySource ) - { - ( (IEnergySource) part ).drawEnergy( amount ); - return; - } - } - } - - @Override - public int getSourceTier() - { - // this is a flawed implementation, that requires a change to the IC2 API. - - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IEnergySource ) - { - return ( (IEnergySource) part ).getSourceTier(); - } - } - - return 0; - } +public class LayerIEnergySource extends LayerBase implements IEnergySource { + + private TileEntity getEnergySourceTile() { + final IPartHost host = (IPartHost) this; + return host.getTile(); + } + + private World getEnergySourceWorld() { + if (this.getEnergySourceTile() == null) { + return null; + } + return this.getEnergySourceTile().getWorldObj(); + } + + private boolean isTileValid() { + final TileEntity te = this.getEnergySourceTile(); + if (te == null) { + return false; + } + return !te.isInvalid(); + } + + private void addToENet() { + if (this.getEnergySourceWorld() == null) { + return; + } + + // re-add + this.removeFromENet(); + + if (!this.isInIC2() && Platform.isServer() && this.isTileValid()) { + this.getLayerFlags().add(LayerFlags.IC2_ENET); + MinecraftForge.EVENT_BUS.post( + new ic2.api.energy.event.EnergyTileLoadEvent((IEnergyTile) this.getEnergySourceTile())); + } + } + + private void removeFromENet() { + if (this.getEnergySourceWorld() == null) { + return; + } + + if (this.isInIC2() && Platform.isServer()) { + this.getLayerFlags().remove(LayerFlags.IC2_ENET); + MinecraftForge.EVENT_BUS.post( + new ic2.api.energy.event.EnergyTileUnloadEvent((IEnergyTile) this.getEnergySourceTile())); + } + } + + private boolean interestedInIC2() { + if (!((IPartHost) this).isInWorld()) { + return false; + } + + int interested = 0; + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getPart(dir); + if (part instanceof IEnergyTile) { + interested++; + } + } + return interested == 1; // if more then one tile is interested we need to abandon... + } + + @Override + public void partChanged() { + super.partChanged(); + + if (this.interestedInIC2()) { + this.addToENet(); + } else { + this.removeFromENet(); + } + } + + @Override + public boolean emitsEnergyTo(final TileEntity receiver, final ForgeDirection direction) { + if (!this.isInIC2()) { + return false; + } + + final IPart part = this.getPart(direction); + if (part instanceof IEnergySink) { + return ((IEnergyEmitter) part).emitsEnergyTo(receiver, direction); + } + return false; + } + + private boolean isInIC2() { + return this.getLayerFlags().contains(LayerFlags.IC2_ENET); + } + + @Override + public double getOfferedEnergy() { + if (!this.isInIC2()) { + return 0; + } + + // this is a flawed implementation, that requires a change to the IC2 API. + + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getPart(dir); + if (part instanceof IEnergySource) { + // use lower number cause ic2 deletes power it sends that isn't received. + return ((IEnergySource) part).getOfferedEnergy(); + } + } + + return 0; + } + + @Override + public void drawEnergy(final double amount) { + // this is a flawed implementation, that requires a change to the IC2 API. + + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getPart(dir); + if (part instanceof IEnergySource) { + ((IEnergySource) part).drawEnergy(amount); + return; + } + } + } + + @Override + public int getSourceTier() { + // this is a flawed implementation, that requires a change to the IC2 API. + + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getPart(dir); + if (part instanceof IEnergySource) { + return ((IEnergySource) part).getSourceTier(); + } + } + + return 0; + } } diff --git a/src/main/java/appeng/parts/layers/LayerIFluidHandler.java b/src/main/java/appeng/parts/layers/LayerIFluidHandler.java index c3b53e8ae40..8c010b9c0a2 100644 --- a/src/main/java/appeng/parts/layers/LayerIFluidHandler.java +++ b/src/main/java/appeng/parts/layers/LayerIFluidHandler.java @@ -18,7 +18,6 @@ package appeng.parts.layers; - import appeng.api.parts.IPart; import appeng.api.parts.LayerBase; import net.minecraftforge.common.util.ForgeDirection; @@ -26,75 +25,61 @@ import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; +public class LayerIFluidHandler extends LayerBase implements IFluidHandler { -public class LayerIFluidHandler extends LayerBase implements IFluidHandler -{ - - private static final FluidTankInfo[] EMPTY_LIST = new FluidTankInfo[0]; + private static final FluidTankInfo[] EMPTY_LIST = new FluidTankInfo[0]; - @Override - public int fill( final ForgeDirection from, final FluidStack resource, final boolean doFill ) - { - final IPart part = this.getPart( from ); - if( part instanceof IFluidHandler ) - { - return ( (IFluidHandler) part ).fill( from, resource, doFill ); - } - return 0; - } + @Override + public int fill(final ForgeDirection from, final FluidStack resource, final boolean doFill) { + final IPart part = this.getPart(from); + if (part instanceof IFluidHandler) { + return ((IFluidHandler) part).fill(from, resource, doFill); + } + return 0; + } - @Override - public FluidStack drain( final ForgeDirection from, final FluidStack resource, final boolean doDrain ) - { - final IPart part = this.getPart( from ); - if( part instanceof IFluidHandler ) - { - return ( (IFluidHandler) part ).drain( from, resource, doDrain ); - } - return null; - } + @Override + public FluidStack drain(final ForgeDirection from, final FluidStack resource, final boolean doDrain) { + final IPart part = this.getPart(from); + if (part instanceof IFluidHandler) { + return ((IFluidHandler) part).drain(from, resource, doDrain); + } + return null; + } - @Override - public FluidStack drain( final ForgeDirection from, final int maxDrain, final boolean doDrain ) - { - final IPart part = this.getPart( from ); - if( part instanceof IFluidHandler ) - { - return ( (IFluidHandler) part ).drain( from, maxDrain, doDrain ); - } - return null; - } + @Override + public FluidStack drain(final ForgeDirection from, final int maxDrain, final boolean doDrain) { + final IPart part = this.getPart(from); + if (part instanceof IFluidHandler) { + return ((IFluidHandler) part).drain(from, maxDrain, doDrain); + } + return null; + } - @Override - public boolean canFill( final ForgeDirection from, final net.minecraftforge.fluids.Fluid fluid ) - { - final IPart part = this.getPart( from ); - if( part instanceof IFluidHandler ) - { - return ( (IFluidHandler) part ).canFill( from, fluid ); - } - return false; - } + @Override + public boolean canFill(final ForgeDirection from, final net.minecraftforge.fluids.Fluid fluid) { + final IPart part = this.getPart(from); + if (part instanceof IFluidHandler) { + return ((IFluidHandler) part).canFill(from, fluid); + } + return false; + } - @Override - public boolean canDrain( final ForgeDirection from, final net.minecraftforge.fluids.Fluid fluid ) - { - final IPart part = this.getPart( from ); - if( part instanceof IFluidHandler ) - { - return ( (IFluidHandler) part ).canDrain( from, fluid ); - } - return false; - } + @Override + public boolean canDrain(final ForgeDirection from, final net.minecraftforge.fluids.Fluid fluid) { + final IPart part = this.getPart(from); + if (part instanceof IFluidHandler) { + return ((IFluidHandler) part).canDrain(from, fluid); + } + return false; + } - @Override - public FluidTankInfo[] getTankInfo( final ForgeDirection from ) - { - final IPart part = this.getPart( from ); - if( part instanceof IFluidHandler ) - { - return ( (IFluidHandler) part ).getTankInfo( from ); - } - return EMPTY_LIST; - } + @Override + public FluidTankInfo[] getTankInfo(final ForgeDirection from) { + final IPart part = this.getPart(from); + if (part instanceof IFluidHandler) { + return ((IFluidHandler) part).getTankInfo(from); + } + return EMPTY_LIST; + } } diff --git a/src/main/java/appeng/parts/layers/LayerIPipeConnection.java b/src/main/java/appeng/parts/layers/LayerIPipeConnection.java index d0daa0842b1..9d748a6fbd1 100644 --- a/src/main/java/appeng/parts/layers/LayerIPipeConnection.java +++ b/src/main/java/appeng/parts/layers/LayerIPipeConnection.java @@ -18,7 +18,6 @@ package appeng.parts.layers; - import appeng.api.parts.IPart; import appeng.api.parts.LayerBase; import appeng.helpers.Reflected; @@ -26,19 +25,15 @@ import buildcraft.api.transport.IPipeTile.PipeType; import net.minecraftforge.common.util.ForgeDirection; - @Reflected -public class LayerIPipeConnection extends LayerBase implements IPipeConnection -{ +public class LayerIPipeConnection extends LayerBase implements IPipeConnection { - @Override - public ConnectOverride overridePipeConnection( final PipeType type, final ForgeDirection with ) - { - final IPart part = this.getPart( with ); - if( part instanceof IPipeConnection ) - { - return ( (IPipeConnection) part ).overridePipeConnection( type, with ); - } - return ConnectOverride.DEFAULT; - } + @Override + public ConnectOverride overridePipeConnection(final PipeType type, final ForgeDirection with) { + final IPart part = this.getPart(with); + if (part instanceof IPipeConnection) { + return ((IPipeConnection) part).overridePipeConnection(type, with); + } + return ConnectOverride.DEFAULT; + } } diff --git a/src/main/java/appeng/parts/layers/LayerISidedInventory.java b/src/main/java/appeng/parts/layers/LayerISidedInventory.java index 928baabffb6..11570778ed8 100644 --- a/src/main/java/appeng/parts/layers/LayerISidedInventory.java +++ b/src/main/java/appeng/parts/layers/LayerISidedInventory.java @@ -18,21 +18,18 @@ package appeng.parts.layers; - import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import appeng.api.parts.LayerBase; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - - /** * Inventory wrapper for parts, *

@@ -43,224 +40,183 @@ * If your inventory changes in between placement and removal, you must trigger a PartChange on the {@link IPartHost} so * it can recalculate the inventory wrapper. */ -public class LayerISidedInventory extends LayerBase implements ISidedInventory -{ - - // a simple empty array for empty stuff.. - private static final int[] NULL_SIDES = {}; - - private InvLayerData invLayer = null; - - /** - * Recalculate inventory wrapper cache. - */ - @Override - public void notifyNeighbors() - { - // cache of inventory state. - - List inventories = new ArrayList(); - int slotCount = 0; - - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart bp = this.getPart( side ); - if( bp instanceof ISidedInventory ) - { - final ISidedInventory part = (ISidedInventory) bp; - slotCount += part.getSizeInventory(); - inventories.add( part ); - } - } - - List slots = null; - int[][] sideData = null; - if( inventories.isEmpty() || slotCount == 0 ) - { - inventories = null; - } - else - { - sideData = new int[][] { NULL_SIDES, NULL_SIDES, NULL_SIDES, NULL_SIDES, NULL_SIDES, NULL_SIDES }; - slots = new ArrayList( Collections.nCopies( slotCount, (InvSot) null ) ); - - int offsetForLayer = 0; - int offsetForPart = 0; - for( final ISidedInventory sides : inventories ) - { - offsetForPart = 0; - slotCount = sides.getSizeInventory(); - - ForgeDirection currentSide = ForgeDirection.UNKNOWN; - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.getPart( side ) == sides ) - { - currentSide = side; - break; - } - } - - final int[] cSidesList = sideData[currentSide.ordinal()] = new int[slotCount]; - for( int cSlot = 0; cSlot < slotCount; cSlot++ ) - { - cSidesList[cSlot] = offsetForLayer; - slots.set( offsetForLayer, new InvSot( sides, offsetForPart ) ); - offsetForLayer++; - offsetForPart++; - } - } - } - - if( sideData == null || slots == null ) - { - this.invLayer = null; - } - else - { - this.invLayer = new InvLayerData( sideData, inventories, slots ); - } - - // make sure inventory is updated before we call FMP. - super.notifyNeighbors(); - } - - @Override - public int getSizeInventory() - { - if( this.invLayer == null ) - { - return 0; - } - - return this.invLayer.getSizeInventory(); - } - - @Override - public ItemStack getStackInSlot( final int slot ) - { - if( this.invLayer == null ) - { - return null; - } - - return this.invLayer.getStackInSlot( slot ); - } - - @Override - public ItemStack decrStackSize( final int slot, final int amount ) - { - if( this.invLayer == null ) - { - return null; - } - - return this.invLayer.decreaseStackSize( slot, amount ); - } - - @Override - public ItemStack getStackInSlotOnClosing( final int slot ) - { - return null; - } - - @Override - public void setInventorySlotContents( final int slot, final ItemStack itemstack ) - { - if( this.invLayer == null ) - { - return; - } - - this.invLayer.setInventorySlotContents( slot, itemstack ); - } - - @Override - public String getInventoryName() - { - return "AEMultiPart"; - } - - @Override - public boolean hasCustomInventoryName() - { - return false; - } - - @Override - public int getInventoryStackLimit() - { - return 64; // no options here. - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return false; - } - - @Override - public void openInventory() - { - } - - @Override - public void closeInventory() - { - } - - @Override - public boolean isItemValidForSlot( final int slot, final ItemStack itemstack ) - { - if( this.invLayer == null ) - { - return false; - } - - return this.invLayer.isItemValidForSlot( slot, itemstack ); - } - - @Override - public void markDirty() - { - if( this.invLayer != null ) - { - this.invLayer.markDirty(); - } - - super.markForSave(); - } - - @Override - public int[] getAccessibleSlotsFromSide( final int side ) - { - if( this.invLayer != null ) - { - return this.invLayer.getAccessibleSlotsFromSide( side ); - } - - return NULL_SIDES; - } - - @Override - public boolean canInsertItem( final int slot, final ItemStack itemstack, final int side ) - { - if( this.invLayer == null ) - { - return false; - } - - return this.invLayer.canInsertItem( slot, itemstack, side ); - } - - @Override - public boolean canExtractItem( final int slot, final ItemStack itemstack, final int side ) - { - if( this.invLayer == null ) - { - return false; - } - - return this.invLayer.canExtractItem( slot, itemstack, side ); - } +public class LayerISidedInventory extends LayerBase implements ISidedInventory { + + // a simple empty array for empty stuff.. + private static final int[] NULL_SIDES = {}; + + private InvLayerData invLayer = null; + + /** + * Recalculate inventory wrapper cache. + */ + @Override + public void notifyNeighbors() { + // cache of inventory state. + + List inventories = new ArrayList(); + int slotCount = 0; + + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + final IPart bp = this.getPart(side); + if (bp instanceof ISidedInventory) { + final ISidedInventory part = (ISidedInventory) bp; + slotCount += part.getSizeInventory(); + inventories.add(part); + } + } + + List slots = null; + int[][] sideData = null; + if (inventories.isEmpty() || slotCount == 0) { + inventories = null; + } else { + sideData = new int[][] {NULL_SIDES, NULL_SIDES, NULL_SIDES, NULL_SIDES, NULL_SIDES, NULL_SIDES}; + slots = new ArrayList(Collections.nCopies(slotCount, (InvSot) null)); + + int offsetForLayer = 0; + int offsetForPart = 0; + for (final ISidedInventory sides : inventories) { + offsetForPart = 0; + slotCount = sides.getSizeInventory(); + + ForgeDirection currentSide = ForgeDirection.UNKNOWN; + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + if (this.getPart(side) == sides) { + currentSide = side; + break; + } + } + + final int[] cSidesList = sideData[currentSide.ordinal()] = new int[slotCount]; + for (int cSlot = 0; cSlot < slotCount; cSlot++) { + cSidesList[cSlot] = offsetForLayer; + slots.set(offsetForLayer, new InvSot(sides, offsetForPart)); + offsetForLayer++; + offsetForPart++; + } + } + } + + if (sideData == null || slots == null) { + this.invLayer = null; + } else { + this.invLayer = new InvLayerData(sideData, inventories, slots); + } + + // make sure inventory is updated before we call FMP. + super.notifyNeighbors(); + } + + @Override + public int getSizeInventory() { + if (this.invLayer == null) { + return 0; + } + + return this.invLayer.getSizeInventory(); + } + + @Override + public ItemStack getStackInSlot(final int slot) { + if (this.invLayer == null) { + return null; + } + + return this.invLayer.getStackInSlot(slot); + } + + @Override + public ItemStack decrStackSize(final int slot, final int amount) { + if (this.invLayer == null) { + return null; + } + + return this.invLayer.decreaseStackSize(slot, amount); + } + + @Override + public ItemStack getStackInSlotOnClosing(final int slot) { + return null; + } + + @Override + public void setInventorySlotContents(final int slot, final ItemStack itemstack) { + if (this.invLayer == null) { + return; + } + + this.invLayer.setInventorySlotContents(slot, itemstack); + } + + @Override + public String getInventoryName() { + return "AEMultiPart"; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public int getInventoryStackLimit() { + return 64; // no options here. + } + + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return false; + } + + @Override + public void openInventory() {} + + @Override + public void closeInventory() {} + + @Override + public boolean isItemValidForSlot(final int slot, final ItemStack itemstack) { + if (this.invLayer == null) { + return false; + } + + return this.invLayer.isItemValidForSlot(slot, itemstack); + } + + @Override + public void markDirty() { + if (this.invLayer != null) { + this.invLayer.markDirty(); + } + + super.markForSave(); + } + + @Override + public int[] getAccessibleSlotsFromSide(final int side) { + if (this.invLayer != null) { + return this.invLayer.getAccessibleSlotsFromSide(side); + } + + return NULL_SIDES; + } + + @Override + public boolean canInsertItem(final int slot, final ItemStack itemstack, final int side) { + if (this.invLayer == null) { + return false; + } + + return this.invLayer.canInsertItem(slot, itemstack, side); + } + + @Override + public boolean canExtractItem(final int slot, final ItemStack itemstack, final int side) { + if (this.invLayer == null) { + return false; + } + + return this.invLayer.canExtractItem(slot, itemstack, side); + } } diff --git a/src/main/java/appeng/parts/layers/LayerITileStorageMonitorable.java b/src/main/java/appeng/parts/layers/LayerITileStorageMonitorable.java index 7d2df96c104..31be9291215 100644 --- a/src/main/java/appeng/parts/layers/LayerITileStorageMonitorable.java +++ b/src/main/java/appeng/parts/layers/LayerITileStorageMonitorable.java @@ -18,7 +18,6 @@ package appeng.parts.layers; - import appeng.api.implementations.tiles.ITileStorageMonitorable; import appeng.api.networking.security.BaseActionSource; import appeng.api.parts.IPart; @@ -26,18 +25,14 @@ import appeng.api.storage.IStorageMonitorable; import net.minecraftforge.common.util.ForgeDirection; +public class LayerITileStorageMonitorable extends LayerBase implements ITileStorageMonitorable { -public class LayerITileStorageMonitorable extends LayerBase implements ITileStorageMonitorable -{ - - @Override - public IStorageMonitorable getMonitorable( final ForgeDirection side, final BaseActionSource src ) - { - final IPart part = this.getPart( side ); - if( part instanceof ITileStorageMonitorable ) - { - return ( (ITileStorageMonitorable) part ).getMonitorable( side, src ); - } - return null; - } + @Override + public IStorageMonitorable getMonitorable(final ForgeDirection side, final BaseActionSource src) { + final IPart part = this.getPart(side); + if (part instanceof ITileStorageMonitorable) { + return ((ITileStorageMonitorable) part).getMonitorable(side, src); + } + return null; + } } diff --git a/src/main/java/appeng/parts/layers/LayerPressure.java b/src/main/java/appeng/parts/layers/LayerPressure.java index a3ce8158573..e3be68a4e0e 100644 --- a/src/main/java/appeng/parts/layers/LayerPressure.java +++ b/src/main/java/appeng/parts/layers/LayerPressure.java @@ -18,30 +18,23 @@ package appeng.parts.layers; - import appeng.api.parts.IPart; import appeng.api.parts.LayerBase; +import javax.annotation.Nullable; import net.minecraftforge.common.util.ForgeDirection; import pneumaticCraft.api.tileentity.IAirHandler; import pneumaticCraft.api.tileentity.ISidedPneumaticMachine; -import javax.annotation.Nullable; - - -public class LayerPressure extends LayerBase implements ISidedPneumaticMachine -{ - - @Nullable - @Override - public IAirHandler getAirHandler( final ForgeDirection side ) - { - final IPart part = this.getPart( side ); - if( part instanceof ISidedPneumaticMachine ) - { - return ( (ISidedPneumaticMachine) part ).getAirHandler( side ); - } +public class LayerPressure extends LayerBase implements ISidedPneumaticMachine { - return null; - } + @Nullable + @Override + public IAirHandler getAirHandler(final ForgeDirection side) { + final IPart part = this.getPart(side); + if (part instanceof ISidedPneumaticMachine) { + return ((ISidedPneumaticMachine) part).getAirHandler(side); + } + return null; + } } diff --git a/src/main/java/appeng/parts/layers/LayerSidedEnvironment.java b/src/main/java/appeng/parts/layers/LayerSidedEnvironment.java index 15c5a5a9c88..39cdb3e202a 100644 --- a/src/main/java/appeng/parts/layers/LayerSidedEnvironment.java +++ b/src/main/java/appeng/parts/layers/LayerSidedEnvironment.java @@ -18,45 +18,37 @@ package appeng.parts.layers; - import appeng.api.parts.IPart; import appeng.api.parts.LayerBase; import appeng.core.Registration; import appeng.helpers.Reflected; import cpw.mods.fml.common.event.FMLInitializationEvent; +import javax.annotation.Nullable; import li.cil.oc.api.network.Node; import li.cil.oc.api.network.SidedEnvironment; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nullable; - - /** * Reflected in {@link Registration#initialize(FMLInitializationEvent)} */ @Reflected -public class LayerSidedEnvironment extends LayerBase implements SidedEnvironment -{ - @Nullable - @Override - public Node sidedNode( final ForgeDirection side ) - { - final IPart part = this.getPart( side ); - if( part instanceof SidedEnvironment ) - { - return ( (SidedEnvironment) part ).sidedNode( side ); - } - return null; - } +public class LayerSidedEnvironment extends LayerBase implements SidedEnvironment { + @Nullable + @Override + public Node sidedNode(final ForgeDirection side) { + final IPart part = this.getPart(side); + if (part instanceof SidedEnvironment) { + return ((SidedEnvironment) part).sidedNode(side); + } + return null; + } - @Override - public boolean canConnect( final ForgeDirection side ) - { - final IPart part = this.getPart( side ); - if( part instanceof SidedEnvironment ) - { - return ( (SidedEnvironment) part ).canConnect( side ); - } - return false; - } + @Override + public boolean canConnect(final ForgeDirection side) { + final IPart part = this.getPart(side); + if (part instanceof SidedEnvironment) { + return ((SidedEnvironment) part).canConnect(side); + } + return false; + } } diff --git a/src/main/java/appeng/parts/misc/PartCableAnchor.java b/src/main/java/appeng/parts/misc/PartCableAnchor.java index 6486613075a..3616dcd97fa 100644 --- a/src/main/java/appeng/parts/misc/PartCableAnchor.java +++ b/src/main/java/appeng/parts/misc/PartCableAnchor.java @@ -18,12 +18,14 @@ package appeng.parts.misc; - import appeng.api.networking.IGridNode; import appeng.api.parts.*; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.IOException; +import java.util.List; +import java.util.Random; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -36,234 +38,170 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; -import java.util.List; -import java.util.Random; - - -public class PartCableAnchor implements IPart -{ - - private ISimplifiedBundle renderCache = null; - private ItemStack is = null; - private IPartHost host = null; - private ForgeDirection mySide = ForgeDirection.UP; - - public PartCableAnchor( final ItemStack is ) - { - this.is = is; - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - if( this.host != null && this.host.getFacadeContainer().getFacade( this.mySide ) != null ) - { - bch.addBox( 7, 7, 10, 9, 9, 14 ); - } - else - { - bch.addBox( 7, 7, 10, 9, 9, 16 ); - } - } - - @Override - public ItemStack getItemStack( final PartItemStack wrenched ) - { - return this.is; - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper instance, final RenderBlocks renderer ) - { - instance.setTexture( this.is.getIconIndex() ); - instance.setBounds( 7, 7, 4, 9, 9, 14 ); - instance.renderInventoryBox( renderer ); - instance.setTexture( null ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.renderCache = rh.useSimplifiedRendering( x, y, z, this, this.renderCache ); - final IIcon myIcon = this.is.getIconIndex(); - rh.setTexture( myIcon ); - if( this.host != null && this.host.getFacadeContainer().getFacade( this.mySide ) != null ) - { - rh.setBounds( 7, 7, 10, 9, 9, 14 ); - } - else - { - rh.setBounds( 7, 7, 10, 9, 9, 16 ); - } - rh.renderBlock( x, y, z, renderer ); - rh.setTexture( null ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderDynamic( final double x, final double y, final double z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - - } - - @Override - public IIcon getBreakingTexture() - { - return null; - } - - @Override - public boolean requireDynamicRender() - { - return false; - } - - @Override - public boolean isSolid() - { - return false; - } - - @Override - public boolean canConnectRedstone() - { - return false; - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - - } - - @Override - public int getLightLevel() - { - return 0; - } - - @Override - public boolean isLadder( final EntityLivingBase entity ) - { - return this.mySide.offsetY == 0 && ( entity.isCollidedHorizontally || !entity.onGround ); - } - - @Override - public void onNeighborChanged() - { - - } - - @Override - public int isProvidingStrongPower() - { - return 0; - } - - @Override - public int isProvidingWeakPower() - { - return 0; - } - - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - - } - - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - return false; - } - - @Override - public IGridNode getGridNode() - { - return null; - } - - @Override - public void onEntityCollision( final Entity entity ) - { - - } - - @Override - public void removeFromWorld() - { - - } - - @Override - public void addToWorld() - { - - } - - @Override - public IGridNode getExternalFacingNode() - { - return null; - } - - @Override - public void setPartHostInfo( final ForgeDirection side, final IPartHost host, final TileEntity tile ) - { - this.host = host; - this.mySide = side; - } - - @Override - public boolean onActivate( final EntityPlayer player, final Vec3 pos ) - { - return false; - } - - @Override - public boolean onShiftActivate( final EntityPlayer player, final Vec3 pos ) - { - return false; - } - - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - - } - - @Override - public int cableConnectionRenderTo() - { - return 0; - } - - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World world, final int x, final int y, final int z, final Random r ) - { - - } - - @Override - public void onPlacement( final EntityPlayer player, final ItemStack held, final ForgeDirection side ) - { - - } - - @Override - public boolean canBePlacedOn( final BusSupport what ) - { - return what == BusSupport.CABLE || what == BusSupport.DENSE_CABLE; - } +public class PartCableAnchor implements IPart { + + private ISimplifiedBundle renderCache = null; + private ItemStack is = null; + private IPartHost host = null; + private ForgeDirection mySide = ForgeDirection.UP; + + public PartCableAnchor(final ItemStack is) { + this.is = is; + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + if (this.host != null && this.host.getFacadeContainer().getFacade(this.mySide) != null) { + bch.addBox(7, 7, 10, 9, 9, 14); + } else { + bch.addBox(7, 7, 10, 9, 9, 16); + } + } + + @Override + public ItemStack getItemStack(final PartItemStack wrenched) { + return this.is; + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper instance, final RenderBlocks renderer) { + instance.setTexture(this.is.getIconIndex()); + instance.setBounds(7, 7, 4, 9, 9, 14); + instance.renderInventoryBox(renderer); + instance.setTexture(null); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + this.renderCache = rh.useSimplifiedRendering(x, y, z, this, this.renderCache); + final IIcon myIcon = this.is.getIconIndex(); + rh.setTexture(myIcon); + if (this.host != null && this.host.getFacadeContainer().getFacade(this.mySide) != null) { + rh.setBounds(7, 7, 10, 9, 9, 14); + } else { + rh.setBounds(7, 7, 10, 9, 9, 16); + } + rh.renderBlock(x, y, z, renderer); + rh.setTexture(null); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderDynamic( + final double x, final double y, final double z, final IPartRenderHelper rh, final RenderBlocks renderer) {} + + @Override + public IIcon getBreakingTexture() { + return null; + } + + @Override + public boolean requireDynamicRender() { + return false; + } + + @Override + public boolean isSolid() { + return false; + } + + @Override + public boolean canConnectRedstone() { + return false; + } + + @Override + public void writeToNBT(final NBTTagCompound data) {} + + @Override + public void readFromNBT(final NBTTagCompound data) {} + + @Override + public int getLightLevel() { + return 0; + } + + @Override + public boolean isLadder(final EntityLivingBase entity) { + return this.mySide.offsetY == 0 && (entity.isCollidedHorizontally || !entity.onGround); + } + + @Override + public void onNeighborChanged() {} + + @Override + public int isProvidingStrongPower() { + return 0; + } + + @Override + public int isProvidingWeakPower() { + return 0; + } + + @Override + public void writeToStream(final ByteBuf data) throws IOException {} + + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + return false; + } + + @Override + public IGridNode getGridNode() { + return null; + } + + @Override + public void onEntityCollision(final Entity entity) {} + + @Override + public void removeFromWorld() {} + + @Override + public void addToWorld() {} + + @Override + public IGridNode getExternalFacingNode() { + return null; + } + + @Override + public void setPartHostInfo(final ForgeDirection side, final IPartHost host, final TileEntity tile) { + this.host = host; + this.mySide = side; + } + + @Override + public boolean onActivate(final EntityPlayer player, final Vec3 pos) { + return false; + } + + @Override + public boolean onShiftActivate(final EntityPlayer player, final Vec3 pos) { + return false; + } + + @Override + public void getDrops(final List drops, final boolean wrenched) {} + + @Override + public int cableConnectionRenderTo() { + return 0; + } + + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick(final World world, final int x, final int y, final int z, final Random r) {} + + @Override + public void onPlacement(final EntityPlayer player, final ItemStack held, final ForgeDirection side) {} + + @Override + public boolean canBePlacedOn(final BusSupport what) { + return what == BusSupport.CABLE || what == BusSupport.DENSE_CABLE; + } } diff --git a/src/main/java/appeng/parts/misc/PartInterface.java b/src/main/java/appeng/parts/misc/PartInterface.java index 981273f82d9..684b024e006 100644 --- a/src/main/java/appeng/parts/misc/PartInterface.java +++ b/src/main/java/appeng/parts/misc/PartInterface.java @@ -18,7 +18,6 @@ package appeng.parts.misc; - import appeng.api.config.Actionable; import appeng.api.config.Upgrades; import appeng.api.implementations.tiles.ITileStorageMonitorable; @@ -54,6 +53,8 @@ import com.google.common.collect.ImmutableSet; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import java.util.List; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; @@ -66,360 +67,339 @@ import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.List; - - public class PartInterface extends PartBasicState - implements IGridTickable, IStorageMonitorable, IInventoryDestination, IInterfaceHost, ISidedInventory, IAEAppEngInventory, ITileStorageMonitorable, IPriorityHost -{ - - private final DualityInterface duality = new DualityInterface( this.getProxy(), this ); - - @Reflected - public PartInterface( final ItemStack is ) - { - super( is ); - } - - @MENetworkEventSubscribe - public void stateChange( final MENetworkChannelsChanged c ) - { - this.duality.notifyNeighbors(); - } - - @MENetworkEventSubscribe - public void stateChange( final MENetworkPowerStatusChange c ) - { - this.duality.notifyNeighbors(); - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 2, 2, 14, 14, 14, 16 ); - bch.addBox( 5, 5, 12, 11, 11, 14 ); - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.duality.getInstalledUpgrades( u ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon() ); - - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 5, 5, 12, 11, 11, 13 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 5, 5, 13, 11, 11, 14 ); - rh.renderInventoryBox( renderer ); - } - - @Override - public void gridChanged() - { - this.duality.gridChanged(); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon() ); - - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon() ); - - rh.setBounds( 5, 5, 12, 11, 11, 13 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon() ); - - rh.setBounds( 5, 5, 13, 11, 11, 14 ); - rh.renderBlock( x, y, z, renderer ); - - this.renderLights( x, y, z, rh, renderer ); - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.duality.readFromNBT( data ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.duality.writeToNBT( data ); - } - - @Override - public void addToWorld() - { - super.addToWorld(); - this.duality.initialize(); - } - - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - this.duality.addDrops( drops ); - } - - @Override - public int cableConnectionRenderTo() - { - return 4; - } - - @Override - public IConfigManager getConfigManager() - { - return this.duality.getConfigManager(); - } - - @Override - public IInventory getInventoryByName( final String name ) - { - return this.duality.getInventoryByName( name ); - } - - @Override - public boolean onPartActivate( final EntityPlayer p, final Vec3 pos ) - { - if( p.isSneaking() ) - { - return false; - } - - if( Platform.isServer() ) - { - Platform.openGUI( p, this.getTileEntity(), this.getSide(), GuiBridge.GUI_INTERFACE ); - } - - return true; - } - - @Override - public IIcon getBreakingTexture() - { - return this.getItemStack().getIconIndex(); - } - - @Override - public boolean canInsert( final ItemStack stack ) - { - return this.duality.canInsert( stack ); - } - - @Override - public IMEMonitor getItemInventory() - { - return this.duality.getItemInventory(); - } - - @Override - public IMEMonitor getFluidInventory() - { - return this.duality.getFluidInventory(); - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return this.duality.getTickingRequest( node ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.duality.tickingRequest( node, ticksSinceLastCall ); - } - - @Override - public int getSizeInventory() - { - return this.duality.getStorage().getSizeInventory(); - } - - @Override - public ItemStack getStackInSlot( final int i ) - { - return this.duality.getStorage().getStackInSlot( i ); - } - - @Override - public ItemStack decrStackSize( final int i, final int j ) - { - return this.duality.getStorage().decrStackSize( i, j ); - } - - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - return this.duality.getStorage().getStackInSlotOnClosing( i ); - } - - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - this.duality.getStorage().setInventorySlotContents( i, itemstack ); - } - - @Override - public String getInventoryName() - { - return this.duality.getStorage().getInventoryName(); - } - - @Override - public boolean hasCustomInventoryName() - { - return this.duality.getStorage().hasCustomInventoryName(); - } - - @Override - public int getInventoryStackLimit() - { - return this.duality.getStorage().getInventoryStackLimit(); - } - - @Override - public void markDirty() - { - this.duality.getStorage().markDirty(); - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return this.duality.getStorage().isUseableByPlayer( entityplayer ); - } - - @Override - public void openInventory() - { - this.duality.getStorage().openInventory(); - } - - @Override - public void closeInventory() - { - this.duality.getStorage().closeInventory(); - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return this.duality.getStorage().isItemValidForSlot( i, itemstack ); - } - - @Override - public int[] getAccessibleSlotsFromSide( final int s ) - { - return this.duality.getAccessibleSlotsFromSide( s ); - } - - @Override - public boolean canInsertItem( final int i, final ItemStack itemstack, final int j ) - { - return true; - } - - @Override - public boolean canExtractItem( final int i, final ItemStack itemstack, final int j ) - { - return true; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - this.duality.onChangeInventory( inv, slot, mc, removedStack, newStack ); - } - - @Override - public DualityInterface getInterfaceDuality() - { - return this.duality; - } - - @Override - public EnumSet getTargets() - { - return EnumSet.of( this.getSide() ); - } - - @Override - public TileEntity getTileEntity() - { - return super.getHost().getTile(); - } - - @Override - public IStorageMonitorable getMonitorable( final ForgeDirection side, final BaseActionSource src ) - { - return this.duality.getMonitorable( side, src, this ); - } - - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table ) - { - return this.duality.pushPattern( patternDetails, table ); - } - - @Override - public boolean isBusy() - { - return this.duality.isBusy(); - } - - @Override - public void provideCrafting( final ICraftingProviderHelper craftingTracker ) - { - this.duality.provideCrafting( craftingTracker ); - } - - @Override - public ImmutableSet getRequestedJobs() - { - return this.duality.getRequestedJobs(); - } - - @Override - public IAEItemStack injectCraftedItems( final ICraftingLink link, final IAEItemStack items, final Actionable mode ) - { - return this.duality.injectCraftedItems( link, items, mode ); - } - - @Override - public void jobStateChange( final ICraftingLink link ) - { - this.duality.jobStateChange( link ); - } - - @Override - public int getPriority() - { - return this.duality.getPriority(); - } - - @Override - public void setPriority( final int newValue ) - { - this.duality.setPriority( newValue ); - } + implements IGridTickable, + IStorageMonitorable, + IInventoryDestination, + IInterfaceHost, + ISidedInventory, + IAEAppEngInventory, + ITileStorageMonitorable, + IPriorityHost { + + private final DualityInterface duality = new DualityInterface(this.getProxy(), this); + + @Reflected + public PartInterface(final ItemStack is) { + super(is); + } + + @MENetworkEventSubscribe + public void stateChange(final MENetworkChannelsChanged c) { + this.duality.notifyNeighbors(); + } + + @MENetworkEventSubscribe + public void stateChange(final MENetworkPowerStatusChange c) { + this.duality.notifyNeighbors(); + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(2, 2, 14, 14, 14, 16); + bch.addBox(5, 5, 12, 11, 11, 14); + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.duality.getInstalledUpgrades(u); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture( + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorSides.getIcon()); + + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderInventoryBox(renderer); + + rh.setBounds(5, 5, 12, 11, 11, 13); + rh.renderInventoryBox(renderer); + + rh.setBounds(5, 5, 13, 11, 11, 14); + rh.renderInventoryBox(renderer); + } + + @Override + public void gridChanged() { + this.duality.gridChanged(); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + this.setRenderCache(rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache())); + rh.setTexture( + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorSides.getIcon()); + + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture( + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorSides.getIcon()); + + rh.setBounds(5, 5, 12, 11, 11, 13); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture( + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon()); + + rh.setBounds(5, 5, 13, 11, 11, 14); + rh.renderBlock(x, y, z, renderer); + + this.renderLights(x, y, z, rh, renderer); + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.duality.readFromNBT(data); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.duality.writeToNBT(data); + } + + @Override + public void addToWorld() { + super.addToWorld(); + this.duality.initialize(); + } + + @Override + public void getDrops(final List drops, final boolean wrenched) { + this.duality.addDrops(drops); + } + + @Override + public int cableConnectionRenderTo() { + return 4; + } + + @Override + public IConfigManager getConfigManager() { + return this.duality.getConfigManager(); + } + + @Override + public IInventory getInventoryByName(final String name) { + return this.duality.getInventoryByName(name); + } + + @Override + public boolean onPartActivate(final EntityPlayer p, final Vec3 pos) { + if (p.isSneaking()) { + return false; + } + + if (Platform.isServer()) { + Platform.openGUI(p, this.getTileEntity(), this.getSide(), GuiBridge.GUI_INTERFACE); + } + + return true; + } + + @Override + public IIcon getBreakingTexture() { + return this.getItemStack().getIconIndex(); + } + + @Override + public boolean canInsert(final ItemStack stack) { + return this.duality.canInsert(stack); + } + + @Override + public IMEMonitor getItemInventory() { + return this.duality.getItemInventory(); + } + + @Override + public IMEMonitor getFluidInventory() { + return this.duality.getFluidInventory(); + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return this.duality.getTickingRequest(node); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.duality.tickingRequest(node, ticksSinceLastCall); + } + + @Override + public int getSizeInventory() { + return this.duality.getStorage().getSizeInventory(); + } + + @Override + public ItemStack getStackInSlot(final int i) { + return this.duality.getStorage().getStackInSlot(i); + } + + @Override + public ItemStack decrStackSize(final int i, final int j) { + return this.duality.getStorage().decrStackSize(i, j); + } + + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + return this.duality.getStorage().getStackInSlotOnClosing(i); + } + + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + this.duality.getStorage().setInventorySlotContents(i, itemstack); + } + + @Override + public String getInventoryName() { + return this.duality.getStorage().getInventoryName(); + } + + @Override + public boolean hasCustomInventoryName() { + return this.duality.getStorage().hasCustomInventoryName(); + } + + @Override + public int getInventoryStackLimit() { + return this.duality.getStorage().getInventoryStackLimit(); + } + + @Override + public void markDirty() { + this.duality.getStorage().markDirty(); + } + + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return this.duality.getStorage().isUseableByPlayer(entityplayer); + } + + @Override + public void openInventory() { + this.duality.getStorage().openInventory(); + } + + @Override + public void closeInventory() { + this.duality.getStorage().closeInventory(); + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return this.duality.getStorage().isItemValidForSlot(i, itemstack); + } + + @Override + public int[] getAccessibleSlotsFromSide(final int s) { + return this.duality.getAccessibleSlotsFromSide(s); + } + + @Override + public boolean canInsertItem(final int i, final ItemStack itemstack, final int j) { + return true; + } + + @Override + public boolean canExtractItem(final int i, final ItemStack itemstack, final int j) { + return true; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) { + this.duality.onChangeInventory(inv, slot, mc, removedStack, newStack); + } + + @Override + public DualityInterface getInterfaceDuality() { + return this.duality; + } + + @Override + public EnumSet getTargets() { + return EnumSet.of(this.getSide()); + } + + @Override + public TileEntity getTileEntity() { + return super.getHost().getTile(); + } + + @Override + public IStorageMonitorable getMonitorable(final ForgeDirection side, final BaseActionSource src) { + return this.duality.getMonitorable(side, src, this); + } + + @Override + public boolean pushPattern(final ICraftingPatternDetails patternDetails, final InventoryCrafting table) { + return this.duality.pushPattern(patternDetails, table); + } + + @Override + public boolean isBusy() { + return this.duality.isBusy(); + } + + @Override + public void provideCrafting(final ICraftingProviderHelper craftingTracker) { + this.duality.provideCrafting(craftingTracker); + } + + @Override + public ImmutableSet getRequestedJobs() { + return this.duality.getRequestedJobs(); + } + + @Override + public IAEItemStack injectCraftedItems(final ICraftingLink link, final IAEItemStack items, final Actionable mode) { + return this.duality.injectCraftedItems(link, items, mode); + } + + @Override + public void jobStateChange(final ICraftingLink link) { + this.duality.jobStateChange(link); + } + + @Override + public int getPriority() { + return this.duality.getPriority(); + } + + @Override + public void setPriority(final int newValue) { + this.duality.setPriority(newValue); + } } diff --git a/src/main/java/appeng/parts/misc/PartInvertedToggleBus.java b/src/main/java/appeng/parts/misc/PartInvertedToggleBus.java index 2b63295ce72..a9e8d29998e 100644 --- a/src/main/java/appeng/parts/misc/PartInvertedToggleBus.java +++ b/src/main/java/appeng/parts/misc/PartInvertedToggleBus.java @@ -18,26 +18,21 @@ package appeng.parts.misc; - import appeng.helpers.Reflected; import net.minecraft.item.ItemStack; +public class PartInvertedToggleBus extends PartToggleBus { + @Reflected + public PartInvertedToggleBus(final ItemStack is) { + super(is); + this.getProxy().setIdlePowerUsage(0.0); + this.getOuterProxy().setIdlePowerUsage(0.0); + this.getProxy().setFlags(); + this.getOuterProxy().setFlags(); + } -public class PartInvertedToggleBus extends PartToggleBus -{ - @Reflected - public PartInvertedToggleBus( final ItemStack is ) - { - super( is ); - this.getProxy().setIdlePowerUsage( 0.0 ); - this.getOuterProxy().setIdlePowerUsage( 0.0 ); - this.getProxy().setFlags(); - this.getOuterProxy().setFlags(); - } - - @Override - protected boolean getIntention() - { - return !super.getIntention(); - } + @Override + protected boolean getIntention() { + return !super.getIntention(); + } } diff --git a/src/main/java/appeng/parts/misc/PartStorageBus.java b/src/main/java/appeng/parts/misc/PartStorageBus.java index 7693724a921..97af3fc0330 100644 --- a/src/main/java/appeng/parts/misc/PartStorageBus.java +++ b/src/main/java/appeng/parts/misc/PartStorageBus.java @@ -18,7 +18,6 @@ package appeng.parts.misc; - import appeng.api.AEApi; import appeng.api.config.*; import appeng.api.networking.IGridNode; @@ -65,6 +64,9 @@ import buildcraft.api.transport.IPipeTile.PipeType; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; @@ -74,511 +76,476 @@ import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - - -@Interface( iname = IntegrationType.BuildCraftTransport, iface = "buildcraft.api.transport.IPipeConnection" ) +@Interface(iname = IntegrationType.BuildCraftTransport, iface = "buildcraft.api.transport.IPipeConnection") public class PartStorageBus extends PartUpgradeable - implements IGridTickable, ICellContainer, IMEMonitorHandlerReceiver, IPipeConnection, IPriorityHost, IOreFilterable -{ - private final BaseActionSource mySrc; - private final AppEngInternalAEInventory Config = new AppEngInternalAEInventory( this, 63 ); - private int priority = 0; - private boolean cached = false; - private MEMonitorIInventory monitor = null; - private MEInventoryHandler handler = null; - private int handlerHash = 0; - private boolean wasActive = false; - private byte resetCacheLogic = 0; - private String oreFilterString = ""; - - @Reflected - public PartStorageBus( final ItemStack is ) - { - super( is ); - this.getConfigManager().registerSetting( Settings.ACCESS, AccessRestriction.READ_WRITE ); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.getConfigManager().registerSetting( Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY ); - this.mySrc = new MachineSource( this ); - } - - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.updateStatus(); - } - - private void updateStatus() - { - final boolean currentActive = this.getProxy().isActive(); - if( this.wasActive != currentActive ) - { - this.wasActive = currentActive; - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - this.getHost().markForUpdate(); - } - catch( final GridAccessException e ) - { - // :P - } - } - } - - @MENetworkEventSubscribe - public void updateChannels( final MENetworkChannelsChanged changedChannels ) - { - this.updateStatus(); - } - - @Override - protected int getUpgradeSlots() - { - return 5; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - this.resetCache( true ); - this.getHost().markForSave(); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - super.onChangeInventory( inv, slot, mc, removedStack, newStack ); - - if( inv == this.Config ) - { - this.resetCache( true ); - } - } - - @Override - public void upgradesChanged() - { - super.upgradesChanged(); - if (getInstalledUpgrades(Upgrades.ORE_FILTER) == 0) - this.oreFilterString = ""; - this.resetCache(true); - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.Config.readFromNBT( data, "config" ); - this.priority = data.getInteger( "priority" ); - this.oreFilterString = data.getString("filter"); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.Config.writeToNBT( data, "config" ); - data.setInteger( "priority", this.priority ); - data.setString("filter", this.oreFilterString); - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "config" ) ) - { - return this.Config; - } - - return super.getInventoryByName( name ); - } - - private void resetCache( final boolean fullReset ) - { - if( this.getHost() == null || this.getHost().getTile() == null || this.getHost().getTile().getWorldObj() == null || this.getHost().getTile().getWorldObj().isRemote ) - { - return; - } - - if( fullReset ) - { - this.resetCacheLogic = 2; - } - else - { - this.resetCacheLogic = 1; - } - - try - { - this.getProxy().getTick().alertDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - @Override - public boolean isValid( final Object verificationToken ) - { - return this.handler == verificationToken; - } - - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final BaseActionSource source ) - { - try - { - if( this.getProxy().isActive() ) - { - this.getProxy().getStorage().postAlterationOfStoredItems( StorageChannel.ITEMS, change, this.mySrc ); - } - } - catch( final GridAccessException e ) - { - // :( - } - } - - @Override - public void onListUpdate() - { - // not used here. - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 3, 3, 15, 13, 13, 16 ); - bch.addBox( 2, 2, 14, 14, 14, 15 ); - bch.addBox( 5, 5, 12, 11, 11, 14 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageSides.getIcon() ); - - rh.setBounds( 3, 3, 15, 13, 13, 16 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 2, 2, 14, 14, 14, 15 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 5, 5, 12, 11, 11, 14 ); - rh.renderInventoryBox( renderer ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageSides.getIcon() ); - - rh.setBounds( 3, 3, 15, 13, 13, 16 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setBounds( 2, 2, 14, 14, 14, 15 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageSides.getIcon() ); - - rh.setBounds( 5, 5, 12, 11, 11, 13 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon() ); - - rh.setBounds( 5, 5, 13, 11, 11, 14 ); - rh.renderBlock( x, y, z, renderer ); - - this.renderLights( x, y, z, rh, renderer ); - } - - @Override - public void onNeighborChanged() - { - this.resetCache( false ); - } - - @Override - public int cableConnectionRenderTo() - { - return 4; - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( !player.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } - - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_STORAGEBUS ); - return true; - } - - return false; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.StorageBus.getMin(), TickRates.StorageBus.getMax(), this.monitor == null, true ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( this.resetCacheLogic != 0 ) - { - this.resetCache(); - } - - if( this.monitor != null ) - { - return this.monitor.onTick(); - } - - return TickRateModulation.SLEEP; - } - - private void resetCache() - { - final boolean fullReset = this.resetCacheLogic == 2; - this.resetCacheLogic = 0; - - final IMEInventory in = this.getInternalHandler(); - IItemList before = AEApi.instance().storage().createItemList(); - if( in != null ) - { - before = in.getAvailableItems( before ); - } - - this.cached = false; - if( fullReset ) - { - this.handlerHash = 0; - } - - final IMEInventory out = this.getInternalHandler(); - - if( this.monitor != null ) - { - this.monitor.onTick(); - } - - IItemList after = AEApi.instance().storage().createItemList(); - if( out != null ) - { - after = out.getAvailableItems( after ); - } - - Platform.postListChanges( before, after, this, this.mySrc ); - } - - public MEInventoryHandler getInternalHandler() - { - if( this.cached ) - { - return this.handler; - } - - final boolean wasSleeping = this.monitor == null; - - this.cached = true; - final TileEntity self = this.getHost().getTile(); - final TileEntity target = self.getWorldObj().getTileEntity( self.xCoord + this.getSide().offsetX, self.yCoord + this.getSide().offsetY, self.zCoord + this.getSide().offsetZ ); - - final int newHandlerHash = Platform.generateTileHash( target ); - - if( this.handlerHash == newHandlerHash && this.handlerHash != 0 ) - { - return this.handler; - } - - this.handlerHash = newHandlerHash; - this.handler = null; - this.monitor = null; - if( target != null ) - { - final IExternalStorageHandler esh = AEApi.instance().registries().externalStorage().getHandler( target, this.getSide().getOpposite(), StorageChannel.ITEMS, this.mySrc ); - if( esh != null ) - { - final IMEInventory inv = esh.getInventory( target, this.getSide().getOpposite(), StorageChannel.ITEMS, this.mySrc ); - - if( inv instanceof MEMonitorIInventory ) - { - final MEMonitorIInventory h = (MEMonitorIInventory) inv; - h.setMode( (StorageFilter) this.getConfigManager().getSetting( Settings.STORAGE_FILTER ) ); - h.setActionSource( new MachineSource( this ) ); - } - - if( inv instanceof MEMonitorIInventory ) - { - this.monitor = (MEMonitorIInventory) inv; - } - - if( inv != null ) - { - this.checkInterfaceVsStorageBus( target, this.getSide().getOpposite() ); - - this.handler = new MEInventoryHandler( inv, StorageChannel.ITEMS ); - - this.handler.setBaseAccess( (AccessRestriction) this.getConfigManager().getSetting( Settings.ACCESS ) ); - this.handler.setWhitelist( this.getInstalledUpgrades( Upgrades.INVERTER ) > 0 ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST ); - this.handler.setPriority( this.priority ); - - if (this.oreFilterString.isEmpty()) { - final IItemList priorityList = AEApi.instance().storage().createItemList(); - - final int slotsToUse = 18 + this.getInstalledUpgrades(Upgrades.CAPACITY) * 9; - for (int x = 0; x < this.Config.getSizeInventory() && x < slotsToUse; x++) { - final IAEItemStack is = this.Config.getAEStackInSlot(x); - if (is != null) - priorityList.add(is); - } - - if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { - this.handler.setPartitionList(new FuzzyPriorityList(priorityList, (FuzzyMode) this.getConfigManager().getSetting(Settings.FUZZY_MODE))); - } else { - this.handler.setPartitionList(new PrecisePriorityList(priorityList)); - } - } - else { - this.handler.setPartitionList(new OreFilteredList(oreFilterString)); - } - - if( inv instanceof IMEMonitor ) - { - ( (IBaseMonitor) inv ).addListener( this, this.handler ); - } - } - } - } - - // update sleep state... - if( wasSleeping != ( this.monitor == null ) ) - { - try - { - final ITickManager tm = this.getProxy().getTick(); - if( this.monitor == null ) - { - tm.sleepDevice( this.getProxy().getNode() ); - } - else - { - tm.wakeDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { - // :( - } - } - - try - { - // force grid to update handlers... - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :3 - } - - return this.handler; - } - - private void checkInterfaceVsStorageBus( final TileEntity target, final ForgeDirection side ) - { - IInterfaceHost achievement = null; - - if( target instanceof IInterfaceHost ) - { - achievement = (IInterfaceHost) target; - } - - if( target instanceof IPartHost ) - { - final Object part = ( (IPartHost) target ).getPart( side ); - if( part instanceof IInterfaceHost ) - { - achievement = (IInterfaceHost) part; - } - } - - if( achievement != null && achievement.getActionableNode() != null ) - { - Platform.addStat( achievement.getActionableNode().getPlayerID(), Achievements.Recursive.getAchievement() ); - // Platform.addStat( getActionableNode().getPlayerID(), Achievements.Recursive.getAchievement() ); - } - } - - @Override - public List getCellArray( final StorageChannel channel ) - { - if( channel == StorageChannel.ITEMS ) - { - final IMEInventoryHandler out = this.getProxy().isActive() ? this.getInternalHandler() : null; - if( out != null ) - { - return Collections.singletonList( out ); - } - } - return Arrays.asList( new IMEInventoryHandler[] {} ); - } - - @Override - public int getPriority() - { - return this.priority; - } - - @Override - public void setPriority( final int newValue ) - { - this.priority = newValue; - this.getHost().markForSave(); - this.resetCache( true ); - } - - @Override - public void blinkCell( final int slot ) - { - } - - @Override - @Method( iname = IntegrationType.BuildCraftTransport ) - public ConnectOverride overridePipeConnection( final PipeType type, final ForgeDirection with ) - { - return type == PipeType.ITEM && with == this.getSide() ? ConnectOverride.CONNECT : ConnectOverride.DISCONNECT; - } - - @Override - public void saveChanges( final IMEInventory cellInventory ) - { - // nope! - } - - @Override - public String getFilter() { - return oreFilterString; - } - - @Override - public void setFilter(String filter) { - oreFilterString = filter; - resetCache(true); - } + implements IGridTickable, + ICellContainer, + IMEMonitorHandlerReceiver, + IPipeConnection, + IPriorityHost, + IOreFilterable { + private final BaseActionSource mySrc; + private final AppEngInternalAEInventory Config = new AppEngInternalAEInventory(this, 63); + private int priority = 0; + private boolean cached = false; + private MEMonitorIInventory monitor = null; + private MEInventoryHandler handler = null; + private int handlerHash = 0; + private boolean wasActive = false; + private byte resetCacheLogic = 0; + private String oreFilterString = ""; + + @Reflected + public PartStorageBus(final ItemStack is) { + super(is); + this.getConfigManager().registerSetting(Settings.ACCESS, AccessRestriction.READ_WRITE); + this.getConfigManager().registerSetting(Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL); + this.getConfigManager().registerSetting(Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY); + this.mySrc = new MachineSource(this); + } + + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.updateStatus(); + } + + private void updateStatus() { + final boolean currentActive = this.getProxy().isActive(); + if (this.wasActive != currentActive) { + this.wasActive = currentActive; + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + this.getHost().markForUpdate(); + } catch (final GridAccessException e) { + // :P + } + } + } + + @MENetworkEventSubscribe + public void updateChannels(final MENetworkChannelsChanged changedChannels) { + this.updateStatus(); + } + + @Override + protected int getUpgradeSlots() { + return 5; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + this.resetCache(true); + this.getHost().markForSave(); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) { + super.onChangeInventory(inv, slot, mc, removedStack, newStack); + + if (inv == this.Config) { + this.resetCache(true); + } + } + + @Override + public void upgradesChanged() { + super.upgradesChanged(); + if (getInstalledUpgrades(Upgrades.ORE_FILTER) == 0) this.oreFilterString = ""; + this.resetCache(true); + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.Config.readFromNBT(data, "config"); + this.priority = data.getInteger("priority"); + this.oreFilterString = data.getString("filter"); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.Config.writeToNBT(data, "config"); + data.setInteger("priority", this.priority); + data.setString("filter", this.oreFilterString); + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("config")) { + return this.Config; + } + + return super.getInventoryByName(name); + } + + private void resetCache(final boolean fullReset) { + if (this.getHost() == null + || this.getHost().getTile() == null + || this.getHost().getTile().getWorldObj() == null + || this.getHost().getTile().getWorldObj().isRemote) { + return; + } + + if (fullReset) { + this.resetCacheLogic = 2; + } else { + this.resetCacheLogic = 1; + } + + try { + this.getProxy().getTick().alertDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // :P + } + } + + @Override + public boolean isValid(final Object verificationToken) { + return this.handler == verificationToken; + } + + @Override + public void postChange( + final IBaseMonitor monitor, + final Iterable change, + final BaseActionSource source) { + try { + if (this.getProxy().isActive()) { + this.getProxy().getStorage().postAlterationOfStoredItems(StorageChannel.ITEMS, change, this.mySrc); + } + } catch (final GridAccessException e) { + // :( + } + } + + @Override + public void onListUpdate() { + // not used here. + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(3, 3, 15, 13, 13, 16); + bch.addBox(2, 2, 14, 14, 14, 15); + bch.addBox(5, 5, 12, 11, 11, 14); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture( + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageSides.getIcon()); + + rh.setBounds(3, 3, 15, 13, 13, 16); + rh.renderInventoryBox(renderer); + + rh.setBounds(2, 2, 14, 14, 14, 15); + rh.renderInventoryBox(renderer); + + rh.setBounds(5, 5, 12, 11, 11, 14); + rh.renderInventoryBox(renderer); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + this.setRenderCache(rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache())); + rh.setTexture( + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageSides.getIcon()); + + rh.setBounds(3, 3, 15, 13, 13, 16); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(2, 2, 14, 14, 14, 15); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture( + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageSides.getIcon()); + + rh.setBounds(5, 5, 12, 11, 11, 13); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture( + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon()); + + rh.setBounds(5, 5, 13, 11, 11, 14); + rh.renderBlock(x, y, z, renderer); + + this.renderLights(x, y, z, rh, renderer); + } + + @Override + public void onNeighborChanged() { + this.resetCache(false); + } + + @Override + public int cableConnectionRenderTo() { + return 4; + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (!player.isSneaking()) { + if (Platform.isClient()) { + return true; + } + + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_STORAGEBUS); + return true; + } + + return false; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest( + TickRates.StorageBus.getMin(), TickRates.StorageBus.getMax(), this.monitor == null, true); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (this.resetCacheLogic != 0) { + this.resetCache(); + } + + if (this.monitor != null) { + return this.monitor.onTick(); + } + + return TickRateModulation.SLEEP; + } + + private void resetCache() { + final boolean fullReset = this.resetCacheLogic == 2; + this.resetCacheLogic = 0; + + final IMEInventory in = this.getInternalHandler(); + IItemList before = AEApi.instance().storage().createItemList(); + if (in != null) { + before = in.getAvailableItems(before); + } + + this.cached = false; + if (fullReset) { + this.handlerHash = 0; + } + + final IMEInventory out = this.getInternalHandler(); + + if (this.monitor != null) { + this.monitor.onTick(); + } + + IItemList after = AEApi.instance().storage().createItemList(); + if (out != null) { + after = out.getAvailableItems(after); + } + + Platform.postListChanges(before, after, this, this.mySrc); + } + + public MEInventoryHandler getInternalHandler() { + if (this.cached) { + return this.handler; + } + + final boolean wasSleeping = this.monitor == null; + + this.cached = true; + final TileEntity self = this.getHost().getTile(); + final TileEntity target = self.getWorldObj() + .getTileEntity( + self.xCoord + this.getSide().offsetX, + self.yCoord + this.getSide().offsetY, + self.zCoord + this.getSide().offsetZ); + + final int newHandlerHash = Platform.generateTileHash(target); + + if (this.handlerHash == newHandlerHash && this.handlerHash != 0) { + return this.handler; + } + + this.handlerHash = newHandlerHash; + this.handler = null; + this.monitor = null; + if (target != null) { + final IExternalStorageHandler esh = AEApi.instance() + .registries() + .externalStorage() + .getHandler(target, this.getSide().getOpposite(), StorageChannel.ITEMS, this.mySrc); + if (esh != null) { + final IMEInventory inv = + esh.getInventory(target, this.getSide().getOpposite(), StorageChannel.ITEMS, this.mySrc); + + if (inv instanceof MEMonitorIInventory) { + final MEMonitorIInventory h = (MEMonitorIInventory) inv; + h.setMode((StorageFilter) this.getConfigManager().getSetting(Settings.STORAGE_FILTER)); + h.setActionSource(new MachineSource(this)); + } + + if (inv instanceof MEMonitorIInventory) { + this.monitor = (MEMonitorIInventory) inv; + } + + if (inv != null) { + this.checkInterfaceVsStorageBus(target, this.getSide().getOpposite()); + + this.handler = new MEInventoryHandler(inv, StorageChannel.ITEMS); + + this.handler.setBaseAccess( + (AccessRestriction) this.getConfigManager().getSetting(Settings.ACCESS)); + this.handler.setWhitelist( + this.getInstalledUpgrades(Upgrades.INVERTER) > 0 + ? IncludeExclude.BLACKLIST + : IncludeExclude.WHITELIST); + this.handler.setPriority(this.priority); + + if (this.oreFilterString.isEmpty()) { + final IItemList priorityList = + AEApi.instance().storage().createItemList(); + + final int slotsToUse = 18 + this.getInstalledUpgrades(Upgrades.CAPACITY) * 9; + for (int x = 0; x < this.Config.getSizeInventory() && x < slotsToUse; x++) { + final IAEItemStack is = this.Config.getAEStackInSlot(x); + if (is != null) priorityList.add(is); + } + + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + this.handler.setPartitionList(new FuzzyPriorityList(priorityList, (FuzzyMode) + this.getConfigManager().getSetting(Settings.FUZZY_MODE))); + } else { + this.handler.setPartitionList(new PrecisePriorityList(priorityList)); + } + } else { + this.handler.setPartitionList(new OreFilteredList(oreFilterString)); + } + + if (inv instanceof IMEMonitor) { + ((IBaseMonitor) inv).addListener(this, this.handler); + } + } + } + } + + // update sleep state... + if (wasSleeping != (this.monitor == null)) { + try { + final ITickManager tm = this.getProxy().getTick(); + if (this.monitor == null) { + tm.sleepDevice(this.getProxy().getNode()); + } else { + tm.wakeDevice(this.getProxy().getNode()); + } + } catch (final GridAccessException e) { + // :( + } + } + + try { + // force grid to update handlers... + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :3 + } + + return this.handler; + } + + private void checkInterfaceVsStorageBus(final TileEntity target, final ForgeDirection side) { + IInterfaceHost achievement = null; + + if (target instanceof IInterfaceHost) { + achievement = (IInterfaceHost) target; + } + + if (target instanceof IPartHost) { + final Object part = ((IPartHost) target).getPart(side); + if (part instanceof IInterfaceHost) { + achievement = (IInterfaceHost) part; + } + } + + if (achievement != null && achievement.getActionableNode() != null) { + Platform.addStat(achievement.getActionableNode().getPlayerID(), Achievements.Recursive.getAchievement()); + // Platform.addStat( getActionableNode().getPlayerID(), Achievements.Recursive.getAchievement() ); + } + } + + @Override + public List getCellArray(final StorageChannel channel) { + if (channel == StorageChannel.ITEMS) { + final IMEInventoryHandler out = this.getProxy().isActive() ? this.getInternalHandler() : null; + if (out != null) { + return Collections.singletonList(out); + } + } + return Arrays.asList(new IMEInventoryHandler[] {}); + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public void setPriority(final int newValue) { + this.priority = newValue; + this.getHost().markForSave(); + this.resetCache(true); + } + + @Override + public void blinkCell(final int slot) {} + + @Override + @Method(iname = IntegrationType.BuildCraftTransport) + public ConnectOverride overridePipeConnection(final PipeType type, final ForgeDirection with) { + return type == PipeType.ITEM && with == this.getSide() ? ConnectOverride.CONNECT : ConnectOverride.DISCONNECT; + } + + @Override + public void saveChanges(final IMEInventory cellInventory) { + // nope! + } + + @Override + public String getFilter() { + return oreFilterString; + } + + @Override + public void setFilter(String filter) { + oreFilterString = filter; + resetCache(true); + } } diff --git a/src/main/java/appeng/parts/misc/PartToggleBus.java b/src/main/java/appeng/parts/misc/PartToggleBus.java index e29429abb4b..d45fc42518b 100644 --- a/src/main/java/appeng/parts/misc/PartToggleBus.java +++ b/src/main/java/appeng/parts/misc/PartToggleBus.java @@ -18,7 +18,6 @@ package appeng.parts.misc; - import appeng.api.AEApi; import appeng.api.exceptions.FailedConnection; import appeng.api.networking.IGridConnection; @@ -34,6 +33,9 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -43,222 +45,200 @@ import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; - - -public class PartToggleBus extends PartBasicState -{ - private static final int REDSTONE_FLAG = 8; - private final AENetworkProxy outerProxy = new AENetworkProxy( this, "outer", null, true ); - private IGridConnection connection; - private boolean hasRedstone = false; - - @Reflected - public PartToggleBus( final ItemStack is ) - { - super( is ); - - this.getProxy().setIdlePowerUsage( 0.0 ); - this.getOuterProxy().setIdlePowerUsage( 0.0 ); - this.getProxy().setFlags(); - this.getOuterProxy().setFlags(); - } - - @Override - public void setColors( final boolean hasChan, final boolean hasPower ) - { - this.hasRedstone = ( this.getClientFlags() & REDSTONE_FLAG ) == REDSTONE_FLAG; - super.setColors( hasChan && this.hasRedstone, hasPower && this.hasRedstone ); - } - - @Override - protected int populateFlags( final int cf ) - { - return cf | ( this.getIntention() ? REDSTONE_FLAG : 0 ); - } - - protected boolean getIntention() - { - return this.getHost().hasRedstone( this.getSide() ); - } - - @Override - public IIcon getBreakingTexture() - { - return this.getItemStack().getIconIndex(); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.GLASS; - } - - @Override - public void securityBreak() - { - if( this.getItemStack().stackSize > 0 ) - { - final List items = new ArrayList(); - items.add( this.getItemStack().copy() ); - this.getHost().removePart( this.getSide(), false ); - Platform.spawnDrops( this.getTile().getWorldObj(), this.getTile().xCoord, this.getTile().yCoord, this.getTile().zCoord, items ); - this.getItemStack().stackSize = 0; - } - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 6, 6, 11, 10, 10, 16 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - GL11.glTranslated( -0.2, -0.3, 0.0 ); - - rh.setTexture( this.getItemStack().getIconIndex() ); - rh.setBounds( 6, 6, 14 - 4, 10, 10, 16 - 4 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 6, 6, 11 - 4, 10, 10, 13 - 4 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 6, 6, 13 - 4, 10, 10, 14 - 4 ); - rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon() ); - rh.renderInventoryBox( renderer ); - - rh.setTexture( CableBusTextures.PartMonitorSidesStatusLights.getIcon() ); - rh.setInvColor( 0x000000 ); - rh.renderInventoryBox( renderer ); - rh.setInvColor( 0xffffff ); - - rh.setTexture( null ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( this.getItemStack().getIconIndex() ); - - rh.setBounds( 6, 6, 14, 10, 10, 16 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setBounds( 6, 6, 11, 10, 10, 13 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon() ); - - rh.setBounds( 6, 6, 13, 10, 10, 14 ); - rh.renderBlock( x, y, z, renderer ); - - this.renderLights( x, y, z, rh, renderer ); - } - - @Override - public void onNeighborChanged() - { - final boolean oldHasRedstone = this.hasRedstone; - this.hasRedstone = this.getHost().hasRedstone( this.getSide() ); - - if( this.hasRedstone != oldHasRedstone ) - { - this.updateInternalState(); - this.getHost().markForUpdate(); - } - } - - @Override - public void readFromNBT( final NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.getOuterProxy().readFromNBT( extra ); - } - - @Override - public void writeToNBT( final NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.getOuterProxy().writeToNBT( extra ); - } - - @Override - public void removeFromWorld() - { - super.removeFromWorld(); - this.getOuterProxy().invalidate(); - } - - @Override - public void addToWorld() - { - super.addToWorld(); - this.getOuterProxy().onReady(); - this.hasRedstone = this.getHost().hasRedstone( this.getSide() ); - this.updateInternalState(); - } - - @Override - public void setPartHostInfo( final ForgeDirection side, final IPartHost host, final TileEntity tile ) - { - super.setPartHostInfo( side, host, tile ); - this.getOuterProxy().setValidSides( EnumSet.of( side ) ); - } - - @Override - public IGridNode getExternalFacingNode() - { - return this.getOuterProxy().getNode(); - } - - @Override - public int cableConnectionRenderTo() - { - return 5; - } - - @Override - public void onPlacement( final EntityPlayer player, final ItemStack held, final ForgeDirection side ) - { - super.onPlacement( player, held, side ); - this.getOuterProxy().setOwner( player ); - } - - private void updateInternalState() - { - final boolean intention = this.getIntention(); - if( intention == ( this.connection == null ) ) - { - if( this.getProxy().getNode() != null && this.getOuterProxy().getNode() != null ) - { - if( intention ) - { - try - { - this.connection = AEApi.instance().createGridConnection( this.getProxy().getNode(), this.getOuterProxy().getNode() ); - } - catch( final FailedConnection e ) - { - // :( - } - } - else - { - this.connection.destroy(); - this.connection = null; - } - } - } - } - - AENetworkProxy getOuterProxy() - { - return this.outerProxy; - } +public class PartToggleBus extends PartBasicState { + private static final int REDSTONE_FLAG = 8; + private final AENetworkProxy outerProxy = new AENetworkProxy(this, "outer", null, true); + private IGridConnection connection; + private boolean hasRedstone = false; + + @Reflected + public PartToggleBus(final ItemStack is) { + super(is); + + this.getProxy().setIdlePowerUsage(0.0); + this.getOuterProxy().setIdlePowerUsage(0.0); + this.getProxy().setFlags(); + this.getOuterProxy().setFlags(); + } + + @Override + public void setColors(final boolean hasChan, final boolean hasPower) { + this.hasRedstone = (this.getClientFlags() & REDSTONE_FLAG) == REDSTONE_FLAG; + super.setColors(hasChan && this.hasRedstone, hasPower && this.hasRedstone); + } + + @Override + protected int populateFlags(final int cf) { + return cf | (this.getIntention() ? REDSTONE_FLAG : 0); + } + + protected boolean getIntention() { + return this.getHost().hasRedstone(this.getSide()); + } + + @Override + public IIcon getBreakingTexture() { + return this.getItemStack().getIconIndex(); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.GLASS; + } + + @Override + public void securityBreak() { + if (this.getItemStack().stackSize > 0) { + final List items = new ArrayList(); + items.add(this.getItemStack().copy()); + this.getHost().removePart(this.getSide(), false); + Platform.spawnDrops( + this.getTile().getWorldObj(), + this.getTile().xCoord, + this.getTile().yCoord, + this.getTile().zCoord, + items); + this.getItemStack().stackSize = 0; + } + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(6, 6, 11, 10, 10, 16); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + GL11.glTranslated(-0.2, -0.3, 0.0); + + rh.setTexture(this.getItemStack().getIconIndex()); + rh.setBounds(6, 6, 14 - 4, 10, 10, 16 - 4); + rh.renderInventoryBox(renderer); + + rh.setBounds(6, 6, 11 - 4, 10, 10, 13 - 4); + rh.renderInventoryBox(renderer); + + rh.setBounds(6, 6, 13 - 4, 10, 10, 14 - 4); + rh.setTexture(CableBusTextures.PartMonitorSidesStatus.getIcon()); + rh.renderInventoryBox(renderer); + + rh.setTexture(CableBusTextures.PartMonitorSidesStatusLights.getIcon()); + rh.setInvColor(0x000000); + rh.renderInventoryBox(renderer); + rh.setInvColor(0xffffff); + + rh.setTexture(null); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + this.setRenderCache(rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache())); + rh.setTexture(this.getItemStack().getIconIndex()); + + rh.setBounds(6, 6, 14, 10, 10, 16); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(6, 6, 11, 10, 10, 13); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture( + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon()); + + rh.setBounds(6, 6, 13, 10, 10, 14); + rh.renderBlock(x, y, z, renderer); + + this.renderLights(x, y, z, rh, renderer); + } + + @Override + public void onNeighborChanged() { + final boolean oldHasRedstone = this.hasRedstone; + this.hasRedstone = this.getHost().hasRedstone(this.getSide()); + + if (this.hasRedstone != oldHasRedstone) { + this.updateInternalState(); + this.getHost().markForUpdate(); + } + } + + @Override + public void readFromNBT(final NBTTagCompound extra) { + super.readFromNBT(extra); + this.getOuterProxy().readFromNBT(extra); + } + + @Override + public void writeToNBT(final NBTTagCompound extra) { + super.writeToNBT(extra); + this.getOuterProxy().writeToNBT(extra); + } + + @Override + public void removeFromWorld() { + super.removeFromWorld(); + this.getOuterProxy().invalidate(); + } + + @Override + public void addToWorld() { + super.addToWorld(); + this.getOuterProxy().onReady(); + this.hasRedstone = this.getHost().hasRedstone(this.getSide()); + this.updateInternalState(); + } + + @Override + public void setPartHostInfo(final ForgeDirection side, final IPartHost host, final TileEntity tile) { + super.setPartHostInfo(side, host, tile); + this.getOuterProxy().setValidSides(EnumSet.of(side)); + } + + @Override + public IGridNode getExternalFacingNode() { + return this.getOuterProxy().getNode(); + } + + @Override + public int cableConnectionRenderTo() { + return 5; + } + + @Override + public void onPlacement(final EntityPlayer player, final ItemStack held, final ForgeDirection side) { + super.onPlacement(player, held, side); + this.getOuterProxy().setOwner(player); + } + + private void updateInternalState() { + final boolean intention = this.getIntention(); + if (intention == (this.connection == null)) { + if (this.getProxy().getNode() != null && this.getOuterProxy().getNode() != null) { + if (intention) { + try { + this.connection = AEApi.instance() + .createGridConnection( + this.getProxy().getNode(), + this.getOuterProxy().getNode()); + } catch (final FailedConnection e) { + // :( + } + } else { + this.connection.destroy(); + this.connection = null; + } + } + } + } + + AENetworkProxy getOuterProxy() { + return this.outerProxy; + } } diff --git a/src/main/java/appeng/parts/networking/PartCable.java b/src/main/java/appeng/parts/networking/PartCable.java index 6914ff7465e..dd4d95df257 100644 --- a/src/main/java/appeng/parts/networking/PartCable.java +++ b/src/main/java/appeng/parts/networking/PartCable.java @@ -18,7 +18,6 @@ package appeng.parts.networking; - import appeng.api.AEApi; import appeng.api.config.SecurityPermissions; import appeng.api.definitions.IParts; @@ -43,6 +42,8 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.IOException; +import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.player.EntityPlayer; @@ -53,1037 +54,967 @@ import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import java.io.IOException; -import java.util.EnumSet; - - -public class PartCable extends AEBasePart implements IPartCable -{ - - private final int[] channelsOnSide = { 0, 0, 0, 0, 0, 0 }; - - private EnumSet connections = EnumSet.noneOf( ForgeDirection.class ); - private boolean powered = false; - - public PartCable( final ItemStack is ) - { - super( is ); - this.getProxy().setFlags( GridFlags.PREFERRED ); - this.getProxy().setIdlePowerUsage( 0.0 ); - this.getProxy().setColor( AEColor.values()[( (ItemMultiPart) is.getItem() ).variantOf( is.getItemDamage() )] ); - } - - @Override - public BusSupport supportsBuses() - { - return BusSupport.CABLE; - } - - @Override - public AEColor getCableColor() - { - return this.getProxy().getColor(); - } - - @Override - public AECableType getCableConnectionType() - { - return AECableType.GLASS; - } - - @Override - public boolean changeColor( final AEColor newColor, final EntityPlayer who ) - { - if( this.getCableColor() != newColor ) - { - ItemStack newPart = null; - - final IParts parts = AEApi.instance().definitions().parts(); - - if( this.getCableConnectionType() == AECableType.GLASS ) - { - newPart = parts.cableGlass().stack( newColor, 1 ); - } - else if( this.getCableConnectionType() == AECableType.COVERED ) - { - newPart = parts.cableCovered().stack( newColor, 1 ); - } - else if( this.getCableConnectionType() == AECableType.SMART ) - { - newPart = parts.cableSmart().stack( newColor, 1 ); - } - else if( this.getCableConnectionType() == AECableType.DENSE ) - { - newPart = parts.cableDense().stack( newColor, 1 ); - } - else if( this.getCableConnectionType() == AECableType.DENSE_COVERED ) - { - newPart = parts.cableDenseCovered().stack( newColor, 1 ); - } - else if( this.getCableConnectionType() == AECableType.ULTRA_DENSE ) - { - newPart = parts.cableDense().stack( newColor, 1 ); - } - else if( this.getCableConnectionType() == AECableType.ULTRA_DENSE_SMART ) - { - newPart = parts.cableDenseCovered().stack( newColor, 1 ); - } - - boolean hasPermission = true; - - try - { - hasPermission = this.getProxy().getSecurity().hasPermission( who, SecurityPermissions.BUILD ); - } - catch( final GridAccessException e ) - { - // :P - } - - if( newPart != null && hasPermission ) - { - if( Platform.isClient() ) - { - return true; - } - - this.getHost().removePart( ForgeDirection.UNKNOWN, true ); - this.getHost().addPart( newPart, ForgeDirection.UNKNOWN, who ); - return true; - } - } - return false; - } - - @Override - public void setValidSides( final EnumSet sides ) - { - this.getProxy().setValidSides( sides ); - } - - @Override - public boolean isConnected( final ForgeDirection side ) - { - return this.getConnections().contains( side ); - } - - public void markForUpdate() - { - this.getHost().markForUpdate(); - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 6.0, 6.0, 6.0, 10.0, 10.0, 10.0 ); - - if( Platform.isServer() ) - { - final IGridNode n = this.getGridNode(); - if( n != null ) - { - this.setConnections( n.getConnectedSides() ); - } - else - { - this.getConnections().clear(); - } - } - - final IPartHost ph = this.getHost(); - if( ph != null ) - { - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart p = ph.getPart( dir ); - if( p instanceof IGridHost ) - { - final double dist = p.cableConnectionRenderTo(); - - if( dist > 8 ) - { - continue; - } - - switch( dir ) - { - case DOWN: - bch.addBox( 6.0, dist, 6.0, 10.0, 6.0, 10.0 ); - break; - case EAST: - bch.addBox( 10.0, 6.0, 6.0, 16.0 - dist, 10.0, 10.0 ); - break; - case NORTH: - bch.addBox( 6.0, 6.0, dist, 10.0, 10.0, 6.0 ); - break; - case SOUTH: - bch.addBox( 6.0, 6.0, 10.0, 10.0, 10.0, 16.0 - dist ); - break; - case UP: - bch.addBox( 6.0, 10.0, 6.0, 10.0, 16.0 - dist, 10.0 ); - break; - case WEST: - bch.addBox( dist, 6.0, 6.0, 6.0, 10.0, 10.0 ); - break; - default: - } - } - } - } - - for( final ForgeDirection of : this.getConnections() ) - { - switch( of ) - { - case DOWN: - bch.addBox( 6.0, 0.0, 6.0, 10.0, 6.0, 10.0 ); - break; - case EAST: - bch.addBox( 10.0, 6.0, 6.0, 16.0, 10.0, 10.0 ); - break; - case NORTH: - bch.addBox( 6.0, 6.0, 0.0, 10.0, 10.0, 6.0 ); - break; - case SOUTH: - bch.addBox( 6.0, 6.0, 10.0, 10.0, 10.0, 16.0 ); - break; - case UP: - bch.addBox( 6.0, 10.0, 6.0, 10.0, 16.0, 10.0 ); - break; - case WEST: - bch.addBox( 0.0, 6.0, 6.0, 6.0, 10.0, 10.0 ); - break; - default: - } - } - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - GL11.glTranslated( -0.0, -0.0, 0.3 ); - - rh.setTexture( this.getTexture( this.getCableColor() ) ); - rh.setBounds( 6.0f, 6.0f, 2.0f, 10.0f, 10.0f, 14.0f ); - rh.renderInventoryBox( renderer ); - rh.setTexture( null ); - } - - public IIcon getTexture( final AEColor c ) - { - return this.getGlassTexture( c ); - } - - public IIcon getGlassTexture( final AEColor c ) - { - switch( c ) - { - case Black: - return CableBusTextures.MECable_Black.getIcon(); - case Blue: - return CableBusTextures.MECable_Blue.getIcon(); - case Brown: - return CableBusTextures.MECable_Brown.getIcon(); - case Cyan: - return CableBusTextures.MECable_Cyan.getIcon(); - case Gray: - return CableBusTextures.MECable_Grey.getIcon(); - case Green: - return CableBusTextures.MECable_Green.getIcon(); - case LightBlue: - return CableBusTextures.MECable_LightBlue.getIcon(); - case LightGray: - return CableBusTextures.MECable_LightGrey.getIcon(); - case Lime: - return CableBusTextures.MECable_Lime.getIcon(); - case Magenta: - return CableBusTextures.MECable_Magenta.getIcon(); - case Orange: - return CableBusTextures.MECable_Orange.getIcon(); - case Pink: - return CableBusTextures.MECable_Pink.getIcon(); - case Purple: - return CableBusTextures.MECable_Purple.getIcon(); - case Red: - return CableBusTextures.MECable_Red.getIcon(); - case White: - return CableBusTextures.MECable_White.getIcon(); - case Yellow: - return CableBusTextures.MECable_Yellow.getIcon(); - default: - } - - final AEColoredItemDefinition glassCable = AEApi.instance().definitions().parts().cableGlass(); - final ItemStack glassCableStack = glassCable.stack( AEColor.Transparent, 1 ); - - return glassCable.item( AEColor.Transparent ).getIconIndex( glassCableStack ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - boolean useCovered = false; - boolean requireDetailed = false; - - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart p = this.getHost().getPart( dir ); - if( p instanceof IGridHost ) - { - final IGridHost igh = (IGridHost) p; - final AECableType type = igh.getCableConnectionType( dir.getOpposite() ); - if( type == AECableType.COVERED || type == AECableType.SMART ) - { - useCovered = true; - break; - } - } - else if( this.getConnections().contains( dir ) ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ ); - final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; - final IGridHost gh = te instanceof IGridHost ? (IGridHost) te : null; - if( partHost == null && gh != null && gh.getCableConnectionType( dir ) != AECableType.GLASS ) - { - requireDetailed = true; - } - } - } - - if( useCovered ) - { - rh.setTexture( this.getCoveredTexture( this.getCableColor() ) ); - } - else - { - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } - - final IPartHost ph = this.getHost(); - for( final ForgeDirection of : EnumSet.complementOf( this.getConnections() ) ) - { - final IPart bp = ph.getPart( of ); - if( bp instanceof IGridHost ) - { - final int len = bp.cableConnectionRenderTo(); - if( len < 8 ) - { - switch( of ) - { - case DOWN: - rh.setBounds( 6, len, 6, 10, 6, 10 ); - break; - case EAST: - rh.setBounds( 10, 6, 6, 16 - len, 10, 10 ); - break; - case NORTH: - rh.setBounds( 6, 6, len, 10, 10, 6 ); - break; - case SOUTH: - rh.setBounds( 6, 6, 10, 10, 10, 16 - len ); - break; - case UP: - rh.setBounds( 6, 10, 6, 10, 16 - len, 10 ); - break; - case WEST: - rh.setBounds( len, 6, 6, 6, 10, 10 ); - break; - default: - continue; - } - rh.renderBlock( x, y, z, renderer ); - } - } - } - - if( this.getConnections().size() != 2 || !this.nonLinear( this.getConnections() ) || useCovered || requireDetailed ) - { - if( useCovered ) - { - rh.setBounds( 5, 5, 5, 11, 11, 11 ); - rh.renderBlock( x, y, z, renderer ); - } - else - { - rh.setBounds( 6, 6, 6, 10, 10, 10 ); - rh.renderBlock( x, y, z, renderer ); - } - - for( final ForgeDirection of : this.getConnections() ) - { - this.renderGlassConnection( x, y, z, rh, renderer, of ); - } - } - else - { - final IIcon def = this.getTexture( this.getCableColor() ); - rh.setTexture( def ); - - for( final ForgeDirection of : this.getConnections() ) - { - rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of, of.getOpposite() ) ) ); - switch( of ) - { - case DOWN: - case UP: - renderer.setRenderBounds( 6 / 16.0, 0, 6 / 16.0, 10 / 16.0, 16 / 16.0, 10 / 16.0 ); - break; - case EAST: - case WEST: - renderer.uvRotateEast = renderer.uvRotateWest = 1; - renderer.uvRotateBottom = renderer.uvRotateTop = 1; - renderer.setRenderBounds( 0, 6 / 16.0, 6 / 16.0, 16 / 16.0, 10 / 16.0, 10 / 16.0 ); - break; - case NORTH: - case SOUTH: - renderer.uvRotateNorth = renderer.uvRotateSouth = 1; - renderer.setRenderBounds( 6 / 16.0, 6 / 16.0, 0, 10 / 16.0, 10 / 16.0, 16 / 16.0 ); - break; - default: - } - } - - rh.renderBlockCurrentBounds( x, y, z, renderer ); - } - - rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - rh.setTexture( null ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - - if( Platform.isServer() ) - { - final IGridNode node = this.getGridNode(); - - if( node != null ) - { - int howMany = 0; - for( final IGridConnection gc : node.getConnections() ) - { - howMany = Math.max( gc.getUsedChannels(), howMany ); - } - - data.setShort( "usedChannels", (short) howMany ); - } - } - } - - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - int cs = 0; - int sideOut = 0; - - final IGridNode n = this.getGridNode(); - if( n != null ) - { - for( final ForgeDirection thisSide : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getHost().getPart( thisSide ); - if( part != null ) - { - if( part.getGridNode() != null ) - { - final IReadOnlyCollection set = part.getGridNode().getConnections(); - for( final IGridConnection gc : set ) - { - if( this.getProxy().getNode().hasFlag( GridFlags.ULTRA_DENSE_CAPACITY ) && gc.getOtherSide( this.getProxy().getNode() ).hasFlag( GridFlags.ULTRA_DENSE_CAPACITY ) ) - { - sideOut |= ( gc.getUsedChannels() / 16 ) << ( 4 * thisSide.ordinal() ); - } - else if( this.getProxy().getNode().hasFlag( GridFlags.DENSE_CAPACITY ) && gc.getOtherSide( this.getProxy().getNode() ).hasFlag( GridFlags.DENSE_CAPACITY ) ) - { - sideOut |= ( gc.getUsedChannels() / 4 ) << ( 4 * thisSide.ordinal() ); - } - else - { - sideOut |= ( gc.getUsedChannels() ) << ( 4 * thisSide.ordinal() ); - } - } - } - } - } - - for( final IGridConnection gc : n.getConnections() ) - { - final ForgeDirection side = gc.getDirection( n ); - if( side != ForgeDirection.UNKNOWN ) - { - final boolean isTier3a = this.getProxy().getNode().hasFlag( GridFlags.ULTRA_DENSE_CAPACITY ); - final boolean isTier3b = gc.getOtherSide( this.getProxy().getNode() ).hasFlag( GridFlags.ULTRA_DENSE_CAPACITY ); - - final boolean isTier2a = this.getProxy().getNode().hasFlag( GridFlags.DENSE_CAPACITY ); - final boolean isTier2b = gc.getOtherSide( this.getProxy().getNode() ).hasFlag( GridFlags.DENSE_CAPACITY ); - - if (isTier3a && isTier3b) - { - sideOut |= ( gc.getUsedChannels() / 16 ) << ( 4 * side.ordinal() ); - } - else if( (isTier3a || isTier2a) && (isTier2b || isTier3b) ) - { - sideOut |= ( gc.getUsedChannels() / 4 ) << ( 4 * side.ordinal() ); - } - else - { - sideOut |= gc.getUsedChannels() << ( 4 * side.ordinal() ); - } - cs |= ( 1 << side.ordinal() ); - } - } - } - - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - cs |= ( 1 << ForgeDirection.UNKNOWN.ordinal() ); - } - } - catch( final GridAccessException e ) - { - // aww... - } - - data.writeByte( (byte) cs ); - data.writeInt( sideOut ); - } - - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - final int cs = data.readByte(); - final int sideOut = data.readInt(); - - final EnumSet myC = this.getConnections().clone(); - final boolean wasPowered = this.powered; - this.powered = false; - boolean channelsChanged = false; - - for( final ForgeDirection d : ForgeDirection.values() ) - { - if( d != ForgeDirection.UNKNOWN ) - { - final int ch = ( sideOut >> ( d.ordinal() * 4 ) ) & 0xF; - if( ch != this.getChannelsOnSide()[d.ordinal()] ) - { - channelsChanged = true; - this.getChannelsOnSide()[d.ordinal()] = ch; - } - } - - if( d == ForgeDirection.UNKNOWN ) - { - final int id = 1 << d.ordinal(); - if( id == ( cs & id ) ) - { - this.powered = true; - } - } - else - { - final int id = 1 << d.ordinal(); - if( id == ( cs & id ) ) - { - this.getConnections().add( d ); - } - else - { - this.getConnections().remove( d ); - } - } - } - - return !myC.equals( this.getConnections() ) || wasPowered != this.powered || channelsChanged; - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getBreakingTexture() - { - return this.getTexture( this.getCableColor() ); - } - - public IIcon getCoveredTexture( final AEColor c ) - { - switch( c ) - { - case Black: - return CableBusTextures.MECovered_Black.getIcon(); - case Blue: - return CableBusTextures.MECovered_Blue.getIcon(); - case Brown: - return CableBusTextures.MECovered_Brown.getIcon(); - case Cyan: - return CableBusTextures.MECovered_Cyan.getIcon(); - case Gray: - return CableBusTextures.MECovered_Gray.getIcon(); - case Green: - return CableBusTextures.MECovered_Green.getIcon(); - case LightBlue: - return CableBusTextures.MECovered_LightBlue.getIcon(); - case LightGray: - return CableBusTextures.MECovered_LightGrey.getIcon(); - case Lime: - return CableBusTextures.MECovered_Lime.getIcon(); - case Magenta: - return CableBusTextures.MECovered_Magenta.getIcon(); - case Orange: - return CableBusTextures.MECovered_Orange.getIcon(); - case Pink: - return CableBusTextures.MECovered_Pink.getIcon(); - case Purple: - return CableBusTextures.MECovered_Purple.getIcon(); - case Red: - return CableBusTextures.MECovered_Red.getIcon(); - case White: - return CableBusTextures.MECovered_White.getIcon(); - case Yellow: - return CableBusTextures.MECovered_Yellow.getIcon(); - default: - } - - final AEColoredItemDefinition coveredCable = AEApi.instance().definitions().parts().cableCovered(); - final ItemStack coveredCableStack = coveredCable.stack( AEColor.Transparent, 1 ); - - return coveredCable.item( AEColor.Transparent ).getIconIndex( coveredCableStack ); - } - - protected boolean nonLinear( final EnumSet sides ) - { - return ( sides.contains( ForgeDirection.EAST ) && sides.contains( ForgeDirection.WEST ) ) || ( sides.contains( ForgeDirection.NORTH ) && sides.contains( ForgeDirection.SOUTH ) ) || ( sides.contains( ForgeDirection.UP ) && sides.contains( ForgeDirection.DOWN ) ); - } - - @SideOnly( Side.CLIENT ) - private void renderGlassConnection( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer, final ForgeDirection of ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( x + of.offsetX, y + of.offsetY, z + of.offsetZ ); - final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; - final IGridHost gh = te instanceof IGridHost ? (IGridHost) te : null; - - rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of ) ) ); - - if( gh != null && partHost != null && gh.getCableConnectionType( of.getOpposite() ) == AECableType.GLASS && partHost.getColor() != AEColor.Transparent && partHost.getPart( of.getOpposite() ) == null ) - { - rh.setTexture( this.getTexture( partHost.getColor() ) ); - } - else if( partHost == null && gh != null && gh.getCableConnectionType( of.getOpposite() ) != AECableType.GLASS ) - { - rh.setTexture( this.getCoveredTexture( this.getCableColor() ) ); - switch( of ) - { - case DOWN: - rh.setBounds( 5, 0, 5, 11, 4, 11 ); - break; - case EAST: - rh.setBounds( 12, 5, 5, 16, 11, 11 ); - break; - case NORTH: - rh.setBounds( 5, 5, 0, 11, 11, 4 ); - break; - case SOUTH: - rh.setBounds( 5, 5, 12, 11, 11, 16 ); - break; - case UP: - rh.setBounds( 5, 12, 5, 11, 16, 11 ); - break; - case WEST: - rh.setBounds( 0, 5, 5, 4, 11, 11 ); - break; - default: - return; - } - - rh.renderBlock( x, y, z, renderer ); - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } - else - { - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } - - switch( of ) - { - case DOWN: - rh.setBounds( 6, 0, 6, 10, 6, 10 ); - break; - case EAST: - rh.setBounds( 10, 6, 6, 16, 10, 10 ); - break; - case NORTH: - rh.setBounds( 6, 6, 0, 10, 10, 6 ); - break; - case SOUTH: - rh.setBounds( 6, 6, 10, 10, 10, 16 ); - break; - case UP: - rh.setBounds( 6, 10, 6, 10, 16, 10 ); - break; - case WEST: - rh.setBounds( 0, 6, 6, 6, 10, 10 ); - break; - default: - return; - } - - rh.renderBlock( x, y, z, renderer ); - rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - } - - @SideOnly( Side.CLIENT ) void renderCoveredConnection( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer, final int channels, final ForgeDirection of ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( x + of.offsetX, y + of.offsetY, z + of.offsetZ ); - final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; - final IGridHost ghh = te instanceof IGridHost ? (IGridHost) te : null; - - rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of ) ) ); - if( ghh != null && partHost != null && ghh.getCableConnectionType( of.getOpposite() ) == AECableType.GLASS && partHost.getPart( of.getOpposite() ) == null && partHost.getColor() != AEColor.Transparent ) - { - rh.setTexture( this.getGlassTexture( partHost.getColor() ) ); - } - else if( partHost == null && ghh != null && ghh.getCableConnectionType( of.getOpposite() ) != AECableType.GLASS ) - { - rh.setTexture( this.getCoveredTexture( this.getCableColor() ) ); - switch( of ) - { - case DOWN: - rh.setBounds( 5, 0, 5, 11, 4, 11 ); - break; - case EAST: - rh.setBounds( 12, 5, 5, 16, 11, 11 ); - break; - case NORTH: - rh.setBounds( 5, 5, 0, 11, 11, 4 ); - break; - case SOUTH: - rh.setBounds( 5, 5, 12, 11, 11, 16 ); - break; - case UP: - rh.setBounds( 5, 12, 5, 11, 16, 11 ); - break; - case WEST: - rh.setBounds( 0, 5, 5, 4, 11, 11 ); - break; - default: - return; - } - - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } - else if( ghh != null && partHost != null && ghh.getCableConnectionType( of.getOpposite() ) == AECableType.COVERED && partHost.getColor() != AEColor.Transparent && partHost.getPart( of.getOpposite() ) == null ) - { - rh.setTexture( this.getCoveredTexture( partHost.getColor() ) ); - } - else - { - rh.setTexture( this.getCoveredTexture( this.getCableColor() ) ); - } - - switch( of ) - { - case DOWN: - rh.setBounds( 6, 0, 6, 10, 5, 10 ); - break; - case EAST: - rh.setBounds( 11, 6, 6, 16, 10, 10 ); - break; - case NORTH: - rh.setBounds( 6, 6, 0, 10, 10, 5 ); - break; - case SOUTH: - rh.setBounds( 6, 6, 11, 10, 10, 16 ); - break; - case UP: - rh.setBounds( 6, 11, 6, 10, 16, 10 ); - break; - case WEST: - rh.setBounds( 0, 6, 6, 5, 10, 10 ); - break; - default: - return; - } - - rh.renderBlock( x, y, z, renderer ); - rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - } - - @SideOnly( Side.CLIENT ) void renderSmartConnection( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer, final int channels, final ForgeDirection of ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( x + of.offsetX, y + of.offsetY, z + of.offsetZ ); - final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; - final IGridHost ghh = te instanceof IGridHost ? (IGridHost) te : null; - AEColor myColor = this.getCableColor(); - - rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of ) ) ); - - boolean isGlass = false; - if( ghh != null && partHost != null && ghh.getCableConnectionType( of.getOpposite() ) == AECableType.GLASS && partHost.getPart( of.getOpposite() ) == null && partHost.getColor() != AEColor.Transparent ) - { - isGlass = true; - rh.setTexture( this.getGlassTexture( myColor = partHost.getColor() ) ); - } - else if( partHost == null && ghh != null && ghh.getCableConnectionType( of.getOpposite() ) != AECableType.GLASS ) - { - rh.setTexture( this.getSmartTexture( myColor ) ); - switch( of ) - { - case DOWN: - rh.setBounds( 5, 0, 5, 11, 4, 11 ); - break; - case EAST: - rh.setBounds( 12, 5, 5, 16, 11, 11 ); - break; - case NORTH: - rh.setBounds( 5, 5, 0, 11, 11, 4 ); - break; - case SOUTH: - rh.setBounds( 5, 5, 12, 11, 11, 16 ); - break; - case UP: - rh.setBounds( 5, 12, 5, 11, 16, 11 ); - break; - case WEST: - rh.setBounds( 0, 5, 5, 4, 11, 11 ); - break; - default: - return; - } - rh.renderBlock( x, y, z, renderer ); - - this.setSmartConnectionRotations( of, renderer ); - final IIcon firstIcon = new TaughtIcon( this.getChannelTex( channels, false ).getIcon(), -0.2f ); - final IIcon secondIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); - - if( of == ForgeDirection.EAST || of == ForgeDirection.WEST ) - { - final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); - final FlippableIcon ico = blk.getRendererInstance().getTexture( ForgeDirection.EAST ); - ico.setFlip( false, true ); - } - - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); - Tessellator.instance.setColorOpaque_I( myColor.blackVariant ); - rh.setTexture( firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - - Tessellator.instance.setColorOpaque_I( myColor.whiteVariant ); - rh.setTexture( secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } - - else if( ghh != null && partHost != null && ghh.getCableConnectionType( of.getOpposite() ) != AECableType.GLASS && partHost.getColor() != AEColor.Transparent && partHost.getPart( of.getOpposite() ) == null ) - { - rh.setTexture( this.getSmartTexture( myColor = partHost.getColor() ) ); - } - else - { - rh.setTexture( this.getSmartTexture( this.getCableColor() ) ); - } - - switch( of ) - { - case DOWN: - rh.setBounds( 6, 0, 6, 10, 5, 10 ); - break; - case EAST: - rh.setBounds( 11, 6, 6, 16, 10, 10 ); - break; - case NORTH: - rh.setBounds( 6, 6, 0, 10, 10, 5 ); - break; - case SOUTH: - rh.setBounds( 6, 6, 11, 10, 10, 16 ); - break; - case UP: - rh.setBounds( 6, 11, 6, 10, 16, 10 ); - break; - case WEST: - rh.setBounds( 0, 6, 6, 5, 10, 10 ); - break; - default: - return; - } - - rh.renderBlock( x, y, z, renderer ); - rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - - if( !isGlass ) - { - this.setSmartConnectionRotations( of, renderer ); - - final IIcon firstIcon = new TaughtIcon( this.getChannelTex( channels, false ).getIcon(), -0.2f ); - final IIcon secondIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); - - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); - Tessellator.instance.setColorOpaque_I( myColor.blackVariant ); - rh.setTexture( firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - - Tessellator.instance.setColorOpaque_I( myColor.whiteVariant ); - rh.setTexture( secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - } - } - - IIcon getSmartTexture( final AEColor c ) - { - switch( c ) - { - case Black: - return CableBusTextures.MESmart_Black.getIcon(); - case Blue: - return CableBusTextures.MESmart_Blue.getIcon(); - case Brown: - return CableBusTextures.MESmart_Brown.getIcon(); - case Cyan: - return CableBusTextures.MESmart_Cyan.getIcon(); - case Gray: - return CableBusTextures.MESmart_Gray.getIcon(); - case Green: - return CableBusTextures.MESmart_Green.getIcon(); - case LightBlue: - return CableBusTextures.MESmart_LightBlue.getIcon(); - case LightGray: - return CableBusTextures.MESmart_LightGrey.getIcon(); - case Lime: - return CableBusTextures.MESmart_Lime.getIcon(); - case Magenta: - return CableBusTextures.MESmart_Magenta.getIcon(); - case Orange: - return CableBusTextures.MESmart_Orange.getIcon(); - case Pink: - return CableBusTextures.MESmart_Pink.getIcon(); - case Purple: - return CableBusTextures.MESmart_Purple.getIcon(); - case Red: - return CableBusTextures.MESmart_Red.getIcon(); - case White: - return CableBusTextures.MESmart_White.getIcon(); - case Yellow: - return CableBusTextures.MESmart_Yellow.getIcon(); - default: - } - - final IParts parts = AEApi.instance().definitions().parts(); - final ItemStack smartCableStack = parts.cableSmart().stack( AEColor.Transparent, 1 ); - - return parts.cableCovered().item( AEColor.Transparent ).getIconIndex( smartCableStack ); - } - - @SideOnly( Side.CLIENT ) - protected void setSmartConnectionRotations( final ForgeDirection of, final RenderBlocks renderer ) - { - switch( of ) - { - case UP: - case DOWN: - renderer.uvRotateTop = 0; - renderer.uvRotateBottom = 0; - renderer.uvRotateSouth = 3; - renderer.uvRotateEast = 3; - break; - case NORTH: - case SOUTH: - renderer.uvRotateTop = 3; - renderer.uvRotateBottom = 3; - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 2; - renderer.uvRotateWest = 1; - break; - case EAST: - case WEST: - renderer.uvRotateEast = 2; - renderer.uvRotateWest = 1; - renderer.uvRotateBottom = 2; - renderer.uvRotateTop = 1; - renderer.uvRotateSouth = 3; - renderer.uvRotateNorth = 0; - break; - default: - break; - } - } - - protected CableBusTextures getChannelTex( int i, final boolean b ) - { - if( !this.powered ) - { - i = 0; - } - - if( b ) - { - switch( i ) - { - default: - return CableBusTextures.Channels10; - case 5: - return CableBusTextures.Channels11; - case 6: - return CableBusTextures.Channels12; - case 7: - return CableBusTextures.Channels13; - case 8: - return CableBusTextures.Channels14; - } - } - else - { - switch( i ) - { - case 0: - return CableBusTextures.Channels00; - case 1: - return CableBusTextures.Channels01; - case 2: - return CableBusTextures.Channels02; - case 3: - return CableBusTextures.Channels03; - default: - return CableBusTextures.Channels04; - } - } - } - - @SideOnly( Side.CLIENT ) - protected void renderAllFaces( final AEBaseBlock blk, final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setBounds( (float) renderer.renderMinX * 16.0f, (float) renderer.renderMinY * 16.0f, (float) renderer.renderMinZ * 16.0f, (float) renderer.renderMaxX * 16.0f, (float) renderer.renderMaxY * 16.0f, (float) renderer.renderMaxZ * 16.0f ); - rh.renderFace( x, y, z, blk.getRendererInstance().getTexture( ForgeDirection.WEST ), ForgeDirection.WEST, renderer ); - rh.renderFace( x, y, z, blk.getRendererInstance().getTexture( ForgeDirection.EAST ), ForgeDirection.EAST, renderer ); - rh.renderFace( x, y, z, blk.getRendererInstance().getTexture( ForgeDirection.NORTH ), ForgeDirection.NORTH, renderer ); - rh.renderFace( x, y, z, blk.getRendererInstance().getTexture( ForgeDirection.SOUTH ), ForgeDirection.SOUTH, renderer ); - rh.renderFace( x, y, z, blk.getRendererInstance().getTexture( ForgeDirection.DOWN ), ForgeDirection.DOWN, renderer ); - rh.renderFace( x, y, z, blk.getRendererInstance().getTexture( ForgeDirection.UP ), ForgeDirection.UP, renderer ); - } - - int[] getChannelsOnSide() - { - return this.channelsOnSide; - } - - EnumSet getConnections() - { - return this.connections; - } - - void setConnections( final EnumSet connections ) - { - this.connections = connections; - } +public class PartCable extends AEBasePart implements IPartCable { + + private final int[] channelsOnSide = {0, 0, 0, 0, 0, 0}; + + private EnumSet connections = EnumSet.noneOf(ForgeDirection.class); + private boolean powered = false; + + public PartCable(final ItemStack is) { + super(is); + this.getProxy().setFlags(GridFlags.PREFERRED); + this.getProxy().setIdlePowerUsage(0.0); + this.getProxy().setColor(AEColor.values()[((ItemMultiPart) is.getItem()).variantOf(is.getItemDamage())]); + } + + @Override + public BusSupport supportsBuses() { + return BusSupport.CABLE; + } + + @Override + public AEColor getCableColor() { + return this.getProxy().getColor(); + } + + @Override + public AECableType getCableConnectionType() { + return AECableType.GLASS; + } + + @Override + public boolean changeColor(final AEColor newColor, final EntityPlayer who) { + if (this.getCableColor() != newColor) { + ItemStack newPart = null; + + final IParts parts = AEApi.instance().definitions().parts(); + + if (this.getCableConnectionType() == AECableType.GLASS) { + newPart = parts.cableGlass().stack(newColor, 1); + } else if (this.getCableConnectionType() == AECableType.COVERED) { + newPart = parts.cableCovered().stack(newColor, 1); + } else if (this.getCableConnectionType() == AECableType.SMART) { + newPart = parts.cableSmart().stack(newColor, 1); + } else if (this.getCableConnectionType() == AECableType.DENSE) { + newPart = parts.cableDense().stack(newColor, 1); + } else if (this.getCableConnectionType() == AECableType.DENSE_COVERED) { + newPart = parts.cableDenseCovered().stack(newColor, 1); + } else if (this.getCableConnectionType() == AECableType.ULTRA_DENSE) { + newPart = parts.cableDense().stack(newColor, 1); + } else if (this.getCableConnectionType() == AECableType.ULTRA_DENSE_SMART) { + newPart = parts.cableDenseCovered().stack(newColor, 1); + } + + boolean hasPermission = true; + + try { + hasPermission = this.getProxy().getSecurity().hasPermission(who, SecurityPermissions.BUILD); + } catch (final GridAccessException e) { + // :P + } + + if (newPart != null && hasPermission) { + if (Platform.isClient()) { + return true; + } + + this.getHost().removePart(ForgeDirection.UNKNOWN, true); + this.getHost().addPart(newPart, ForgeDirection.UNKNOWN, who); + return true; + } + } + return false; + } + + @Override + public void setValidSides(final EnumSet sides) { + this.getProxy().setValidSides(sides); + } + + @Override + public boolean isConnected(final ForgeDirection side) { + return this.getConnections().contains(side); + } + + public void markForUpdate() { + this.getHost().markForUpdate(); + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(6.0, 6.0, 6.0, 10.0, 10.0, 10.0); + + if (Platform.isServer()) { + final IGridNode n = this.getGridNode(); + if (n != null) { + this.setConnections(n.getConnectedSides()); + } else { + this.getConnections().clear(); + } + } + + final IPartHost ph = this.getHost(); + if (ph != null) { + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart p = ph.getPart(dir); + if (p instanceof IGridHost) { + final double dist = p.cableConnectionRenderTo(); + + if (dist > 8) { + continue; + } + + switch (dir) { + case DOWN: + bch.addBox(6.0, dist, 6.0, 10.0, 6.0, 10.0); + break; + case EAST: + bch.addBox(10.0, 6.0, 6.0, 16.0 - dist, 10.0, 10.0); + break; + case NORTH: + bch.addBox(6.0, 6.0, dist, 10.0, 10.0, 6.0); + break; + case SOUTH: + bch.addBox(6.0, 6.0, 10.0, 10.0, 10.0, 16.0 - dist); + break; + case UP: + bch.addBox(6.0, 10.0, 6.0, 10.0, 16.0 - dist, 10.0); + break; + case WEST: + bch.addBox(dist, 6.0, 6.0, 6.0, 10.0, 10.0); + break; + default: + } + } + } + } + + for (final ForgeDirection of : this.getConnections()) { + switch (of) { + case DOWN: + bch.addBox(6.0, 0.0, 6.0, 10.0, 6.0, 10.0); + break; + case EAST: + bch.addBox(10.0, 6.0, 6.0, 16.0, 10.0, 10.0); + break; + case NORTH: + bch.addBox(6.0, 6.0, 0.0, 10.0, 10.0, 6.0); + break; + case SOUTH: + bch.addBox(6.0, 6.0, 10.0, 10.0, 10.0, 16.0); + break; + case UP: + bch.addBox(6.0, 10.0, 6.0, 10.0, 16.0, 10.0); + break; + case WEST: + bch.addBox(0.0, 6.0, 6.0, 6.0, 10.0, 10.0); + break; + default: + } + } + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + GL11.glTranslated(-0.0, -0.0, 0.3); + + rh.setTexture(this.getTexture(this.getCableColor())); + rh.setBounds(6.0f, 6.0f, 2.0f, 10.0f, 10.0f, 14.0f); + rh.renderInventoryBox(renderer); + rh.setTexture(null); + } + + public IIcon getTexture(final AEColor c) { + return this.getGlassTexture(c); + } + + public IIcon getGlassTexture(final AEColor c) { + switch (c) { + case Black: + return CableBusTextures.MECable_Black.getIcon(); + case Blue: + return CableBusTextures.MECable_Blue.getIcon(); + case Brown: + return CableBusTextures.MECable_Brown.getIcon(); + case Cyan: + return CableBusTextures.MECable_Cyan.getIcon(); + case Gray: + return CableBusTextures.MECable_Grey.getIcon(); + case Green: + return CableBusTextures.MECable_Green.getIcon(); + case LightBlue: + return CableBusTextures.MECable_LightBlue.getIcon(); + case LightGray: + return CableBusTextures.MECable_LightGrey.getIcon(); + case Lime: + return CableBusTextures.MECable_Lime.getIcon(); + case Magenta: + return CableBusTextures.MECable_Magenta.getIcon(); + case Orange: + return CableBusTextures.MECable_Orange.getIcon(); + case Pink: + return CableBusTextures.MECable_Pink.getIcon(); + case Purple: + return CableBusTextures.MECable_Purple.getIcon(); + case Red: + return CableBusTextures.MECable_Red.getIcon(); + case White: + return CableBusTextures.MECable_White.getIcon(); + case Yellow: + return CableBusTextures.MECable_Yellow.getIcon(); + default: + } + + final AEColoredItemDefinition glassCable = + AEApi.instance().definitions().parts().cableGlass(); + final ItemStack glassCableStack = glassCable.stack(AEColor.Transparent, 1); + + return glassCable.item(AEColor.Transparent).getIconIndex(glassCableStack); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + this.setRenderCache(rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache())); + boolean useCovered = false; + boolean requireDetailed = false; + + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart p = this.getHost().getPart(dir); + if (p instanceof IGridHost) { + final IGridHost igh = (IGridHost) p; + final AECableType type = igh.getCableConnectionType(dir.getOpposite()); + if (type == AECableType.COVERED || type == AECableType.SMART) { + useCovered = true; + break; + } + } else if (this.getConnections().contains(dir)) { + final TileEntity te = + this.getTile().getWorldObj().getTileEntity(x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ); + final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; + final IGridHost gh = te instanceof IGridHost ? (IGridHost) te : null; + if (partHost == null && gh != null && gh.getCableConnectionType(dir) != AECableType.GLASS) { + requireDetailed = true; + } + } + } + + if (useCovered) { + rh.setTexture(this.getCoveredTexture(this.getCableColor())); + } else { + rh.setTexture(this.getTexture(this.getCableColor())); + } + + final IPartHost ph = this.getHost(); + for (final ForgeDirection of : EnumSet.complementOf(this.getConnections())) { + final IPart bp = ph.getPart(of); + if (bp instanceof IGridHost) { + final int len = bp.cableConnectionRenderTo(); + if (len < 8) { + switch (of) { + case DOWN: + rh.setBounds(6, len, 6, 10, 6, 10); + break; + case EAST: + rh.setBounds(10, 6, 6, 16 - len, 10, 10); + break; + case NORTH: + rh.setBounds(6, 6, len, 10, 10, 6); + break; + case SOUTH: + rh.setBounds(6, 6, 10, 10, 10, 16 - len); + break; + case UP: + rh.setBounds(6, 10, 6, 10, 16 - len, 10); + break; + case WEST: + rh.setBounds(len, 6, 6, 6, 10, 10); + break; + default: + continue; + } + rh.renderBlock(x, y, z, renderer); + } + } + } + + if (this.getConnections().size() != 2 + || !this.nonLinear(this.getConnections()) + || useCovered + || requireDetailed) { + if (useCovered) { + rh.setBounds(5, 5, 5, 11, 11, 11); + rh.renderBlock(x, y, z, renderer); + } else { + rh.setBounds(6, 6, 6, 10, 10, 10); + rh.renderBlock(x, y, z, renderer); + } + + for (final ForgeDirection of : this.getConnections()) { + this.renderGlassConnection(x, y, z, rh, renderer, of); + } + } else { + final IIcon def = this.getTexture(this.getCableColor()); + rh.setTexture(def); + + for (final ForgeDirection of : this.getConnections()) { + rh.setFacesToRender(EnumSet.complementOf(EnumSet.of(of, of.getOpposite()))); + switch (of) { + case DOWN: + case UP: + renderer.setRenderBounds(6 / 16.0, 0, 6 / 16.0, 10 / 16.0, 16 / 16.0, 10 / 16.0); + break; + case EAST: + case WEST: + renderer.uvRotateEast = renderer.uvRotateWest = 1; + renderer.uvRotateBottom = renderer.uvRotateTop = 1; + renderer.setRenderBounds(0, 6 / 16.0, 6 / 16.0, 16 / 16.0, 10 / 16.0, 10 / 16.0); + break; + case NORTH: + case SOUTH: + renderer.uvRotateNorth = renderer.uvRotateSouth = 1; + renderer.setRenderBounds(6 / 16.0, 6 / 16.0, 0, 10 / 16.0, 10 / 16.0, 16 / 16.0); + break; + default: + } + } + + rh.renderBlockCurrentBounds(x, y, z, renderer); + } + + rh.setFacesToRender(EnumSet.allOf(ForgeDirection.class)); + rh.setTexture(null); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + + if (Platform.isServer()) { + final IGridNode node = this.getGridNode(); + + if (node != null) { + int howMany = 0; + for (final IGridConnection gc : node.getConnections()) { + howMany = Math.max(gc.getUsedChannels(), howMany); + } + + data.setShort("usedChannels", (short) howMany); + } + } + } + + @Override + public void writeToStream(final ByteBuf data) throws IOException { + int cs = 0; + int sideOut = 0; + + final IGridNode n = this.getGridNode(); + if (n != null) { + for (final ForgeDirection thisSide : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getHost().getPart(thisSide); + if (part != null) { + if (part.getGridNode() != null) { + final IReadOnlyCollection set = + part.getGridNode().getConnections(); + for (final IGridConnection gc : set) { + if (this.getProxy().getNode().hasFlag(GridFlags.ULTRA_DENSE_CAPACITY) + && gc.getOtherSide(this.getProxy().getNode()) + .hasFlag(GridFlags.ULTRA_DENSE_CAPACITY)) { + sideOut |= (gc.getUsedChannels() / 16) << (4 * thisSide.ordinal()); + } else if (this.getProxy().getNode().hasFlag(GridFlags.DENSE_CAPACITY) + && gc.getOtherSide(this.getProxy().getNode()) + .hasFlag(GridFlags.DENSE_CAPACITY)) { + sideOut |= (gc.getUsedChannels() / 4) << (4 * thisSide.ordinal()); + } else { + sideOut |= (gc.getUsedChannels()) << (4 * thisSide.ordinal()); + } + } + } + } + } + + for (final IGridConnection gc : n.getConnections()) { + final ForgeDirection side = gc.getDirection(n); + if (side != ForgeDirection.UNKNOWN) { + final boolean isTier3a = this.getProxy().getNode().hasFlag(GridFlags.ULTRA_DENSE_CAPACITY); + final boolean isTier3b = + gc.getOtherSide(this.getProxy().getNode()).hasFlag(GridFlags.ULTRA_DENSE_CAPACITY); + + final boolean isTier2a = this.getProxy().getNode().hasFlag(GridFlags.DENSE_CAPACITY); + final boolean isTier2b = + gc.getOtherSide(this.getProxy().getNode()).hasFlag(GridFlags.DENSE_CAPACITY); + + if (isTier3a && isTier3b) { + sideOut |= (gc.getUsedChannels() / 16) << (4 * side.ordinal()); + } else if ((isTier3a || isTier2a) && (isTier2b || isTier3b)) { + sideOut |= (gc.getUsedChannels() / 4) << (4 * side.ordinal()); + } else { + sideOut |= gc.getUsedChannels() << (4 * side.ordinal()); + } + cs |= (1 << side.ordinal()); + } + } + } + + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + cs |= (1 << ForgeDirection.UNKNOWN.ordinal()); + } + } catch (final GridAccessException e) { + // aww... + } + + data.writeByte((byte) cs); + data.writeInt(sideOut); + } + + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + final int cs = data.readByte(); + final int sideOut = data.readInt(); + + final EnumSet myC = this.getConnections().clone(); + final boolean wasPowered = this.powered; + this.powered = false; + boolean channelsChanged = false; + + for (final ForgeDirection d : ForgeDirection.values()) { + if (d != ForgeDirection.UNKNOWN) { + final int ch = (sideOut >> (d.ordinal() * 4)) & 0xF; + if (ch != this.getChannelsOnSide()[d.ordinal()]) { + channelsChanged = true; + this.getChannelsOnSide()[d.ordinal()] = ch; + } + } + + if (d == ForgeDirection.UNKNOWN) { + final int id = 1 << d.ordinal(); + if (id == (cs & id)) { + this.powered = true; + } + } else { + final int id = 1 << d.ordinal(); + if (id == (cs & id)) { + this.getConnections().add(d); + } else { + this.getConnections().remove(d); + } + } + } + + return !myC.equals(this.getConnections()) || wasPowered != this.powered || channelsChanged; + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getBreakingTexture() { + return this.getTexture(this.getCableColor()); + } + + public IIcon getCoveredTexture(final AEColor c) { + switch (c) { + case Black: + return CableBusTextures.MECovered_Black.getIcon(); + case Blue: + return CableBusTextures.MECovered_Blue.getIcon(); + case Brown: + return CableBusTextures.MECovered_Brown.getIcon(); + case Cyan: + return CableBusTextures.MECovered_Cyan.getIcon(); + case Gray: + return CableBusTextures.MECovered_Gray.getIcon(); + case Green: + return CableBusTextures.MECovered_Green.getIcon(); + case LightBlue: + return CableBusTextures.MECovered_LightBlue.getIcon(); + case LightGray: + return CableBusTextures.MECovered_LightGrey.getIcon(); + case Lime: + return CableBusTextures.MECovered_Lime.getIcon(); + case Magenta: + return CableBusTextures.MECovered_Magenta.getIcon(); + case Orange: + return CableBusTextures.MECovered_Orange.getIcon(); + case Pink: + return CableBusTextures.MECovered_Pink.getIcon(); + case Purple: + return CableBusTextures.MECovered_Purple.getIcon(); + case Red: + return CableBusTextures.MECovered_Red.getIcon(); + case White: + return CableBusTextures.MECovered_White.getIcon(); + case Yellow: + return CableBusTextures.MECovered_Yellow.getIcon(); + default: + } + + final AEColoredItemDefinition coveredCable = + AEApi.instance().definitions().parts().cableCovered(); + final ItemStack coveredCableStack = coveredCable.stack(AEColor.Transparent, 1); + + return coveredCable.item(AEColor.Transparent).getIconIndex(coveredCableStack); + } + + protected boolean nonLinear(final EnumSet sides) { + return (sides.contains(ForgeDirection.EAST) && sides.contains(ForgeDirection.WEST)) + || (sides.contains(ForgeDirection.NORTH) && sides.contains(ForgeDirection.SOUTH)) + || (sides.contains(ForgeDirection.UP) && sides.contains(ForgeDirection.DOWN)); + } + + @SideOnly(Side.CLIENT) + private void renderGlassConnection( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer, + final ForgeDirection of) { + final TileEntity te = + this.getTile().getWorldObj().getTileEntity(x + of.offsetX, y + of.offsetY, z + of.offsetZ); + final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; + final IGridHost gh = te instanceof IGridHost ? (IGridHost) te : null; + + rh.setFacesToRender(EnumSet.complementOf(EnumSet.of(of))); + + if (gh != null + && partHost != null + && gh.getCableConnectionType(of.getOpposite()) == AECableType.GLASS + && partHost.getColor() != AEColor.Transparent + && partHost.getPart(of.getOpposite()) == null) { + rh.setTexture(this.getTexture(partHost.getColor())); + } else if (partHost == null && gh != null && gh.getCableConnectionType(of.getOpposite()) != AECableType.GLASS) { + rh.setTexture(this.getCoveredTexture(this.getCableColor())); + switch (of) { + case DOWN: + rh.setBounds(5, 0, 5, 11, 4, 11); + break; + case EAST: + rh.setBounds(12, 5, 5, 16, 11, 11); + break; + case NORTH: + rh.setBounds(5, 5, 0, 11, 11, 4); + break; + case SOUTH: + rh.setBounds(5, 5, 12, 11, 11, 16); + break; + case UP: + rh.setBounds(5, 12, 5, 11, 16, 11); + break; + case WEST: + rh.setBounds(0, 5, 5, 4, 11, 11); + break; + default: + return; + } + + rh.renderBlock(x, y, z, renderer); + rh.setTexture(this.getTexture(this.getCableColor())); + } else { + rh.setTexture(this.getTexture(this.getCableColor())); + } + + switch (of) { + case DOWN: + rh.setBounds(6, 0, 6, 10, 6, 10); + break; + case EAST: + rh.setBounds(10, 6, 6, 16, 10, 10); + break; + case NORTH: + rh.setBounds(6, 6, 0, 10, 10, 6); + break; + case SOUTH: + rh.setBounds(6, 6, 10, 10, 10, 16); + break; + case UP: + rh.setBounds(6, 10, 6, 10, 16, 10); + break; + case WEST: + rh.setBounds(0, 6, 6, 6, 10, 10); + break; + default: + return; + } + + rh.renderBlock(x, y, z, renderer); + rh.setFacesToRender(EnumSet.allOf(ForgeDirection.class)); + } + + @SideOnly(Side.CLIENT) + void renderCoveredConnection( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer, + final int channels, + final ForgeDirection of) { + final TileEntity te = + this.getTile().getWorldObj().getTileEntity(x + of.offsetX, y + of.offsetY, z + of.offsetZ); + final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; + final IGridHost ghh = te instanceof IGridHost ? (IGridHost) te : null; + + rh.setFacesToRender(EnumSet.complementOf(EnumSet.of(of))); + if (ghh != null + && partHost != null + && ghh.getCableConnectionType(of.getOpposite()) == AECableType.GLASS + && partHost.getPart(of.getOpposite()) == null + && partHost.getColor() != AEColor.Transparent) { + rh.setTexture(this.getGlassTexture(partHost.getColor())); + } else if (partHost == null + && ghh != null + && ghh.getCableConnectionType(of.getOpposite()) != AECableType.GLASS) { + rh.setTexture(this.getCoveredTexture(this.getCableColor())); + switch (of) { + case DOWN: + rh.setBounds(5, 0, 5, 11, 4, 11); + break; + case EAST: + rh.setBounds(12, 5, 5, 16, 11, 11); + break; + case NORTH: + rh.setBounds(5, 5, 0, 11, 11, 4); + break; + case SOUTH: + rh.setBounds(5, 5, 12, 11, 11, 16); + break; + case UP: + rh.setBounds(5, 12, 5, 11, 16, 11); + break; + case WEST: + rh.setBounds(0, 5, 5, 4, 11, 11); + break; + default: + return; + } + + rh.renderBlock(x, y, z, renderer); + + rh.setTexture(this.getTexture(this.getCableColor())); + } else if (ghh != null + && partHost != null + && ghh.getCableConnectionType(of.getOpposite()) == AECableType.COVERED + && partHost.getColor() != AEColor.Transparent + && partHost.getPart(of.getOpposite()) == null) { + rh.setTexture(this.getCoveredTexture(partHost.getColor())); + } else { + rh.setTexture(this.getCoveredTexture(this.getCableColor())); + } + + switch (of) { + case DOWN: + rh.setBounds(6, 0, 6, 10, 5, 10); + break; + case EAST: + rh.setBounds(11, 6, 6, 16, 10, 10); + break; + case NORTH: + rh.setBounds(6, 6, 0, 10, 10, 5); + break; + case SOUTH: + rh.setBounds(6, 6, 11, 10, 10, 16); + break; + case UP: + rh.setBounds(6, 11, 6, 10, 16, 10); + break; + case WEST: + rh.setBounds(0, 6, 6, 5, 10, 10); + break; + default: + return; + } + + rh.renderBlock(x, y, z, renderer); + rh.setFacesToRender(EnumSet.allOf(ForgeDirection.class)); + rh.setFacesToRender(EnumSet.allOf(ForgeDirection.class)); + } + + @SideOnly(Side.CLIENT) + void renderSmartConnection( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer, + final int channels, + final ForgeDirection of) { + final TileEntity te = + this.getTile().getWorldObj().getTileEntity(x + of.offsetX, y + of.offsetY, z + of.offsetZ); + final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; + final IGridHost ghh = te instanceof IGridHost ? (IGridHost) te : null; + AEColor myColor = this.getCableColor(); + + rh.setFacesToRender(EnumSet.complementOf(EnumSet.of(of))); + + boolean isGlass = false; + if (ghh != null + && partHost != null + && ghh.getCableConnectionType(of.getOpposite()) == AECableType.GLASS + && partHost.getPart(of.getOpposite()) == null + && partHost.getColor() != AEColor.Transparent) { + isGlass = true; + rh.setTexture(this.getGlassTexture(myColor = partHost.getColor())); + } else if (partHost == null + && ghh != null + && ghh.getCableConnectionType(of.getOpposite()) != AECableType.GLASS) { + rh.setTexture(this.getSmartTexture(myColor)); + switch (of) { + case DOWN: + rh.setBounds(5, 0, 5, 11, 4, 11); + break; + case EAST: + rh.setBounds(12, 5, 5, 16, 11, 11); + break; + case NORTH: + rh.setBounds(5, 5, 0, 11, 11, 4); + break; + case SOUTH: + rh.setBounds(5, 5, 12, 11, 11, 16); + break; + case UP: + rh.setBounds(5, 12, 5, 11, 16, 11); + break; + case WEST: + rh.setBounds(0, 5, 5, 4, 11, 11); + break; + default: + return; + } + rh.renderBlock(x, y, z, renderer); + + this.setSmartConnectionRotations(of, renderer); + final IIcon firstIcon = + new TaughtIcon(this.getChannelTex(channels, false).getIcon(), -0.2f); + final IIcon secondIcon = + new TaughtIcon(this.getChannelTex(channels, true).getIcon(), -0.2f); + + if (of == ForgeDirection.EAST || of == ForgeDirection.WEST) { + final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); + final FlippableIcon ico = blk.getRendererInstance().getTexture(ForgeDirection.EAST); + ico.setFlip(false, true); + } + + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); + Tessellator.instance.setColorOpaque_I(myColor.blackVariant); + rh.setTexture(firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + + Tessellator.instance.setColorOpaque_I(myColor.whiteVariant); + rh.setTexture(secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + + renderer.uvRotateBottom = renderer.uvRotateEast = + renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + + rh.setTexture(this.getTexture(this.getCableColor())); + } else if (ghh != null + && partHost != null + && ghh.getCableConnectionType(of.getOpposite()) != AECableType.GLASS + && partHost.getColor() != AEColor.Transparent + && partHost.getPart(of.getOpposite()) == null) { + rh.setTexture(this.getSmartTexture(myColor = partHost.getColor())); + } else { + rh.setTexture(this.getSmartTexture(this.getCableColor())); + } + + switch (of) { + case DOWN: + rh.setBounds(6, 0, 6, 10, 5, 10); + break; + case EAST: + rh.setBounds(11, 6, 6, 16, 10, 10); + break; + case NORTH: + rh.setBounds(6, 6, 0, 10, 10, 5); + break; + case SOUTH: + rh.setBounds(6, 6, 11, 10, 10, 16); + break; + case UP: + rh.setBounds(6, 11, 6, 10, 16, 10); + break; + case WEST: + rh.setBounds(0, 6, 6, 5, 10, 10); + break; + default: + return; + } + + rh.renderBlock(x, y, z, renderer); + rh.setFacesToRender(EnumSet.allOf(ForgeDirection.class)); + + if (!isGlass) { + this.setSmartConnectionRotations(of, renderer); + + final IIcon firstIcon = + new TaughtIcon(this.getChannelTex(channels, false).getIcon(), -0.2f); + final IIcon secondIcon = + new TaughtIcon(this.getChannelTex(channels, true).getIcon(), -0.2f); + + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); + Tessellator.instance.setColorOpaque_I(myColor.blackVariant); + rh.setTexture(firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + + Tessellator.instance.setColorOpaque_I(myColor.whiteVariant); + rh.setTexture(secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + + renderer.uvRotateBottom = renderer.uvRotateEast = + renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + } + } + + IIcon getSmartTexture(final AEColor c) { + switch (c) { + case Black: + return CableBusTextures.MESmart_Black.getIcon(); + case Blue: + return CableBusTextures.MESmart_Blue.getIcon(); + case Brown: + return CableBusTextures.MESmart_Brown.getIcon(); + case Cyan: + return CableBusTextures.MESmart_Cyan.getIcon(); + case Gray: + return CableBusTextures.MESmart_Gray.getIcon(); + case Green: + return CableBusTextures.MESmart_Green.getIcon(); + case LightBlue: + return CableBusTextures.MESmart_LightBlue.getIcon(); + case LightGray: + return CableBusTextures.MESmart_LightGrey.getIcon(); + case Lime: + return CableBusTextures.MESmart_Lime.getIcon(); + case Magenta: + return CableBusTextures.MESmart_Magenta.getIcon(); + case Orange: + return CableBusTextures.MESmart_Orange.getIcon(); + case Pink: + return CableBusTextures.MESmart_Pink.getIcon(); + case Purple: + return CableBusTextures.MESmart_Purple.getIcon(); + case Red: + return CableBusTextures.MESmart_Red.getIcon(); + case White: + return CableBusTextures.MESmart_White.getIcon(); + case Yellow: + return CableBusTextures.MESmart_Yellow.getIcon(); + default: + } + + final IParts parts = AEApi.instance().definitions().parts(); + final ItemStack smartCableStack = parts.cableSmart().stack(AEColor.Transparent, 1); + + return parts.cableCovered().item(AEColor.Transparent).getIconIndex(smartCableStack); + } + + @SideOnly(Side.CLIENT) + protected void setSmartConnectionRotations(final ForgeDirection of, final RenderBlocks renderer) { + switch (of) { + case UP: + case DOWN: + renderer.uvRotateTop = 0; + renderer.uvRotateBottom = 0; + renderer.uvRotateSouth = 3; + renderer.uvRotateEast = 3; + break; + case NORTH: + case SOUTH: + renderer.uvRotateTop = 3; + renderer.uvRotateBottom = 3; + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 2; + renderer.uvRotateWest = 1; + break; + case EAST: + case WEST: + renderer.uvRotateEast = 2; + renderer.uvRotateWest = 1; + renderer.uvRotateBottom = 2; + renderer.uvRotateTop = 1; + renderer.uvRotateSouth = 3; + renderer.uvRotateNorth = 0; + break; + default: + break; + } + } + + protected CableBusTextures getChannelTex(int i, final boolean b) { + if (!this.powered) { + i = 0; + } + + if (b) { + switch (i) { + default: + return CableBusTextures.Channels10; + case 5: + return CableBusTextures.Channels11; + case 6: + return CableBusTextures.Channels12; + case 7: + return CableBusTextures.Channels13; + case 8: + return CableBusTextures.Channels14; + } + } else { + switch (i) { + case 0: + return CableBusTextures.Channels00; + case 1: + return CableBusTextures.Channels01; + case 2: + return CableBusTextures.Channels02; + case 3: + return CableBusTextures.Channels03; + default: + return CableBusTextures.Channels04; + } + } + } + + @SideOnly(Side.CLIENT) + protected void renderAllFaces( + final AEBaseBlock blk, + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer) { + rh.setBounds( + (float) renderer.renderMinX * 16.0f, + (float) renderer.renderMinY * 16.0f, + (float) renderer.renderMinZ * 16.0f, + (float) renderer.renderMaxX * 16.0f, + (float) renderer.renderMaxY * 16.0f, + (float) renderer.renderMaxZ * 16.0f); + rh.renderFace( + x, y, z, blk.getRendererInstance().getTexture(ForgeDirection.WEST), ForgeDirection.WEST, renderer); + rh.renderFace( + x, y, z, blk.getRendererInstance().getTexture(ForgeDirection.EAST), ForgeDirection.EAST, renderer); + rh.renderFace( + x, y, z, blk.getRendererInstance().getTexture(ForgeDirection.NORTH), ForgeDirection.NORTH, renderer); + rh.renderFace( + x, y, z, blk.getRendererInstance().getTexture(ForgeDirection.SOUTH), ForgeDirection.SOUTH, renderer); + rh.renderFace( + x, y, z, blk.getRendererInstance().getTexture(ForgeDirection.DOWN), ForgeDirection.DOWN, renderer); + rh.renderFace(x, y, z, blk.getRendererInstance().getTexture(ForgeDirection.UP), ForgeDirection.UP, renderer); + } + + int[] getChannelsOnSide() { + return this.channelsOnSide; + } + + EnumSet getConnections() { + return this.connections; + } + + void setConnections(final EnumSet connections) { + this.connections = connections; + } } diff --git a/src/main/java/appeng/parts/networking/PartCableCovered.java b/src/main/java/appeng/parts/networking/PartCableCovered.java index 64c8fefc56d..699ae81a756 100644 --- a/src/main/java/appeng/parts/networking/PartCableCovered.java +++ b/src/main/java/appeng/parts/networking/PartCableCovered.java @@ -18,7 +18,6 @@ package appeng.parts.networking; - import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.networking.events.MENetworkChannelsChanged; @@ -35,226 +34,197 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import java.util.EnumSet; - - -public class PartCableCovered extends PartCable -{ - @Reflected - public PartCableCovered( final ItemStack is ) - { - super( is ); - } - - @MENetworkEventSubscribe - public void channelUpdated( final MENetworkChannelsChanged c ) - { - this.getHost().markForUpdate(); - } - - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } - - @Override - public AECableType getCableConnectionType() - { - return AECableType.COVERED; - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 5.0, 5.0, 5.0, 11.0, 11.0, 11.0 ); - - if( Platform.isServer() ) - { - final IGridNode n = this.getGridNode(); - if( n != null ) - { - this.setConnections( n.getConnectedSides() ); - } - else - { - this.getConnections().clear(); - } - } - - for( final ForgeDirection of : this.getConnections() ) - { - switch( of ) - { - case DOWN: - bch.addBox( 5.0, 0.0, 5.0, 11.0, 5.0, 11.0 ); - break; - case EAST: - bch.addBox( 11.0, 5.0, 5.0, 16.0, 11.0, 11.0 ); - break; - case NORTH: - bch.addBox( 5.0, 5.0, 0.0, 11.0, 11.0, 5.0 ); - break; - case SOUTH: - bch.addBox( 5.0, 5.0, 11.0, 11.0, 11.0, 16.0 ); - break; - case UP: - bch.addBox( 5.0, 11.0, 5.0, 11.0, 16.0, 11.0 ); - break; - case WEST: - bch.addBox( 0.0, 5.0, 5.0, 5.0, 11.0, 11.0 ); - break; - default: - } - } - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - GL11.glTranslated( -0.0, -0.0, 0.3 ); - - rh.setBounds( 5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f ); - float offU = 0; - float offV = 9; - - OffsetIcon main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); - - for( final ForgeDirection side : EnumSet.of( ForgeDirection.UP, ForgeDirection.DOWN ) ) - { - rh.renderInventoryFace( main, side, renderer ); - } - - offU = 9; - offV = 0; - main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); - - for( final ForgeDirection side : EnumSet.of( ForgeDirection.EAST, ForgeDirection.WEST ) ) - { - rh.renderInventoryFace( main, side, renderer ); - } - - main = new OffsetIcon( this.getTexture( this.getCableColor() ), 0, 0 ); - - for( final ForgeDirection side : EnumSet.of( ForgeDirection.SOUTH, ForgeDirection.NORTH ) ) - { - rh.renderInventoryFace( main, side, renderer ); - } - - rh.setTexture( null ); - } - - @Override - public IIcon getTexture( final AEColor c ) - { - return this.getCoveredTexture( c ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( this.getTexture( this.getCableColor() ) ); - - final EnumSet sides = this.getConnections().clone(); - - boolean hasBuses = false; - final IPartHost ph = this.getHost(); - for( final ForgeDirection of : EnumSet.complementOf( this.getConnections() ) ) - { - final IPart bp = ph.getPart( of ); - if( bp instanceof IGridHost ) - { - if( of != ForgeDirection.UNKNOWN ) - { - sides.add( of ); - hasBuses = true; - } - - final int len = bp.cableConnectionRenderTo(); - if( len < 8 ) - { - switch( of ) - { - case DOWN: - rh.setBounds( 6, len, 6, 10, 5, 10 ); - break; - case EAST: - rh.setBounds( 11, 6, 6, 16 - len, 10, 10 ); - break; - case NORTH: - rh.setBounds( 6, 6, len, 10, 10, 5 ); - break; - case SOUTH: - rh.setBounds( 6, 6, 11, 10, 10, 16 - len ); - break; - case UP: - rh.setBounds( 6, 11, 6, 10, 16 - len, 10 ); - break; - case WEST: - rh.setBounds( len, 6, 6, 5, 10, 10 ); - break; - default: - continue; - } - rh.renderBlock( x, y, z, renderer ); - } - } - } - - if( sides.size() != 2 || !this.nonLinear( sides ) || hasBuses ) - { - for( final ForgeDirection of : this.getConnections() ) - { - this.renderCoveredConnection( x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of ); - } - - rh.setTexture( this.getTexture( this.getCableColor() ) ); - rh.setBounds( 5, 5, 5, 11, 11, 11 ); - rh.renderBlock( x, y, z, renderer ); - } - else - { - final IIcon def = this.getTexture( this.getCableColor() ); - final IIcon off = new OffsetIcon( def, 0, -12 ); - for( final ForgeDirection of : this.getConnections() ) - { - switch( of ) - { - case DOWN: - case UP: - rh.setTexture( def, def, off, off, off, off ); - renderer.setRenderBounds( 5 / 16.0, 0, 5 / 16.0, 11 / 16.0, 16 / 16.0, 11 / 16.0 ); - break; - case EAST: - case WEST: - rh.setTexture( off, off, off, off, def, def ); - renderer.uvRotateEast = renderer.uvRotateWest = 1; - renderer.uvRotateBottom = renderer.uvRotateTop = 1; - renderer.setRenderBounds( 0, 5 / 16.0, 5 / 16.0, 16 / 16.0, 11 / 16.0, 11 / 16.0 ); - break; - case NORTH: - case SOUTH: - rh.setTexture( off, off, def, def, off, off ); - renderer.uvRotateNorth = renderer.uvRotateSouth = 1; - renderer.setRenderBounds( 5 / 16.0, 5 / 16.0, 0, 11 / 16.0, 11 / 16.0, 16 / 16.0 ); - break; - default: - } - } - - rh.renderBlockCurrentBounds( x, y, z, renderer ); - } - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - rh.setTexture( null ); - } +public class PartCableCovered extends PartCable { + @Reflected + public PartCableCovered(final ItemStack is) { + super(is); + } + + @MENetworkEventSubscribe + public void channelUpdated(final MENetworkChannelsChanged c) { + this.getHost().markForUpdate(); + } + + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } + + @Override + public AECableType getCableConnectionType() { + return AECableType.COVERED; + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(5.0, 5.0, 5.0, 11.0, 11.0, 11.0); + + if (Platform.isServer()) { + final IGridNode n = this.getGridNode(); + if (n != null) { + this.setConnections(n.getConnectedSides()); + } else { + this.getConnections().clear(); + } + } + + for (final ForgeDirection of : this.getConnections()) { + switch (of) { + case DOWN: + bch.addBox(5.0, 0.0, 5.0, 11.0, 5.0, 11.0); + break; + case EAST: + bch.addBox(11.0, 5.0, 5.0, 16.0, 11.0, 11.0); + break; + case NORTH: + bch.addBox(5.0, 5.0, 0.0, 11.0, 11.0, 5.0); + break; + case SOUTH: + bch.addBox(5.0, 5.0, 11.0, 11.0, 11.0, 16.0); + break; + case UP: + bch.addBox(5.0, 11.0, 5.0, 11.0, 16.0, 11.0); + break; + case WEST: + bch.addBox(0.0, 5.0, 5.0, 5.0, 11.0, 11.0); + break; + default: + } + } + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + GL11.glTranslated(-0.0, -0.0, 0.3); + + rh.setBounds(5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f); + float offU = 0; + float offV = 9; + + OffsetIcon main = new OffsetIcon(this.getTexture(this.getCableColor()), offU, offV); + + for (final ForgeDirection side : EnumSet.of(ForgeDirection.UP, ForgeDirection.DOWN)) { + rh.renderInventoryFace(main, side, renderer); + } + + offU = 9; + offV = 0; + main = new OffsetIcon(this.getTexture(this.getCableColor()), offU, offV); + + for (final ForgeDirection side : EnumSet.of(ForgeDirection.EAST, ForgeDirection.WEST)) { + rh.renderInventoryFace(main, side, renderer); + } + + main = new OffsetIcon(this.getTexture(this.getCableColor()), 0, 0); + + for (final ForgeDirection side : EnumSet.of(ForgeDirection.SOUTH, ForgeDirection.NORTH)) { + rh.renderInventoryFace(main, side, renderer); + } + + rh.setTexture(null); + } + + @Override + public IIcon getTexture(final AEColor c) { + return this.getCoveredTexture(c); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + this.setRenderCache(rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache())); + rh.setTexture(this.getTexture(this.getCableColor())); + + final EnumSet sides = this.getConnections().clone(); + + boolean hasBuses = false; + final IPartHost ph = this.getHost(); + for (final ForgeDirection of : EnumSet.complementOf(this.getConnections())) { + final IPart bp = ph.getPart(of); + if (bp instanceof IGridHost) { + if (of != ForgeDirection.UNKNOWN) { + sides.add(of); + hasBuses = true; + } + + final int len = bp.cableConnectionRenderTo(); + if (len < 8) { + switch (of) { + case DOWN: + rh.setBounds(6, len, 6, 10, 5, 10); + break; + case EAST: + rh.setBounds(11, 6, 6, 16 - len, 10, 10); + break; + case NORTH: + rh.setBounds(6, 6, len, 10, 10, 5); + break; + case SOUTH: + rh.setBounds(6, 6, 11, 10, 10, 16 - len); + break; + case UP: + rh.setBounds(6, 11, 6, 10, 16 - len, 10); + break; + case WEST: + rh.setBounds(len, 6, 6, 5, 10, 10); + break; + default: + continue; + } + rh.renderBlock(x, y, z, renderer); + } + } + } + + if (sides.size() != 2 || !this.nonLinear(sides) || hasBuses) { + for (final ForgeDirection of : this.getConnections()) { + this.renderCoveredConnection(x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of); + } + + rh.setTexture(this.getTexture(this.getCableColor())); + rh.setBounds(5, 5, 5, 11, 11, 11); + rh.renderBlock(x, y, z, renderer); + } else { + final IIcon def = this.getTexture(this.getCableColor()); + final IIcon off = new OffsetIcon(def, 0, -12); + for (final ForgeDirection of : this.getConnections()) { + switch (of) { + case DOWN: + case UP: + rh.setTexture(def, def, off, off, off, off); + renderer.setRenderBounds(5 / 16.0, 0, 5 / 16.0, 11 / 16.0, 16 / 16.0, 11 / 16.0); + break; + case EAST: + case WEST: + rh.setTexture(off, off, off, off, def, def); + renderer.uvRotateEast = renderer.uvRotateWest = 1; + renderer.uvRotateBottom = renderer.uvRotateTop = 1; + renderer.setRenderBounds(0, 5 / 16.0, 5 / 16.0, 16 / 16.0, 11 / 16.0, 11 / 16.0); + break; + case NORTH: + case SOUTH: + rh.setTexture(off, off, def, def, off, off); + renderer.uvRotateNorth = renderer.uvRotateSouth = 1; + renderer.setRenderBounds(5 / 16.0, 5 / 16.0, 0, 11 / 16.0, 11 / 16.0, 16 / 16.0); + break; + default: + } + } + + rh.renderBlockCurrentBounds(x, y, z, renderer); + } + + renderer.uvRotateBottom = renderer.uvRotateEast = + renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + rh.setTexture(null); + } } diff --git a/src/main/java/appeng/parts/networking/PartCableGlass.java b/src/main/java/appeng/parts/networking/PartCableGlass.java index d9d738f248a..33573414909 100644 --- a/src/main/java/appeng/parts/networking/PartCableGlass.java +++ b/src/main/java/appeng/parts/networking/PartCableGlass.java @@ -18,16 +18,12 @@ package appeng.parts.networking; - import appeng.helpers.Reflected; import net.minecraft.item.ItemStack; - -public class PartCableGlass extends PartCable -{ - @Reflected - public PartCableGlass( final ItemStack is ) - { - super( is ); - } +public class PartCableGlass extends PartCable { + @Reflected + public PartCableGlass(final ItemStack is) { + super(is); + } } diff --git a/src/main/java/appeng/parts/networking/PartCableSmart.java b/src/main/java/appeng/parts/networking/PartCableSmart.java index f3e6e684476..2e68179fd02 100644 --- a/src/main/java/appeng/parts/networking/PartCableSmart.java +++ b/src/main/java/appeng/parts/networking/PartCableSmart.java @@ -18,7 +18,6 @@ package appeng.parts.networking; - import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.networking.events.MENetworkChannelsChanged; @@ -38,6 +37,7 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.item.ItemStack; @@ -45,330 +45,339 @@ import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import java.util.EnumSet; - - -public class PartCableSmart extends PartCable -{ - @Reflected - public PartCableSmart( final ItemStack is ) - { - super( is ); - } - - @MENetworkEventSubscribe - public void channelUpdated( final MENetworkChannelsChanged c ) - { - this.getHost().markForUpdate(); - } - - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } - - @Override - public AECableType getCableConnectionType() - { - return AECableType.SMART; - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 5.0, 5.0, 5.0, 11.0, 11.0, 11.0 ); - - if( Platform.isServer() ) - { - final IGridNode n = this.getGridNode(); - if( n != null ) - { - this.setConnections( n.getConnectedSides() ); - } - else - { - this.getConnections().clear(); - } - } - - for( final ForgeDirection of : this.getConnections() ) - { - switch( of ) - { - case DOWN: - bch.addBox( 5.0, 0.0, 5.0, 11.0, 5.0, 11.0 ); - break; - case EAST: - bch.addBox( 11.0, 5.0, 5.0, 16.0, 11.0, 11.0 ); - break; - case NORTH: - bch.addBox( 5.0, 5.0, 0.0, 11.0, 11.0, 5.0 ); - break; - case SOUTH: - bch.addBox( 5.0, 5.0, 11.0, 11.0, 11.0, 16.0 ); - break; - case UP: - bch.addBox( 5.0, 11.0, 5.0, 11.0, 16.0, 11.0 ); - break; - case WEST: - bch.addBox( 0.0, 5.0, 5.0, 5.0, 11.0, 11.0 ); - break; - default: - } - } - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - GL11.glTranslated( -0.0, -0.0, 0.3 ); - - float offU = 0; - float offV = 9; - - OffsetIcon main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); - OffsetIcon ch1 = new OffsetIcon( this.getChannelTex( 4, false ).getIcon(), offU, offV ); - OffsetIcon ch2 = new OffsetIcon( this.getChannelTex( 4, true ).getIcon(), offU, offV ); - - for( final ForgeDirection side : EnumSet.of( ForgeDirection.UP, ForgeDirection.DOWN ) ) - { - rh.setBounds( 5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f ); - rh.renderInventoryFace( main, side, renderer ); - rh.renderInventoryFace( ch1, side, renderer ); - rh.renderInventoryFace( ch2, side, renderer ); - } - - offU = 9; - offV = 0; - main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); - ch1 = new OffsetIcon( this.getChannelTex( 4, false ).getIcon(), offU, offV ); - ch2 = new OffsetIcon( this.getChannelTex( 4, true ).getIcon(), offU, offV ); - - for( final ForgeDirection side : EnumSet.of( ForgeDirection.EAST, ForgeDirection.WEST ) ) - { - rh.setBounds( 5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f ); - rh.renderInventoryFace( main, side, renderer ); - rh.renderInventoryFace( ch1, side, renderer ); - rh.renderInventoryFace( ch2, side, renderer ); - } - - main = new OffsetIcon( this.getTexture( this.getCableColor() ), 0, 0 ); - ch1 = new OffsetIcon( this.getChannelTex( 4, false ).getIcon(), 0, 0 ); - ch2 = new OffsetIcon( this.getChannelTex( 4, true ).getIcon(), 0, 0 ); - - for( final ForgeDirection side : EnumSet.of( ForgeDirection.SOUTH, ForgeDirection.NORTH ) ) - { - rh.setBounds( 5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f ); - rh.renderInventoryFace( main, side, renderer ); - rh.renderInventoryFace( ch1, side, renderer ); - rh.renderInventoryFace( ch2, side, renderer ); - } - - rh.setTexture( null ); - } - - @Override - public IIcon getTexture( final AEColor c ) - { - return this.getSmartTexture( c ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( this.getTexture( this.getCableColor() ) ); - - final EnumSet sides = this.getConnections().clone(); - - boolean hasBuses = false; - final IPartHost ph = this.getHost(); - for( final ForgeDirection of : EnumSet.complementOf( this.getConnections() ) ) - { - final IPart bp = ph.getPart( of ); - if( bp instanceof IGridHost ) - { - if( of != ForgeDirection.UNKNOWN ) - { - sides.add( of ); - hasBuses = true; - } - - final int len = bp.cableConnectionRenderTo(); - if( len < 8 ) - { - switch( of ) - { - case DOWN: - rh.setBounds( 6, len, 6, 10, 5, 10 ); - break; - case EAST: - rh.setBounds( 11, 6, 6, 16 - len, 10, 10 ); - break; - case NORTH: - rh.setBounds( 6, 6, len, 10, 10, 5 ); - break; - case SOUTH: - rh.setBounds( 6, 6, 11, 10, 10, 16 - len ); - break; - case UP: - rh.setBounds( 6, 11, 6, 10, 16 - len, 10 ); - break; - case WEST: - rh.setBounds( len, 6, 6, 5, 10, 10 ); - break; - default: - continue; - } - rh.renderBlock( x, y, z, renderer ); - - this.setSmartConnectionRotations( of, renderer ); - final IIcon firstIcon = new TaughtIcon( this.getChannelTex( this.getChannelsOnSide()[of.ordinal()], false ).getIcon(), -0.2f ); - final IIcon secondIcon = new TaughtIcon( this.getChannelTex( this.getChannelsOnSide()[of.ordinal()], true ).getIcon(), -0.2f ); - - if( of == ForgeDirection.EAST || of == ForgeDirection.WEST ) - { - final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); - final FlippableIcon ico = blk.getRendererInstance().getTexture( ForgeDirection.EAST ); - ico.setFlip( false, true ); - } - - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); - Tessellator.instance.setColorOpaque_I( this.getCableColor().blackVariant ); - rh.setTexture( firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - - Tessellator.instance.setColorOpaque_I( this.getCableColor().whiteVariant ); - rh.setTexture( secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } - } - } - - if( sides.size() != 2 || !this.nonLinear( sides ) || hasBuses ) - { - for( final ForgeDirection of : this.getConnections() ) - { - this.renderSmartConnection( x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of ); - } - - rh.setTexture( this.getCoveredTexture( this.getCableColor() ) ); - rh.setBounds( 5, 5, 5, 11, 11, 11 ); - rh.renderBlock( x, y, z, renderer ); - } - else - { - ForgeDirection selectedSide = ForgeDirection.UNKNOWN; - - for( final ForgeDirection of : this.getConnections() ) - { - selectedSide = of; - break; - } - - final int channels = this.getChannelsOnSide()[selectedSide.ordinal()]; - final IIcon def = this.getTexture( this.getCableColor() ); - final IIcon off = new OffsetIcon( def, 0, -12 ); - - final IIcon firstTaughtIcon = new TaughtIcon( this.getChannelTex( channels, false ).getIcon(), -0.2f ); - final IIcon firstOffsetIcon = new OffsetIcon( firstTaughtIcon, 0, -12 ); - - final IIcon secondTaughtIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); - final IIcon secondOffsetIcon = new OffsetIcon( secondTaughtIcon, 0, -12 ); - - switch( selectedSide ) - { - case DOWN: - case UP: - renderer.setRenderBounds( 5 / 16.0, 0, 5 / 16.0, 11 / 16.0, 16 / 16.0, 11 / 16.0 ); - rh.setTexture( def, def, off, off, off, off ); - rh.renderBlockCurrentBounds( x, y, z, renderer ); - - renderer.uvRotateTop = 0; - renderer.uvRotateBottom = 0; - renderer.uvRotateSouth = 3; - renderer.uvRotateEast = 3; - - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); - - Tessellator.instance.setColorOpaque_I( this.getCableColor().blackVariant ); - rh.setTexture( firstTaughtIcon, firstTaughtIcon, firstOffsetIcon, firstOffsetIcon, firstOffsetIcon, firstOffsetIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - - Tessellator.instance.setColorOpaque_I( this.getCableColor().whiteVariant ); - rh.setTexture( secondTaughtIcon, secondTaughtIcon, secondOffsetIcon, secondOffsetIcon, secondOffsetIcon, secondOffsetIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - break; - case EAST: - case WEST: - rh.setTexture( off, off, off, off, def, def ); - renderer.uvRotateEast = 2; - renderer.uvRotateWest = 1; - renderer.uvRotateBottom = 2; - renderer.uvRotateTop = 1; - renderer.uvRotateSouth = 0; - renderer.uvRotateNorth = 0; - - final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); - final FlippableIcon ico = blk.getRendererInstance().getTexture( ForgeDirection.EAST ); - ico.setFlip( false, true ); - - renderer.setRenderBounds( 0, 5 / 16.0, 5 / 16.0, 16 / 16.0, 11 / 16.0, 11 / 16.0 ); - rh.renderBlockCurrentBounds( x, y, z, renderer ); - - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); - - FlippableIcon fpA = new FlippableIcon( firstTaughtIcon ); - FlippableIcon fpB = new FlippableIcon( secondTaughtIcon ); - - fpA = new FlippableIcon( firstTaughtIcon ); - fpB = new FlippableIcon( secondTaughtIcon ); - - fpA.setFlip( true, false ); - fpB.setFlip( true, false ); - - Tessellator.instance.setColorOpaque_I( this.getCableColor().blackVariant ); - rh.setTexture( firstOffsetIcon, firstOffsetIcon, firstOffsetIcon, firstOffsetIcon, firstTaughtIcon, fpA ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - - Tessellator.instance.setColorOpaque_I( this.getCableColor().whiteVariant ); - rh.setTexture( secondOffsetIcon, secondOffsetIcon, secondOffsetIcon, secondOffsetIcon, secondTaughtIcon, fpB ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - break; - case NORTH: - case SOUTH: - rh.setTexture( off, off, def, def, off, off ); - renderer.uvRotateTop = 3; - renderer.uvRotateBottom = 3; - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 2; - renderer.uvRotateWest = 1; - renderer.setRenderBounds( 5 / 16.0, 5 / 16.0, 0, 11 / 16.0, 11 / 16.0, 16 / 16.0 ); - rh.renderBlockCurrentBounds( x, y, z, renderer ); - - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); - - Tessellator.instance.setColorOpaque_I( this.getCableColor().blackVariant ); - rh.setTexture( firstOffsetIcon, firstOffsetIcon, firstTaughtIcon, firstTaughtIcon, firstOffsetIcon, firstOffsetIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - - Tessellator.instance.setColorOpaque_I( this.getCableColor().whiteVariant ); - rh.setTexture( secondOffsetIcon, secondOffsetIcon, secondTaughtIcon, secondTaughtIcon, secondOffsetIcon, secondOffsetIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - break; - default: - break; - } - } - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - rh.setTexture( null ); - } +public class PartCableSmart extends PartCable { + @Reflected + public PartCableSmart(final ItemStack is) { + super(is); + } + + @MENetworkEventSubscribe + public void channelUpdated(final MENetworkChannelsChanged c) { + this.getHost().markForUpdate(); + } + + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } + + @Override + public AECableType getCableConnectionType() { + return AECableType.SMART; + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(5.0, 5.0, 5.0, 11.0, 11.0, 11.0); + + if (Platform.isServer()) { + final IGridNode n = this.getGridNode(); + if (n != null) { + this.setConnections(n.getConnectedSides()); + } else { + this.getConnections().clear(); + } + } + + for (final ForgeDirection of : this.getConnections()) { + switch (of) { + case DOWN: + bch.addBox(5.0, 0.0, 5.0, 11.0, 5.0, 11.0); + break; + case EAST: + bch.addBox(11.0, 5.0, 5.0, 16.0, 11.0, 11.0); + break; + case NORTH: + bch.addBox(5.0, 5.0, 0.0, 11.0, 11.0, 5.0); + break; + case SOUTH: + bch.addBox(5.0, 5.0, 11.0, 11.0, 11.0, 16.0); + break; + case UP: + bch.addBox(5.0, 11.0, 5.0, 11.0, 16.0, 11.0); + break; + case WEST: + bch.addBox(0.0, 5.0, 5.0, 5.0, 11.0, 11.0); + break; + default: + } + } + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + GL11.glTranslated(-0.0, -0.0, 0.3); + + float offU = 0; + float offV = 9; + + OffsetIcon main = new OffsetIcon(this.getTexture(this.getCableColor()), offU, offV); + OffsetIcon ch1 = new OffsetIcon(this.getChannelTex(4, false).getIcon(), offU, offV); + OffsetIcon ch2 = new OffsetIcon(this.getChannelTex(4, true).getIcon(), offU, offV); + + for (final ForgeDirection side : EnumSet.of(ForgeDirection.UP, ForgeDirection.DOWN)) { + rh.setBounds(5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f); + rh.renderInventoryFace(main, side, renderer); + rh.renderInventoryFace(ch1, side, renderer); + rh.renderInventoryFace(ch2, side, renderer); + } + + offU = 9; + offV = 0; + main = new OffsetIcon(this.getTexture(this.getCableColor()), offU, offV); + ch1 = new OffsetIcon(this.getChannelTex(4, false).getIcon(), offU, offV); + ch2 = new OffsetIcon(this.getChannelTex(4, true).getIcon(), offU, offV); + + for (final ForgeDirection side : EnumSet.of(ForgeDirection.EAST, ForgeDirection.WEST)) { + rh.setBounds(5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f); + rh.renderInventoryFace(main, side, renderer); + rh.renderInventoryFace(ch1, side, renderer); + rh.renderInventoryFace(ch2, side, renderer); + } + + main = new OffsetIcon(this.getTexture(this.getCableColor()), 0, 0); + ch1 = new OffsetIcon(this.getChannelTex(4, false).getIcon(), 0, 0); + ch2 = new OffsetIcon(this.getChannelTex(4, true).getIcon(), 0, 0); + + for (final ForgeDirection side : EnumSet.of(ForgeDirection.SOUTH, ForgeDirection.NORTH)) { + rh.setBounds(5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f); + rh.renderInventoryFace(main, side, renderer); + rh.renderInventoryFace(ch1, side, renderer); + rh.renderInventoryFace(ch2, side, renderer); + } + + rh.setTexture(null); + } + + @Override + public IIcon getTexture(final AEColor c) { + return this.getSmartTexture(c); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + this.setRenderCache(rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache())); + rh.setTexture(this.getTexture(this.getCableColor())); + + final EnumSet sides = this.getConnections().clone(); + + boolean hasBuses = false; + final IPartHost ph = this.getHost(); + for (final ForgeDirection of : EnumSet.complementOf(this.getConnections())) { + final IPart bp = ph.getPart(of); + if (bp instanceof IGridHost) { + if (of != ForgeDirection.UNKNOWN) { + sides.add(of); + hasBuses = true; + } + + final int len = bp.cableConnectionRenderTo(); + if (len < 8) { + switch (of) { + case DOWN: + rh.setBounds(6, len, 6, 10, 5, 10); + break; + case EAST: + rh.setBounds(11, 6, 6, 16 - len, 10, 10); + break; + case NORTH: + rh.setBounds(6, 6, len, 10, 10, 5); + break; + case SOUTH: + rh.setBounds(6, 6, 11, 10, 10, 16 - len); + break; + case UP: + rh.setBounds(6, 11, 6, 10, 16 - len, 10); + break; + case WEST: + rh.setBounds(len, 6, 6, 5, 10, 10); + break; + default: + continue; + } + rh.renderBlock(x, y, z, renderer); + + this.setSmartConnectionRotations(of, renderer); + final IIcon firstIcon = new TaughtIcon( + this.getChannelTex(this.getChannelsOnSide()[of.ordinal()], false) + .getIcon(), + -0.2f); + final IIcon secondIcon = new TaughtIcon( + this.getChannelTex(this.getChannelsOnSide()[of.ordinal()], true) + .getIcon(), + -0.2f); + + if (of == ForgeDirection.EAST || of == ForgeDirection.WEST) { + final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); + final FlippableIcon ico = blk.getRendererInstance().getTexture(ForgeDirection.EAST); + ico.setFlip(false, true); + } + + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); + Tessellator.instance.setColorOpaque_I(this.getCableColor().blackVariant); + rh.setTexture(firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + + Tessellator.instance.setColorOpaque_I(this.getCableColor().whiteVariant); + rh.setTexture(secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = + renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + + rh.setTexture(this.getTexture(this.getCableColor())); + } + } + } + + if (sides.size() != 2 || !this.nonLinear(sides) || hasBuses) { + for (final ForgeDirection of : this.getConnections()) { + this.renderSmartConnection(x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of); + } + + rh.setTexture(this.getCoveredTexture(this.getCableColor())); + rh.setBounds(5, 5, 5, 11, 11, 11); + rh.renderBlock(x, y, z, renderer); + } else { + ForgeDirection selectedSide = ForgeDirection.UNKNOWN; + + for (final ForgeDirection of : this.getConnections()) { + selectedSide = of; + break; + } + + final int channels = this.getChannelsOnSide()[selectedSide.ordinal()]; + final IIcon def = this.getTexture(this.getCableColor()); + final IIcon off = new OffsetIcon(def, 0, -12); + + final IIcon firstTaughtIcon = + new TaughtIcon(this.getChannelTex(channels, false).getIcon(), -0.2f); + final IIcon firstOffsetIcon = new OffsetIcon(firstTaughtIcon, 0, -12); + + final IIcon secondTaughtIcon = + new TaughtIcon(this.getChannelTex(channels, true).getIcon(), -0.2f); + final IIcon secondOffsetIcon = new OffsetIcon(secondTaughtIcon, 0, -12); + + switch (selectedSide) { + case DOWN: + case UP: + renderer.setRenderBounds(5 / 16.0, 0, 5 / 16.0, 11 / 16.0, 16 / 16.0, 11 / 16.0); + rh.setTexture(def, def, off, off, off, off); + rh.renderBlockCurrentBounds(x, y, z, renderer); + + renderer.uvRotateTop = 0; + renderer.uvRotateBottom = 0; + renderer.uvRotateSouth = 3; + renderer.uvRotateEast = 3; + + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); + + Tessellator.instance.setColorOpaque_I(this.getCableColor().blackVariant); + rh.setTexture( + firstTaughtIcon, + firstTaughtIcon, + firstOffsetIcon, + firstOffsetIcon, + firstOffsetIcon, + firstOffsetIcon); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + + Tessellator.instance.setColorOpaque_I(this.getCableColor().whiteVariant); + rh.setTexture( + secondTaughtIcon, + secondTaughtIcon, + secondOffsetIcon, + secondOffsetIcon, + secondOffsetIcon, + secondOffsetIcon); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + break; + case EAST: + case WEST: + rh.setTexture(off, off, off, off, def, def); + renderer.uvRotateEast = 2; + renderer.uvRotateWest = 1; + renderer.uvRotateBottom = 2; + renderer.uvRotateTop = 1; + renderer.uvRotateSouth = 0; + renderer.uvRotateNorth = 0; + + final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); + final FlippableIcon ico = blk.getRendererInstance().getTexture(ForgeDirection.EAST); + ico.setFlip(false, true); + + renderer.setRenderBounds(0, 5 / 16.0, 5 / 16.0, 16 / 16.0, 11 / 16.0, 11 / 16.0); + rh.renderBlockCurrentBounds(x, y, z, renderer); + + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); + + FlippableIcon fpA = new FlippableIcon(firstTaughtIcon); + FlippableIcon fpB = new FlippableIcon(secondTaughtIcon); + + fpA = new FlippableIcon(firstTaughtIcon); + fpB = new FlippableIcon(secondTaughtIcon); + + fpA.setFlip(true, false); + fpB.setFlip(true, false); + + Tessellator.instance.setColorOpaque_I(this.getCableColor().blackVariant); + rh.setTexture( + firstOffsetIcon, firstOffsetIcon, firstOffsetIcon, firstOffsetIcon, firstTaughtIcon, fpA); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + + Tessellator.instance.setColorOpaque_I(this.getCableColor().whiteVariant); + rh.setTexture( + secondOffsetIcon, + secondOffsetIcon, + secondOffsetIcon, + secondOffsetIcon, + secondTaughtIcon, + fpB); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + break; + case NORTH: + case SOUTH: + rh.setTexture(off, off, def, def, off, off); + renderer.uvRotateTop = 3; + renderer.uvRotateBottom = 3; + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 2; + renderer.uvRotateWest = 1; + renderer.setRenderBounds(5 / 16.0, 5 / 16.0, 0, 11 / 16.0, 11 / 16.0, 16 / 16.0); + rh.renderBlockCurrentBounds(x, y, z, renderer); + + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); + + Tessellator.instance.setColorOpaque_I(this.getCableColor().blackVariant); + rh.setTexture( + firstOffsetIcon, + firstOffsetIcon, + firstTaughtIcon, + firstTaughtIcon, + firstOffsetIcon, + firstOffsetIcon); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + + Tessellator.instance.setColorOpaque_I(this.getCableColor().whiteVariant); + rh.setTexture( + secondOffsetIcon, + secondOffsetIcon, + secondTaughtIcon, + secondTaughtIcon, + secondOffsetIcon, + secondOffsetIcon); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + break; + default: + break; + } + } + + renderer.uvRotateBottom = renderer.uvRotateEast = + renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + rh.setTexture(null); + } } diff --git a/src/main/java/appeng/parts/networking/PartDenseCable.java b/src/main/java/appeng/parts/networking/PartDenseCable.java index 2f22df7fdbe..e47ed2d08b2 100644 --- a/src/main/java/appeng/parts/networking/PartDenseCable.java +++ b/src/main/java/appeng/parts/networking/PartDenseCable.java @@ -18,7 +18,6 @@ package appeng.parts.networking; - import appeng.api.AEApi; import appeng.api.networking.GridFlags; import appeng.api.networking.IGridHost; @@ -41,6 +40,7 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.item.ItemStack; @@ -49,481 +49,466 @@ import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import java.util.EnumSet; - - -public class PartDenseCable extends PartCable -{ - @Reflected - public PartDenseCable( final ItemStack is ) - { - super( is ); - - this.getProxy().setFlags( GridFlags.DENSE_CAPACITY, GridFlags.PREFERRED ); - } - - @Override - public BusSupport supportsBuses() - { - return BusSupport.DENSE_CABLE; - } - - @Override - public AECableType getCableConnectionType() - { - return AECableType.DENSE; - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - final boolean noLadder = !bch.isBBCollision(); - final double min = noLadder ? 3.0 : 4.9; - final double max = noLadder ? 13.0 : 11.1; - - bch.addBox( min, min, min, max, max, max ); - - if( Platform.isServer() ) - { - final IGridNode n = this.getGridNode(); - if( n != null ) - { - this.setConnections( n.getConnectedSides() ); - } - else - { - this.getConnections().clear(); - } - } - - for( final ForgeDirection of : this.getConnections() ) - { - if( this.isDense( of ) ) - { - switch( of ) - { - case DOWN: - bch.addBox( min, 0.0, min, max, min, max ); - break; - case EAST: - bch.addBox( max, min, min, 16.0, max, max ); - break; - case NORTH: - bch.addBox( min, min, 0.0, max, max, min ); - break; - case SOUTH: - bch.addBox( min, min, max, max, max, 16.0 ); - break; - case UP: - bch.addBox( min, max, min, max, 16.0, max ); - break; - case WEST: - bch.addBox( 0.0, min, min, min, max, max ); - break; - default: - } - } - else - { - switch( of ) - { - case DOWN: - bch.addBox( 5.0, 0.0, 5.0, 11.0, 5.0, 11.0 ); - break; - case EAST: - bch.addBox( 11.0, 5.0, 5.0, 16.0, 11.0, 11.0 ); - break; - case NORTH: - bch.addBox( 5.0, 5.0, 0.0, 11.0, 11.0, 5.0 ); - break; - case SOUTH: - bch.addBox( 5.0, 5.0, 11.0, 11.0, 11.0, 16.0 ); - break; - case UP: - bch.addBox( 5.0, 11.0, 5.0, 11.0, 16.0, 11.0 ); - break; - case WEST: - bch.addBox( 0.0, 5.0, 5.0, 5.0, 11.0, 11.0 ); - break; - default: - } - } - } - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - GL11.glTranslated( -0.0, -0.0, 0.3 ); - rh.setBounds( 4.0f, 4.0f, 2.0f, 12.0f, 12.0f, 14.0f ); - - float offU = 0; - float offV = 9; - - OffsetIcon main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); - OffsetIcon ch1 = new OffsetIcon( this.getChannelTex( 4, false ).getIcon(), offU, offV ); - OffsetIcon ch2 = new OffsetIcon( this.getChannelTex( 4, true ).getIcon(), offU, offV ); - - for( final ForgeDirection side : EnumSet.of( ForgeDirection.UP, ForgeDirection.DOWN ) ) - { - rh.renderInventoryFace( main, side, renderer ); - rh.renderInventoryFace( ch1, side, renderer ); - rh.renderInventoryFace( ch2, side, renderer ); - } - - offU = 9; - offV = 0; - main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); - ch1 = new OffsetIcon( this.getChannelTex( 4, false ).getIcon(), offU, offV ); - ch2 = new OffsetIcon( this.getChannelTex( 4, true ).getIcon(), offU, offV ); - - for( final ForgeDirection side : EnumSet.of( ForgeDirection.EAST, ForgeDirection.WEST ) ) - { - rh.renderInventoryFace( main, side, renderer ); - rh.renderInventoryFace( ch1, side, renderer ); - rh.renderInventoryFace( ch2, side, renderer ); - } - - main = new OffsetIcon( this.getTexture( this.getCableColor() ), 0, 0 ); - ch1 = new OffsetIcon( this.getChannelTex( 4, false ).getIcon(), 0, 0 ); - ch2 = new OffsetIcon( this.getChannelTex( 4, true ).getIcon(), 0, 0 ); - - for( final ForgeDirection side : EnumSet.of( ForgeDirection.SOUTH, ForgeDirection.NORTH ) ) - { - rh.renderInventoryFace( main, side, renderer ); - rh.renderInventoryFace( ch1, side, renderer ); - rh.renderInventoryFace( ch2, side, renderer ); - } - - rh.setTexture( null ); - } - - @Override - public IIcon getTexture( final AEColor c ) - { - if( c == AEColor.Transparent ) - { - return AEApi.instance().definitions().parts().cableSmart().stack( AEColor.Transparent, 1 ).getIconIndex(); - } - - return this.getSmartTexture( c ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( this.getTexture( this.getCableColor() ) ); - - final EnumSet sides = this.getConnections().clone(); - - boolean hasBuses = false; - for( final ForgeDirection of : this.getConnections() ) - { - if( !this.isDense( of ) ) - { - hasBuses = true; - } - } - - if( sides.size() != 2 || !this.nonLinear( sides ) || hasBuses ) - { - for( final ForgeDirection of : this.getConnections() ) - { - if( this.isDense( of ) ) - { - this.renderDenseConnection( x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of ); - } - else if( this.isSmart( of ) ) - { - this.renderSmartConnection( x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of ); - } - else - { - this.renderCoveredConnection( x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of ); - } - } - - rh.setTexture( this.getDenseTexture( this.getCableColor() ) ); - rh.setBounds( 3, 3, 3, 13, 13, 13 ); - rh.renderBlock( x, y, z, renderer ); - } - else - { - ForgeDirection selectedSide = ForgeDirection.UNKNOWN; - - for( final ForgeDirection of : this.getConnections() ) - { - selectedSide = of; - break; - } - - final int channels = this.getChannelsOnSide()[selectedSide.ordinal()]; - final IIcon def = this.getTexture( this.getCableColor() ); - final IIcon off = new OffsetIcon( def, 0, -12 ); - - final IIcon firstIcon = new TaughtIcon( this.getChannelTex( channels, false ).getIcon(), -0.2f ); - final IIcon firstOffset = new OffsetIcon( firstIcon, 0, -12 ); - - final IIcon secondIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); - final IIcon secondOffset = new OffsetIcon( secondIcon, 0, -12 ); - - switch( selectedSide ) - { - case DOWN: - case UP: - renderer.setRenderBounds( 3 / 16.0, 0, 3 / 16.0, 13 / 16.0, 16 / 16.0, 13 / 16.0 ); - rh.setTexture( def, def, off, off, off, off ); - rh.renderBlockCurrentBounds( x, y, z, renderer ); - - renderer.uvRotateTop = 0; - renderer.uvRotateBottom = 0; - renderer.uvRotateSouth = 3; - renderer.uvRotateEast = 3; - - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); - - Tessellator.instance.setColorOpaque_I( this.getCableColor().blackVariant ); - rh.setTexture( firstIcon, firstIcon, firstOffset, firstOffset, firstOffset, firstOffset ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - - Tessellator.instance.setColorOpaque_I( this.getCableColor().whiteVariant ); - rh.setTexture( secondIcon, secondIcon, secondOffset, secondOffset, secondOffset, secondOffset ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - break; - case EAST: - case WEST: - rh.setTexture( off, off, off, off, def, def ); - renderer.uvRotateEast = 2; - renderer.uvRotateWest = 1; - renderer.uvRotateBottom = 2; - renderer.uvRotateTop = 1; - renderer.uvRotateSouth = 0; - renderer.uvRotateNorth = 0; - - final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); - final FlippableIcon ico = blk.getRendererInstance().getTexture( ForgeDirection.EAST ); - ico.setFlip( false, true ); - - renderer.setRenderBounds( 0, 3 / 16.0, 3 / 16.0, 16 / 16.0, 13 / 16.0, 13 / 16.0 ); - rh.renderBlockCurrentBounds( x, y, z, renderer ); - - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); - - final FlippableIcon fpA = new FlippableIcon( firstIcon ); - final FlippableIcon fpB = new FlippableIcon( secondIcon ); - - fpA.setFlip( true, false ); - fpB.setFlip( true, false ); - - Tessellator.instance.setColorOpaque_I( this.getCableColor().blackVariant ); - rh.setTexture( firstOffset, firstOffset, firstOffset, firstOffset, firstIcon, fpA ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - - Tessellator.instance.setColorOpaque_I( this.getCableColor().whiteVariant ); - rh.setTexture( secondOffset, secondOffset, secondOffset, secondOffset, secondIcon, fpB ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - break; - case NORTH: - case SOUTH: - rh.setTexture( off, off, def, def, off, off ); - renderer.uvRotateTop = 3; - renderer.uvRotateBottom = 3; - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 2; - renderer.uvRotateWest = 1; - renderer.setRenderBounds( 3 / 16.0, 3 / 16.0, 0, 13 / 16.0, 13 / 16.0, 16 / 16.0 ); - rh.renderBlockCurrentBounds( x, y, z, renderer ); - - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); - - Tessellator.instance.setColorOpaque_I( this.getCableColor().blackVariant ); - rh.setTexture( firstOffset, firstOffset, firstIcon, firstIcon, firstOffset, firstOffset ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - - Tessellator.instance.setColorOpaque_I( this.getCableColor().whiteVariant ); - rh.setTexture( secondOffset, secondOffset, secondIcon, secondIcon, secondOffset, secondOffset ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - break; - default: - break; - } - } - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - rh.setTexture( null ); - } - - @SideOnly( Side.CLIENT ) - private void renderDenseConnection( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer, final int channels, final ForgeDirection of ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( x + of.offsetX, y + of.offsetY, z + of.offsetZ ); - final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; - final IGridHost ghh = te instanceof IGridHost ? (IGridHost) te : null; - AEColor myColor = this.getCableColor(); - /* - * ( ghh != null && partHost != null && ghh.getCableConnectionType( of ) == AECableType.GLASS && - * partHost.getPart( - * of.getOpposite() ) == null ) { isGlass = true; rh.setTexture( getGlassTexture( myColor = partHost.getColor() - * ) ); - * } else if ( partHost == null && ghh != null && ghh.getCableConnectionType( of ) != AECableType.GLASS ) { - * rh.setTexture( getSmartTexture( myColor ) ); switch (of) { case DOWN: rh.setBounds( 3, 0, 3, 13, 4, 13 ); - * break; case EAST: rh.setBounds( 12, 3, 3, 16, 13, 13 ); break; case NORTH: rh.setBounds( 3, 3, 0, 13, 13, 4 - * ); break; case SOUTH: rh.setBounds( 3, 3, 12, 13, 13, 16 ); break; case UP: rh.setBounds( 3, 12, 3, 13, 16, - * 13 ); break; case WEST: rh.setBounds( 0, 3, 3, 4, 13, 13 ); break; default: return; } rh.renderBlock( x, y, - * z, renderer ); - * if ( true ) { setSmartConnectionRotations( of, renderer ); IIcon firstIcon = new TaughtIcon( getChannelTex( - * channels, false ).getIcon(), -0.2f ); IIcon secondIcon = new TaughtIcon( getChannelTex( channels, true - * ).getIcon(), - * -0.2f ); - * if ( of == ForgeDirection.EAST || of == ForgeDirection.WEST ) { AEBaseBlock blk = (AEBaseBlock) - * rh.getBlock(); FlippableIcon ico = blk.getRendererInstance().getTexture( ForgeDirection.EAST ); ico.setFlip( - * false, true ); } - * Tessellator.INSTANCE.setBrightness( 15 << 20 | 15 << 5 ); Tessellator.INSTANCE.setColorOpaque_I( - * myColor.mediumVariant ); rh.setTexture( firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon ); - * renderAllFaces( (AEBaseBlock) - * rh.getBlock(), x, y, z, renderer ); - * Tessellator.INSTANCE.setColorOpaque_I( myColor.whiteVariant ); rh.setTexture( secondIcon, secondIcon, - * secondIcon, secondIcon, secondIcon, - * secondIcon ); renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, renderer ); - * renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = - * renderer.uvRotateTop = renderer.uvRotateWest = 0; } - * rh.setTexture( getTexture( getCableColor() ) ); } - */ - - rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of, of.getOpposite() ) ) ); - if( ghh != null && partHost != null && ghh.getCableConnectionType( of ) != AECableType.GLASS && partHost.getColor() != AEColor.Transparent && partHost.getPart( of.getOpposite() ) == null ) - { - rh.setTexture( this.getTexture( myColor = partHost.getColor() ) ); - } - else - { - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } - - switch( of ) - { - case DOWN: - rh.setBounds( 4, 0, 4, 12, 5, 12 ); - break; - case EAST: - rh.setBounds( 11, 4, 4, 16, 12, 12 ); - break; - case NORTH: - rh.setBounds( 4, 4, 0, 12, 12, 5 ); - break; - case SOUTH: - rh.setBounds( 4, 4, 11, 12, 12, 16 ); - break; - case UP: - rh.setBounds( 4, 11, 4, 12, 16, 12 ); - break; - case WEST: - rh.setBounds( 0, 4, 4, 5, 12, 12 ); - break; - default: - return; - } - - rh.renderBlock( x, y, z, renderer ); - - rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - final boolean isGlass = false; - if( !isGlass ) - { - this.setSmartConnectionRotations( of, renderer ); - - final IIcon firstIcon = new TaughtIcon( this.getChannelTex( channels, false ).getIcon(), -0.2f ); - final IIcon secondIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); - - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); - Tessellator.instance.setColorOpaque_I( myColor.blackVariant ); - rh.setTexture( firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - - Tessellator.instance.setColorOpaque_I( myColor.whiteVariant ); - rh.setTexture( secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - } - } - - private boolean isSmart( final ForgeDirection of ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( this.getTile().xCoord + of.offsetX, this.getTile().yCoord + of.offsetY, this.getTile().zCoord + of.offsetZ ); - if( te instanceof IGridHost ) - { - final AECableType t = ( (IGridHost) te ).getCableConnectionType( of.getOpposite() ); - return t == AECableType.SMART; - } - return false; - } - - protected IIcon getDenseTexture( final AEColor c ) - { - switch( c ) - { - case Black: - return CableBusTextures.MEDense_Black.getIcon(); - case Blue: - return CableBusTextures.MEDense_Blue.getIcon(); - case Brown: - return CableBusTextures.MEDense_Brown.getIcon(); - case Cyan: - return CableBusTextures.MEDense_Cyan.getIcon(); - case Gray: - return CableBusTextures.MEDense_Gray.getIcon(); - case Green: - return CableBusTextures.MEDense_Green.getIcon(); - case LightBlue: - return CableBusTextures.MEDense_LightBlue.getIcon(); - case LightGray: - return CableBusTextures.MEDense_LightGrey.getIcon(); - case Lime: - return CableBusTextures.MEDense_Lime.getIcon(); - case Magenta: - return CableBusTextures.MEDense_Magenta.getIcon(); - case Orange: - return CableBusTextures.MEDense_Orange.getIcon(); - case Pink: - return CableBusTextures.MEDense_Pink.getIcon(); - case Purple: - return CableBusTextures.MEDense_Purple.getIcon(); - case Red: - return CableBusTextures.MEDense_Red.getIcon(); - case White: - return CableBusTextures.MEDense_White.getIcon(); - case Yellow: - return CableBusTextures.MEDense_Yellow.getIcon(); - default: - } - - return this.getItemStack().getIconIndex(); - } - - private boolean isDense( final ForgeDirection of ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( this.getTile().xCoord + of.offsetX, this.getTile().yCoord + of.offsetY, this.getTile().zCoord + of.offsetZ ); - if( te instanceof IGridHost ) - { - final AECableType t = ( (IGridHost) te ).getCableConnectionType( of.getOpposite() ); - return t == AECableType.DENSE || t == AECableType.DENSE_COVERED || t == AECableType.ULTRA_DENSE_SMART || t == AECableType.ULTRA_DENSE; - } - return false; - } - - @MENetworkEventSubscribe - public void channelUpdated( final MENetworkChannelsChanged c ) - { - this.getHost().markForUpdate(); - } - - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } +public class PartDenseCable extends PartCable { + @Reflected + public PartDenseCable(final ItemStack is) { + super(is); + + this.getProxy().setFlags(GridFlags.DENSE_CAPACITY, GridFlags.PREFERRED); + } + + @Override + public BusSupport supportsBuses() { + return BusSupport.DENSE_CABLE; + } + + @Override + public AECableType getCableConnectionType() { + return AECableType.DENSE; + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + final boolean noLadder = !bch.isBBCollision(); + final double min = noLadder ? 3.0 : 4.9; + final double max = noLadder ? 13.0 : 11.1; + + bch.addBox(min, min, min, max, max, max); + + if (Platform.isServer()) { + final IGridNode n = this.getGridNode(); + if (n != null) { + this.setConnections(n.getConnectedSides()); + } else { + this.getConnections().clear(); + } + } + + for (final ForgeDirection of : this.getConnections()) { + if (this.isDense(of)) { + switch (of) { + case DOWN: + bch.addBox(min, 0.0, min, max, min, max); + break; + case EAST: + bch.addBox(max, min, min, 16.0, max, max); + break; + case NORTH: + bch.addBox(min, min, 0.0, max, max, min); + break; + case SOUTH: + bch.addBox(min, min, max, max, max, 16.0); + break; + case UP: + bch.addBox(min, max, min, max, 16.0, max); + break; + case WEST: + bch.addBox(0.0, min, min, min, max, max); + break; + default: + } + } else { + switch (of) { + case DOWN: + bch.addBox(5.0, 0.0, 5.0, 11.0, 5.0, 11.0); + break; + case EAST: + bch.addBox(11.0, 5.0, 5.0, 16.0, 11.0, 11.0); + break; + case NORTH: + bch.addBox(5.0, 5.0, 0.0, 11.0, 11.0, 5.0); + break; + case SOUTH: + bch.addBox(5.0, 5.0, 11.0, 11.0, 11.0, 16.0); + break; + case UP: + bch.addBox(5.0, 11.0, 5.0, 11.0, 16.0, 11.0); + break; + case WEST: + bch.addBox(0.0, 5.0, 5.0, 5.0, 11.0, 11.0); + break; + default: + } + } + } + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + GL11.glTranslated(-0.0, -0.0, 0.3); + rh.setBounds(4.0f, 4.0f, 2.0f, 12.0f, 12.0f, 14.0f); + + float offU = 0; + float offV = 9; + + OffsetIcon main = new OffsetIcon(this.getTexture(this.getCableColor()), offU, offV); + OffsetIcon ch1 = new OffsetIcon(this.getChannelTex(4, false).getIcon(), offU, offV); + OffsetIcon ch2 = new OffsetIcon(this.getChannelTex(4, true).getIcon(), offU, offV); + + for (final ForgeDirection side : EnumSet.of(ForgeDirection.UP, ForgeDirection.DOWN)) { + rh.renderInventoryFace(main, side, renderer); + rh.renderInventoryFace(ch1, side, renderer); + rh.renderInventoryFace(ch2, side, renderer); + } + + offU = 9; + offV = 0; + main = new OffsetIcon(this.getTexture(this.getCableColor()), offU, offV); + ch1 = new OffsetIcon(this.getChannelTex(4, false).getIcon(), offU, offV); + ch2 = new OffsetIcon(this.getChannelTex(4, true).getIcon(), offU, offV); + + for (final ForgeDirection side : EnumSet.of(ForgeDirection.EAST, ForgeDirection.WEST)) { + rh.renderInventoryFace(main, side, renderer); + rh.renderInventoryFace(ch1, side, renderer); + rh.renderInventoryFace(ch2, side, renderer); + } + + main = new OffsetIcon(this.getTexture(this.getCableColor()), 0, 0); + ch1 = new OffsetIcon(this.getChannelTex(4, false).getIcon(), 0, 0); + ch2 = new OffsetIcon(this.getChannelTex(4, true).getIcon(), 0, 0); + + for (final ForgeDirection side : EnumSet.of(ForgeDirection.SOUTH, ForgeDirection.NORTH)) { + rh.renderInventoryFace(main, side, renderer); + rh.renderInventoryFace(ch1, side, renderer); + rh.renderInventoryFace(ch2, side, renderer); + } + + rh.setTexture(null); + } + + @Override + public IIcon getTexture(final AEColor c) { + if (c == AEColor.Transparent) { + return AEApi.instance() + .definitions() + .parts() + .cableSmart() + .stack(AEColor.Transparent, 1) + .getIconIndex(); + } + + return this.getSmartTexture(c); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + this.setRenderCache(rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache())); + rh.setTexture(this.getTexture(this.getCableColor())); + + final EnumSet sides = this.getConnections().clone(); + + boolean hasBuses = false; + for (final ForgeDirection of : this.getConnections()) { + if (!this.isDense(of)) { + hasBuses = true; + } + } + + if (sides.size() != 2 || !this.nonLinear(sides) || hasBuses) { + for (final ForgeDirection of : this.getConnections()) { + if (this.isDense(of)) { + this.renderDenseConnection(x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of); + } else if (this.isSmart(of)) { + this.renderSmartConnection(x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of); + } else { + this.renderCoveredConnection(x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of); + } + } + + rh.setTexture(this.getDenseTexture(this.getCableColor())); + rh.setBounds(3, 3, 3, 13, 13, 13); + rh.renderBlock(x, y, z, renderer); + } else { + ForgeDirection selectedSide = ForgeDirection.UNKNOWN; + + for (final ForgeDirection of : this.getConnections()) { + selectedSide = of; + break; + } + + final int channels = this.getChannelsOnSide()[selectedSide.ordinal()]; + final IIcon def = this.getTexture(this.getCableColor()); + final IIcon off = new OffsetIcon(def, 0, -12); + + final IIcon firstIcon = + new TaughtIcon(this.getChannelTex(channels, false).getIcon(), -0.2f); + final IIcon firstOffset = new OffsetIcon(firstIcon, 0, -12); + + final IIcon secondIcon = + new TaughtIcon(this.getChannelTex(channels, true).getIcon(), -0.2f); + final IIcon secondOffset = new OffsetIcon(secondIcon, 0, -12); + + switch (selectedSide) { + case DOWN: + case UP: + renderer.setRenderBounds(3 / 16.0, 0, 3 / 16.0, 13 / 16.0, 16 / 16.0, 13 / 16.0); + rh.setTexture(def, def, off, off, off, off); + rh.renderBlockCurrentBounds(x, y, z, renderer); + + renderer.uvRotateTop = 0; + renderer.uvRotateBottom = 0; + renderer.uvRotateSouth = 3; + renderer.uvRotateEast = 3; + + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); + + Tessellator.instance.setColorOpaque_I(this.getCableColor().blackVariant); + rh.setTexture(firstIcon, firstIcon, firstOffset, firstOffset, firstOffset, firstOffset); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + + Tessellator.instance.setColorOpaque_I(this.getCableColor().whiteVariant); + rh.setTexture(secondIcon, secondIcon, secondOffset, secondOffset, secondOffset, secondOffset); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + break; + case EAST: + case WEST: + rh.setTexture(off, off, off, off, def, def); + renderer.uvRotateEast = 2; + renderer.uvRotateWest = 1; + renderer.uvRotateBottom = 2; + renderer.uvRotateTop = 1; + renderer.uvRotateSouth = 0; + renderer.uvRotateNorth = 0; + + final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); + final FlippableIcon ico = blk.getRendererInstance().getTexture(ForgeDirection.EAST); + ico.setFlip(false, true); + + renderer.setRenderBounds(0, 3 / 16.0, 3 / 16.0, 16 / 16.0, 13 / 16.0, 13 / 16.0); + rh.renderBlockCurrentBounds(x, y, z, renderer); + + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); + + final FlippableIcon fpA = new FlippableIcon(firstIcon); + final FlippableIcon fpB = new FlippableIcon(secondIcon); + + fpA.setFlip(true, false); + fpB.setFlip(true, false); + + Tessellator.instance.setColorOpaque_I(this.getCableColor().blackVariant); + rh.setTexture(firstOffset, firstOffset, firstOffset, firstOffset, firstIcon, fpA); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + + Tessellator.instance.setColorOpaque_I(this.getCableColor().whiteVariant); + rh.setTexture(secondOffset, secondOffset, secondOffset, secondOffset, secondIcon, fpB); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + break; + case NORTH: + case SOUTH: + rh.setTexture(off, off, def, def, off, off); + renderer.uvRotateTop = 3; + renderer.uvRotateBottom = 3; + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 2; + renderer.uvRotateWest = 1; + renderer.setRenderBounds(3 / 16.0, 3 / 16.0, 0, 13 / 16.0, 13 / 16.0, 16 / 16.0); + rh.renderBlockCurrentBounds(x, y, z, renderer); + + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); + + Tessellator.instance.setColorOpaque_I(this.getCableColor().blackVariant); + rh.setTexture(firstOffset, firstOffset, firstIcon, firstIcon, firstOffset, firstOffset); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + + Tessellator.instance.setColorOpaque_I(this.getCableColor().whiteVariant); + rh.setTexture(secondOffset, secondOffset, secondIcon, secondIcon, secondOffset, secondOffset); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + break; + default: + break; + } + } + + renderer.uvRotateBottom = renderer.uvRotateEast = + renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + rh.setTexture(null); + } + + @SideOnly(Side.CLIENT) + private void renderDenseConnection( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer, + final int channels, + final ForgeDirection of) { + final TileEntity te = + this.getTile().getWorldObj().getTileEntity(x + of.offsetX, y + of.offsetY, z + of.offsetZ); + final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; + final IGridHost ghh = te instanceof IGridHost ? (IGridHost) te : null; + AEColor myColor = this.getCableColor(); + /* + * ( ghh != null && partHost != null && ghh.getCableConnectionType( of ) == AECableType.GLASS && + * partHost.getPart( + * of.getOpposite() ) == null ) { isGlass = true; rh.setTexture( getGlassTexture( myColor = partHost.getColor() + * ) ); + * } else if ( partHost == null && ghh != null && ghh.getCableConnectionType( of ) != AECableType.GLASS ) { + * rh.setTexture( getSmartTexture( myColor ) ); switch (of) { case DOWN: rh.setBounds( 3, 0, 3, 13, 4, 13 ); + * break; case EAST: rh.setBounds( 12, 3, 3, 16, 13, 13 ); break; case NORTH: rh.setBounds( 3, 3, 0, 13, 13, 4 + * ); break; case SOUTH: rh.setBounds( 3, 3, 12, 13, 13, 16 ); break; case UP: rh.setBounds( 3, 12, 3, 13, 16, + * 13 ); break; case WEST: rh.setBounds( 0, 3, 3, 4, 13, 13 ); break; default: return; } rh.renderBlock( x, y, + * z, renderer ); + * if ( true ) { setSmartConnectionRotations( of, renderer ); IIcon firstIcon = new TaughtIcon( getChannelTex( + * channels, false ).getIcon(), -0.2f ); IIcon secondIcon = new TaughtIcon( getChannelTex( channels, true + * ).getIcon(), + * -0.2f ); + * if ( of == ForgeDirection.EAST || of == ForgeDirection.WEST ) { AEBaseBlock blk = (AEBaseBlock) + * rh.getBlock(); FlippableIcon ico = blk.getRendererInstance().getTexture( ForgeDirection.EAST ); ico.setFlip( + * false, true ); } + * Tessellator.INSTANCE.setBrightness( 15 << 20 | 15 << 5 ); Tessellator.INSTANCE.setColorOpaque_I( + * myColor.mediumVariant ); rh.setTexture( firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon ); + * renderAllFaces( (AEBaseBlock) + * rh.getBlock(), x, y, z, renderer ); + * Tessellator.INSTANCE.setColorOpaque_I( myColor.whiteVariant ); rh.setTexture( secondIcon, secondIcon, + * secondIcon, secondIcon, secondIcon, + * secondIcon ); renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, renderer ); + * renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = + * renderer.uvRotateTop = renderer.uvRotateWest = 0; } + * rh.setTexture( getTexture( getCableColor() ) ); } + */ + + rh.setFacesToRender(EnumSet.complementOf(EnumSet.of(of, of.getOpposite()))); + if (ghh != null + && partHost != null + && ghh.getCableConnectionType(of) != AECableType.GLASS + && partHost.getColor() != AEColor.Transparent + && partHost.getPart(of.getOpposite()) == null) { + rh.setTexture(this.getTexture(myColor = partHost.getColor())); + } else { + rh.setTexture(this.getTexture(this.getCableColor())); + } + + switch (of) { + case DOWN: + rh.setBounds(4, 0, 4, 12, 5, 12); + break; + case EAST: + rh.setBounds(11, 4, 4, 16, 12, 12); + break; + case NORTH: + rh.setBounds(4, 4, 0, 12, 12, 5); + break; + case SOUTH: + rh.setBounds(4, 4, 11, 12, 12, 16); + break; + case UP: + rh.setBounds(4, 11, 4, 12, 16, 12); + break; + case WEST: + rh.setBounds(0, 4, 4, 5, 12, 12); + break; + default: + return; + } + + rh.renderBlock(x, y, z, renderer); + + rh.setFacesToRender(EnumSet.allOf(ForgeDirection.class)); + final boolean isGlass = false; + if (!isGlass) { + this.setSmartConnectionRotations(of, renderer); + + final IIcon firstIcon = + new TaughtIcon(this.getChannelTex(channels, false).getIcon(), -0.2f); + final IIcon secondIcon = + new TaughtIcon(this.getChannelTex(channels, true).getIcon(), -0.2f); + + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); + Tessellator.instance.setColorOpaque_I(myColor.blackVariant); + rh.setTexture(firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + + Tessellator.instance.setColorOpaque_I(myColor.whiteVariant); + rh.setTexture(secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); + + renderer.uvRotateBottom = renderer.uvRotateEast = + renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + } + } + + private boolean isSmart(final ForgeDirection of) { + final TileEntity te = this.getTile() + .getWorldObj() + .getTileEntity( + this.getTile().xCoord + of.offsetX, + this.getTile().yCoord + of.offsetY, + this.getTile().zCoord + of.offsetZ); + if (te instanceof IGridHost) { + final AECableType t = ((IGridHost) te).getCableConnectionType(of.getOpposite()); + return t == AECableType.SMART; + } + return false; + } + + protected IIcon getDenseTexture(final AEColor c) { + switch (c) { + case Black: + return CableBusTextures.MEDense_Black.getIcon(); + case Blue: + return CableBusTextures.MEDense_Blue.getIcon(); + case Brown: + return CableBusTextures.MEDense_Brown.getIcon(); + case Cyan: + return CableBusTextures.MEDense_Cyan.getIcon(); + case Gray: + return CableBusTextures.MEDense_Gray.getIcon(); + case Green: + return CableBusTextures.MEDense_Green.getIcon(); + case LightBlue: + return CableBusTextures.MEDense_LightBlue.getIcon(); + case LightGray: + return CableBusTextures.MEDense_LightGrey.getIcon(); + case Lime: + return CableBusTextures.MEDense_Lime.getIcon(); + case Magenta: + return CableBusTextures.MEDense_Magenta.getIcon(); + case Orange: + return CableBusTextures.MEDense_Orange.getIcon(); + case Pink: + return CableBusTextures.MEDense_Pink.getIcon(); + case Purple: + return CableBusTextures.MEDense_Purple.getIcon(); + case Red: + return CableBusTextures.MEDense_Red.getIcon(); + case White: + return CableBusTextures.MEDense_White.getIcon(); + case Yellow: + return CableBusTextures.MEDense_Yellow.getIcon(); + default: + } + + return this.getItemStack().getIconIndex(); + } + + private boolean isDense(final ForgeDirection of) { + final TileEntity te = this.getTile() + .getWorldObj() + .getTileEntity( + this.getTile().xCoord + of.offsetX, + this.getTile().yCoord + of.offsetY, + this.getTile().zCoord + of.offsetZ); + if (te instanceof IGridHost) { + final AECableType t = ((IGridHost) te).getCableConnectionType(of.getOpposite()); + return t == AECableType.DENSE + || t == AECableType.DENSE_COVERED + || t == AECableType.ULTRA_DENSE_SMART + || t == AECableType.ULTRA_DENSE; + } + return false; + } + + @MENetworkEventSubscribe + public void channelUpdated(final MENetworkChannelsChanged c) { + this.getHost().markForUpdate(); + } + + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } } diff --git a/src/main/java/appeng/parts/networking/PartDenseCableCovered.java b/src/main/java/appeng/parts/networking/PartDenseCableCovered.java index 402cfa6b3a2..78fdb2b59cd 100644 --- a/src/main/java/appeng/parts/networking/PartDenseCableCovered.java +++ b/src/main/java/appeng/parts/networking/PartDenseCableCovered.java @@ -18,7 +18,6 @@ package appeng.parts.networking; - import appeng.api.AEApi; import appeng.api.networking.GridFlags; import appeng.api.networking.IGridHost; @@ -40,6 +39,7 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; @@ -47,355 +47,335 @@ import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import java.util.EnumSet; - - -public class PartDenseCableCovered extends PartCable -{ - @Reflected - public PartDenseCableCovered(final ItemStack is ) - { - super( is ); - - this.getProxy().setFlags( GridFlags.DENSE_CAPACITY, GridFlags.PREFERRED ); - } - - @Override - public BusSupport supportsBuses() - { - return BusSupport.DENSE_CABLE; - } - - @Override - public AECableType getCableConnectionType() - { - return AECableType.DENSE_COVERED; - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - final boolean noLadder = !bch.isBBCollision(); - final double min = noLadder ? 3.0 : 4.9; - final double max = noLadder ? 13.0 : 11.1; - - bch.addBox( min, min, min, max, max, max ); - - if( Platform.isServer() ) - { - final IGridNode n = this.getGridNode(); - if( n != null ) - { - this.setConnections( n.getConnectedSides() ); - } - else - { - this.getConnections().clear(); - } - } - - for( final ForgeDirection of : this.getConnections() ) - { - if( this.isDense( of ) ) - { - switch( of ) - { - case DOWN: - bch.addBox( min, 0.0, min, max, min, max ); - break; - case EAST: - bch.addBox( max, min, min, 16.0, max, max ); - break; - case NORTH: - bch.addBox( min, min, 0.0, max, max, min ); - break; - case SOUTH: - bch.addBox( min, min, max, max, max, 16.0 ); - break; - case UP: - bch.addBox( min, max, min, max, 16.0, max ); - break; - case WEST: - bch.addBox( 0.0, min, min, min, max, max ); - break; - default: - } - } - else - { - switch( of ) - { - case DOWN: - bch.addBox( 5.0, 0.0, 5.0, 11.0, 5.0, 11.0 ); - break; - case EAST: - bch.addBox( 11.0, 5.0, 5.0, 16.0, 11.0, 11.0 ); - break; - case NORTH: - bch.addBox( 5.0, 5.0, 0.0, 11.0, 11.0, 5.0 ); - break; - case SOUTH: - bch.addBox( 5.0, 5.0, 11.0, 11.0, 11.0, 16.0 ); - break; - case UP: - bch.addBox( 5.0, 11.0, 5.0, 11.0, 16.0, 11.0 ); - break; - case WEST: - bch.addBox( 0.0, 5.0, 5.0, 5.0, 11.0, 11.0 ); - break; - default: - } - } - } - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - GL11.glTranslated( -0.0, -0.0, 0.3 ); - rh.setBounds( 4.0f, 4.0f, 2.0f, 12.0f, 12.0f, 14.0f ); - - float offU = 0; - float offV = 9; - - OffsetIcon main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); - - for( final ForgeDirection side : EnumSet.of( ForgeDirection.UP, ForgeDirection.DOWN ) ) - { - rh.renderInventoryFace( main, side, renderer ); - } - - offU = 9; - offV = 0; - main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); - - for( final ForgeDirection side : EnumSet.of( ForgeDirection.EAST, ForgeDirection.WEST ) ) - { - rh.renderInventoryFace( main, side, renderer ); - } - - main = new OffsetIcon( this.getTexture( this.getCableColor() ), 0, 0 ); - - for( final ForgeDirection side : EnumSet.of( ForgeDirection.SOUTH, ForgeDirection.NORTH ) ) { - rh.renderInventoryFace( main, side, renderer ); - } - - rh.setTexture( null ); - } - - @Override - public IIcon getTexture( final AEColor c ) - { - if( c == AEColor.Transparent ) - { - return AEApi.instance().definitions().parts().cableCovered().stack( AEColor.Transparent, 1 ).getIconIndex(); - } - - return this.getCoveredTexture( c ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( this.getTexture( this.getCableColor() ) ); - - final EnumSet sides = this.getConnections().clone(); - - boolean hasBuses = false; - for( final ForgeDirection of : this.getConnections() ) - { - if( !this.isDense( of ) ) - { - hasBuses = true; - } - } - - if( sides.size() != 2 || !this.nonLinear( sides ) || hasBuses ) - { - for( final ForgeDirection of : this.getConnections() ) - { - if( this.isDense( of ) ) - { - this.renderDenseCoveredConnection( x, y, z, rh, renderer, of ); - } - else - { - this.renderCoveredConnection( x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of ); - } - } - - rh.setTexture( this.getDenseCoveredTexture( this.getCableColor() ) ); - rh.setBounds( 3, 3, 3, 13, 13, 13 ); - rh.renderBlock( x, y, z, renderer ); - } - else - { - ForgeDirection selectedSide = ForgeDirection.UNKNOWN; - - for( final ForgeDirection of : this.getConnections() ) - { - selectedSide = of; - break; - } - - final IIcon def = this.getTexture( this.getCableColor() ); - final IIcon off = new OffsetIcon( def, 0, -12 ); - - switch( selectedSide ) - { - case DOWN: - case UP: - renderer.setRenderBounds( 3 / 16.0, 0, 3 / 16.0, 13 / 16.0, 16 / 16.0, 13 / 16.0 ); - rh.setTexture( def, def, off, off, off, off ); - rh.renderBlockCurrentBounds( x, y, z, renderer ); - break; - case EAST: - case WEST: - rh.setTexture( off, off, off, off, def, def ); - renderer.uvRotateEast = 2; - renderer.uvRotateWest = 1; - renderer.uvRotateBottom = 2; - renderer.uvRotateTop = 1; - renderer.uvRotateSouth = 0; - renderer.uvRotateNorth = 0; - - final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); - final FlippableIcon ico = blk.getRendererInstance().getTexture( ForgeDirection.EAST ); - ico.setFlip( false, true ); - - renderer.setRenderBounds( 0, 3 / 16.0, 3 / 16.0, 16 / 16.0, 13 / 16.0, 13 / 16.0 ); - rh.renderBlockCurrentBounds( x, y, z, renderer ); - break; - case NORTH: - case SOUTH: - rh.setTexture( off, off, def, def, off, off ); - renderer.uvRotateTop = 3; - renderer.uvRotateBottom = 3; - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 2; - renderer.uvRotateWest = 1; - renderer.setRenderBounds( 3 / 16.0, 3 / 16.0, 0, 13 / 16.0, 13 / 16.0, 16 / 16.0 ); - rh.renderBlockCurrentBounds( x, y, z, renderer ); - break; - default: - break; - } - } - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - rh.setTexture( null ); - } - - @SideOnly( Side.CLIENT ) - private void renderDenseCoveredConnection(final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer, final ForgeDirection of ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( x + of.offsetX, y + of.offsetY, z + of.offsetZ ); - final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; - final IGridHost ghh = te instanceof IGridHost ? (IGridHost) te : null; - - rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of, of.getOpposite() ) ) ); - if( ghh != null && partHost != null && ghh.getCableConnectionType( of ) != AECableType.GLASS && partHost.getColor() != AEColor.Transparent && partHost.getPart( of.getOpposite() ) == null ) - { - rh.setTexture( this.getTexture( partHost.getColor() ) ); - } - else - { - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } - - switch( of ) - { - case DOWN: - rh.setBounds( 4, 0, 4, 12, 5, 12 ); - break; - case EAST: - rh.setBounds( 11, 4, 4, 16, 12, 12 ); - break; - case NORTH: - rh.setBounds( 4, 4, 0, 12, 12, 5 ); - break; - case SOUTH: - rh.setBounds( 4, 4, 11, 12, 12, 16 ); - break; - case UP: - rh.setBounds( 4, 11, 4, 12, 16, 12 ); - break; - case WEST: - rh.setBounds( 0, 4, 4, 5, 12, 12 ); - break; - default: - return; - } - - rh.renderBlock( x, y, z, renderer ); - rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - } - - protected IIcon getDenseCoveredTexture(final AEColor c ) - { - switch( c ) - { - case Black: - return CableBusTextures.MEDenseCovered_Black.getIcon(); - case Blue: - return CableBusTextures.MEDenseCovered_Blue.getIcon(); - case Brown: - return CableBusTextures.MEDenseCovered_Brown.getIcon(); - case Cyan: - return CableBusTextures.MEDenseCovered_Cyan.getIcon(); - case Gray: - return CableBusTextures.MEDenseCovered_Gray.getIcon(); - case Green: - return CableBusTextures.MEDenseCovered_Green.getIcon(); - case LightBlue: - return CableBusTextures.MEDenseCovered_LightBlue.getIcon(); - case LightGray: - return CableBusTextures.MEDenseCovered_LightGrey.getIcon(); - case Lime: - return CableBusTextures.MEDenseCovered_Lime.getIcon(); - case Magenta: - return CableBusTextures.MEDenseCovered_Magenta.getIcon(); - case Orange: - return CableBusTextures.MEDenseCovered_Orange.getIcon(); - case Pink: - return CableBusTextures.MEDenseCovered_Pink.getIcon(); - case Purple: - return CableBusTextures.MEDenseCovered_Purple.getIcon(); - case Red: - return CableBusTextures.MEDenseCovered_Red.getIcon(); - case White: - return CableBusTextures.MEDenseCovered_White.getIcon(); - case Yellow: - return CableBusTextures.MEDenseCovered_Yellow.getIcon(); - default: - } - - return this.getItemStack().getIconIndex(); - } - - private boolean isDense( final ForgeDirection of ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( this.getTile().xCoord + of.offsetX, this.getTile().yCoord + of.offsetY, this.getTile().zCoord + of.offsetZ ); - if( te instanceof IGridHost ) - { - final AECableType t = ( (IGridHost) te ).getCableConnectionType( of.getOpposite() ); - return t == AECableType.DENSE || t == AECableType.DENSE_COVERED || t == AECableType.ULTRA_DENSE || t == AECableType.ULTRA_DENSE_SMART ; - } - return false; - } - - @MENetworkEventSubscribe - public void channelUpdated( final MENetworkChannelsChanged c ) - { - this.getHost().markForUpdate(); - } - - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } +public class PartDenseCableCovered extends PartCable { + @Reflected + public PartDenseCableCovered(final ItemStack is) { + super(is); + + this.getProxy().setFlags(GridFlags.DENSE_CAPACITY, GridFlags.PREFERRED); + } + + @Override + public BusSupport supportsBuses() { + return BusSupport.DENSE_CABLE; + } + + @Override + public AECableType getCableConnectionType() { + return AECableType.DENSE_COVERED; + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + final boolean noLadder = !bch.isBBCollision(); + final double min = noLadder ? 3.0 : 4.9; + final double max = noLadder ? 13.0 : 11.1; + + bch.addBox(min, min, min, max, max, max); + + if (Platform.isServer()) { + final IGridNode n = this.getGridNode(); + if (n != null) { + this.setConnections(n.getConnectedSides()); + } else { + this.getConnections().clear(); + } + } + + for (final ForgeDirection of : this.getConnections()) { + if (this.isDense(of)) { + switch (of) { + case DOWN: + bch.addBox(min, 0.0, min, max, min, max); + break; + case EAST: + bch.addBox(max, min, min, 16.0, max, max); + break; + case NORTH: + bch.addBox(min, min, 0.0, max, max, min); + break; + case SOUTH: + bch.addBox(min, min, max, max, max, 16.0); + break; + case UP: + bch.addBox(min, max, min, max, 16.0, max); + break; + case WEST: + bch.addBox(0.0, min, min, min, max, max); + break; + default: + } + } else { + switch (of) { + case DOWN: + bch.addBox(5.0, 0.0, 5.0, 11.0, 5.0, 11.0); + break; + case EAST: + bch.addBox(11.0, 5.0, 5.0, 16.0, 11.0, 11.0); + break; + case NORTH: + bch.addBox(5.0, 5.0, 0.0, 11.0, 11.0, 5.0); + break; + case SOUTH: + bch.addBox(5.0, 5.0, 11.0, 11.0, 11.0, 16.0); + break; + case UP: + bch.addBox(5.0, 11.0, 5.0, 11.0, 16.0, 11.0); + break; + case WEST: + bch.addBox(0.0, 5.0, 5.0, 5.0, 11.0, 11.0); + break; + default: + } + } + } + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + GL11.glTranslated(-0.0, -0.0, 0.3); + rh.setBounds(4.0f, 4.0f, 2.0f, 12.0f, 12.0f, 14.0f); + + float offU = 0; + float offV = 9; + + OffsetIcon main = new OffsetIcon(this.getTexture(this.getCableColor()), offU, offV); + + for (final ForgeDirection side : EnumSet.of(ForgeDirection.UP, ForgeDirection.DOWN)) { + rh.renderInventoryFace(main, side, renderer); + } + + offU = 9; + offV = 0; + main = new OffsetIcon(this.getTexture(this.getCableColor()), offU, offV); + + for (final ForgeDirection side : EnumSet.of(ForgeDirection.EAST, ForgeDirection.WEST)) { + rh.renderInventoryFace(main, side, renderer); + } + + main = new OffsetIcon(this.getTexture(this.getCableColor()), 0, 0); + + for (final ForgeDirection side : EnumSet.of(ForgeDirection.SOUTH, ForgeDirection.NORTH)) { + rh.renderInventoryFace(main, side, renderer); + } + + rh.setTexture(null); + } + + @Override + public IIcon getTexture(final AEColor c) { + if (c == AEColor.Transparent) { + return AEApi.instance() + .definitions() + .parts() + .cableCovered() + .stack(AEColor.Transparent, 1) + .getIconIndex(); + } + + return this.getCoveredTexture(c); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + this.setRenderCache(rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache())); + rh.setTexture(this.getTexture(this.getCableColor())); + + final EnumSet sides = this.getConnections().clone(); + + boolean hasBuses = false; + for (final ForgeDirection of : this.getConnections()) { + if (!this.isDense(of)) { + hasBuses = true; + } + } + + if (sides.size() != 2 || !this.nonLinear(sides) || hasBuses) { + for (final ForgeDirection of : this.getConnections()) { + if (this.isDense(of)) { + this.renderDenseCoveredConnection(x, y, z, rh, renderer, of); + } else { + this.renderCoveredConnection(x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of); + } + } + + rh.setTexture(this.getDenseCoveredTexture(this.getCableColor())); + rh.setBounds(3, 3, 3, 13, 13, 13); + rh.renderBlock(x, y, z, renderer); + } else { + ForgeDirection selectedSide = ForgeDirection.UNKNOWN; + + for (final ForgeDirection of : this.getConnections()) { + selectedSide = of; + break; + } + + final IIcon def = this.getTexture(this.getCableColor()); + final IIcon off = new OffsetIcon(def, 0, -12); + + switch (selectedSide) { + case DOWN: + case UP: + renderer.setRenderBounds(3 / 16.0, 0, 3 / 16.0, 13 / 16.0, 16 / 16.0, 13 / 16.0); + rh.setTexture(def, def, off, off, off, off); + rh.renderBlockCurrentBounds(x, y, z, renderer); + break; + case EAST: + case WEST: + rh.setTexture(off, off, off, off, def, def); + renderer.uvRotateEast = 2; + renderer.uvRotateWest = 1; + renderer.uvRotateBottom = 2; + renderer.uvRotateTop = 1; + renderer.uvRotateSouth = 0; + renderer.uvRotateNorth = 0; + + final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); + final FlippableIcon ico = blk.getRendererInstance().getTexture(ForgeDirection.EAST); + ico.setFlip(false, true); + + renderer.setRenderBounds(0, 3 / 16.0, 3 / 16.0, 16 / 16.0, 13 / 16.0, 13 / 16.0); + rh.renderBlockCurrentBounds(x, y, z, renderer); + break; + case NORTH: + case SOUTH: + rh.setTexture(off, off, def, def, off, off); + renderer.uvRotateTop = 3; + renderer.uvRotateBottom = 3; + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 2; + renderer.uvRotateWest = 1; + renderer.setRenderBounds(3 / 16.0, 3 / 16.0, 0, 13 / 16.0, 13 / 16.0, 16 / 16.0); + rh.renderBlockCurrentBounds(x, y, z, renderer); + break; + default: + break; + } + } + + renderer.uvRotateBottom = renderer.uvRotateEast = + renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + rh.setTexture(null); + } + + @SideOnly(Side.CLIENT) + private void renderDenseCoveredConnection( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer, + final ForgeDirection of) { + final TileEntity te = + this.getTile().getWorldObj().getTileEntity(x + of.offsetX, y + of.offsetY, z + of.offsetZ); + final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; + final IGridHost ghh = te instanceof IGridHost ? (IGridHost) te : null; + + rh.setFacesToRender(EnumSet.complementOf(EnumSet.of(of, of.getOpposite()))); + if (ghh != null + && partHost != null + && ghh.getCableConnectionType(of) != AECableType.GLASS + && partHost.getColor() != AEColor.Transparent + && partHost.getPart(of.getOpposite()) == null) { + rh.setTexture(this.getTexture(partHost.getColor())); + } else { + rh.setTexture(this.getTexture(this.getCableColor())); + } + + switch (of) { + case DOWN: + rh.setBounds(4, 0, 4, 12, 5, 12); + break; + case EAST: + rh.setBounds(11, 4, 4, 16, 12, 12); + break; + case NORTH: + rh.setBounds(4, 4, 0, 12, 12, 5); + break; + case SOUTH: + rh.setBounds(4, 4, 11, 12, 12, 16); + break; + case UP: + rh.setBounds(4, 11, 4, 12, 16, 12); + break; + case WEST: + rh.setBounds(0, 4, 4, 5, 12, 12); + break; + default: + return; + } + + rh.renderBlock(x, y, z, renderer); + rh.setFacesToRender(EnumSet.allOf(ForgeDirection.class)); + } + + protected IIcon getDenseCoveredTexture(final AEColor c) { + switch (c) { + case Black: + return CableBusTextures.MEDenseCovered_Black.getIcon(); + case Blue: + return CableBusTextures.MEDenseCovered_Blue.getIcon(); + case Brown: + return CableBusTextures.MEDenseCovered_Brown.getIcon(); + case Cyan: + return CableBusTextures.MEDenseCovered_Cyan.getIcon(); + case Gray: + return CableBusTextures.MEDenseCovered_Gray.getIcon(); + case Green: + return CableBusTextures.MEDenseCovered_Green.getIcon(); + case LightBlue: + return CableBusTextures.MEDenseCovered_LightBlue.getIcon(); + case LightGray: + return CableBusTextures.MEDenseCovered_LightGrey.getIcon(); + case Lime: + return CableBusTextures.MEDenseCovered_Lime.getIcon(); + case Magenta: + return CableBusTextures.MEDenseCovered_Magenta.getIcon(); + case Orange: + return CableBusTextures.MEDenseCovered_Orange.getIcon(); + case Pink: + return CableBusTextures.MEDenseCovered_Pink.getIcon(); + case Purple: + return CableBusTextures.MEDenseCovered_Purple.getIcon(); + case Red: + return CableBusTextures.MEDenseCovered_Red.getIcon(); + case White: + return CableBusTextures.MEDenseCovered_White.getIcon(); + case Yellow: + return CableBusTextures.MEDenseCovered_Yellow.getIcon(); + default: + } + + return this.getItemStack().getIconIndex(); + } + + private boolean isDense(final ForgeDirection of) { + final TileEntity te = this.getTile() + .getWorldObj() + .getTileEntity( + this.getTile().xCoord + of.offsetX, + this.getTile().yCoord + of.offsetY, + this.getTile().zCoord + of.offsetZ); + if (te instanceof IGridHost) { + final AECableType t = ((IGridHost) te).getCableConnectionType(of.getOpposite()); + return t == AECableType.DENSE + || t == AECableType.DENSE_COVERED + || t == AECableType.ULTRA_DENSE + || t == AECableType.ULTRA_DENSE_SMART; + } + return false; + } + + @MENetworkEventSubscribe + public void channelUpdated(final MENetworkChannelsChanged c) { + this.getHost().markForUpdate(); + } + + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } } diff --git a/src/main/java/appeng/parts/networking/PartQuartzFiber.java b/src/main/java/appeng/parts/networking/PartQuartzFiber.java index 574f36c1a67..b0105d7a0ec 100644 --- a/src/main/java/appeng/parts/networking/PartQuartzFiber.java +++ b/src/main/java/appeng/parts/networking/PartQuartzFiber.java @@ -18,7 +18,6 @@ package appeng.parts.networking; - import appeng.api.config.Actionable; import appeng.api.networking.GridFlags; import appeng.api.networking.IGridNode; @@ -33,6 +32,8 @@ import appeng.parts.AEBasePart; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.EnumSet; +import java.util.Set; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -42,199 +43,160 @@ import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import java.util.EnumSet; -import java.util.Set; - - -public class PartQuartzFiber extends AEBasePart implements IEnergyGridProvider -{ - - private final AENetworkProxy outerProxy = new AENetworkProxy( this, "outer", this.getProxy().getMachineRepresentation(), true ); - - public PartQuartzFiber( final ItemStack is ) - { - super( is ); - this.getProxy().setIdlePowerUsage( 0 ); - this.getProxy().setFlags( GridFlags.CANNOT_CARRY ); - this.outerProxy.setIdlePowerUsage( 0 ); - this.outerProxy.setFlags( GridFlags.CANNOT_CARRY ); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.GLASS; - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 6, 6, 10, 10, 10, 16 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - GL11.glTranslated( -0.2, -0.3, 0.0 ); - - rh.setTexture( this.getItemStack().getIconIndex() ); - rh.setBounds( 6.0f, 6.0f, 5.0f, 10.0f, 10.0f, 11.0f ); - rh.renderInventoryBox( renderer ); - rh.setTexture( null ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - final IIcon myIcon = this.getItemStack().getIconIndex(); - rh.setTexture( myIcon ); - rh.setBounds( 6, 6, 10, 10, 10, 16 ); - rh.renderBlock( x, y, z, renderer ); - rh.setTexture( null ); - } - - @Override - public void readFromNBT( final NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.outerProxy.readFromNBT( extra ); - } - - @Override - public void writeToNBT( final NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.outerProxy.writeToNBT( extra ); - } - - @Override - public void removeFromWorld() - { - super.removeFromWorld(); - this.outerProxy.invalidate(); - } - - @Override - public void addToWorld() - { - super.addToWorld(); - this.outerProxy.onReady(); - } - - @Override - public void setPartHostInfo( final ForgeDirection side, final IPartHost host, final TileEntity tile ) - { - super.setPartHostInfo( side, host, tile ); - this.outerProxy.setValidSides( EnumSet.of( side ) ); - } - - @Override - public IGridNode getExternalFacingNode() - { - return this.outerProxy.getNode(); - } - - @Override - public int cableConnectionRenderTo() - { - return 16; - } - - @Override - public void onPlacement( final EntityPlayer player, final ItemStack held, final ForgeDirection side ) - { - super.onPlacement( player, held, side ); - this.outerProxy.setOwner( player ); - } - - @Override - public double extractAEPower( final double amt, final Actionable mode, final Set seen ) - { - double acquiredPower = 0; - - try - { - final IEnergyGrid eg = this.getProxy().getEnergy(); - acquiredPower += eg.extractAEPower( amt - acquiredPower, mode, seen ); - } - catch( final GridAccessException e ) - { - // :P - } - - try - { - final IEnergyGrid eg = this.outerProxy.getEnergy(); - acquiredPower += eg.extractAEPower( amt - acquiredPower, mode, seen ); - } - catch( final GridAccessException e ) - { - // :P - } - - return acquiredPower; - } - - @Override - public double injectAEPower( final double amt, final Actionable mode, final Set seen ) - { - - try - { - final IEnergyGrid eg = this.getProxy().getEnergy(); - if( !seen.contains( eg ) ) - { - return eg.injectAEPower( amt, mode, seen ); - } - } - catch( final GridAccessException e ) - { - // :P - } - - try - { - final IEnergyGrid eg = this.outerProxy.getEnergy(); - if( !seen.contains( eg ) ) - { - return eg.injectAEPower( amt, mode, seen ); - } - } - catch( final GridAccessException e ) - { - // :P - } - - return amt; - } - - @Override - public double getEnergyDemand( final double amt, final Set seen ) - { - double demand = 0; - - try - { - final IEnergyGrid eg = this.getProxy().getEnergy(); - demand += eg.getEnergyDemand( amt - demand, seen ); - } - catch( final GridAccessException e ) - { - // :P - } - - try - { - final IEnergyGrid eg = this.outerProxy.getEnergy(); - demand += eg.getEnergyDemand( amt - demand, seen ); - } - catch( final GridAccessException e ) - { - // :P - } - - return demand; - } +public class PartQuartzFiber extends AEBasePart implements IEnergyGridProvider { + + private final AENetworkProxy outerProxy = + new AENetworkProxy(this, "outer", this.getProxy().getMachineRepresentation(), true); + + public PartQuartzFiber(final ItemStack is) { + super(is); + this.getProxy().setIdlePowerUsage(0); + this.getProxy().setFlags(GridFlags.CANNOT_CARRY); + this.outerProxy.setIdlePowerUsage(0); + this.outerProxy.setFlags(GridFlags.CANNOT_CARRY); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.GLASS; + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(6, 6, 10, 10, 10, 16); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + GL11.glTranslated(-0.2, -0.3, 0.0); + + rh.setTexture(this.getItemStack().getIconIndex()); + rh.setBounds(6.0f, 6.0f, 5.0f, 10.0f, 10.0f, 11.0f); + rh.renderInventoryBox(renderer); + rh.setTexture(null); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + final IIcon myIcon = this.getItemStack().getIconIndex(); + rh.setTexture(myIcon); + rh.setBounds(6, 6, 10, 10, 10, 16); + rh.renderBlock(x, y, z, renderer); + rh.setTexture(null); + } + + @Override + public void readFromNBT(final NBTTagCompound extra) { + super.readFromNBT(extra); + this.outerProxy.readFromNBT(extra); + } + + @Override + public void writeToNBT(final NBTTagCompound extra) { + super.writeToNBT(extra); + this.outerProxy.writeToNBT(extra); + } + + @Override + public void removeFromWorld() { + super.removeFromWorld(); + this.outerProxy.invalidate(); + } + + @Override + public void addToWorld() { + super.addToWorld(); + this.outerProxy.onReady(); + } + + @Override + public void setPartHostInfo(final ForgeDirection side, final IPartHost host, final TileEntity tile) { + super.setPartHostInfo(side, host, tile); + this.outerProxy.setValidSides(EnumSet.of(side)); + } + + @Override + public IGridNode getExternalFacingNode() { + return this.outerProxy.getNode(); + } + + @Override + public int cableConnectionRenderTo() { + return 16; + } + + @Override + public void onPlacement(final EntityPlayer player, final ItemStack held, final ForgeDirection side) { + super.onPlacement(player, held, side); + this.outerProxy.setOwner(player); + } + + @Override + public double extractAEPower(final double amt, final Actionable mode, final Set seen) { + double acquiredPower = 0; + + try { + final IEnergyGrid eg = this.getProxy().getEnergy(); + acquiredPower += eg.extractAEPower(amt - acquiredPower, mode, seen); + } catch (final GridAccessException e) { + // :P + } + + try { + final IEnergyGrid eg = this.outerProxy.getEnergy(); + acquiredPower += eg.extractAEPower(amt - acquiredPower, mode, seen); + } catch (final GridAccessException e) { + // :P + } + + return acquiredPower; + } + + @Override + public double injectAEPower(final double amt, final Actionable mode, final Set seen) { + + try { + final IEnergyGrid eg = this.getProxy().getEnergy(); + if (!seen.contains(eg)) { + return eg.injectAEPower(amt, mode, seen); + } + } catch (final GridAccessException e) { + // :P + } + + try { + final IEnergyGrid eg = this.outerProxy.getEnergy(); + if (!seen.contains(eg)) { + return eg.injectAEPower(amt, mode, seen); + } + } catch (final GridAccessException e) { + // :P + } + + return amt; + } + + @Override + public double getEnergyDemand(final double amt, final Set seen) { + double demand = 0; + + try { + final IEnergyGrid eg = this.getProxy().getEnergy(); + demand += eg.getEnergyDemand(amt - demand, seen); + } catch (final GridAccessException e) { + // :P + } + + try { + final IEnergyGrid eg = this.outerProxy.getEnergy(); + demand += eg.getEnergyDemand(amt - demand, seen); + } catch (final GridAccessException e) { + // :P + } + + return demand; + } } diff --git a/src/main/java/appeng/parts/networking/PartUltraDenseCableCovered.java b/src/main/java/appeng/parts/networking/PartUltraDenseCableCovered.java index 2965b46191a..10b26f54d47 100644 --- a/src/main/java/appeng/parts/networking/PartUltraDenseCableCovered.java +++ b/src/main/java/appeng/parts/networking/PartUltraDenseCableCovered.java @@ -9,37 +9,35 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; -public class PartUltraDenseCableCovered extends PartDenseCableCovered -{ +public class PartUltraDenseCableCovered extends PartDenseCableCovered { @Reflected - public PartUltraDenseCableCovered(final ItemStack is ) - { - super( is ); - this.getProxy().setFlags( GridFlags.ULTRA_DENSE_CAPACITY, GridFlags.PREFERRED ); + public PartUltraDenseCableCovered(final ItemStack is) { + super(is); + this.getProxy().setFlags(GridFlags.ULTRA_DENSE_CAPACITY, GridFlags.PREFERRED); } @Override - public AECableType getCableConnectionType() - { + public AECableType getCableConnectionType() { return AECableType.ULTRA_DENSE; } @Override - public IIcon getTexture(final AEColor c ) - { - if( c == AEColor.Transparent ) - { - return AEApi.instance().definitions().parts().cableUltraDenseCovered().stack( AEColor.Transparent, 1 ).getIconIndex(); + public IIcon getTexture(final AEColor c) { + if (c == AEColor.Transparent) { + return AEApi.instance() + .definitions() + .parts() + .cableUltraDenseCovered() + .stack(AEColor.Transparent, 1) + .getIconIndex(); } - return this.getDenseCoveredTexture( c ); + return this.getDenseCoveredTexture(c); } @Override - protected IIcon getDenseCoveredTexture(final AEColor c ) - { - switch( c ) - { + protected IIcon getDenseCoveredTexture(final AEColor c) { + switch (c) { case Black: return CableBusTextures.MEUltraDenseCovered_Black.getIcon(); case Blue: diff --git a/src/main/java/appeng/parts/networking/PartUltraDenseCableSmart.java b/src/main/java/appeng/parts/networking/PartUltraDenseCableSmart.java index 4a578841087..08d412b3ebd 100644 --- a/src/main/java/appeng/parts/networking/PartUltraDenseCableSmart.java +++ b/src/main/java/appeng/parts/networking/PartUltraDenseCableSmart.java @@ -11,34 +11,33 @@ public class PartUltraDenseCableSmart extends PartDenseCable { @Reflected - public PartUltraDenseCableSmart(final ItemStack is ) - { - super( is ); - this.getProxy().setFlags( GridFlags.ULTRA_DENSE_CAPACITY, GridFlags.PREFERRED ); + public PartUltraDenseCableSmart(final ItemStack is) { + super(is); + this.getProxy().setFlags(GridFlags.ULTRA_DENSE_CAPACITY, GridFlags.PREFERRED); } @Override - public AECableType getCableConnectionType() - { + public AECableType getCableConnectionType() { return AECableType.ULTRA_DENSE; } @Override - public IIcon getTexture(final AEColor c ) - { - if( c == AEColor.Transparent ) - { - return AEApi.instance().definitions().parts().cableUltraDenseSmart().stack( AEColor.Transparent, 1 ).getIconIndex(); + public IIcon getTexture(final AEColor c) { + if (c == AEColor.Transparent) { + return AEApi.instance() + .definitions() + .parts() + .cableUltraDenseSmart() + .stack(AEColor.Transparent, 1) + .getIconIndex(); } - return this.getDenseTexture( c ); + return this.getDenseTexture(c); } @Override - protected IIcon getDenseTexture( final AEColor c ) - { - switch( c ) - { + protected IIcon getDenseTexture(final AEColor c) { + switch (c) { case Black: return CableBusTextures.MEUltraDense_Black.getIcon(); case Blue: diff --git a/src/main/java/appeng/parts/p2p/PartP2PGT5Power.java b/src/main/java/appeng/parts/p2p/PartP2PGT5Power.java index ff337630ad0..00219f2a8ff 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PGT5Power.java +++ b/src/main/java/appeng/parts/p2p/PartP2PGT5Power.java @@ -10,6 +10,7 @@ import gregtech.api.interfaces.tileentity.IEnergyConnected; import gregtech.api.util.GT_Utility; import ic2.api.energy.tile.IEnergySink; +import javax.annotation.Nullable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; @@ -18,8 +19,6 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nullable; - public class PartP2PGT5Power extends PartP2PTunnel implements IPartGT5Power { private TileEntity cachedTarget; private boolean isCachedTargetValid; @@ -58,19 +57,23 @@ protected IIcon getTypeTexture() { @Override public boolean onPartActivate(EntityPlayer player, Vec3 pos) { - if (!super.onPartActivate(player, pos) && !player.worldObj.isRemote && player.inventory.getCurrentItem() == null) { + if (!super.onPartActivate(player, pos) + && !player.worldObj.isRemote + && player.inventory.getCurrentItem() == null) { PartP2PGT5Power input = this.getInput(); String inputLoc; if (input == null) { inputLoc = "no input"; } else { TileEntity te = input.getHost().getTile(); - inputLoc = "[" + te.getWorldObj().provider.dimensionId + "](" + te.xCoord + ", " + te.yCoord + ", " + te.zCoord + ")"; + inputLoc = "[" + te.getWorldObj().provider.dimensionId + "](" + te.xCoord + ", " + te.yCoord + ", " + + te.zCoord + ")"; } player.addChatMessage(chatComponent("------", "")); player.addChatMessage(chatComponent("Input location: ", (input == this ? "this block " : "") + inputLoc)); - player.addChatMessage(chatComponent("Name: ", input != null ? input.getCustomName() : this.getCustomName())); + player.addChatMessage( + chatComponent("Name: ", input != null ? input.getCustomName() : this.getCustomName())); player.addChatMessage(chatComponent("Freq: ", "" + this.getFrequency())); return true; } else { @@ -84,12 +87,11 @@ public long injectEnergyUnits(long voltage, long amperage) { long amperes = amperage; long outvoltage = (long) (voltage * (1 - AEConfig.TUNNEL_POWER_LOSS)); try { - for (PartP2PGT5Power t: getOutputs()) { + for (PartP2PGT5Power t : getOutputs()) { long received = t.doOutput(outvoltage, amperes); amperesUsed += received; amperes -= received; - if (amperes <= 0L) - break; + if (amperes <= 0L) break; } } catch (GridAccessException ignored) { } @@ -120,7 +122,8 @@ private TileEntity getTarget() { this.isCachedTargetValid = true; te = this.getTile(); ForgeDirection side = this.getSide(); - return this.cachedTarget = te.getWorldObj().getTileEntity(te.xCoord + side.offsetX, te.yCoord + side.offsetY, te.zCoord + side.offsetZ); + return this.cachedTarget = te.getWorldObj() + .getTileEntity(te.xCoord + side.offsetX, te.yCoord + side.offsetY, te.zCoord + side.offsetZ); } private long doOutput(long aVoltage, long aAmperage) { @@ -133,13 +136,17 @@ private long doOutput(long aVoltage, long aAmperage) { } else { ForgeDirection oppositeSide = this.getSide().getOpposite(); if (te instanceof IEnergyConnected) { - return ((IEnergyConnected) te).injectEnergyUnits((byte) oppositeSide.ordinal(), aVoltage, aAmperage); + return ((IEnergyConnected) te) + .injectEnergyUnits((byte) oppositeSide.ordinal(), aVoltage, aAmperage); } else { if (te instanceof IEnergySink) { if (((IEnergySink) te).acceptsEnergyFrom(this.getTile(), oppositeSide)) { long rUsedAmperes = 0L; - while (aAmperage > rUsedAmperes && ((IEnergySink) te).getDemandedEnergy() > 0.0D && ((IEnergySink) te).injectEnergy(oppositeSide, (double) aVoltage, (double) aVoltage) < (double) aVoltage) - ++rUsedAmperes; + while (aAmperage > rUsedAmperes + && ((IEnergySink) te).getDemandedEnergy() > 0.0D + && ((IEnergySink) te) + .injectEnergy(oppositeSide, (double) aVoltage, (double) aVoltage) + < (double) aVoltage) ++rUsedAmperes; return rUsedAmperes; } @@ -150,16 +157,47 @@ private long doOutput(long aVoltage, long aAmperage) { return 1L; } - if (GregTech_API.mRFExplosions && GregTech_API.sMachineExplosions && ((IEnergyReceiver) te).getMaxEnergyStored(oppositeSide) < rfOut * 600 && rfOut > 32 * GregTech_API.mEUtoRF / 100) { - float tStrength = (long) rfOut < GT_Values.V[0] ? 1.0F : ((long) rfOut < GT_Values.V[1] ? 2.0F : ((long) rfOut < GT_Values.V[2] ? 3.0F : ((long) rfOut < GT_Values.V[3] ? 4.0F : ((long) rfOut < GT_Values.V[4] ? 5.0F : ((long) rfOut < GT_Values.V[4] * 2L ? 6.0F : ((long) rfOut < GT_Values.V[5] ? 7.0F : ((long) rfOut < GT_Values.V[6] ? 8.0F : ((long) rfOut < GT_Values.V[7] ? 9.0F : 10.0F)))))))); + if (GregTech_API.mRFExplosions + && GregTech_API.sMachineExplosions + && ((IEnergyReceiver) te).getMaxEnergyStored(oppositeSide) < rfOut * 600 + && rfOut > 32 * GregTech_API.mEUtoRF / 100) { + float tStrength = (long) rfOut < GT_Values.V[0] + ? 1.0F + : ((long) rfOut < GT_Values.V[1] + ? 2.0F + : ((long) rfOut < GT_Values.V[2] + ? 3.0F + : ((long) rfOut < GT_Values.V[3] + ? 4.0F + : ((long) rfOut < GT_Values.V[4] + ? 5.0F + : ((long) rfOut < GT_Values.V[4] * 2L + ? 6.0F + : ((long) rfOut < GT_Values.V[5] + ? 7.0F + : ((long) rfOut < GT_Values.V[6] + ? 8.0F + : ((long) rfOut + < GT_Values + .V[ + 7] + ? 9.0F + : 10.0F)))))))); int tX = te.xCoord; int tY = te.yCoord; int tZ = te.zCoord; World tWorld = te.getWorldObj(); - GT_Utility.sendSoundToPlayers(tWorld, GregTech_API.sSoundList.get(209), 1.0F, -1.0F, tX, tY, tZ); + GT_Utility.sendSoundToPlayers( + tWorld, GregTech_API.sSoundList.get(209), 1.0F, -1.0F, tX, tY, tZ); tWorld.setBlock(tX, tY, tZ, Blocks.air); if (GregTech_API.sMachineExplosions) { - tWorld.createExplosion(null, (double) tX + 0.5D, (double) tY + 0.5D, (double) tZ + 0.5D, tStrength, true); + tWorld.createExplosion( + null, + (double) tX + 0.5D, + (double) tY + 0.5D, + (double) tZ + 0.5D, + tStrength, + true); } } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PIC2Power.java b/src/main/java/appeng/parts/p2p/PartP2PIC2Power.java index 55e8cc71cd5..cfb9dea6430 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PIC2Power.java +++ b/src/main/java/appeng/parts/p2p/PartP2PIC2Power.java @@ -18,7 +18,6 @@ package appeng.parts.p2p; - import appeng.api.config.PowerUnits; import appeng.integration.IntegrationType; import appeng.me.GridAccessException; @@ -28,6 +27,7 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.LinkedList; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -35,229 +35,189 @@ import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import java.util.LinkedList; - - -@InterfaceList( value = { @Interface( iface = "ic2.api.energy.tile.IEnergySink", iname = IntegrationType.IC2 ), @Interface( iface = "ic2.api.energy.tile.IEnergySource", iname = IntegrationType.IC2 ) } ) -public class PartP2PIC2Power extends PartP2PTunnel implements ic2.api.energy.tile.IEnergySink, ic2.api.energy.tile.IEnergySource -{ - - // two packet buffering... - private double OutputEnergyA; - private double OutputEnergyB; - // two packet buffering... - private double OutputVoltageA; - private double OutputVoltageB; - - public PartP2PIC2Power( final ItemStack is ) - { - super( is ); - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getTypeTexture() - { - return Blocks.diamond_block.getBlockTextureFromSide( 0 ); - } - - @Override - public void readFromNBT( final NBTTagCompound tag ) - { - super.readFromNBT( tag ); - this.OutputEnergyA = tag.getDouble( "OutputPacket" ); - this.OutputEnergyB = tag.getDouble( "OutputPacket2" ); - this.OutputVoltageA = tag.getDouble( "OutputVoltageA" ); - this.OutputVoltageB = tag.getDouble( "OutputVoltageB" ); - } - - @Override - public void writeToNBT( final NBTTagCompound tag ) - { - super.writeToNBT( tag ); - tag.setDouble( "OutputPacket", this.OutputEnergyA ); - tag.setDouble( "OutputPacket2", this.OutputEnergyB ); - tag.setDouble( "OutputVoltageA", this.OutputVoltageA ); - tag.setDouble( "OutputVoltageB", this.OutputVoltageB ); - } - - @Override - public void onTunnelConfigChange() - { - this.getHost().partChanged(); - } - - @Override - public void onTunnelNetworkChange() - { - this.getHost().notifyNeighbors(); - } - - @Override - public boolean acceptsEnergyFrom( final TileEntity emitter, final ForgeDirection direction ) - { - if( !this.isOutput() ) - { - return direction == this.getSide(); - } - return false; - } - - @Override - public boolean emitsEnergyTo( final TileEntity receiver, final ForgeDirection direction ) - { - if( this.isOutput() ) - { - return direction == this.getSide(); - } - return false; - } - - @Override - public double getDemandedEnergy() - { - if( this.isOutput() ) - { - return 0; - } - - try - { - for( final PartP2PIC2Power t : this.getOutputs() ) - { - if( t.OutputEnergyA <= 0.0001 || t.OutputEnergyB <= 0.0001 ) - { - return 2048; - } - } - } - catch( final GridAccessException e ) - { - return 0; - } - - return 0; - } - - @Override - public int getSinkTier() - { - return 4; - } - - @Override - public double injectEnergy( final ForgeDirection directionFrom, final double amount, final double voltage ) - { - final TunnelCollection outs; - try - { - outs = this.getOutputs(); - } - catch( final GridAccessException e ) - { - return amount; - } - - if( outs.isEmpty() ) - { - return amount; - } - - final LinkedList options = new LinkedList(); - for( final PartP2PIC2Power o : outs ) - { - if( o.OutputEnergyA <= 0.01 ) - { - options.add( o ); - } - } - - if( options.isEmpty() ) - { - for( final PartP2PIC2Power o : outs ) - { - if( o.OutputEnergyB <= 0.01 ) - { - options.add( o ); - } - } - } - - if( options.isEmpty() ) - { - for( final PartP2PIC2Power o : outs ) - { - options.add( o ); - } - } - - if( options.isEmpty() ) - { - return amount; - } - - final PartP2PIC2Power x = Platform.pickRandom( options ); - - if( x != null && x.OutputEnergyA <= 0.001 ) - { - this.queueTunnelDrain( PowerUnits.EU, amount ); - x.OutputEnergyA = amount; - x.OutputVoltageA = voltage; - return 0; - } - - if( x != null && x.OutputEnergyB <= 0.001 ) - { - this.queueTunnelDrain( PowerUnits.EU, amount ); - x.OutputEnergyB = amount; - x.OutputVoltageB = voltage; - return 0; - } - - return amount; - } - - public float getPowerDrainPerTick() - { - return 0.5f; - } - - @Override - public double getOfferedEnergy() - { - if( this.isOutput() ) - { - return this.OutputEnergyA; - } - return 0; - } - - @Override - public void drawEnergy( final double amount ) - { - this.OutputEnergyA -= amount; - if( this.OutputEnergyA < 0.001 ) - { - this.OutputEnergyA = this.OutputEnergyB; - this.OutputEnergyB = 0; - - this.OutputVoltageA = this.OutputVoltageB; - this.OutputVoltageB = 0; - } - } - - @Override - public int getSourceTier() - { - if( this.isOutput() ) - { - return this.calculateTierFromVoltage( this.OutputVoltageA ); - } - return 4; - } - - private int calculateTierFromVoltage( final double voltage ) - { - return ic2.api.energy.EnergyNet.instance.getTierFromPower( voltage ); - } +@InterfaceList( + value = { + @Interface(iface = "ic2.api.energy.tile.IEnergySink", iname = IntegrationType.IC2), + @Interface(iface = "ic2.api.energy.tile.IEnergySource", iname = IntegrationType.IC2) + }) +public class PartP2PIC2Power extends PartP2PTunnel + implements ic2.api.energy.tile.IEnergySink, ic2.api.energy.tile.IEnergySource { + + // two packet buffering... + private double OutputEnergyA; + private double OutputEnergyB; + // two packet buffering... + private double OutputVoltageA; + private double OutputVoltageB; + + public PartP2PIC2Power(final ItemStack is) { + super(is); + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getTypeTexture() { + return Blocks.diamond_block.getBlockTextureFromSide(0); + } + + @Override + public void readFromNBT(final NBTTagCompound tag) { + super.readFromNBT(tag); + this.OutputEnergyA = tag.getDouble("OutputPacket"); + this.OutputEnergyB = tag.getDouble("OutputPacket2"); + this.OutputVoltageA = tag.getDouble("OutputVoltageA"); + this.OutputVoltageB = tag.getDouble("OutputVoltageB"); + } + + @Override + public void writeToNBT(final NBTTagCompound tag) { + super.writeToNBT(tag); + tag.setDouble("OutputPacket", this.OutputEnergyA); + tag.setDouble("OutputPacket2", this.OutputEnergyB); + tag.setDouble("OutputVoltageA", this.OutputVoltageA); + tag.setDouble("OutputVoltageB", this.OutputVoltageB); + } + + @Override + public void onTunnelConfigChange() { + this.getHost().partChanged(); + } + + @Override + public void onTunnelNetworkChange() { + this.getHost().notifyNeighbors(); + } + + @Override + public boolean acceptsEnergyFrom(final TileEntity emitter, final ForgeDirection direction) { + if (!this.isOutput()) { + return direction == this.getSide(); + } + return false; + } + + @Override + public boolean emitsEnergyTo(final TileEntity receiver, final ForgeDirection direction) { + if (this.isOutput()) { + return direction == this.getSide(); + } + return false; + } + + @Override + public double getDemandedEnergy() { + if (this.isOutput()) { + return 0; + } + + try { + for (final PartP2PIC2Power t : this.getOutputs()) { + if (t.OutputEnergyA <= 0.0001 || t.OutputEnergyB <= 0.0001) { + return 2048; + } + } + } catch (final GridAccessException e) { + return 0; + } + + return 0; + } + + @Override + public int getSinkTier() { + return 4; + } + + @Override + public double injectEnergy(final ForgeDirection directionFrom, final double amount, final double voltage) { + final TunnelCollection outs; + try { + outs = this.getOutputs(); + } catch (final GridAccessException e) { + return amount; + } + + if (outs.isEmpty()) { + return amount; + } + + final LinkedList options = new LinkedList(); + for (final PartP2PIC2Power o : outs) { + if (o.OutputEnergyA <= 0.01) { + options.add(o); + } + } + + if (options.isEmpty()) { + for (final PartP2PIC2Power o : outs) { + if (o.OutputEnergyB <= 0.01) { + options.add(o); + } + } + } + + if (options.isEmpty()) { + for (final PartP2PIC2Power o : outs) { + options.add(o); + } + } + + if (options.isEmpty()) { + return amount; + } + + final PartP2PIC2Power x = Platform.pickRandom(options); + + if (x != null && x.OutputEnergyA <= 0.001) { + this.queueTunnelDrain(PowerUnits.EU, amount); + x.OutputEnergyA = amount; + x.OutputVoltageA = voltage; + return 0; + } + + if (x != null && x.OutputEnergyB <= 0.001) { + this.queueTunnelDrain(PowerUnits.EU, amount); + x.OutputEnergyB = amount; + x.OutputVoltageB = voltage; + return 0; + } + + return amount; + } + + public float getPowerDrainPerTick() { + return 0.5f; + } + + @Override + public double getOfferedEnergy() { + if (this.isOutput()) { + return this.OutputEnergyA; + } + return 0; + } + + @Override + public void drawEnergy(final double amount) { + this.OutputEnergyA -= amount; + if (this.OutputEnergyA < 0.001) { + this.OutputEnergyA = this.OutputEnergyB; + this.OutputEnergyB = 0; + + this.OutputVoltageA = this.OutputVoltageB; + this.OutputVoltageB = 0; + } + } + + @Override + public int getSourceTier() { + if (this.isOutput()) { + return this.calculateTierFromVoltage(this.OutputVoltageA); + } + return 4; + } + + private int calculateTierFromVoltage(final double voltage) { + return ic2.api.energy.EnergyNet.instance.getTierFromPower(voltage); + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PItems.java b/src/main/java/appeng/parts/p2p/PartP2PItems.java index 79499ad0b4f..1b470a7c3f0 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PItems.java +++ b/src/main/java/appeng/parts/p2p/PartP2PItems.java @@ -18,7 +18,6 @@ package appeng.parts.p2p; - import appeng.api.networking.IGridNode; import appeng.api.networking.events.MENetworkBootingStatusChange; import appeng.api.networking.events.MENetworkChannelsChanged; @@ -44,6 +43,8 @@ import buildcraft.api.transport.IPipeTile.PipeType; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.LinkedList; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.inventory.IInventory; @@ -54,336 +55,272 @@ import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import java.util.LinkedList; -import java.util.List; - - -@Interface( iface = "buildcraft.api.transport.IPipeConnection", iname = IntegrationType.BuildCraftTransport ) -public class PartP2PItems extends PartP2PTunnel implements IPipeConnection, ISidedInventory, IGridTickable -{ - - private final LinkedList which = new LinkedList(); - private int oldSize = 0; - private boolean requested; - private IInventory cachedInv; - - public PartP2PItems( final ItemStack is ) - { - super( is ); - } - - @Override - public void onNeighborChanged() - { - this.cachedInv = null; - final PartP2PItems input = this.getInput(); - if( input != null && this.isOutput() ) - { - input.onTunnelNetworkChange(); - } - } - - private IInventory getDestination() - { - this.requested = true; - - if( this.cachedInv != null ) - { - return this.cachedInv; - } - - final List outs = new LinkedList(); - final TunnelCollection itemTunnels; - - try - { - itemTunnels = this.getOutputs(); - } - catch( final GridAccessException e ) - { - return new AppEngNullInventory(); - } - - for( final PartP2PItems t : itemTunnels ) - { - final IInventory inv = t.getOutputInv(); - if( inv != null ) - { - if( Platform.getRandomInt() % 2 == 0 ) - { - outs.add( inv ); - } - else - { - outs.add( 0, inv ); - } - } - } - - return this.cachedInv = new WrapperChainedInventory( outs ); - } - - private IInventory getOutputInv() - { - IInventory output = null; - - if( this.getProxy().isActive() ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( this.getTile().xCoord + this.getSide().offsetX, this.getTile().yCoord + this.getSide().offsetY, this.getTile().zCoord + this.getSide().offsetZ ); - - if( this.which.contains( this ) ) - { - return null; - } - - this.which.add( this ); - - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport buildcraft = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - if( buildcraft.isPipe( te, this.getSide().getOpposite() ) ) - { - try - { - output = new WrapperBCPipe( te, this.getSide().getOpposite() ); - } - catch( final Throwable ignore ) - { - } - } - } - - /* - * if ( AppEng.INSTANCE.isIntegrationEnabled( "TE" ) ) { ITE thermal = (ITE) AppEng.INSTANCE.getIntegration( - * "TE" ); if ( thermal != null ) { if ( thermal.isPipe( te, side.getOpposite() ) ) { try { output = new - * WrapperTEPipe( te, side.getOpposite() ); } catch (Throwable ignore) { } } } } - */ - - if( output == null ) - { - if( te instanceof TileEntityChest ) - { - output = Platform.GetChestInv( te ); - } - else if( te instanceof ISidedInventory ) - { - output = new WrapperMCISidedInventory( (ISidedInventory) te, this.getSide().getOpposite() ); - } - else if( te instanceof IInventory ) - { - output = (IInventory) te; - } - } - - this.which.pop(); - } - - return output; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.ItemTunnel.getMin(), TickRates.ItemTunnel.getMax(), false, false ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - final boolean wasReq = this.requested; - - if( this.requested && this.cachedInv != null ) - { - ( (WrapperChainedInventory) this.cachedInv ).cycleOrder(); - } - - this.requested = false; - return wasReq ? TickRateModulation.FASTER : TickRateModulation.SLOWER; - } - - @MENetworkEventSubscribe - public void changeStateA( final MENetworkBootingStatusChange bs ) - { - if( !this.isOutput() ) - { - this.cachedInv = null; - final int olderSize = this.oldSize; - this.oldSize = this.getDestination().getSizeInventory(); - if( olderSize != this.oldSize ) - { - this.getHost().notifyNeighbors(); - } - } - } - - @MENetworkEventSubscribe - public void changeStateB( final MENetworkChannelsChanged bs ) - { - if( !this.isOutput() ) - { - this.cachedInv = null; - final int olderSize = this.oldSize; - this.oldSize = this.getDestination().getSizeInventory(); - if( olderSize != this.oldSize ) - { - this.getHost().notifyNeighbors(); - } - } - } - - @MENetworkEventSubscribe - public void changeStateC( final MENetworkPowerStatusChange bs ) - { - if( !this.isOutput() ) - { - this.cachedInv = null; - final int olderSize = this.oldSize; - this.oldSize = this.getDestination().getSizeInventory(); - if( olderSize != this.oldSize ) - { - this.getHost().notifyNeighbors(); - } - } - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getTypeTexture() - { - return Blocks.hopper.getBlockTextureFromSide( 0 ); - } - - @Override - public void onTunnelNetworkChange() - { - if( !this.isOutput() ) - { - this.cachedInv = null; - final int olderSize = this.oldSize; - this.oldSize = this.getDestination().getSizeInventory(); - if( olderSize != this.oldSize ) - { - this.getHost().notifyNeighbors(); - } - } - else - { - final PartP2PItems input = this.getInput(); - if( input != null ) - { - input.getHost().notifyNeighbors(); - } - } - } - - @Override - public int[] getAccessibleSlotsFromSide( final int var1 ) - { - final int[] slots = new int[this.getSizeInventory()]; - for( int x = 0; x < this.getSizeInventory(); x++ ) - { - slots[x] = x; - } - return slots; - } - - @Override - public int getSizeInventory() - { - return this.getDestination().getSizeInventory(); - } - - @Override - public ItemStack getStackInSlot( final int i ) - { - return this.getDestination().getStackInSlot( i ); - } - - @Override - public ItemStack decrStackSize( final int i, final int j ) - { - return this.getDestination().decrStackSize( i, j ); - } - - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - return null; - } - - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - this.getDestination().setInventorySlotContents( i, itemstack ); - } - - @Override - public String getInventoryName() - { - return null; - } - - @Override - public boolean hasCustomInventoryName() - { - return false; - } - - @Override - public int getInventoryStackLimit() - { - return this.getDestination().getInventoryStackLimit(); - } - - @Override - public void markDirty() - { - // eh? - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return false; - } - - @Override - public void openInventory() - { - } - - @Override - public void closeInventory() - { - } - - @Override - public boolean isItemValidForSlot( final int i, final net.minecraft.item.ItemStack itemstack ) - { - return this.getDestination().isItemValidForSlot( i, itemstack ); - } - - @Override - public boolean canInsertItem( final int i, final ItemStack itemstack, final int j ) - { - return this.getDestination().isItemValidForSlot( i, itemstack ); - } - - @Override - public boolean canExtractItem( final int i, final ItemStack itemstack, final int j ) - { - return false; - } - - public float getPowerDrainPerTick() - { - return 2.0f; - } - - @Override - @Method( iname = IntegrationType.BuildCraftTransport ) - public ConnectOverride overridePipeConnection( final PipeType type, final ForgeDirection with ) - { - return this.getSide() == with && type == PipeType.ITEM ? ConnectOverride.CONNECT : ConnectOverride.DEFAULT; - } +@Interface(iface = "buildcraft.api.transport.IPipeConnection", iname = IntegrationType.BuildCraftTransport) +public class PartP2PItems extends PartP2PTunnel + implements IPipeConnection, ISidedInventory, IGridTickable { + + private final LinkedList which = new LinkedList(); + private int oldSize = 0; + private boolean requested; + private IInventory cachedInv; + + public PartP2PItems(final ItemStack is) { + super(is); + } + + @Override + public void onNeighborChanged() { + this.cachedInv = null; + final PartP2PItems input = this.getInput(); + if (input != null && this.isOutput()) { + input.onTunnelNetworkChange(); + } + } + + private IInventory getDestination() { + this.requested = true; + + if (this.cachedInv != null) { + return this.cachedInv; + } + + final List outs = new LinkedList(); + final TunnelCollection itemTunnels; + + try { + itemTunnels = this.getOutputs(); + } catch (final GridAccessException e) { + return new AppEngNullInventory(); + } + + for (final PartP2PItems t : itemTunnels) { + final IInventory inv = t.getOutputInv(); + if (inv != null) { + if (Platform.getRandomInt() % 2 == 0) { + outs.add(inv); + } else { + outs.add(0, inv); + } + } + } + + return this.cachedInv = new WrapperChainedInventory(outs); + } + + private IInventory getOutputInv() { + IInventory output = null; + + if (this.getProxy().isActive()) { + final TileEntity te = this.getTile() + .getWorldObj() + .getTileEntity( + this.getTile().xCoord + this.getSide().offsetX, + this.getTile().yCoord + this.getSide().offsetY, + this.getTile().zCoord + this.getSide().offsetZ); + + if (this.which.contains(this)) { + return null; + } + + this.which.add(this); + + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport)) { + final IBuildCraftTransport buildcraft = (IBuildCraftTransport) + IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport); + if (buildcraft.isPipe(te, this.getSide().getOpposite())) { + try { + output = new WrapperBCPipe(te, this.getSide().getOpposite()); + } catch (final Throwable ignore) { + } + } + } + + /* + * if ( AppEng.INSTANCE.isIntegrationEnabled( "TE" ) ) { ITE thermal = (ITE) AppEng.INSTANCE.getIntegration( + * "TE" ); if ( thermal != null ) { if ( thermal.isPipe( te, side.getOpposite() ) ) { try { output = new + * WrapperTEPipe( te, side.getOpposite() ); } catch (Throwable ignore) { } } } } + */ + + if (output == null) { + if (te instanceof TileEntityChest) { + output = Platform.GetChestInv(te); + } else if (te instanceof ISidedInventory) { + output = new WrapperMCISidedInventory( + (ISidedInventory) te, this.getSide().getOpposite()); + } else if (te instanceof IInventory) { + output = (IInventory) te; + } + } + + this.which.pop(); + } + + return output; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.ItemTunnel.getMin(), TickRates.ItemTunnel.getMax(), false, false); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + final boolean wasReq = this.requested; + + if (this.requested && this.cachedInv != null) { + ((WrapperChainedInventory) this.cachedInv).cycleOrder(); + } + + this.requested = false; + return wasReq ? TickRateModulation.FASTER : TickRateModulation.SLOWER; + } + + @MENetworkEventSubscribe + public void changeStateA(final MENetworkBootingStatusChange bs) { + if (!this.isOutput()) { + this.cachedInv = null; + final int olderSize = this.oldSize; + this.oldSize = this.getDestination().getSizeInventory(); + if (olderSize != this.oldSize) { + this.getHost().notifyNeighbors(); + } + } + } + + @MENetworkEventSubscribe + public void changeStateB(final MENetworkChannelsChanged bs) { + if (!this.isOutput()) { + this.cachedInv = null; + final int olderSize = this.oldSize; + this.oldSize = this.getDestination().getSizeInventory(); + if (olderSize != this.oldSize) { + this.getHost().notifyNeighbors(); + } + } + } + + @MENetworkEventSubscribe + public void changeStateC(final MENetworkPowerStatusChange bs) { + if (!this.isOutput()) { + this.cachedInv = null; + final int olderSize = this.oldSize; + this.oldSize = this.getDestination().getSizeInventory(); + if (olderSize != this.oldSize) { + this.getHost().notifyNeighbors(); + } + } + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getTypeTexture() { + return Blocks.hopper.getBlockTextureFromSide(0); + } + + @Override + public void onTunnelNetworkChange() { + if (!this.isOutput()) { + this.cachedInv = null; + final int olderSize = this.oldSize; + this.oldSize = this.getDestination().getSizeInventory(); + if (olderSize != this.oldSize) { + this.getHost().notifyNeighbors(); + } + } else { + final PartP2PItems input = this.getInput(); + if (input != null) { + input.getHost().notifyNeighbors(); + } + } + } + + @Override + public int[] getAccessibleSlotsFromSide(final int var1) { + final int[] slots = new int[this.getSizeInventory()]; + for (int x = 0; x < this.getSizeInventory(); x++) { + slots[x] = x; + } + return slots; + } + + @Override + public int getSizeInventory() { + return this.getDestination().getSizeInventory(); + } + + @Override + public ItemStack getStackInSlot(final int i) { + return this.getDestination().getStackInSlot(i); + } + + @Override + public ItemStack decrStackSize(final int i, final int j) { + return this.getDestination().decrStackSize(i, j); + } + + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + return null; + } + + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + this.getDestination().setInventorySlotContents(i, itemstack); + } + + @Override + public String getInventoryName() { + return null; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public int getInventoryStackLimit() { + return this.getDestination().getInventoryStackLimit(); + } + + @Override + public void markDirty() { + // eh? + } + + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return false; + } + + @Override + public void openInventory() {} + + @Override + public void closeInventory() {} + + @Override + public boolean isItemValidForSlot(final int i, final net.minecraft.item.ItemStack itemstack) { + return this.getDestination().isItemValidForSlot(i, itemstack); + } + + @Override + public boolean canInsertItem(final int i, final ItemStack itemstack, final int j) { + return this.getDestination().isItemValidForSlot(i, itemstack); + } + + @Override + public boolean canExtractItem(final int i, final ItemStack itemstack, final int j) { + return false; + } + + public float getPowerDrainPerTick() { + return 2.0f; + } + + @Override + @Method(iname = IntegrationType.BuildCraftTransport) + public ConnectOverride overridePipeConnection(final PipeType type, final ForgeDirection with) { + return this.getSide() == with && type == PipeType.ITEM ? ConnectOverride.CONNECT : ConnectOverride.DEFAULT; + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PLight.java b/src/main/java/appeng/parts/p2p/PartP2PLight.java index 88b593ae5a8..07996cad29f 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PLight.java +++ b/src/main/java/appeng/parts/p2p/PartP2PLight.java @@ -18,7 +18,6 @@ package appeng.parts.p2p; - import appeng.api.networking.IGridNode; import appeng.api.networking.events.MENetworkChannelsChanged; import appeng.api.networking.events.MENetworkPowerStatusChange; @@ -30,6 +29,7 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.IOException; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -37,189 +37,159 @@ import net.minecraft.util.IIcon; import net.minecraft.world.World; -import java.io.IOException; - - -public class PartP2PLight extends PartP2PTunnel implements IGridTickable -{ - - private int lastValue = 0; - private float opacity = -1; - - public PartP2PLight( final ItemStack is ) - { - super( is ); - } - - @Override - public void chanRender( final MENetworkChannelsChanged c ) - { - this.onTunnelNetworkChange(); - super.chanRender( c ); - } - - @Override - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.onTunnelNetworkChange(); - super.powerRender( c ); - } - - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - data.writeInt( this.isOutput() ? this.lastValue : 0 ); - } - - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - super.readFromStream( data ); - this.lastValue = data.readInt(); - this.setOutput( this.lastValue > 0 ); - return false; - } - - private boolean doWork() - { - if( this.isOutput() ) - { - return false; - } - - final TileEntity te = this.getTile(); - final World w = te.getWorldObj(); - - final int newLevel = w.getBlockLightValue( te.xCoord + this.getSide().offsetX, te.yCoord + this.getSide().offsetY, te.zCoord + this.getSide().offsetZ ); - - if( this.lastValue != newLevel && this.getProxy().isActive() ) - { - this.lastValue = newLevel; - try - { - for( final PartP2PLight out : this.getOutputs() ) - { - out.setLightLevel( this.lastValue ); - } - } - catch( final GridAccessException e ) - { - // :P - } - return true; - } - return false; - } - - @Override - public void onNeighborChanged() - { - this.opacity = -1; - - this.doWork(); - - if( this.isOutput() ) - { - this.getHost().markForUpdate(); - } - } - - @Override - public int getLightLevel() - { - if( this.isOutput() && this.isPowered() ) - { - return this.blockLight( this.lastValue ); - } - - return 0; - } - - private void setLightLevel( final int out ) - { - this.lastValue = out; - this.getHost().markForUpdate(); - } - - private int blockLight( final int emit ) - { - if( this.opacity < 0 ) - { - final TileEntity te = this.getTile(); - this.opacity = 255 - te.getWorldObj().getBlockLightOpacity( te.xCoord + this.getSide().offsetX, te.yCoord + this.getSide().offsetY, te.zCoord + this.getSide().offsetZ ); - } - - return (int) ( emit * ( this.opacity / 255.0f ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getTypeTexture() - { - return Blocks.quartz_block.getBlockTextureFromSide( 0 ); - } - - @Override - public void readFromNBT( final NBTTagCompound tag ) - { - super.readFromNBT( tag ); - if( tag.hasKey( "opacity" ) ) - { - this.opacity = tag.getFloat( "opacity" ); - } - this.lastValue = tag.getInteger( "lastValue" ); - } - - @Override - public void writeToNBT( final NBTTagCompound tag ) - { - super.writeToNBT( tag ); - tag.setFloat( "opacity", this.opacity ); - tag.setInteger( "lastValue", this.lastValue ); - } - - @Override - public void onTunnelConfigChange() - { - this.onTunnelNetworkChange(); - } - - @Override - public void onTunnelNetworkChange() - { - if( this.isOutput() ) - { - final PartP2PLight src = this.getInput(); - if( src != null && src.getProxy().isActive() ) - { - this.setLightLevel( src.lastValue ); - } - else - { - this.getHost().markForUpdate(); - } - } - else - { - this.doWork(); - } - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.LightTunnel.getMin(), TickRates.LightTunnel.getMax(), false, false ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.doWork() ? TickRateModulation.FASTER : TickRateModulation.SLOWER; - } - - public float getPowerDrainPerTick() - { - return 0.5f; - } +public class PartP2PLight extends PartP2PTunnel implements IGridTickable { + + private int lastValue = 0; + private float opacity = -1; + + public PartP2PLight(final ItemStack is) { + super(is); + } + + @Override + public void chanRender(final MENetworkChannelsChanged c) { + this.onTunnelNetworkChange(); + super.chanRender(c); + } + + @Override + public void powerRender(final MENetworkPowerStatusChange c) { + this.onTunnelNetworkChange(); + super.powerRender(c); + } + + @Override + public void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + data.writeInt(this.isOutput() ? this.lastValue : 0); + } + + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + super.readFromStream(data); + this.lastValue = data.readInt(); + this.setOutput(this.lastValue > 0); + return false; + } + + private boolean doWork() { + if (this.isOutput()) { + return false; + } + + final TileEntity te = this.getTile(); + final World w = te.getWorldObj(); + + final int newLevel = w.getBlockLightValue( + te.xCoord + this.getSide().offsetX, + te.yCoord + this.getSide().offsetY, + te.zCoord + this.getSide().offsetZ); + + if (this.lastValue != newLevel && this.getProxy().isActive()) { + this.lastValue = newLevel; + try { + for (final PartP2PLight out : this.getOutputs()) { + out.setLightLevel(this.lastValue); + } + } catch (final GridAccessException e) { + // :P + } + return true; + } + return false; + } + + @Override + public void onNeighborChanged() { + this.opacity = -1; + + this.doWork(); + + if (this.isOutput()) { + this.getHost().markForUpdate(); + } + } + + @Override + public int getLightLevel() { + if (this.isOutput() && this.isPowered()) { + return this.blockLight(this.lastValue); + } + + return 0; + } + + private void setLightLevel(final int out) { + this.lastValue = out; + this.getHost().markForUpdate(); + } + + private int blockLight(final int emit) { + if (this.opacity < 0) { + final TileEntity te = this.getTile(); + this.opacity = 255 + - te.getWorldObj() + .getBlockLightOpacity( + te.xCoord + this.getSide().offsetX, + te.yCoord + this.getSide().offsetY, + te.zCoord + this.getSide().offsetZ); + } + + return (int) (emit * (this.opacity / 255.0f)); + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getTypeTexture() { + return Blocks.quartz_block.getBlockTextureFromSide(0); + } + + @Override + public void readFromNBT(final NBTTagCompound tag) { + super.readFromNBT(tag); + if (tag.hasKey("opacity")) { + this.opacity = tag.getFloat("opacity"); + } + this.lastValue = tag.getInteger("lastValue"); + } + + @Override + public void writeToNBT(final NBTTagCompound tag) { + super.writeToNBT(tag); + tag.setFloat("opacity", this.opacity); + tag.setInteger("lastValue", this.lastValue); + } + + @Override + public void onTunnelConfigChange() { + this.onTunnelNetworkChange(); + } + + @Override + public void onTunnelNetworkChange() { + if (this.isOutput()) { + final PartP2PLight src = this.getInput(); + if (src != null && src.getProxy().isActive()) { + this.setLightLevel(src.lastValue); + } else { + this.getHost().markForUpdate(); + } + } else { + this.doWork(); + } + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.LightTunnel.getMin(), TickRates.LightTunnel.getMax(), false, false); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.doWork() ? TickRateModulation.FASTER : TickRateModulation.SLOWER; + } + + public float getPowerDrainPerTick() { + return 0.5f; + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PLiquids.java b/src/main/java/appeng/parts/p2p/PartP2PLiquids.java index fca3418fb09..0d1a88dd64f 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PLiquids.java +++ b/src/main/java/appeng/parts/p2p/PartP2PLiquids.java @@ -18,10 +18,13 @@ package appeng.parts.p2p; - import appeng.me.GridAccessException; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Stack; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; @@ -32,293 +35,230 @@ import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Stack; - - -public class PartP2PLiquids extends PartP2PTunnel implements IFluidHandler -{ - - private static final ThreadLocal> DEPTH = new ThreadLocal<>(); - private static final FluidTankInfo[] ACTIVE_TANK = { new FluidTankInfo( null, 10000 ) }; - private static final FluidTankInfo[] INACTIVE_TANK = { new FluidTankInfo( null, 0 ) }; - private IFluidHandler cachedTank; - private int tmpUsed; - - public PartP2PLiquids( final ItemStack is ) - { - super( is ); - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getTypeTexture() - { - return Blocks.lapis_block.getBlockTextureFromSide( 0 ); - } - - @Override - public void onTunnelNetworkChange() - { - this.cachedTank = null; - } - - @Override - public void onNeighborChanged() - { - this.cachedTank = null; - if( this.isOutput() ) - { - final PartP2PLiquids in = this.getInput(); - if( in != null ) - { - in.onTunnelNetworkChange(); - } - } - } - - @Override - public int fill( final ForgeDirection from, final FluidStack resource, final boolean doFill ) - { - if (resource == null || resource.getFluid() == null) - return 0; - - final Stack stack = this.getDepth(); - - for( final PartP2PLiquids t : stack ) - { - if( t == this ) - { - return 0; - } - } - - stack.push( this ); - - final List list = this.getOutputs( resource.getFluid() ); - PartP2PLiquids input = getInput(); - if (input != null) { - list.add(input); - } - - int requestTotal = 0; - - Iterator i = list.iterator(); - while( i.hasNext() ) - { - final PartP2PLiquids l = i.next(); - if (l == this) - continue; - final IFluidHandler tank = l.getTarget(); - if( tank != null ) - { - l.tmpUsed = tank.fill( l.getSide().getOpposite(), resource.copy(), false ); - } - else - { - l.tmpUsed = 0; - } - - if( l.tmpUsed <= 0 ) - { - i.remove(); - } - else - { - requestTotal += l.tmpUsed; - } - } - - if( requestTotal <= 0 ) - { - if( stack.pop() != this ) - { - throw new IllegalStateException( "Invalid Recursion detected." ); - } - - return 0; - } - - if( !doFill ) - { - if( stack.pop() != this ) - { - throw new IllegalStateException( "Invalid Recursion detected." ); - } - - return Math.min( resource.amount, requestTotal ); - } - - int available = resource.amount; - - i = list.iterator(); - int used = 0; - while( i.hasNext() ) - { - final PartP2PLiquids l = i.next(); - if (l == this) - continue; - - final FluidStack insert = resource.copy(); - insert.amount = (int) Math.ceil( insert.amount * ( (double) l.tmpUsed / (double) requestTotal ) ); - if( insert.amount > available ) - { - insert.amount = available; - } - - final IFluidHandler tank = l.getTarget(); - if( tank != null ) - { - l.tmpUsed = tank.fill( l.getSide().getOpposite(), insert, true ); - } - else - { - l.tmpUsed = 0; - } - - available -= l.tmpUsed; - used += l.tmpUsed; - } - - if( stack.pop() != this ) - { - throw new IllegalStateException( "Invalid Recursion detected." ); - } - - return used; - } - - private Stack getDepth() - { - Stack s = DEPTH.get(); - - if( s == null ) - { - DEPTH.set( s = new Stack<>() ); - } - - return s; - } - - private List getOutputs( final Fluid input ) - { - final List outs = new LinkedList<>(); - if (input == null) - return outs; - try - { - for( final PartP2PLiquids l : this.getOutputs() ) - { - if (l == this) - continue; - final IFluidHandler handler = l.getTarget(); - if( handler != null ) - { - if( handler.canFill( l.getSide().getOpposite(), input ) ) - { - outs.add( l ); - } - } - } - } - catch( final GridAccessException e ) - { - // :P - } - - return outs; - } - - private IFluidHandler getTarget() - { - if( !this.getProxy().isActive() ) - { - return null; - } - - if( this.cachedTank != null ) - { - return this.cachedTank; - } - - final TileEntity te = this.getTile().getWorldObj().getTileEntity( this.getTile().xCoord + this.getSide().offsetX, this.getTile().yCoord + this.getSide().offsetY, this.getTile().zCoord + this.getSide().offsetZ ); - if( te instanceof IFluidHandler ) - { - return this.cachedTank = (IFluidHandler) te; - } - - return null; - } - - @Override - public FluidStack drain( final ForgeDirection from, final FluidStack resource, final boolean doDrain ) - { - return null; - } - - @Override - public FluidStack drain( final ForgeDirection from, final int maxDrain, final boolean doDrain ) - { - return null; - } - - private boolean inputAcceptsFluid(Fluid input) - { - PartP2PLiquids l = getInput(); - if (l == null || l == this || input == null) - return false; - final IFluidHandler handler = l.getTarget(); - return handler != null && handler.canFill(l.getSide().getOpposite(), input); - } - - @Override - public boolean canFill( final ForgeDirection from, final Fluid fluid ) - { - return from == this.getSide() && (!this.getOutputs( fluid ).isEmpty() || inputAcceptsFluid(fluid)); - } - - @Override - public boolean canDrain( final ForgeDirection from, final Fluid fluid ) - { - return false; - } - - @Override - public FluidTankInfo[] getTankInfo( final ForgeDirection from ) - { - if( from == this.getSide() ) - { - return this.getTank(); - } - return new FluidTankInfo[0]; - } - - private FluidTankInfo[] getTank() - { - if( this.isOutput() ) - { - final PartP2PLiquids tun = this.getInput(); - if( tun != null ) - { - return ACTIVE_TANK; - } - } - else - { - try - { - if( !this.getOutputs().isEmpty() ) - { - return ACTIVE_TANK; - } - } - catch( final GridAccessException e ) - { - // :( - } - } - return INACTIVE_TANK; - } +public class PartP2PLiquids extends PartP2PTunnel implements IFluidHandler { + + private static final ThreadLocal> DEPTH = new ThreadLocal<>(); + private static final FluidTankInfo[] ACTIVE_TANK = {new FluidTankInfo(null, 10000)}; + private static final FluidTankInfo[] INACTIVE_TANK = {new FluidTankInfo(null, 0)}; + private IFluidHandler cachedTank; + private int tmpUsed; + + public PartP2PLiquids(final ItemStack is) { + super(is); + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getTypeTexture() { + return Blocks.lapis_block.getBlockTextureFromSide(0); + } + + @Override + public void onTunnelNetworkChange() { + this.cachedTank = null; + } + + @Override + public void onNeighborChanged() { + this.cachedTank = null; + if (this.isOutput()) { + final PartP2PLiquids in = this.getInput(); + if (in != null) { + in.onTunnelNetworkChange(); + } + } + } + + @Override + public int fill(final ForgeDirection from, final FluidStack resource, final boolean doFill) { + if (resource == null || resource.getFluid() == null) return 0; + + final Stack stack = this.getDepth(); + + for (final PartP2PLiquids t : stack) { + if (t == this) { + return 0; + } + } + + stack.push(this); + + final List list = this.getOutputs(resource.getFluid()); + PartP2PLiquids input = getInput(); + if (input != null) { + list.add(input); + } + + int requestTotal = 0; + + Iterator i = list.iterator(); + while (i.hasNext()) { + final PartP2PLiquids l = i.next(); + if (l == this) continue; + final IFluidHandler tank = l.getTarget(); + if (tank != null) { + l.tmpUsed = tank.fill(l.getSide().getOpposite(), resource.copy(), false); + } else { + l.tmpUsed = 0; + } + + if (l.tmpUsed <= 0) { + i.remove(); + } else { + requestTotal += l.tmpUsed; + } + } + + if (requestTotal <= 0) { + if (stack.pop() != this) { + throw new IllegalStateException("Invalid Recursion detected."); + } + + return 0; + } + + if (!doFill) { + if (stack.pop() != this) { + throw new IllegalStateException("Invalid Recursion detected."); + } + + return Math.min(resource.amount, requestTotal); + } + + int available = resource.amount; + + i = list.iterator(); + int used = 0; + while (i.hasNext()) { + final PartP2PLiquids l = i.next(); + if (l == this) continue; + + final FluidStack insert = resource.copy(); + insert.amount = (int) Math.ceil(insert.amount * ((double) l.tmpUsed / (double) requestTotal)); + if (insert.amount > available) { + insert.amount = available; + } + + final IFluidHandler tank = l.getTarget(); + if (tank != null) { + l.tmpUsed = tank.fill(l.getSide().getOpposite(), insert, true); + } else { + l.tmpUsed = 0; + } + + available -= l.tmpUsed; + used += l.tmpUsed; + } + + if (stack.pop() != this) { + throw new IllegalStateException("Invalid Recursion detected."); + } + + return used; + } + + private Stack getDepth() { + Stack s = DEPTH.get(); + + if (s == null) { + DEPTH.set(s = new Stack<>()); + } + + return s; + } + + private List getOutputs(final Fluid input) { + final List outs = new LinkedList<>(); + if (input == null) return outs; + try { + for (final PartP2PLiquids l : this.getOutputs()) { + if (l == this) continue; + final IFluidHandler handler = l.getTarget(); + if (handler != null) { + if (handler.canFill(l.getSide().getOpposite(), input)) { + outs.add(l); + } + } + } + } catch (final GridAccessException e) { + // :P + } + + return outs; + } + + private IFluidHandler getTarget() { + if (!this.getProxy().isActive()) { + return null; + } + + if (this.cachedTank != null) { + return this.cachedTank; + } + + final TileEntity te = this.getTile() + .getWorldObj() + .getTileEntity( + this.getTile().xCoord + this.getSide().offsetX, + this.getTile().yCoord + this.getSide().offsetY, + this.getTile().zCoord + this.getSide().offsetZ); + if (te instanceof IFluidHandler) { + return this.cachedTank = (IFluidHandler) te; + } + + return null; + } + + @Override + public FluidStack drain(final ForgeDirection from, final FluidStack resource, final boolean doDrain) { + return null; + } + + @Override + public FluidStack drain(final ForgeDirection from, final int maxDrain, final boolean doDrain) { + return null; + } + + private boolean inputAcceptsFluid(Fluid input) { + PartP2PLiquids l = getInput(); + if (l == null || l == this || input == null) return false; + final IFluidHandler handler = l.getTarget(); + return handler != null && handler.canFill(l.getSide().getOpposite(), input); + } + + @Override + public boolean canFill(final ForgeDirection from, final Fluid fluid) { + return from == this.getSide() && (!this.getOutputs(fluid).isEmpty() || inputAcceptsFluid(fluid)); + } + + @Override + public boolean canDrain(final ForgeDirection from, final Fluid fluid) { + return false; + } + + @Override + public FluidTankInfo[] getTankInfo(final ForgeDirection from) { + if (from == this.getSide()) { + return this.getTank(); + } + return new FluidTankInfo[0]; + } + + private FluidTankInfo[] getTank() { + if (this.isOutput()) { + final PartP2PLiquids tun = this.getInput(); + if (tun != null) { + return ACTIVE_TANK; + } + } else { + try { + if (!this.getOutputs().isEmpty()) { + return ACTIVE_TANK; + } + } catch (final GridAccessException e) { + // :( + } + } + return INACTIVE_TANK; + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2POpenComputers.java b/src/main/java/appeng/parts/p2p/PartP2POpenComputers.java index 48c20892df4..06ea7466347 100644 --- a/src/main/java/appeng/parts/p2p/PartP2POpenComputers.java +++ b/src/main/java/appeng/parts/p2p/PartP2POpenComputers.java @@ -18,7 +18,6 @@ package appeng.parts.p2p; - import appeng.api.networking.events.MENetworkBootingStatusChange; import appeng.api.networking.events.MENetworkChannelsChanged; import appeng.api.networking.events.MENetworkEventSubscribe; @@ -29,6 +28,7 @@ import appeng.transformer.annotations.Integration.InterfaceList; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import javax.annotation.Nullable; import li.cil.oc.api.API; import li.cil.oc.api.Items; import li.cil.oc.api.Network; @@ -38,147 +38,118 @@ import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nullable; - - -@InterfaceList( value = { @Interface( iface = "li.cil.oc.api.network.Environment", iname = IntegrationType.OpenComputers ), @Interface( iface = "li.cil.oc.api.network.SidedEnvironment", iname = IntegrationType.OpenComputers ) } ) -public final class PartP2POpenComputers extends PartP2PTunnel implements Environment, SidedEnvironment -{ - @Nullable - private final Node node; - - public PartP2POpenComputers( final ItemStack is ) - { - super( is ); - - if( !IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.OpenComputers ) ) - { - throw new RuntimeException( "OpenComputers is not installed!" ); - } - - // Avoid NPE when called in pre-init phase (part population). - if( API.network != null ) - { - this.node = Network.newNode( this, Visibility.None ).create(); - } - else - { - this.node = null; // to satisfy final - } - } - - @MENetworkEventSubscribe - public void changeStateA( final MENetworkBootingStatusChange bs ) - { - this.updateConnections(); - } - - @MENetworkEventSubscribe - public void changeStateB( final MENetworkChannelsChanged bs ) - { - this.updateConnections(); - } - - @MENetworkEventSubscribe - public void changeStateC( final MENetworkPowerStatusChange bs ) - { - this.updateConnections(); - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getTypeTexture() - { - return Items.get( "adapter" ).block().getBlockTextureFromSide( 2 ); - } - - @Override - public void removeFromWorld() - { - super.removeFromWorld(); - if( this.node != null ) - { - this.node.remove(); - } - } - - @Override - public void onTunnelNetworkChange() - { - this.updateConnections(); - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - if( this.node != null ) - { - this.node.load( data ); - } - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - if( this.node != null ) - { - this.node.save( data ); - } - } - - private void updateConnections() - { - if( this.getProxy().isPowered() && this.getProxy().isActive() ) - { - // Make sure we're connected to existing OC nodes in the world. - Network.joinOrCreateNetwork( this.getTile() ); - - if( this.isOutput() && this.getInput() != null && this.node != null ) - { - Network.joinOrCreateNetwork( this.getInput().getTile() ); - this.node.connect( this.getInput().node() ); - } - } - else if( this.node != null ) - { - this.node.remove(); - } - } - - @Nullable - @Override - public Node node() - { - return this.node; - } - - @Override - public void onConnect( final Node node ) - { - } - - @Override - public void onDisconnect( final Node node ) - { - } - - @Override - public void onMessage( final Message message ) - { - } - - @Nullable - @Override - public Node sidedNode( final ForgeDirection side ) - { - return side == this.getSide() ? this.node : null; - } - - @Override - public boolean canConnect( final ForgeDirection side ) - { - return side == this.getSide(); - } +@InterfaceList( + value = { + @Interface(iface = "li.cil.oc.api.network.Environment", iname = IntegrationType.OpenComputers), + @Interface(iface = "li.cil.oc.api.network.SidedEnvironment", iname = IntegrationType.OpenComputers) + }) +public final class PartP2POpenComputers extends PartP2PTunnel + implements Environment, SidedEnvironment { + @Nullable + private final Node node; + + public PartP2POpenComputers(final ItemStack is) { + super(is); + + if (!IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.OpenComputers)) { + throw new RuntimeException("OpenComputers is not installed!"); + } + + // Avoid NPE when called in pre-init phase (part population). + if (API.network != null) { + this.node = Network.newNode(this, Visibility.None).create(); + } else { + this.node = null; // to satisfy final + } + } + + @MENetworkEventSubscribe + public void changeStateA(final MENetworkBootingStatusChange bs) { + this.updateConnections(); + } + + @MENetworkEventSubscribe + public void changeStateB(final MENetworkChannelsChanged bs) { + this.updateConnections(); + } + + @MENetworkEventSubscribe + public void changeStateC(final MENetworkPowerStatusChange bs) { + this.updateConnections(); + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getTypeTexture() { + return Items.get("adapter").block().getBlockTextureFromSide(2); + } + + @Override + public void removeFromWorld() { + super.removeFromWorld(); + if (this.node != null) { + this.node.remove(); + } + } + + @Override + public void onTunnelNetworkChange() { + this.updateConnections(); + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + if (this.node != null) { + this.node.load(data); + } + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + if (this.node != null) { + this.node.save(data); + } + } + + private void updateConnections() { + if (this.getProxy().isPowered() && this.getProxy().isActive()) { + // Make sure we're connected to existing OC nodes in the world. + Network.joinOrCreateNetwork(this.getTile()); + + if (this.isOutput() && this.getInput() != null && this.node != null) { + Network.joinOrCreateNetwork(this.getInput().getTile()); + this.node.connect(this.getInput().node()); + } + } else if (this.node != null) { + this.node.remove(); + } + } + + @Nullable + @Override + public Node node() { + return this.node; + } + + @Override + public void onConnect(final Node node) {} + + @Override + public void onDisconnect(final Node node) {} + + @Override + public void onMessage(final Message message) {} + + @Nullable + @Override + public Node sidedNode(final ForgeDirection side) { + return side == this.getSide() ? this.node : null; + } + + @Override + public boolean canConnect(final ForgeDirection side) { + return side == this.getSide(); + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PPressure.java b/src/main/java/appeng/parts/p2p/PartP2PPressure.java index 2e83eaadd85..49170177880 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PPressure.java +++ b/src/main/java/appeng/parts/p2p/PartP2PPressure.java @@ -18,7 +18,6 @@ package appeng.parts.p2p; - import appeng.api.networking.IGridNode; import appeng.api.networking.ticking.IGridTickable; import appeng.api.networking.ticking.TickRateModulation; @@ -27,6 +26,8 @@ import appeng.integration.IntegrationType; import appeng.transformer.annotations.Integration.Interface; import appeng.util.Platform; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; @@ -37,144 +38,122 @@ import pneumaticCraft.api.tileentity.IAirHandler; import pneumaticCraft.api.tileentity.ISidedPneumaticMachine; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - - -@Interface( iface = "pneumaticCraft.api.tileentity.ISidedPneumaticMachine", iname = IntegrationType.PneumaticCraft ) -public final class PartP2PPressure extends PartP2PTunnel implements ISidedPneumaticMachine, IGridTickable -{ - private static final String PRESSURE_NBT_TAG = "pneumaticCraft"; - private static final String PRESSURE_TYPE_ICON_NAME = "compressedIronBlock"; - - /** - * The pressure should never exceed 30f, thus preventing the tunnel from exploding. - */ - private static final float MAX_PRESSURE = 30f; - private static final int VOLUME = 1000; - - @Nonnull - private final IAirHandler handler; - private boolean isConnected = false; - private boolean isValid = false; - - public PartP2PPressure( final ItemStack is ) - { - super( is ); - this.handler = AirHandlerSupplier.getAirHandler( MAX_PRESSURE, MAX_PRESSURE, VOLUME ); - } - - @Override - protected IIcon getTypeTexture() - { - return BlockSupplier.getBlock( PRESSURE_TYPE_ICON_NAME ).getIcon( 0, 0 ); - } - - @Nullable - @Override - public IAirHandler getAirHandler( final ForgeDirection side ) - { - if( side == this.getSide() ) - { - return this.getInternalHandler(); - } - - return null; - } - - @Override - public void onNeighborChanged() - { - super.onNeighborChanged(); - - if( this.isValid ) - { - this.getInternalHandler().onNeighborChange(); - } - } - - @Override - public void addToWorld() - { - super.addToWorld(); - - this.getInternalHandler().validateI( this.getTile() ); - this.isValid = true; - } - - @Override - public void removeFromWorld() - { - super.removeFromWorld(); - - this.isValid = false; - if( this.isOutput() && this.getInput() != null ) - { - this.getInternalHandler().removeConnection( this.getInput().getInternalHandler() ); - this.isConnected = false; - } - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.PressureTunnel.getMin(), TickRates.PressureTunnel.getMax(), false, false ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int TicksSinceLastCall ) - { - if( this.getProxy().isPowered() && this.getProxy().isActive() ) - { - if( !this.isConnected ) - { - this.updateHandler(); - } - - this.getInternalHandler().updateEntityI(); - return TickRateModulation.URGENT; - } - - return TickRateModulation.IDLE; - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - final NBTTagCompound pneumaticNBT = new NBTTagCompound(); - - this.getInternalHandler().writeToNBTI( pneumaticNBT ); - data.setTag( PRESSURE_NBT_TAG, pneumaticNBT ); - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.getInternalHandler().readFromNBTI( data.getCompoundTag( PRESSURE_NBT_TAG ) ); - } - - @Nonnull - private IAirHandler getInternalHandler() - { - return this.handler; - } - - private void updateHandler() - { - if( this.getProxy().isPowered() && this.getProxy().isActive() ) - { - - if( this.isOutput() && this.getInput() != null ) - { - this.getInternalHandler().createConnection( this.getInput().getInternalHandler() ); - this.isConnected = true; - } - - final TileEntity te = this.getTile(); - Platform.notifyBlocksOfNeighbors( te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord ); - } - } - +@Interface(iface = "pneumaticCraft.api.tileentity.ISidedPneumaticMachine", iname = IntegrationType.PneumaticCraft) +public final class PartP2PPressure extends PartP2PTunnel + implements ISidedPneumaticMachine, IGridTickable { + private static final String PRESSURE_NBT_TAG = "pneumaticCraft"; + private static final String PRESSURE_TYPE_ICON_NAME = "compressedIronBlock"; + + /** + * The pressure should never exceed 30f, thus preventing the tunnel from exploding. + */ + private static final float MAX_PRESSURE = 30f; + + private static final int VOLUME = 1000; + + @Nonnull + private final IAirHandler handler; + + private boolean isConnected = false; + private boolean isValid = false; + + public PartP2PPressure(final ItemStack is) { + super(is); + this.handler = AirHandlerSupplier.getAirHandler(MAX_PRESSURE, MAX_PRESSURE, VOLUME); + } + + @Override + protected IIcon getTypeTexture() { + return BlockSupplier.getBlock(PRESSURE_TYPE_ICON_NAME).getIcon(0, 0); + } + + @Nullable + @Override + public IAirHandler getAirHandler(final ForgeDirection side) { + if (side == this.getSide()) { + return this.getInternalHandler(); + } + + return null; + } + + @Override + public void onNeighborChanged() { + super.onNeighborChanged(); + + if (this.isValid) { + this.getInternalHandler().onNeighborChange(); + } + } + + @Override + public void addToWorld() { + super.addToWorld(); + + this.getInternalHandler().validateI(this.getTile()); + this.isValid = true; + } + + @Override + public void removeFromWorld() { + super.removeFromWorld(); + + this.isValid = false; + if (this.isOutput() && this.getInput() != null) { + this.getInternalHandler().removeConnection(this.getInput().getInternalHandler()); + this.isConnected = false; + } + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.PressureTunnel.getMin(), TickRates.PressureTunnel.getMax(), false, false); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int TicksSinceLastCall) { + if (this.getProxy().isPowered() && this.getProxy().isActive()) { + if (!this.isConnected) { + this.updateHandler(); + } + + this.getInternalHandler().updateEntityI(); + return TickRateModulation.URGENT; + } + + return TickRateModulation.IDLE; + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + final NBTTagCompound pneumaticNBT = new NBTTagCompound(); + + this.getInternalHandler().writeToNBTI(pneumaticNBT); + data.setTag(PRESSURE_NBT_TAG, pneumaticNBT); + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.getInternalHandler().readFromNBTI(data.getCompoundTag(PRESSURE_NBT_TAG)); + } + + @Nonnull + private IAirHandler getInternalHandler() { + return this.handler; + } + + private void updateHandler() { + if (this.getProxy().isPowered() && this.getProxy().isActive()) { + + if (this.isOutput() && this.getInput() != null) { + this.getInternalHandler().createConnection(this.getInput().getInternalHandler()); + this.isConnected = true; + } + + final TileEntity te = this.getTile(); + Platform.notifyBlocksOfNeighbors(te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord); + } + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PRFPower.java b/src/main/java/appeng/parts/p2p/PartP2PRFPower.java index 63ea248bb2e..6d771a70096 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PRFPower.java +++ b/src/main/java/appeng/parts/p2p/PartP2PRFPower.java @@ -18,7 +18,6 @@ package appeng.parts.p2p; - import appeng.api.config.PowerUnits; import appeng.integration.IntegrationType; import appeng.integration.modules.helpers.NullRFHandler; @@ -29,244 +28,205 @@ import cofh.api.energy.IEnergyReceiver; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Stack; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Stack; - - -@InterfaceList( value = { @Interface( iface = "cofh.api.energy.IEnergyReceiver", iname = IntegrationType.RF ) } ) -public final class PartP2PRFPower extends PartP2PTunnel implements IEnergyReceiver -{ - private static final ThreadLocal> THREAD_STACK = new ThreadLocal>(); - /** - * Default element based on the null element pattern - */ - private static final IEnergyReceiver NULL_HANDLER = new NullRFHandler(); - private boolean cachedTarget = false; - private IEnergyReceiver outputTarget; - - public PartP2PRFPower( final ItemStack is ) - { - super( is ); - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getTypeTexture() - { - return Blocks.iron_block.getBlockTextureFromSide( 0 ); - } - - @Override - public void onTunnelNetworkChange() - { - this.getHost().notifyNeighbors(); - } - - @Override - public void onNeighborChanged() - { - super.onNeighborChanged(); - - this.cachedTarget = false; - } - - @Override - public int receiveEnergy( final ForgeDirection from, int maxReceive, final boolean simulate ) - { - if( this.isOutput() ) - { - return 0; - } - - if( this.isActive() ) - { - final Stack stack = this.getDepth(); - - for( final PartP2PRFPower t : stack ) - { - if( t == this ) - { - return 0; - } - } - - stack.push( this ); - - int total = 0; - - try - { - for( final PartP2PRFPower t : this.getOutputs() ) - { - if( Platform.getRandomInt() % 2 > 0 ) - { - final int receiver = t.getOutput().receiveEnergy( t.getSide().getOpposite(), maxReceive, simulate ); - maxReceive -= receiver; - total += receiver; - - if( maxReceive <= 0 ) - { - break; - } - } - } - - if( maxReceive > 0 ) - { - for( final PartP2PRFPower t : this.getOutputs() ) - { - final int receiver = t.getOutput().receiveEnergy( t.getSide().getOpposite(), maxReceive, simulate ); - maxReceive -= receiver; - total += receiver; - - if( maxReceive <= 0 ) - { - break; - } - } - } - - this.queueTunnelDrain( PowerUnits.RF, total ); - } - catch( final GridAccessException ignored ) - { - } - - if( stack.pop() != this ) - { - throw new IllegalStateException( "Invalid Recursion detected." ); - } - - return total; - } - - return 0; - } - - private Stack getDepth() - { - Stack s = THREAD_STACK.get(); - - if( s == null ) - { - THREAD_STACK.set( s = new Stack() ); - } - - return s; - } - - private IEnergyReceiver getOutput() - { - if( this.isOutput() ) - { - if( !this.cachedTarget ) - { - final TileEntity self = this.getTile(); - final TileEntity te = self.getWorldObj().getTileEntity( self.xCoord + this.getSide().offsetX, self.yCoord + this.getSide().offsetY, self.zCoord + this.getSide().offsetZ ); - this.outputTarget = te instanceof IEnergyReceiver ? (IEnergyReceiver) te : null; - this.cachedTarget = true; - } - - if( this.outputTarget == null || !this.outputTarget.canConnectEnergy( this.getSide().getOpposite() ) ) - { - return NULL_HANDLER; - } - - return this.outputTarget; - } - return NULL_HANDLER; - } - - @Override - public int getEnergyStored( final ForgeDirection from ) - { - if( this.isOutput() || !this.isActive() ) - { - return 0; - } - - final Stack stack = this.getDepth(); - - for( final PartP2PRFPower t : stack ) - { - if( t == this ) - { - return 0; - } - } - - stack.push( this ); - - int total = 0; - try - { - for( final PartP2PRFPower t : this.getOutputs() ) - { - total += t.getOutput().getEnergyStored( t.getSide().getOpposite() ); - } - } - catch( final GridAccessException e ) - { - return 0; - } - - if( stack.pop() != this ) - { - throw new IllegalStateException( "Invalid Recursion detected." ); - } - - return total; - } - - @Override - public int getMaxEnergyStored( final ForgeDirection from ) - { - if( this.isOutput() || !this.isActive() ) - { - return 0; - } - - final Stack stack = this.getDepth(); - - for( final PartP2PRFPower t : stack ) - { - if( t == this ) - { - return 0; - } - } - - stack.push( this ); - - int total = 0; - try - { - for( final PartP2PRFPower t : this.getOutputs() ) - { - total += t.getOutput().getMaxEnergyStored( t.getSide().getOpposite() ); - } - } - catch( final GridAccessException e ) - { - return 0; - } - - if( stack.pop() != this ) - { - throw new IllegalStateException( "Invalid Recursion detected." ); - } - - return total; - } - - @Override - public boolean canConnectEnergy( final ForgeDirection from ) - { - return true; - } +@InterfaceList(value = {@Interface(iface = "cofh.api.energy.IEnergyReceiver", iname = IntegrationType.RF)}) +public final class PartP2PRFPower extends PartP2PTunnel implements IEnergyReceiver { + private static final ThreadLocal> THREAD_STACK = new ThreadLocal>(); + /** + * Default element based on the null element pattern + */ + private static final IEnergyReceiver NULL_HANDLER = new NullRFHandler(); + + private boolean cachedTarget = false; + private IEnergyReceiver outputTarget; + + public PartP2PRFPower(final ItemStack is) { + super(is); + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getTypeTexture() { + return Blocks.iron_block.getBlockTextureFromSide(0); + } + + @Override + public void onTunnelNetworkChange() { + this.getHost().notifyNeighbors(); + } + + @Override + public void onNeighborChanged() { + super.onNeighborChanged(); + + this.cachedTarget = false; + } + + @Override + public int receiveEnergy(final ForgeDirection from, int maxReceive, final boolean simulate) { + if (this.isOutput()) { + return 0; + } + + if (this.isActive()) { + final Stack stack = this.getDepth(); + + for (final PartP2PRFPower t : stack) { + if (t == this) { + return 0; + } + } + + stack.push(this); + + int total = 0; + + try { + for (final PartP2PRFPower t : this.getOutputs()) { + if (Platform.getRandomInt() % 2 > 0) { + final int receiver = + t.getOutput().receiveEnergy(t.getSide().getOpposite(), maxReceive, simulate); + maxReceive -= receiver; + total += receiver; + + if (maxReceive <= 0) { + break; + } + } + } + + if (maxReceive > 0) { + for (final PartP2PRFPower t : this.getOutputs()) { + final int receiver = + t.getOutput().receiveEnergy(t.getSide().getOpposite(), maxReceive, simulate); + maxReceive -= receiver; + total += receiver; + + if (maxReceive <= 0) { + break; + } + } + } + + this.queueTunnelDrain(PowerUnits.RF, total); + } catch (final GridAccessException ignored) { + } + + if (stack.pop() != this) { + throw new IllegalStateException("Invalid Recursion detected."); + } + + return total; + } + + return 0; + } + + private Stack getDepth() { + Stack s = THREAD_STACK.get(); + + if (s == null) { + THREAD_STACK.set(s = new Stack()); + } + + return s; + } + + private IEnergyReceiver getOutput() { + if (this.isOutput()) { + if (!this.cachedTarget) { + final TileEntity self = this.getTile(); + final TileEntity te = self.getWorldObj() + .getTileEntity( + self.xCoord + this.getSide().offsetX, + self.yCoord + this.getSide().offsetY, + self.zCoord + this.getSide().offsetZ); + this.outputTarget = te instanceof IEnergyReceiver ? (IEnergyReceiver) te : null; + this.cachedTarget = true; + } + + if (this.outputTarget == null + || !this.outputTarget.canConnectEnergy(this.getSide().getOpposite())) { + return NULL_HANDLER; + } + + return this.outputTarget; + } + return NULL_HANDLER; + } + + @Override + public int getEnergyStored(final ForgeDirection from) { + if (this.isOutput() || !this.isActive()) { + return 0; + } + + final Stack stack = this.getDepth(); + + for (final PartP2PRFPower t : stack) { + if (t == this) { + return 0; + } + } + + stack.push(this); + + int total = 0; + try { + for (final PartP2PRFPower t : this.getOutputs()) { + total += t.getOutput().getEnergyStored(t.getSide().getOpposite()); + } + } catch (final GridAccessException e) { + return 0; + } + + if (stack.pop() != this) { + throw new IllegalStateException("Invalid Recursion detected."); + } + + return total; + } + + @Override + public int getMaxEnergyStored(final ForgeDirection from) { + if (this.isOutput() || !this.isActive()) { + return 0; + } + + final Stack stack = this.getDepth(); + + for (final PartP2PRFPower t : stack) { + if (t == this) { + return 0; + } + } + + stack.push(this); + + int total = 0; + try { + for (final PartP2PRFPower t : this.getOutputs()) { + total += t.getOutput().getMaxEnergyStored(t.getSide().getOpposite()); + } + } catch (final GridAccessException e) { + return 0; + } + + if (stack.pop() != this) { + throw new IllegalStateException("Invalid Recursion detected."); + } + + return total; + } + + @Override + public boolean canConnectEnergy(final ForgeDirection from) { + return true; + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PRedstone.java b/src/main/java/appeng/parts/p2p/PartP2PRedstone.java index d2b421569bb..fbbfefc202f 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PRedstone.java +++ b/src/main/java/appeng/parts/p2p/PartP2PRedstone.java @@ -18,7 +18,6 @@ package appeng.parts.p2p; - import appeng.api.networking.events.MENetworkBootingStatusChange; import appeng.api.networking.events.MENetworkChannelsChanged; import appeng.api.networking.events.MENetworkEventSubscribe; @@ -35,177 +34,145 @@ import net.minecraft.util.IIcon; import net.minecraft.world.World; - -public class PartP2PRedstone extends PartP2PTunnel -{ - - private int power; - private boolean recursive = false; - - public PartP2PRedstone( final ItemStack is ) - { - super( is ); - } - - @MENetworkEventSubscribe - public void changeStateA( final MENetworkBootingStatusChange bs ) - { - this.setNetworkReady(); - } - - private void setNetworkReady() - { - if( this.isOutput() ) - { - final PartP2PRedstone in = this.getInput(); - if( in != null ) - { - this.putInput( in.power ); - } - } - } - - private void putInput( final Object o ) - { - if( this.recursive ) - { - return; - } - - this.recursive = true; - if( this.isOutput() && this.getProxy().isActive() ) - { - final int newPower = (Integer) o; - if( this.power != newPower ) - { - this.power = newPower; - this.notifyNeighbors(); - } - } - this.recursive = false; - } - - private void notifyNeighbors() - { - final World worldObj = this.getTile().getWorldObj(); - - final int xCoord = this.getTile().xCoord; - final int yCoord = this.getTile().yCoord; - final int zCoord = this.getTile().zCoord; - - Platform.notifyBlocksOfNeighbors( worldObj, xCoord, yCoord, zCoord ); - - // and this cause sometimes it can go thought walls. - Platform.notifyBlocksOfNeighbors( worldObj, xCoord - 1, yCoord, zCoord ); - Platform.notifyBlocksOfNeighbors( worldObj, xCoord, yCoord - 1, zCoord ); - Platform.notifyBlocksOfNeighbors( worldObj, xCoord, yCoord, zCoord - 1 ); - Platform.notifyBlocksOfNeighbors( worldObj, xCoord, yCoord, zCoord + 1 ); - Platform.notifyBlocksOfNeighbors( worldObj, xCoord, yCoord + 1, zCoord ); - Platform.notifyBlocksOfNeighbors( worldObj, xCoord + 1, yCoord, zCoord ); - } - - @MENetworkEventSubscribe - public void changeStateB( final MENetworkChannelsChanged bs ) - { - this.setNetworkReady(); - } - - @MENetworkEventSubscribe - public void changeStateC( final MENetworkPowerStatusChange bs ) - { - this.setNetworkReady(); - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getTypeTexture() - { - return Blocks.redstone_block.getBlockTextureFromSide( 0 ); - } - - @Override - public void readFromNBT( final NBTTagCompound tag ) - { - super.readFromNBT( tag ); - this.power = tag.getInteger( "power" ); - } - - @Override - public void writeToNBT( final NBTTagCompound tag ) - { - super.writeToNBT( tag ); - tag.setInteger( "power", this.power ); - } - - @Override - public void onTunnelNetworkChange() - { - this.setNetworkReady(); - } - - public float getPowerDrainPerTick() - { - return 0.5f; - } - - @Override - public void onNeighborChanged() - { - if( !this.isOutput() ) - { - final int x = this.getTile().xCoord + this.getSide().offsetX; - final int y = this.getTile().yCoord + this.getSide().offsetY; - final int z = this.getTile().zCoord + this.getSide().offsetZ; - - final Block b = this.getTile().getWorldObj().getBlock( x, y, z ); - if( b != null && !this.isOutput() ) - { - int srcSide = this.getSide().ordinal(); - if( b instanceof BlockRedstoneWire ) - { - srcSide = 1; - } - this.power = b.isProvidingStrongPower( this.getTile().getWorldObj(), x, y, z, srcSide ); - this.power = Math.max( this.power, b.isProvidingWeakPower( this.getTile().getWorldObj(), x, y, z, srcSide ) ); - this.sendToOutput( this.power ); - } - else - { - this.sendToOutput( 0 ); - } - } - } - - @Override - public boolean canConnectRedstone() - { - return true; - } - - @Override - public int isProvidingStrongPower() - { - return this.isOutput() ? this.power : 0; - } - - @Override - public int isProvidingWeakPower() - { - return this.isOutput() ? this.power : 0; - } - - private void sendToOutput( final int power ) - { - try - { - for( final PartP2PRedstone rs : this.getOutputs() ) - { - rs.putInput( power ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } +public class PartP2PRedstone extends PartP2PTunnel { + + private int power; + private boolean recursive = false; + + public PartP2PRedstone(final ItemStack is) { + super(is); + } + + @MENetworkEventSubscribe + public void changeStateA(final MENetworkBootingStatusChange bs) { + this.setNetworkReady(); + } + + private void setNetworkReady() { + if (this.isOutput()) { + final PartP2PRedstone in = this.getInput(); + if (in != null) { + this.putInput(in.power); + } + } + } + + private void putInput(final Object o) { + if (this.recursive) { + return; + } + + this.recursive = true; + if (this.isOutput() && this.getProxy().isActive()) { + final int newPower = (Integer) o; + if (this.power != newPower) { + this.power = newPower; + this.notifyNeighbors(); + } + } + this.recursive = false; + } + + private void notifyNeighbors() { + final World worldObj = this.getTile().getWorldObj(); + + final int xCoord = this.getTile().xCoord; + final int yCoord = this.getTile().yCoord; + final int zCoord = this.getTile().zCoord; + + Platform.notifyBlocksOfNeighbors(worldObj, xCoord, yCoord, zCoord); + + // and this cause sometimes it can go thought walls. + Platform.notifyBlocksOfNeighbors(worldObj, xCoord - 1, yCoord, zCoord); + Platform.notifyBlocksOfNeighbors(worldObj, xCoord, yCoord - 1, zCoord); + Platform.notifyBlocksOfNeighbors(worldObj, xCoord, yCoord, zCoord - 1); + Platform.notifyBlocksOfNeighbors(worldObj, xCoord, yCoord, zCoord + 1); + Platform.notifyBlocksOfNeighbors(worldObj, xCoord, yCoord + 1, zCoord); + Platform.notifyBlocksOfNeighbors(worldObj, xCoord + 1, yCoord, zCoord); + } + + @MENetworkEventSubscribe + public void changeStateB(final MENetworkChannelsChanged bs) { + this.setNetworkReady(); + } + + @MENetworkEventSubscribe + public void changeStateC(final MENetworkPowerStatusChange bs) { + this.setNetworkReady(); + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getTypeTexture() { + return Blocks.redstone_block.getBlockTextureFromSide(0); + } + + @Override + public void readFromNBT(final NBTTagCompound tag) { + super.readFromNBT(tag); + this.power = tag.getInteger("power"); + } + + @Override + public void writeToNBT(final NBTTagCompound tag) { + super.writeToNBT(tag); + tag.setInteger("power", this.power); + } + + @Override + public void onTunnelNetworkChange() { + this.setNetworkReady(); + } + + public float getPowerDrainPerTick() { + return 0.5f; + } + + @Override + public void onNeighborChanged() { + if (!this.isOutput()) { + final int x = this.getTile().xCoord + this.getSide().offsetX; + final int y = this.getTile().yCoord + this.getSide().offsetY; + final int z = this.getTile().zCoord + this.getSide().offsetZ; + + final Block b = this.getTile().getWorldObj().getBlock(x, y, z); + if (b != null && !this.isOutput()) { + int srcSide = this.getSide().ordinal(); + if (b instanceof BlockRedstoneWire) { + srcSide = 1; + } + this.power = b.isProvidingStrongPower(this.getTile().getWorldObj(), x, y, z, srcSide); + this.power = Math.max( + this.power, b.isProvidingWeakPower(this.getTile().getWorldObj(), x, y, z, srcSide)); + this.sendToOutput(this.power); + } else { + this.sendToOutput(0); + } + } + } + + @Override + public boolean canConnectRedstone() { + return true; + } + + @Override + public int isProvidingStrongPower() { + return this.isOutput() ? this.power : 0; + } + + @Override + public int isProvidingWeakPower() { + return this.isOutput() ? this.power : 0; + } + + private void sendToOutput(final int power) { + try { + for (final PartP2PRedstone rs : this.getOutputs()) { + rs.putInput(power); + } + } catch (final GridAccessException e) { + // :P + } + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PTunnel.java b/src/main/java/appeng/parts/p2p/PartP2PTunnel.java index debebaec9b2..a7c3c0a4762 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PTunnel.java +++ b/src/main/java/appeng/parts/p2p/PartP2PTunnel.java @@ -18,7 +18,6 @@ package appeng.parts.p2p; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -44,6 +43,8 @@ import com.google.common.base.Optional; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.Collection; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.entity.player.EntityPlayer; @@ -55,506 +56,445 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.ForgeEventFactory; -import java.util.ArrayList; -import java.util.Collection; - - -public abstract class PartP2PTunnel extends PartBasicState -{ - private final TunnelCollection type = new TunnelCollection( null, this.getClass() ); - private boolean output; - private long freq; - - public PartP2PTunnel( final ItemStack is ) - { - super( is ); - } - - public TunnelCollection getCollection( final Collection collection, final Class c ) - { - if( this.type.matches( c ) ) - { - this.type.setSource( collection ); - return this.type; - } - - return null; - } - - public T getInput() - { - if( this.getFrequency() == 0 ) - { - return null; - } - - try - { - final PartP2PTunnel tunnel = this.getProxy().getP2P().getInput( this.getFrequency() ); - if( this.getClass().isInstance( tunnel ) ) - { - return (T) tunnel; - } - } - catch( final GridAccessException e ) - { - // :P - } - return null; - } - - public TunnelCollection getOutputs() throws GridAccessException - { - if( this.getProxy().isActive() ) - { - return (TunnelCollection) this.getProxy().getP2P().getOutputs( this.getFrequency(), this.getClass() ); - } - return new TunnelCollection( new ArrayList(), this.getClass() ); - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 5, 5, 12, 11, 11, 13 ); - bch.addBox( 3, 3, 13, 13, 13, 14 ); - bch.addBox( 2, 2, 14, 14, 14, 16 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) - { - rh.setTexture( this.getTypeTexture() ); - - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderInventoryBox( renderer ); - - rh.setTexture( CableBusTextures.PartTunnelSides.getIcon(), CableBusTextures.PartTunnelSides.getIcon(), CableBusTextures.BlockP2PTunnel2.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartTunnelSides.getIcon(), CableBusTextures.PartTunnelSides.getIcon() ); - - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderInventoryBox( renderer ); - } - - /** - * @return If enabled it returns the icon of an AE quartz block, else vanilla quartz block icon - */ - protected IIcon getTypeTexture() - { - final Optional maybeBlock = AEApi.instance().definitions().blocks().quartz().maybeBlock(); - if( maybeBlock.isPresent() ) - { - return maybeBlock.get().getIcon( 0, 0 ); - } - else - { - return Blocks.quartz_block.getIcon( 0, 0 ); - } - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( this.getTypeTexture() ); - - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( CableBusTextures.PartTunnelSides.getIcon(), CableBusTextures.PartTunnelSides.getIcon(), CableBusTextures.BlockP2PTunnel2.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartTunnelSides.getIcon(), CableBusTextures.PartTunnelSides.getIcon() ); - - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setBounds( 3, 3, 13, 13, 13, 14 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( CableBusTextures.BlockP2PTunnel3.getIcon() ); - - rh.setBounds( 6, 5, 12, 10, 11, 13 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setBounds( 5, 6, 12, 11, 10, 13 ); - rh.renderBlock( x, y, z, renderer ); - - this.renderLights( x, y, z, rh, renderer ); - } - - @Override - public ItemStack getItemStack( final PartItemStack type ) - { - if( type == PartItemStack.World || type == PartItemStack.Network || type == PartItemStack.Wrench || type == PartItemStack.Pick ) - { - return super.getItemStack( type ); - } - - final Optional maybeMEStack = AEApi.instance().definitions().parts().p2PTunnelME().maybeStack( 1 ); - if( maybeMEStack.isPresent() ) - { - return maybeMEStack.get(); - } - - return super.getItemStack( type ); - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.setOutput( data.getBoolean( "output" ) ); - this.setFrequency( data.getLong( "freq" ) ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setBoolean( "output", this.isOutput() ); - data.setLong( "freq", this.getFrequency() ); - } - - @Override - public int cableConnectionRenderTo() - { - return 1; - } - - @Override - public boolean useStandardMemoryCard() - { - return false; - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - final ItemStack is = player.inventory.getCurrentItem(); - - // UniqueIdentifier id = GameRegistry.findUniqueIdentifierFor( is.getItem() ); - // AELog.info( "ID:" + id.toString() + " : " + is.getItemDamage() ); - - final TunnelType tt = AEApi.instance().registries().p2pTunnel().getTunnelTypeByItem( is ); - if( is != null && is.getItem() instanceof IMemoryCard ) - { - if( ForgeEventFactory.onItemUseStart( player, is, 1 ) <= 0 ) - return false; - - final IMemoryCard mc = (IMemoryCard) is.getItem(); - final NBTTagCompound data = mc.getData( is ); - - final ItemStack newType = ItemStack.loadItemStackFromNBT( data ); - final long freq = data.getLong( "freq" ); - - if( newType != null ) - { - if( newType.getItem() instanceof IPartItem ) - { - final IPart testPart = ( (IPartItem) newType.getItem() ).createPartFromItemStack( newType ); - if( testPart instanceof PartP2PTunnel ) - { - this.getHost().removePart( this.getSide(), true ); - final ForgeDirection dir = this.getHost().addPart( newType, this.getSide(), player ); - final IPart newBus = this.getHost().getPart( dir ); - - if( newBus instanceof PartP2PTunnel ) - { - final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; - newTunnel.setOutput( true ); - - try - { - final P2PCache p2p = newTunnel.getProxy().getP2P(); - p2p.updateFreq( newTunnel, freq ); - PartP2PTunnel input = p2p.getInput(freq); - if (input != null) - newTunnel.setCustomNameInternal(input.getCustomName()); - } - catch( final GridAccessException e ) - { - // :P - } - - newTunnel.onTunnelNetworkChange(); - } - - mc.notifyUser( player, MemoryCardMessages.SETTINGS_LOADED ); - return true; - } - } - } - mc.notifyUser( player, MemoryCardMessages.INVALID_MACHINE ); - } - else if( !player.isSneaking() && is != null && is.getItem() instanceof IToolWrench && !Platform.isClient()) - { - printConnectionInfo(player); - } - else if( tt != null ) // attunement - { - ItemStack newType = null; - - final IParts parts = AEApi.instance().definitions().parts(); - - switch( tt ) - { - case LIGHT: - for( final ItemStack stack : parts.p2PTunnelLight().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case RF_POWER: - for( final ItemStack stack : parts.p2PTunnelRF().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case FLUID: - for( final ItemStack stack : parts.p2PTunnelLiquids().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case IC2_POWER: - for( final ItemStack stack : parts.p2PTunnelEU().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case ITEM: - for( final ItemStack stack : parts.p2PTunnelItems().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case ME: - for( final ItemStack stack : parts.p2PTunnelME().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case REDSTONE: - for( final ItemStack stack : parts.p2PTunnelRedstone().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case COMPUTER_MESSAGE: - for( final ItemStack stack : parts.p2PTunnelOpenComputers().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case PRESSURE: - for( final ItemStack stack : parts.p2PTunnelPneumaticCraft().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case GT_POWER: - for( final ItemStack stack : parts.p2PTunnelGregtech().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - default: - break; - } - - if( newType != null && !Platform.isSameItem( newType, this.getItemStack() ) ) - { - final boolean oldOutput = this.isOutput(); - final long myFreq = this.getFrequency(); - - this.getHost().removePart( this.getSide(), false ); - final ForgeDirection dir = this.getHost().addPart( newType, this.getSide(), player ); - final IPart newBus = this.getHost().getPart( dir ); - - if( newBus instanceof PartP2PTunnel ) - { - final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; - newTunnel.setOutput( oldOutput ); - newTunnel.onTunnelNetworkChange(); - - try - { - final P2PCache p2p = newTunnel.getProxy().getP2P(); - p2p.updateFreq( newTunnel, myFreq ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - Platform.notifyBlocksOfNeighbors( this.getTile().getWorldObj(), this.getTile().xCoord, this.getTile().yCoord, this.getTile().zCoord ); - return true; - } - } - - return false; - } - - private void printConnectionInfo(EntityPlayer player) - { - if (isOutput()) - { - PartP2PTunnel input = getInput(); - if (input == null) - player.addChatMessage(PlayerMessages.TunnelNotConnected.get()); - else - { - TileEntity t = input.getTile(); - player.addChatMessage(new ChatComponentTranslation( PlayerMessages.TunnelInputIsAt.getName(), t.xCoord,t.yCoord,t.zCoord)); - } - } - else - { - try - { - TunnelCollection oo = getOutputs(); - if (oo.isEmpty()) - player.addChatMessage(PlayerMessages.TunnelHasNoOutputs.get()); - else - { - player.addChatMessage(PlayerMessages.TunnelOutputsAreAt.get()); - for (PartP2PTunnel t : oo) - { - TileEntity te = t.getTile(); - if (te != null) - player.addChatMessage(new ChatComponentText("(" + te.xCoord + ", " + te.yCoord + ", " + te.zCoord + ")")); - } - } - } - catch (GridAccessException ignored) - { - player.addChatMessage(PlayerMessages.TunnelNotConnected.get()); - } - } - } - - @Override - public boolean onPartShiftActivate( final EntityPlayer player, final Vec3 pos ) - { - final ItemStack is = player.inventory.getCurrentItem(); - if( is != null && is.getItem() instanceof IMemoryCard ) - { - if( ForgeEventFactory.onItemUseStart( player, is, 1 ) <= 0 ) - return false; - - final IMemoryCard mc = (IMemoryCard) is.getItem(); - final NBTTagCompound data = new NBTTagCompound(); - - long newFreq = this.getFrequency(); - final boolean wasOutput = this.isOutput(); - this.setOutput( false ); - - if( wasOutput || this.getFrequency() == 0 ) - { - newFreq = System.currentTimeMillis(); - } - - try - { - this.getProxy().getP2P().updateFreq( this, newFreq ); - } - catch( final GridAccessException e ) - { - // :P - } - - this.onTunnelConfigChange(); - - final ItemStack p2pItem = this.getItemStack( PartItemStack.Wrench ); - final String type = p2pItem.getUnlocalizedName(); - - p2pItem.writeToNBT( data ); - data.setLong( "freq", this.getFrequency() ); - if (hasCustomName()) - data.setString("custom_name", getCustomName()); - - mc.setMemoryCardContents( is, type + ".name", data ); - mc.notifyUser( player, MemoryCardMessages.SETTINGS_SAVED ); - return true; - } - return false; - } - - public void onTunnelConfigChange() - { - } - - public void onTunnelNetworkChange() - { - - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getBreakingTexture() - { - return CableBusTextures.BlockP2PTunnel2.getIcon(); - } - - protected void queueTunnelDrain( final PowerUnits unit, final double f ) - { - final double ae_to_tax = unit.convertTo( PowerUnits.AE, f * AEConfig.TUNNEL_POWER_LOSS ); - - try - { - this.getProxy().getEnergy().extractAEPower( ae_to_tax, Actionable.MODULATE, PowerMultiplier.ONE ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - public long getFrequency() - { - return this.freq; - } - - public void setFrequency( final long freq ) - { - this.freq = freq; - } - - public boolean isOutput() - { - return this.output; - } - - void setOutput( final boolean output ) - { - this.output = output; - } - - @Override - public void setCustomName(String name) { - T i = getInput(); - if (i != null) { - i.setCustomNameInternal(name); - try { - for (T o : getOutputs()) - o.setCustomNameInternal(name); - } catch (GridAccessException ignored) { - } - } - else // let unlinked tunnel have a name - super.setCustomName(name); - } - void setCustomNameInternal(String name) - { - super.setCustomName(name); - } +public abstract class PartP2PTunnel extends PartBasicState { + private final TunnelCollection type = new TunnelCollection(null, this.getClass()); + private boolean output; + private long freq; + + public PartP2PTunnel(final ItemStack is) { + super(is); + } + + public TunnelCollection getCollection( + final Collection collection, final Class c) { + if (this.type.matches(c)) { + this.type.setSource(collection); + return this.type; + } + + return null; + } + + public T getInput() { + if (this.getFrequency() == 0) { + return null; + } + + try { + final PartP2PTunnel tunnel = this.getProxy().getP2P().getInput(this.getFrequency()); + if (this.getClass().isInstance(tunnel)) { + return (T) tunnel; + } + } catch (final GridAccessException e) { + // :P + } + return null; + } + + public TunnelCollection getOutputs() throws GridAccessException { + if (this.getProxy().isActive()) { + return (TunnelCollection) this.getProxy().getP2P().getOutputs(this.getFrequency(), this.getClass()); + } + return new TunnelCollection(new ArrayList(), this.getClass()); + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(5, 5, 12, 11, 11, 13); + bch.addBox(3, 3, 13, 13, 13, 14); + bch.addBox(2, 2, 14, 14, 14, 16); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture(this.getTypeTexture()); + + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderInventoryBox(renderer); + + rh.setTexture( + CableBusTextures.PartTunnelSides.getIcon(), + CableBusTextures.PartTunnelSides.getIcon(), + CableBusTextures.BlockP2PTunnel2.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartTunnelSides.getIcon(), + CableBusTextures.PartTunnelSides.getIcon()); + + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderInventoryBox(renderer); + } + + /** + * @return If enabled it returns the icon of an AE quartz block, else vanilla quartz block icon + */ + protected IIcon getTypeTexture() { + final Optional maybeBlock = + AEApi.instance().definitions().blocks().quartz().maybeBlock(); + if (maybeBlock.isPresent()) { + return maybeBlock.get().getIcon(0, 0); + } else { + return Blocks.quartz_block.getIcon(0, 0); + } + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + this.setRenderCache(rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache())); + rh.setTexture(this.getTypeTexture()); + + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture( + CableBusTextures.PartTunnelSides.getIcon(), + CableBusTextures.PartTunnelSides.getIcon(), + CableBusTextures.BlockP2PTunnel2.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartTunnelSides.getIcon(), + CableBusTextures.PartTunnelSides.getIcon()); + + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(3, 3, 13, 13, 13, 14); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture(CableBusTextures.BlockP2PTunnel3.getIcon()); + + rh.setBounds(6, 5, 12, 10, 11, 13); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(5, 6, 12, 11, 10, 13); + rh.renderBlock(x, y, z, renderer); + + this.renderLights(x, y, z, rh, renderer); + } + + @Override + public ItemStack getItemStack(final PartItemStack type) { + if (type == PartItemStack.World + || type == PartItemStack.Network + || type == PartItemStack.Wrench + || type == PartItemStack.Pick) { + return super.getItemStack(type); + } + + final Optional maybeMEStack = + AEApi.instance().definitions().parts().p2PTunnelME().maybeStack(1); + if (maybeMEStack.isPresent()) { + return maybeMEStack.get(); + } + + return super.getItemStack(type); + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.setOutput(data.getBoolean("output")); + this.setFrequency(data.getLong("freq")); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setBoolean("output", this.isOutput()); + data.setLong("freq", this.getFrequency()); + } + + @Override + public int cableConnectionRenderTo() { + return 1; + } + + @Override + public boolean useStandardMemoryCard() { + return false; + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + final ItemStack is = player.inventory.getCurrentItem(); + + // UniqueIdentifier id = GameRegistry.findUniqueIdentifierFor( is.getItem() ); + // AELog.info( "ID:" + id.toString() + " : " + is.getItemDamage() ); + + final TunnelType tt = AEApi.instance().registries().p2pTunnel().getTunnelTypeByItem(is); + if (is != null && is.getItem() instanceof IMemoryCard) { + if (ForgeEventFactory.onItemUseStart(player, is, 1) <= 0) return false; + + final IMemoryCard mc = (IMemoryCard) is.getItem(); + final NBTTagCompound data = mc.getData(is); + + final ItemStack newType = ItemStack.loadItemStackFromNBT(data); + final long freq = data.getLong("freq"); + + if (newType != null) { + if (newType.getItem() instanceof IPartItem) { + final IPart testPart = ((IPartItem) newType.getItem()).createPartFromItemStack(newType); + if (testPart instanceof PartP2PTunnel) { + this.getHost().removePart(this.getSide(), true); + final ForgeDirection dir = this.getHost().addPart(newType, this.getSide(), player); + final IPart newBus = this.getHost().getPart(dir); + + if (newBus instanceof PartP2PTunnel) { + final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; + newTunnel.setOutput(true); + + try { + final P2PCache p2p = newTunnel.getProxy().getP2P(); + p2p.updateFreq(newTunnel, freq); + PartP2PTunnel input = p2p.getInput(freq); + if (input != null) newTunnel.setCustomNameInternal(input.getCustomName()); + } catch (final GridAccessException e) { + // :P + } + + newTunnel.onTunnelNetworkChange(); + } + + mc.notifyUser(player, MemoryCardMessages.SETTINGS_LOADED); + return true; + } + } + } + mc.notifyUser(player, MemoryCardMessages.INVALID_MACHINE); + } else if (!player.isSneaking() && is != null && is.getItem() instanceof IToolWrench && !Platform.isClient()) { + printConnectionInfo(player); + } else if (tt != null) // attunement + { + ItemStack newType = null; + + final IParts parts = AEApi.instance().definitions().parts(); + + switch (tt) { + case LIGHT: + for (final ItemStack stack : + parts.p2PTunnelLight().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case RF_POWER: + for (final ItemStack stack : + parts.p2PTunnelRF().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case FLUID: + for (final ItemStack stack : + parts.p2PTunnelLiquids().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case IC2_POWER: + for (final ItemStack stack : + parts.p2PTunnelEU().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case ITEM: + for (final ItemStack stack : + parts.p2PTunnelItems().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case ME: + for (final ItemStack stack : + parts.p2PTunnelME().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case REDSTONE: + for (final ItemStack stack : + parts.p2PTunnelRedstone().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case COMPUTER_MESSAGE: + for (final ItemStack stack : + parts.p2PTunnelOpenComputers().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case PRESSURE: + for (final ItemStack stack : + parts.p2PTunnelPneumaticCraft().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case GT_POWER: + for (final ItemStack stack : + parts.p2PTunnelGregtech().maybeStack(1).asSet()) { + newType = stack; + } + break; + + default: + break; + } + + if (newType != null && !Platform.isSameItem(newType, this.getItemStack())) { + final boolean oldOutput = this.isOutput(); + final long myFreq = this.getFrequency(); + + this.getHost().removePart(this.getSide(), false); + final ForgeDirection dir = this.getHost().addPart(newType, this.getSide(), player); + final IPart newBus = this.getHost().getPart(dir); + + if (newBus instanceof PartP2PTunnel) { + final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; + newTunnel.setOutput(oldOutput); + newTunnel.onTunnelNetworkChange(); + + try { + final P2PCache p2p = newTunnel.getProxy().getP2P(); + p2p.updateFreq(newTunnel, myFreq); + } catch (final GridAccessException e) { + // :P + } + } + + Platform.notifyBlocksOfNeighbors( + this.getTile().getWorldObj(), + this.getTile().xCoord, + this.getTile().yCoord, + this.getTile().zCoord); + return true; + } + } + + return false; + } + + private void printConnectionInfo(EntityPlayer player) { + if (isOutput()) { + PartP2PTunnel input = getInput(); + if (input == null) player.addChatMessage(PlayerMessages.TunnelNotConnected.get()); + else { + TileEntity t = input.getTile(); + player.addChatMessage(new ChatComponentTranslation( + PlayerMessages.TunnelInputIsAt.getName(), t.xCoord, t.yCoord, t.zCoord)); + } + } else { + try { + TunnelCollection oo = getOutputs(); + if (oo.isEmpty()) player.addChatMessage(PlayerMessages.TunnelHasNoOutputs.get()); + else { + player.addChatMessage(PlayerMessages.TunnelOutputsAreAt.get()); + for (PartP2PTunnel t : oo) { + TileEntity te = t.getTile(); + if (te != null) + player.addChatMessage( + new ChatComponentText("(" + te.xCoord + ", " + te.yCoord + ", " + te.zCoord + ")")); + } + } + } catch (GridAccessException ignored) { + player.addChatMessage(PlayerMessages.TunnelNotConnected.get()); + } + } + } + + @Override + public boolean onPartShiftActivate(final EntityPlayer player, final Vec3 pos) { + final ItemStack is = player.inventory.getCurrentItem(); + if (is != null && is.getItem() instanceof IMemoryCard) { + if (ForgeEventFactory.onItemUseStart(player, is, 1) <= 0) return false; + + final IMemoryCard mc = (IMemoryCard) is.getItem(); + final NBTTagCompound data = new NBTTagCompound(); + + long newFreq = this.getFrequency(); + final boolean wasOutput = this.isOutput(); + this.setOutput(false); + + if (wasOutput || this.getFrequency() == 0) { + newFreq = System.currentTimeMillis(); + } + + try { + this.getProxy().getP2P().updateFreq(this, newFreq); + } catch (final GridAccessException e) { + // :P + } + + this.onTunnelConfigChange(); + + final ItemStack p2pItem = this.getItemStack(PartItemStack.Wrench); + final String type = p2pItem.getUnlocalizedName(); + + p2pItem.writeToNBT(data); + data.setLong("freq", this.getFrequency()); + if (hasCustomName()) data.setString("custom_name", getCustomName()); + + mc.setMemoryCardContents(is, type + ".name", data); + mc.notifyUser(player, MemoryCardMessages.SETTINGS_SAVED); + return true; + } + return false; + } + + public void onTunnelConfigChange() {} + + public void onTunnelNetworkChange() {} + + @Override + @SideOnly(Side.CLIENT) + public IIcon getBreakingTexture() { + return CableBusTextures.BlockP2PTunnel2.getIcon(); + } + + protected void queueTunnelDrain(final PowerUnits unit, final double f) { + final double ae_to_tax = unit.convertTo(PowerUnits.AE, f * AEConfig.TUNNEL_POWER_LOSS); + + try { + this.getProxy().getEnergy().extractAEPower(ae_to_tax, Actionable.MODULATE, PowerMultiplier.ONE); + } catch (final GridAccessException e) { + // :P + } + } + + public long getFrequency() { + return this.freq; + } + + public void setFrequency(final long freq) { + this.freq = freq; + } + + public boolean isOutput() { + return this.output; + } + + void setOutput(final boolean output) { + this.output = output; + } + + @Override + public void setCustomName(String name) { + T i = getInput(); + if (i != null) { + i.setCustomNameInternal(name); + try { + for (T o : getOutputs()) o.setCustomNameInternal(name); + } catch (GridAccessException ignored) { + } + } else // let unlinked tunnel have a name + super.setCustomName(name); + } + + void setCustomNameInternal(String name) { + super.setCustomName(name); + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java b/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java index 7e49047ec64..59c0ebca8eb 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java +++ b/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java @@ -18,7 +18,6 @@ package appeng.parts.p2p; - import appeng.api.AEApi; import appeng.api.exceptions.FailedConnection; import appeng.api.networking.GridFlags; @@ -36,217 +35,183 @@ import appeng.me.cache.helpers.Connections; import appeng.me.cache.helpers.TunnelConnection; import appeng.me.helpers.AENetworkProxy; +import java.util.EnumSet; +import java.util.Iterator; +import java.util.LinkedList; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.LinkedList; - - -public class PartP2PTunnelME extends PartP2PTunnel implements IGridTickable -{ - - private final Connections connection = new Connections( this ); - private final AENetworkProxy outerProxy = new AENetworkProxy( this, "outer", null, true ); - - public PartP2PTunnelME( final ItemStack is ) - { - super( is ); - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL, GridFlags.COMPRESSED_CHANNEL ); - if (AEConfig.instance.p2pBackboneTransfer) - this.outerProxy.setFlags( GridFlags.DENSE_CAPACITY, GridFlags.ULTRA_DENSE_CAPACITY, GridFlags.CANNOT_CARRY_COMPRESSED ); - else - this.outerProxy.setFlags( GridFlags.DENSE_CAPACITY, GridFlags.CANNOT_CARRY_COMPRESSED ); - } - - @Override - public void readFromNBT( final NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.outerProxy.readFromNBT( extra ); - } - - @Override - public void writeToNBT( final NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.outerProxy.writeToNBT( extra ); - } - - @Override - public void onTunnelNetworkChange() - { - super.onTunnelNetworkChange(); - if( !this.isOutput() ) - { - try - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.DENSE; - } - - @Override - public void removeFromWorld() - { - super.removeFromWorld(); - this.outerProxy.invalidate(); - } - - @Override - public void addToWorld() - { - super.addToWorld(); - this.outerProxy.onReady(); - } - - @Override - public void setPartHostInfo( final ForgeDirection side, final IPartHost host, final TileEntity tile ) - { - super.setPartHostInfo( side, host, tile ); - this.outerProxy.setValidSides( EnumSet.of( side ) ); - } - - @Override - public IGridNode getExternalFacingNode() - { - return this.outerProxy.getNode(); - } - - @Override - public void onPlacement( final EntityPlayer player, final ItemStack held, final ForgeDirection side ) - { - super.onPlacement( player, held, side ); - this.outerProxy.setOwner( player ); - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.METunnel.getMin(), TickRates.METunnel.getMax(), true, false ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - // just move on... - try - { - if( !this.getProxy().getPath().isNetworkBooting() ) - { - if( !this.getProxy().getEnergy().isNetworkPowered() ) - { - this.connection.markDestroy(); - TickHandler.INSTANCE.addCallable( this.getTile().getWorldObj(), this.connection ); - } - else - { - if( this.getProxy().isActive() ) - { - this.connection.markCreate(); - TickHandler.INSTANCE.addCallable( this.getTile().getWorldObj(), this.connection ); - } - else - { - this.connection.markDestroy(); - TickHandler.INSTANCE.addCallable( this.getTile().getWorldObj(), this.connection ); - } - } - - return TickRateModulation.SLEEP; - } - } - catch( final GridAccessException e ) - { - // meh? - } - - return TickRateModulation.IDLE; - } - - public void updateConnections( final Connections connections ) - { - if( connections.isDestroy() ) - { - for( final TunnelConnection cw : this.connection.getConnections().values() ) - { - cw.getConnection().destroy(); - } - - this.connection.getConnections().clear(); - } - else if( connections.isCreate() ) - { - - final Iterator i = this.connection.getConnections().values().iterator(); - while( i.hasNext() ) - { - final TunnelConnection cw = i.next(); - try - { - if( cw.getTunnel().getProxy().getGrid() != this.getProxy().getGrid() ) - { - cw.getConnection().destroy(); - i.remove(); - } - else if( !cw.getTunnel().getProxy().isActive() ) - { - cw.getConnection().destroy(); - i.remove(); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - - final LinkedList newSides = new LinkedList(); - try - { - for( final PartP2PTunnelME me : this.getOutputs() ) - { - if( me.getProxy().isActive() && connections.getConnections().get( me.getGridNode() ) == null ) - { - newSides.add( me ); - } - } - - for( final PartP2PTunnelME me : newSides ) - { - try - { - connections.getConnections().put( me.getGridNode(), new TunnelConnection( me, AEApi.instance().createGridConnection( this.outerProxy.getNode(), me.outerProxy.getNode() ) ) ); - } - catch( final FailedConnection e ) - { - final TileEntity start = this.getTile(); - final TileEntity end = me.getTile(); - AELog.warn( "Failed to establish a ME P2P Tunnel between the tunnels at [x=%d, y=%d, z=%d, dim=%d] and [x=%d, y=%d, z=%d, dim=%d]", - start.xCoord, start.yCoord, start.zCoord, start.hasWorldObj() ? start.getWorldObj().provider.dimensionId : Integer.MAX_VALUE, - end.xCoord, end.yCoord, end.zCoord, end.hasWorldObj() ? end.getWorldObj().provider.dimensionId : Integer.MAX_VALUE ); - // :( - } - } - } - catch( final GridAccessException e ) - { - AELog.debug( e ); - } - } - } +public class PartP2PTunnelME extends PartP2PTunnel implements IGridTickable { + + private final Connections connection = new Connections(this); + private final AENetworkProxy outerProxy = new AENetworkProxy(this, "outer", null, true); + + public PartP2PTunnelME(final ItemStack is) { + super(is); + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL, GridFlags.COMPRESSED_CHANNEL); + if (AEConfig.instance.p2pBackboneTransfer) + this.outerProxy.setFlags( + GridFlags.DENSE_CAPACITY, GridFlags.ULTRA_DENSE_CAPACITY, GridFlags.CANNOT_CARRY_COMPRESSED); + else this.outerProxy.setFlags(GridFlags.DENSE_CAPACITY, GridFlags.CANNOT_CARRY_COMPRESSED); + } + + @Override + public void readFromNBT(final NBTTagCompound extra) { + super.readFromNBT(extra); + this.outerProxy.readFromNBT(extra); + } + + @Override + public void writeToNBT(final NBTTagCompound extra) { + super.writeToNBT(extra); + this.outerProxy.writeToNBT(extra); + } + + @Override + public void onTunnelNetworkChange() { + super.onTunnelNetworkChange(); + if (!this.isOutput()) { + try { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // :P + } + } + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.DENSE; + } + + @Override + public void removeFromWorld() { + super.removeFromWorld(); + this.outerProxy.invalidate(); + } + + @Override + public void addToWorld() { + super.addToWorld(); + this.outerProxy.onReady(); + } + + @Override + public void setPartHostInfo(final ForgeDirection side, final IPartHost host, final TileEntity tile) { + super.setPartHostInfo(side, host, tile); + this.outerProxy.setValidSides(EnumSet.of(side)); + } + + @Override + public IGridNode getExternalFacingNode() { + return this.outerProxy.getNode(); + } + + @Override + public void onPlacement(final EntityPlayer player, final ItemStack held, final ForgeDirection side) { + super.onPlacement(player, held, side); + this.outerProxy.setOwner(player); + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.METunnel.getMin(), TickRates.METunnel.getMax(), true, false); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + // just move on... + try { + if (!this.getProxy().getPath().isNetworkBooting()) { + if (!this.getProxy().getEnergy().isNetworkPowered()) { + this.connection.markDestroy(); + TickHandler.INSTANCE.addCallable(this.getTile().getWorldObj(), this.connection); + } else { + if (this.getProxy().isActive()) { + this.connection.markCreate(); + TickHandler.INSTANCE.addCallable(this.getTile().getWorldObj(), this.connection); + } else { + this.connection.markDestroy(); + TickHandler.INSTANCE.addCallable(this.getTile().getWorldObj(), this.connection); + } + } + + return TickRateModulation.SLEEP; + } + } catch (final GridAccessException e) { + // meh? + } + + return TickRateModulation.IDLE; + } + + public void updateConnections(final Connections connections) { + if (connections.isDestroy()) { + for (final TunnelConnection cw : this.connection.getConnections().values()) { + cw.getConnection().destroy(); + } + + this.connection.getConnections().clear(); + } else if (connections.isCreate()) { + + final Iterator i = + this.connection.getConnections().values().iterator(); + while (i.hasNext()) { + final TunnelConnection cw = i.next(); + try { + if (cw.getTunnel().getProxy().getGrid() != this.getProxy().getGrid()) { + cw.getConnection().destroy(); + i.remove(); + } else if (!cw.getTunnel().getProxy().isActive()) { + cw.getConnection().destroy(); + i.remove(); + } + } catch (final GridAccessException e) { + // :P + } + } + + final LinkedList newSides = new LinkedList(); + try { + for (final PartP2PTunnelME me : this.getOutputs()) { + if (me.getProxy().isActive() && connections.getConnections().get(me.getGridNode()) == null) { + newSides.add(me); + } + } + + for (final PartP2PTunnelME me : newSides) { + try { + connections + .getConnections() + .put( + me.getGridNode(), + new TunnelConnection( + me, + AEApi.instance() + .createGridConnection( + this.outerProxy.getNode(), me.outerProxy.getNode()))); + } catch (final FailedConnection e) { + final TileEntity start = this.getTile(); + final TileEntity end = me.getTile(); + AELog.warn( + "Failed to establish a ME P2P Tunnel between the tunnels at [x=%d, y=%d, z=%d, dim=%d] and [x=%d, y=%d, z=%d, dim=%d]", + start.xCoord, + start.yCoord, + start.zCoord, + start.hasWorldObj() ? start.getWorldObj().provider.dimensionId : Integer.MAX_VALUE, + end.xCoord, + end.yCoord, + end.zCoord, + end.hasWorldObj() ? end.getWorldObj().provider.dimensionId : Integer.MAX_VALUE); + // :( + } + } + } catch (final GridAccessException e) { + AELog.debug(e); + } + } + } } diff --git a/src/main/java/appeng/parts/reporting/AbstractPartDisplay.java b/src/main/java/appeng/parts/reporting/AbstractPartDisplay.java index 013777aea8f..1b5c869d351 100644 --- a/src/main/java/appeng/parts/reporting/AbstractPartDisplay.java +++ b/src/main/java/appeng/parts/reporting/AbstractPartDisplay.java @@ -18,7 +18,6 @@ package appeng.parts.reporting; - import appeng.api.parts.IPartRenderHelper; import appeng.client.texture.CableBusTextures; import cpw.mods.fml.relauncher.Side; @@ -29,7 +28,6 @@ import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; - /** * A more sophisticated part overlapping all 3 textures. *

@@ -41,112 +39,112 @@ * @version rv3 * @since rv3 */ -public abstract class AbstractPartDisplay extends AbstractPartReporting -{ - - public AbstractPartDisplay( final ItemStack is ) - { - super( is, true ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - - final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); - final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); - - rh.setTexture( sideTexture, sideTexture, backTexture, this.getItemStack().getIconIndex(), sideTexture, sideTexture ); - rh.renderInventoryBox( renderer ); - - rh.setInvColor( this.getColor().whiteVariant ); - rh.renderInventoryFace( this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer ); - - rh.setInvColor( this.getColor().mediumVariant ); - rh.renderInventoryFace( this.getFrontDark().getIcon(), ForgeDirection.SOUTH, renderer ); - - rh.setInvColor( this.getColor().blackVariant ); - rh.renderInventoryFace( this.getFrontColored().getIcon(), ForgeDirection.SOUTH, renderer ); - - rh.setBounds( 4, 4, 13, 12, 12, 14 ); - rh.renderInventoryBox( renderer ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - - final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); - final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); - - rh.setTexture( sideTexture, sideTexture, backTexture, this.getItemStack().getIconIndex(), sideTexture, sideTexture ); - - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderBlock( x, y, z, renderer ); - - if( this.getLightLevel() > 0 ) - { - final int l = 13; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - } - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = this.getSpin(); - - Tessellator.instance.setColorOpaque_I( this.getColor().whiteVariant ); - rh.renderFace( x, y, z, this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer ); - - Tessellator.instance.setColorOpaque_I( this.getColor().mediumVariant ); - rh.renderFace( x, y, z, this.getFrontDark().getIcon(), ForgeDirection.SOUTH, renderer ); - - Tessellator.instance.setColorOpaque_I( this.getColor().blackVariant ); - rh.renderFace( x, y, z, this.getFrontColored().getIcon(), ForgeDirection.SOUTH, renderer ); - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - - final IIcon sideStatusTexture = CableBusTextures.PartMonitorSidesStatus.getIcon(); - - rh.setTexture( sideStatusTexture, sideStatusTexture, backTexture, this.getItemStack().getIconIndex(), sideStatusTexture, sideStatusTexture ); - - rh.setBounds( 4, 4, 13, 12, 12, 14 ); - rh.renderBlock( x, y, z, renderer ); - - final boolean hasChan = ( this.getClientFlags() & ( PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG ) ) == ( PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG ); - final boolean hasPower = ( this.getClientFlags() & PartPanel.POWERED_FLAG ) == PartPanel.POWERED_FLAG; - - if( hasChan ) - { - final int l = 14; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - Tessellator.instance.setColorOpaque_I( this.getColor().blackVariant ); - } - else if( hasPower ) - { - final int l = 9; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - Tessellator.instance.setColorOpaque_I( this.getColor().whiteVariant ); - } - else - { - Tessellator.instance.setBrightness( 0 ); - Tessellator.instance.setColorOpaque_I( 0x000000 ); - } - - final IIcon sideStatusLightTexture = CableBusTextures.PartMonitorSidesStatusLights.getIcon(); - - rh.renderFace( x, y, z, sideStatusLightTexture, ForgeDirection.EAST, renderer ); - rh.renderFace( x, y, z, sideStatusLightTexture, ForgeDirection.WEST, renderer ); - rh.renderFace( x, y, z, sideStatusLightTexture, ForgeDirection.UP, renderer ); - rh.renderFace( x, y, z, sideStatusLightTexture, ForgeDirection.DOWN, renderer ); - } +public abstract class AbstractPartDisplay extends AbstractPartReporting { - @Override - public boolean isLightSource() - { - return false; - } + public AbstractPartDisplay(final ItemStack is) { + super(is, true); + } + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setBounds(2, 2, 14, 14, 14, 16); + + final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); + final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); + + rh.setTexture( + sideTexture, sideTexture, backTexture, this.getItemStack().getIconIndex(), sideTexture, sideTexture); + rh.renderInventoryBox(renderer); + + rh.setInvColor(this.getColor().whiteVariant); + rh.renderInventoryFace(this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer); + + rh.setInvColor(this.getColor().mediumVariant); + rh.renderInventoryFace(this.getFrontDark().getIcon(), ForgeDirection.SOUTH, renderer); + + rh.setInvColor(this.getColor().blackVariant); + rh.renderInventoryFace(this.getFrontColored().getIcon(), ForgeDirection.SOUTH, renderer); + + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderInventoryBox(renderer); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + this.setRenderCache(rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache())); + + final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); + final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); + + rh.setTexture( + sideTexture, sideTexture, backTexture, this.getItemStack().getIconIndex(), sideTexture, sideTexture); + + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderBlock(x, y, z, renderer); + + if (this.getLightLevel() > 0) { + final int l = 13; + Tessellator.instance.setBrightness(l << 20 | l << 4); + } + + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = + renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = this.getSpin(); + + Tessellator.instance.setColorOpaque_I(this.getColor().whiteVariant); + rh.renderFace(x, y, z, this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer); + + Tessellator.instance.setColorOpaque_I(this.getColor().mediumVariant); + rh.renderFace(x, y, z, this.getFrontDark().getIcon(), ForgeDirection.SOUTH, renderer); + + Tessellator.instance.setColorOpaque_I(this.getColor().blackVariant); + rh.renderFace(x, y, z, this.getFrontColored().getIcon(), ForgeDirection.SOUTH, renderer); + + renderer.uvRotateBottom = renderer.uvRotateEast = + renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + + final IIcon sideStatusTexture = CableBusTextures.PartMonitorSidesStatus.getIcon(); + + rh.setTexture( + sideStatusTexture, + sideStatusTexture, + backTexture, + this.getItemStack().getIconIndex(), + sideStatusTexture, + sideStatusTexture); + + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderBlock(x, y, z, renderer); + + final boolean hasChan = (this.getClientFlags() & (PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG)) + == (PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG); + final boolean hasPower = (this.getClientFlags() & PartPanel.POWERED_FLAG) == PartPanel.POWERED_FLAG; + + if (hasChan) { + final int l = 14; + Tessellator.instance.setBrightness(l << 20 | l << 4); + Tessellator.instance.setColorOpaque_I(this.getColor().blackVariant); + } else if (hasPower) { + final int l = 9; + Tessellator.instance.setBrightness(l << 20 | l << 4); + Tessellator.instance.setColorOpaque_I(this.getColor().whiteVariant); + } else { + Tessellator.instance.setBrightness(0); + Tessellator.instance.setColorOpaque_I(0x000000); + } + + final IIcon sideStatusLightTexture = CableBusTextures.PartMonitorSidesStatusLights.getIcon(); + + rh.renderFace(x, y, z, sideStatusLightTexture, ForgeDirection.EAST, renderer); + rh.renderFace(x, y, z, sideStatusLightTexture, ForgeDirection.WEST, renderer); + rh.renderFace(x, y, z, sideStatusLightTexture, ForgeDirection.UP, renderer); + rh.renderFace(x, y, z, sideStatusLightTexture, ForgeDirection.DOWN, renderer); + } + + @Override + public boolean isLightSource() { + return false; + } } diff --git a/src/main/java/appeng/parts/reporting/AbstractPartMonitor.java b/src/main/java/appeng/parts/reporting/AbstractPartMonitor.java index ff14669a17f..3bbf4d6877f 100644 --- a/src/main/java/appeng/parts/reporting/AbstractPartMonitor.java +++ b/src/main/java/appeng/parts/reporting/AbstractPartMonitor.java @@ -18,7 +18,6 @@ package appeng.parts.reporting; - import appeng.api.implementations.parts.IPartStorageMonitor; import appeng.api.networking.security.BaseActionSource; import appeng.api.networking.storage.IStackWatcher; @@ -41,6 +40,7 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.IOException; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.GLAllocation; @@ -57,9 +57,6 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import java.io.IOException; - - /** * A basic subclass for any item monitor like display with an item icon and an amount. *

@@ -71,364 +68,312 @@ * @version rv3 * @since rv3 */ -public abstract class AbstractPartMonitor extends AbstractPartDisplay implements IPartStorageMonitor, IStackWatcherHost -{ - private static final IWideReadableNumberConverter NUMBER_CONVERTER = ReadableNumberConverter.INSTANCE; - private IAEItemStack configuredItem; - private String lastHumanReadableText; - private boolean isLocked; - private IStackWatcher myWatcher; - @SideOnly( Side.CLIENT ) - private boolean updateList; - @SideOnly( Side.CLIENT ) - private Integer dspList; - - @Reflected - public AbstractPartMonitor( final ItemStack is ) - { - super( is ); - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - - this.isLocked = data.getBoolean( "isLocked" ); - - final NBTTagCompound myItem = data.getCompoundTag( "configuredItem" ); - this.configuredItem = AEItemStack.loadItemStackFromNBT( myItem ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - - data.setBoolean( "isLocked", this.isLocked ); - - final NBTTagCompound myItem = new NBTTagCompound(); - if( this.configuredItem != null ) - { - this.configuredItem.writeToNBT( myItem ); - } - - data.setTag( "configuredItem", myItem ); - } - - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - - data.writeBoolean( this.isLocked ); - data.writeBoolean( this.configuredItem != null ); - if( this.configuredItem != null ) - { - this.configuredItem.writeToPacket( data ); - } - } - - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - boolean needRedraw = super.readFromStream( data ); - - final boolean isLocked = data.readBoolean(); - needRedraw = this.isLocked != isLocked; - - this.isLocked = isLocked; - - final boolean val = data.readBoolean(); - if( val ) - { - this.configuredItem = AEItemStack.loadItemStackFromPacket( data ); - } - else - { - this.configuredItem = null; - } - - this.updateList = true; - - return needRedraw; - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( Platform.isClient() ) - { - return true; - } - - if( !this.getProxy().isActive() ) - { - return false; - } - - if( !Platform.hasPermissions( this.getLocation(), player ) ) - { - return false; - } - - final TileEntity te = this.getTile(); - final ItemStack eq = player.getCurrentEquippedItem(); - - if( Platform.isWrench( player, eq, te.xCoord, te.yCoord, te.zCoord ) ) - { - this.isLocked = !this.isLocked; - player.addChatMessage( ( this.isLocked ? PlayerMessages.isNowLocked : PlayerMessages.isNowUnlocked ).get() ); - this.getHost().markForUpdate(); - } - else if( !this.isLocked ) - { - this.configuredItem = AEItemStack.create( eq ); - this.configureWatchers(); - this.getHost().markForUpdate(); - } - else - { - this.extractItem( player ); - } - - return true; - } - - // update the system... - private void configureWatchers() - { - if( this.myWatcher != null ) - { - this.myWatcher.clear(); - } - - try - { - if( this.configuredItem != null ) - { - if( this.myWatcher != null ) - { - this.myWatcher.add( this.configuredItem ); - } - - this.updateReportingValue( this.getProxy().getStorage().getItemInventory() ); - } - } - catch( final GridAccessException e ) - { - // >.> - } - } - - protected void extractItem( final EntityPlayer player ) - { - - } - - private void updateReportingValue( final IMEMonitor itemInventory ) - { - if( this.configuredItem != null ) - { - final IAEItemStack result = itemInventory.getStorageList().findPrecise( this.configuredItem ); - if( result == null ) - { - this.configuredItem.setStackSize( 0 ); - } - else - { - this.configuredItem.setStackSize( result.getStackSize() ); - } - } - } - - @Override - @SideOnly( Side.CLIENT ) - protected void finalize() throws Throwable - { - super.finalize(); - - if( this.dspList != null ) - { - GLAllocation.deleteDisplayLists( this.dspList ); - } - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderDynamic( final double x, final double y, final double z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - if( this.dspList == null ) - { - this.dspList = GLAllocation.generateDisplayLists( 1 ); - } - - final Tessellator tess = Tessellator.instance; - - if( ( this.getClientFlags() & ( PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG ) ) != ( PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG ) ) - { - return; - } - - final IAEItemStack ais = (IAEItemStack) this.getDisplayed(); - - if( ais != null ) - { - GL11.glPushMatrix(); - GL11.glTranslated( x + 0.5, y + 0.5, z + 0.5 ); - - if( this.updateList ) - { - this.updateList = false; - GL11.glNewList( this.dspList, GL11.GL_COMPILE_AND_EXECUTE ); - this.tesrRenderScreen( tess, ais ); - GL11.glEndList(); - } - else - { - GL11.glCallList( this.dspList ); - } - - GL11.glPopMatrix(); - } - } - - @Override - public boolean requireDynamicRender() - { - return true; - } - - @Override - public IAEStack getDisplayed() - { - return this.configuredItem; - } - - private void tesrRenderScreen( final Tessellator tess, final IAEItemStack ais ) - { - // GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); - - final ForgeDirection d = this.getSide(); - - GL11.glTranslated( d.offsetX * 0.77, d.offsetY * 0.77, d.offsetZ * 0.77 ); - - switch( d ) - { - case UP: - GL11.glScalef( 1.0f, -1.0f, 1.0f ); - GL11.glRotatef( 90.0f, 1.0f, 0.0f, 0.0f ); - GL11.glRotatef( this.getSpin() * 90.0F, 0, 0, 1 ); - break; - case DOWN: - GL11.glScalef( 1.0f, -1.0f, 1.0f ); - GL11.glRotatef( -90.0f, 1.0f, 0.0f, 0.0f ); - GL11.glRotatef( this.getSpin() * -90.0F, 0, 0, 1 ); - break; - case EAST: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - GL11.glRotatef( -90.0f, 0.0f, 1.0f, 0.0f ); - break; - case WEST: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - GL11.glRotatef( 90.0f, 0.0f, 1.0f, 0.0f ); - break; - case NORTH: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - break; - case SOUTH: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - GL11.glRotatef( 180.0f, 0.0f, 1.0f, 0.0f ); - break; - - default: - break; - } - - try - { - final ItemStack sis = ais.getItemStack(); - sis.stackSize = 1; - - final int br = 16 << 20 | 16 << 4; - final int var11 = br % 65536; - final int var12 = br / 65536; - OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, var11 * 0.8F, var12 * 0.8F ); - - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - // RenderHelper.enableGUIStandardItemLighting(); - tess.setColorOpaque_F( 1.0f, 1.0f, 1.0f ); - - ClientHelper.proxy.doRenderItem( sis, this.getTile().getWorldObj() ); - } - catch( final Exception e ) - { - AELog.debug( e ); - } - finally - { - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - } - - GL11.glTranslatef( 0.0f, 0.14f, -0.24f ); - GL11.glScalef( 1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f ); - - final long stackSize = ais.getStackSize(); - final String renderedStackSize = NUMBER_CONVERTER.toWideReadableForm( stackSize ); - - final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - final int width = fr.getStringWidth( renderedStackSize ); - GL11.glTranslatef( -0.5f * width, 0.0f, -1.0f ); - fr.drawString( renderedStackSize, 0, 0, 0 ); - - // GL11.glPopAttrib(); - } - - @Override - public boolean isLocked() - { - return this.isLocked; - } - - @Override - public void updateWatcher( final IStackWatcher newWatcher ) - { - this.myWatcher = newWatcher; - this.configureWatchers(); - } - - @Override - public void onStackChange( final IItemList o, final IAEStack fullStack, final IAEStack diffStack, final BaseActionSource src, final StorageChannel chan ) - { - if( this.configuredItem != null ) - { - if( fullStack == null ) - { - this.configuredItem.setStackSize( 0 ); - } - else - { - this.configuredItem.setStackSize( fullStack.getStackSize() ); - } - - final long stackSize = this.configuredItem.getStackSize(); - final String humanReadableText = NUMBER_CONVERTER.toWideReadableForm( stackSize ); - - if( !humanReadableText.equals( this.lastHumanReadableText ) ) - { - this.lastHumanReadableText = humanReadableText; - this.getHost().markForUpdate(); - } - } - } - - @Override - public boolean showNetworkInfo( final MovingObjectPosition where ) - { - return false; - } +public abstract class AbstractPartMonitor extends AbstractPartDisplay + implements IPartStorageMonitor, IStackWatcherHost { + private static final IWideReadableNumberConverter NUMBER_CONVERTER = ReadableNumberConverter.INSTANCE; + private IAEItemStack configuredItem; + private String lastHumanReadableText; + private boolean isLocked; + private IStackWatcher myWatcher; + + @SideOnly(Side.CLIENT) + private boolean updateList; + + @SideOnly(Side.CLIENT) + private Integer dspList; + + @Reflected + public AbstractPartMonitor(final ItemStack is) { + super(is); + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + + this.isLocked = data.getBoolean("isLocked"); + + final NBTTagCompound myItem = data.getCompoundTag("configuredItem"); + this.configuredItem = AEItemStack.loadItemStackFromNBT(myItem); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + + data.setBoolean("isLocked", this.isLocked); + + final NBTTagCompound myItem = new NBTTagCompound(); + if (this.configuredItem != null) { + this.configuredItem.writeToNBT(myItem); + } + + data.setTag("configuredItem", myItem); + } + + @Override + public void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + + data.writeBoolean(this.isLocked); + data.writeBoolean(this.configuredItem != null); + if (this.configuredItem != null) { + this.configuredItem.writeToPacket(data); + } + } + + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + boolean needRedraw = super.readFromStream(data); + + final boolean isLocked = data.readBoolean(); + needRedraw = this.isLocked != isLocked; + + this.isLocked = isLocked; + + final boolean val = data.readBoolean(); + if (val) { + this.configuredItem = AEItemStack.loadItemStackFromPacket(data); + } else { + this.configuredItem = null; + } + + this.updateList = true; + + return needRedraw; + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (Platform.isClient()) { + return true; + } + + if (!this.getProxy().isActive()) { + return false; + } + + if (!Platform.hasPermissions(this.getLocation(), player)) { + return false; + } + + final TileEntity te = this.getTile(); + final ItemStack eq = player.getCurrentEquippedItem(); + + if (Platform.isWrench(player, eq, te.xCoord, te.yCoord, te.zCoord)) { + this.isLocked = !this.isLocked; + player.addChatMessage((this.isLocked ? PlayerMessages.isNowLocked : PlayerMessages.isNowUnlocked).get()); + this.getHost().markForUpdate(); + } else if (!this.isLocked) { + this.configuredItem = AEItemStack.create(eq); + this.configureWatchers(); + this.getHost().markForUpdate(); + } else { + this.extractItem(player); + } + + return true; + } + + // update the system... + private void configureWatchers() { + if (this.myWatcher != null) { + this.myWatcher.clear(); + } + + try { + if (this.configuredItem != null) { + if (this.myWatcher != null) { + this.myWatcher.add(this.configuredItem); + } + + this.updateReportingValue(this.getProxy().getStorage().getItemInventory()); + } + } catch (final GridAccessException e) { + // >.> + } + } + + protected void extractItem(final EntityPlayer player) {} + + private void updateReportingValue(final IMEMonitor itemInventory) { + if (this.configuredItem != null) { + final IAEItemStack result = itemInventory.getStorageList().findPrecise(this.configuredItem); + if (result == null) { + this.configuredItem.setStackSize(0); + } else { + this.configuredItem.setStackSize(result.getStackSize()); + } + } + } + + @Override + @SideOnly(Side.CLIENT) + protected void finalize() throws Throwable { + super.finalize(); + + if (this.dspList != null) { + GLAllocation.deleteDisplayLists(this.dspList); + } + } + + @Override + @SideOnly(Side.CLIENT) + public void renderDynamic( + final double x, final double y, final double z, final IPartRenderHelper rh, final RenderBlocks renderer) { + if (this.dspList == null) { + this.dspList = GLAllocation.generateDisplayLists(1); + } + + final Tessellator tess = Tessellator.instance; + + if ((this.getClientFlags() & (PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG)) + != (PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG)) { + return; + } + + final IAEItemStack ais = (IAEItemStack) this.getDisplayed(); + + if (ais != null) { + GL11.glPushMatrix(); + GL11.glTranslated(x + 0.5, y + 0.5, z + 0.5); + + if (this.updateList) { + this.updateList = false; + GL11.glNewList(this.dspList, GL11.GL_COMPILE_AND_EXECUTE); + this.tesrRenderScreen(tess, ais); + GL11.glEndList(); + } else { + GL11.glCallList(this.dspList); + } + + GL11.glPopMatrix(); + } + } + + @Override + public boolean requireDynamicRender() { + return true; + } + + @Override + public IAEStack getDisplayed() { + return this.configuredItem; + } + + private void tesrRenderScreen(final Tessellator tess, final IAEItemStack ais) { + // GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); + + final ForgeDirection d = this.getSide(); + + GL11.glTranslated(d.offsetX * 0.77, d.offsetY * 0.77, d.offsetZ * 0.77); + + switch (d) { + case UP: + GL11.glScalef(1.0f, -1.0f, 1.0f); + GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f); + GL11.glRotatef(this.getSpin() * 90.0F, 0, 0, 1); + break; + case DOWN: + GL11.glScalef(1.0f, -1.0f, 1.0f); + GL11.glRotatef(-90.0f, 1.0f, 0.0f, 0.0f); + GL11.glRotatef(this.getSpin() * -90.0F, 0, 0, 1); + break; + case EAST: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(-90.0f, 0.0f, 1.0f, 0.0f); + break; + case WEST: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(90.0f, 0.0f, 1.0f, 0.0f); + break; + case NORTH: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + break; + case SOUTH: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(180.0f, 0.0f, 1.0f, 0.0f); + break; + + default: + break; + } + + try { + final ItemStack sis = ais.getItemStack(); + sis.stackSize = 1; + + final int br = 16 << 20 | 16 << 4; + final int var11 = br % 65536; + final int var12 = br / 65536; + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, var11 * 0.8F, var12 * 0.8F); + + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + // RenderHelper.enableGUIStandardItemLighting(); + tess.setColorOpaque_F(1.0f, 1.0f, 1.0f); + + ClientHelper.proxy.doRenderItem(sis, this.getTile().getWorldObj()); + } catch (final Exception e) { + AELog.debug(e); + } finally { + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + } + + GL11.glTranslatef(0.0f, 0.14f, -0.24f); + GL11.glScalef(1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f); + + final long stackSize = ais.getStackSize(); + final String renderedStackSize = NUMBER_CONVERTER.toWideReadableForm(stackSize); + + final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + final int width = fr.getStringWidth(renderedStackSize); + GL11.glTranslatef(-0.5f * width, 0.0f, -1.0f); + fr.drawString(renderedStackSize, 0, 0, 0); + + // GL11.glPopAttrib(); + } + + @Override + public boolean isLocked() { + return this.isLocked; + } + + @Override + public void updateWatcher(final IStackWatcher newWatcher) { + this.myWatcher = newWatcher; + this.configureWatchers(); + } + + @Override + public void onStackChange( + final IItemList o, + final IAEStack fullStack, + final IAEStack diffStack, + final BaseActionSource src, + final StorageChannel chan) { + if (this.configuredItem != null) { + if (fullStack == null) { + this.configuredItem.setStackSize(0); + } else { + this.configuredItem.setStackSize(fullStack.getStackSize()); + } + + final long stackSize = this.configuredItem.getStackSize(); + final String humanReadableText = NUMBER_CONVERTER.toWideReadableForm(stackSize); + + if (!humanReadableText.equals(this.lastHumanReadableText)) { + this.lastHumanReadableText = humanReadableText; + this.getHost().markForUpdate(); + } + } + } + + @Override + public boolean showNetworkInfo(final MovingObjectPosition where) { + return false; + } } diff --git a/src/main/java/appeng/parts/reporting/AbstractPartPanel.java b/src/main/java/appeng/parts/reporting/AbstractPartPanel.java index 470c7d92f0c..9ce30b98eda 100644 --- a/src/main/java/appeng/parts/reporting/AbstractPartPanel.java +++ b/src/main/java/appeng/parts/reporting/AbstractPartPanel.java @@ -18,7 +18,6 @@ package appeng.parts.reporting; - import appeng.api.parts.IPartRenderHelper; import appeng.api.util.AEColor; import appeng.client.texture.CableBusTextures; @@ -30,7 +29,6 @@ import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; - /** * A very simple part for emitting light. *

@@ -41,91 +39,84 @@ * @version rv3 * @since rv3 */ -public abstract class AbstractPartPanel extends AbstractPartReporting -{ - private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartMonitor_Bright; - private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartMonitor_Colored; - private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartMonitor_Colored; - - public AbstractPartPanel( final ItemStack is ) - { - super( is, false ); - } - - @Override - public CableBusTextures getFrontBright() - { - return FRONT_BRIGHT_ICON; - } - - @Override - public CableBusTextures getFrontColored() - { - return FRONT_COLORED_ICON; - } - - @Override - public CableBusTextures getFrontDark() - { - return FRONT_DARK_ICON; - } - - @Override - public boolean isLightSource() - { - return true; - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - - final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); - final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); - - rh.setTexture( sideTexture, sideTexture, backTexture, this.getItemStack().getIconIndex(), sideTexture, sideTexture ); - rh.renderInventoryBox( renderer ); - - rh.setInvColor( this.getBrightnessColor() ); - rh.renderInventoryFace( this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer ); - - rh.setBounds( 4, 4, 13, 12, 12, 14 ); - rh.renderInventoryBox( renderer ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); - final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); - - rh.setTexture( sideTexture, sideTexture, backTexture, this.getItemStack().getIconIndex(), sideTexture, sideTexture ); - - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderBlock( x, y, z, renderer ); - - if( this.getLightLevel() > 0 ) - { - final int l = 13; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - } - - Tessellator.instance.setColorOpaque_I( this.getBrightnessColor() ); - rh.renderFace( x, y, z, this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer ); - - rh.setBounds( 4, 4, 13, 12, 12, 14 ); - rh.renderBlock( x, y, z, renderer ); - } - - /** - * How bright the color the panel should appear. Usually it depends on a {@link AEColor} variant. - * This does not affect the actual light level of the part. - * - * @return the brightness to be used. - */ - protected abstract int getBrightnessColor(); - +public abstract class AbstractPartPanel extends AbstractPartReporting { + private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartMonitor_Bright; + private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartMonitor_Colored; + private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartMonitor_Colored; + + public AbstractPartPanel(final ItemStack is) { + super(is, false); + } + + @Override + public CableBusTextures getFrontBright() { + return FRONT_BRIGHT_ICON; + } + + @Override + public CableBusTextures getFrontColored() { + return FRONT_COLORED_ICON; + } + + @Override + public CableBusTextures getFrontDark() { + return FRONT_DARK_ICON; + } + + @Override + public boolean isLightSource() { + return true; + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setBounds(2, 2, 14, 14, 14, 16); + + final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); + final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); + + rh.setTexture( + sideTexture, sideTexture, backTexture, this.getItemStack().getIconIndex(), sideTexture, sideTexture); + rh.renderInventoryBox(renderer); + + rh.setInvColor(this.getBrightnessColor()); + rh.renderInventoryFace(this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer); + + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderInventoryBox(renderer); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer) { + final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); + final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); + + rh.setTexture( + sideTexture, sideTexture, backTexture, this.getItemStack().getIconIndex(), sideTexture, sideTexture); + + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderBlock(x, y, z, renderer); + + if (this.getLightLevel() > 0) { + final int l = 13; + Tessellator.instance.setBrightness(l << 20 | l << 4); + } + + Tessellator.instance.setColorOpaque_I(this.getBrightnessColor()); + rh.renderFace(x, y, z, this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer); + + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderBlock(x, y, z, renderer); + } + + /** + * How bright the color the panel should appear. Usually it depends on a {@link AEColor} variant. + * This does not affect the actual light level of the part. + * + * @return the brightness to be used. + */ + protected abstract int getBrightnessColor(); } diff --git a/src/main/java/appeng/parts/reporting/AbstractPartReporting.java b/src/main/java/appeng/parts/reporting/AbstractPartReporting.java index 529d51ff827..762a003f18c 100644 --- a/src/main/java/appeng/parts/reporting/AbstractPartReporting.java +++ b/src/main/java/appeng/parts/reporting/AbstractPartReporting.java @@ -18,7 +18,6 @@ package appeng.parts.reporting; - import appeng.api.implementations.IPowerChannelState; import appeng.api.implementations.parts.IPartMonitor; import appeng.api.networking.GridFlags; @@ -31,6 +30,7 @@ import appeng.parts.AEBasePart; import appeng.util.Platform; import io.netty.buffer.ByteBuf; +import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -39,9 +39,6 @@ import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; - - /** * The most basic class for any part reporting information, like terminals or monitors. This can also include basic * panels which just provide light. @@ -56,268 +53,225 @@ * @version rv3 * @since rv3 */ -public abstract class AbstractPartReporting extends AEBasePart implements IPartMonitor, IPowerChannelState -{ - - protected static final int POWERED_FLAG = 4; - protected static final int CHANNEL_FLAG = 16; - private static final int BOOTING_FLAG = 8; - - private byte spin = 0; // 0-3 - private int clientFlags = 0; // sent as byte. - private float opacity = -1; - - public AbstractPartReporting( final ItemStack is ) - { - this( is, false ); - } - - protected AbstractPartReporting( final ItemStack is, final boolean requireChannel ) - { - super( is ); - - if( requireChannel ) - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.getProxy().setIdlePowerUsage( 1.0 / 2.0 ); - } - else - { - this.getProxy().setIdlePowerUsage( 1.0 / 16.0 ); // lights drain a little bit. - } - } - - @MENetworkEventSubscribe - public final void bootingRender( final MENetworkBootingStatusChange c ) - { - if( !this.isLightSource() ) - { - this.getHost().markForUpdate(); - } - } - - @MENetworkEventSubscribe - public final void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } - - @Override - public final void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 2, 2, 14, 14, 14, 16 ); - bch.addBox( 4, 4, 13, 12, 12, 14 ); - } - - @Override - public void onNeighborChanged() - { - this.opacity = -1; - this.getHost().markForUpdate(); - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - if( data.hasKey( "opacity" ) ) - { - this.opacity = data.getFloat( "opacity" ); - } - this.spin = data.getByte( "spin" ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setFloat( "opacity", this.opacity ); - data.setByte( "spin", this.getSpin() ); - } - - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - this.clientFlags = this.getSpin() & 3; - - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - this.clientFlags = this.getClientFlags() | AbstractPartReporting.POWERED_FLAG; - } - - if( this.getProxy().getPath().isNetworkBooting() ) - { - this.clientFlags = this.getClientFlags() | AbstractPartReporting.BOOTING_FLAG; - } - - if( this.getProxy().getNode().meetsChannelRequirements() ) - { - this.clientFlags = this.getClientFlags() | AbstractPartReporting.CHANNEL_FLAG; - } - } - catch( final GridAccessException e ) - { - // um.. nothing. - } - - data.writeByte( (byte) this.getClientFlags() ); - } - - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - super.readFromStream( data ); - final int oldFlags = this.getClientFlags(); - this.clientFlags = data.readByte(); - this.spin = (byte) ( this.getClientFlags() & 3 ); - return this.getClientFlags() != oldFlags; - } - - @Override - public final int getLightLevel() - { - return this.blockLight( this.isPowered() ? ( this.isLightSource() ? 15 : 9 ) : 0 ); - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - final TileEntity te = this.getTile(); - - if( !player.isSneaking() && Platform.isWrench( player, player.inventory.getCurrentItem(), te.xCoord, te.yCoord, te.zCoord ) ) - { - if( Platform.isServer() ) - { - if( this.getSpin() > 3 ) - { - this.spin = 0; - } - - switch( this.getSpin() ) - { - case 0: - this.spin = 1; - break; - case 1: - this.spin = 3; - break; - case 2: - this.spin = 0; - break; - case 3: - this.spin = 2; - break; - } - - this.getHost().markForUpdate(); - this.saveChanges(); - } - return true; - } - else - { - return super.onPartActivate( player, pos ); - } - } - - @Override - public final void onPlacement( final EntityPlayer player, final ItemStack held, final ForgeDirection side ) - { - super.onPlacement( player, held, side ); - - final byte rotation = (byte) ( MathHelper.floor_double( ( player.rotationYaw * 4F ) / 360F + 2.5D ) & 3 ); - if( side == ForgeDirection.UP ) - { - this.spin = rotation; - } - else if( side == ForgeDirection.DOWN ) - { - this.spin = rotation; - } - } - - private final int blockLight( final int emit ) - { - if( this.opacity < 0 ) - { - final TileEntity te = this.getTile(); - this.opacity = 255 - te.getWorldObj().getBlockLightOpacity( te.xCoord + this.getSide().offsetX, te.yCoord + this.getSide().offsetY, te.zCoord + this.getSide().offsetZ ); - } - - return (int) ( emit * ( this.opacity / 255.0f ) ); - } - - @Override - public final boolean isPowered() - { - try - { - if( Platform.isServer() ) - { - return this.getProxy().getEnergy().isNetworkPowered(); - } - else - { - return ( ( this.getClientFlags() & PartPanel.POWERED_FLAG ) == PartPanel.POWERED_FLAG ); - } - } - catch( final GridAccessException e ) - { - return false; - } - } - - @Override - public final boolean isActive() - { - if( !this.isLightSource() ) - { - return ( ( this.getClientFlags() & ( PartPanel.CHANNEL_FLAG | PartPanel.POWERED_FLAG ) ) == ( PartPanel.CHANNEL_FLAG | PartPanel.POWERED_FLAG ) ); - } - else - { - return this.isPowered(); - } - } - - public final int getClientFlags() - { - return this.clientFlags; - } - - public final byte getSpin() - { - return this.spin; - } - - /** - * The texture used for the bright front layer. - *

- * The final texture can overlap any of the the texture in no particular order. - */ - public abstract CableBusTextures getFrontBright(); - - /** - * The texture used for the colored (medium) front layer. - *

- * The final texture can overlap any of the the texture in no particular order. - */ - public abstract CableBusTextures getFrontColored(); - - /** - * The texture used for the dark front layer. - *

- * The final texture can overlap any of the the texture in no particular order. - */ - public abstract CableBusTextures getFrontDark(); - - /** - * Should the part emit light. This actually only affects the light level, light source use a level of 15 and non - * light source 9. - */ - public abstract boolean isLightSource(); - +public abstract class AbstractPartReporting extends AEBasePart implements IPartMonitor, IPowerChannelState { + + protected static final int POWERED_FLAG = 4; + protected static final int CHANNEL_FLAG = 16; + private static final int BOOTING_FLAG = 8; + + private byte spin = 0; // 0-3 + private int clientFlags = 0; // sent as byte. + private float opacity = -1; + + public AbstractPartReporting(final ItemStack is) { + this(is, false); + } + + protected AbstractPartReporting(final ItemStack is, final boolean requireChannel) { + super(is); + + if (requireChannel) { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.getProxy().setIdlePowerUsage(1.0 / 2.0); + } else { + this.getProxy().setIdlePowerUsage(1.0 / 16.0); // lights drain a little bit. + } + } + + @MENetworkEventSubscribe + public final void bootingRender(final MENetworkBootingStatusChange c) { + if (!this.isLightSource()) { + this.getHost().markForUpdate(); + } + } + + @MENetworkEventSubscribe + public final void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } + + @Override + public final void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(2, 2, 14, 14, 14, 16); + bch.addBox(4, 4, 13, 12, 12, 14); + } + + @Override + public void onNeighborChanged() { + this.opacity = -1; + this.getHost().markForUpdate(); + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + if (data.hasKey("opacity")) { + this.opacity = data.getFloat("opacity"); + } + this.spin = data.getByte("spin"); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setFloat("opacity", this.opacity); + data.setByte("spin", this.getSpin()); + } + + @Override + public void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + this.clientFlags = this.getSpin() & 3; + + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + this.clientFlags = this.getClientFlags() | AbstractPartReporting.POWERED_FLAG; + } + + if (this.getProxy().getPath().isNetworkBooting()) { + this.clientFlags = this.getClientFlags() | AbstractPartReporting.BOOTING_FLAG; + } + + if (this.getProxy().getNode().meetsChannelRequirements()) { + this.clientFlags = this.getClientFlags() | AbstractPartReporting.CHANNEL_FLAG; + } + } catch (final GridAccessException e) { + // um.. nothing. + } + + data.writeByte((byte) this.getClientFlags()); + } + + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + super.readFromStream(data); + final int oldFlags = this.getClientFlags(); + this.clientFlags = data.readByte(); + this.spin = (byte) (this.getClientFlags() & 3); + return this.getClientFlags() != oldFlags; + } + + @Override + public final int getLightLevel() { + return this.blockLight(this.isPowered() ? (this.isLightSource() ? 15 : 9) : 0); + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + final TileEntity te = this.getTile(); + + if (!player.isSneaking() + && Platform.isWrench(player, player.inventory.getCurrentItem(), te.xCoord, te.yCoord, te.zCoord)) { + if (Platform.isServer()) { + if (this.getSpin() > 3) { + this.spin = 0; + } + + switch (this.getSpin()) { + case 0: + this.spin = 1; + break; + case 1: + this.spin = 3; + break; + case 2: + this.spin = 0; + break; + case 3: + this.spin = 2; + break; + } + + this.getHost().markForUpdate(); + this.saveChanges(); + } + return true; + } else { + return super.onPartActivate(player, pos); + } + } + + @Override + public final void onPlacement(final EntityPlayer player, final ItemStack held, final ForgeDirection side) { + super.onPlacement(player, held, side); + + final byte rotation = (byte) (MathHelper.floor_double((player.rotationYaw * 4F) / 360F + 2.5D) & 3); + if (side == ForgeDirection.UP) { + this.spin = rotation; + } else if (side == ForgeDirection.DOWN) { + this.spin = rotation; + } + } + + private final int blockLight(final int emit) { + if (this.opacity < 0) { + final TileEntity te = this.getTile(); + this.opacity = 255 + - te.getWorldObj() + .getBlockLightOpacity( + te.xCoord + this.getSide().offsetX, + te.yCoord + this.getSide().offsetY, + te.zCoord + this.getSide().offsetZ); + } + + return (int) (emit * (this.opacity / 255.0f)); + } + + @Override + public final boolean isPowered() { + try { + if (Platform.isServer()) { + return this.getProxy().getEnergy().isNetworkPowered(); + } else { + return ((this.getClientFlags() & PartPanel.POWERED_FLAG) == PartPanel.POWERED_FLAG); + } + } catch (final GridAccessException e) { + return false; + } + } + + @Override + public final boolean isActive() { + if (!this.isLightSource()) { + return ((this.getClientFlags() & (PartPanel.CHANNEL_FLAG | PartPanel.POWERED_FLAG)) + == (PartPanel.CHANNEL_FLAG | PartPanel.POWERED_FLAG)); + } else { + return this.isPowered(); + } + } + + public final int getClientFlags() { + return this.clientFlags; + } + + public final byte getSpin() { + return this.spin; + } + + /** + * The texture used for the bright front layer. + *

+ * The final texture can overlap any of the the texture in no particular order. + */ + public abstract CableBusTextures getFrontBright(); + + /** + * The texture used for the colored (medium) front layer. + *

+ * The final texture can overlap any of the the texture in no particular order. + */ + public abstract CableBusTextures getFrontColored(); + + /** + * The texture used for the dark front layer. + *

+ * The final texture can overlap any of the the texture in no particular order. + */ + public abstract CableBusTextures getFrontDark(); + + /** + * Should the part emit light. This actually only affects the light level, light source use a level of 15 and non + * light source 9. + */ + public abstract boolean isLightSource(); } diff --git a/src/main/java/appeng/parts/reporting/AbstractPartTerminal.java b/src/main/java/appeng/parts/reporting/AbstractPartTerminal.java index 5b19542e0eb..a0f8c0bd7e6 100644 --- a/src/main/java/appeng/parts/reporting/AbstractPartTerminal.java +++ b/src/main/java/appeng/parts/reporting/AbstractPartTerminal.java @@ -18,7 +18,6 @@ package appeng.parts.reporting; - import appeng.api.config.Settings; import appeng.api.config.SortDir; import appeng.api.config.SortOrder; @@ -37,15 +36,13 @@ import appeng.util.ConfigManager; import appeng.util.IConfigManagerHost; import appeng.util.Platform; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; -import java.util.List; - - /** * Anything resembling an network terminal with view cells can reuse this. *

@@ -57,125 +54,105 @@ * @version rv3 * @since rv3 */ -public abstract class AbstractPartTerminal extends AbstractPartDisplay implements ITerminalHost, IConfigManagerHost, IViewCellStorage, IAEAppEngInventory -{ - - private final IConfigManager cm = new ConfigManager( this ); - private final AppEngInternalInventory viewCell = new AppEngInternalInventory( this, 5 ); - - public AbstractPartTerminal( final ItemStack is ) - { - super( is ); - - this.cm.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - this.cm.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - this.cm.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); - } - - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - super.getDrops( drops, wrenched ); - - for( final ItemStack is : this.viewCell ) - { - if( is != null ) - { - drops.add( is ); - } - } - } - - @Override - public IConfigManager getConfigManager() - { - return this.cm; - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.cm.readFromNBT( data ); - this.viewCell.readFromNBT( data, "viewCell" ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.cm.writeToNBT( data ); - this.viewCell.writeToNBT( data, "viewCell" ); - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( !super.onPartActivate( player, pos ) ) - { - if( !player.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } - - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), this.getGui( player ) ); - - return true; - } - } - return false; - } - - public GuiBridge getGui( final EntityPlayer player ) - { - return GuiBridge.GUI_ME; - } - - @Override - public IMEMonitor getItemInventory() - { - try - { - return this.getProxy().getStorage().getItemInventory(); - } - catch( final GridAccessException e ) - { - // err nope? - } - return null; - } - - @Override - public IMEMonitor getFluidInventory() - { - try - { - return this.getProxy().getStorage().getFluidInventory(); - } - catch( final GridAccessException e ) - { - // err nope? - } - return null; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - - } - - @Override - public IInventory getViewCellStorage() - { - return this.viewCell; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - this.getHost().markForSave(); - } +public abstract class AbstractPartTerminal extends AbstractPartDisplay + implements ITerminalHost, IConfigManagerHost, IViewCellStorage, IAEAppEngInventory { + + private final IConfigManager cm = new ConfigManager(this); + private final AppEngInternalInventory viewCell = new AppEngInternalInventory(this, 5); + + public AbstractPartTerminal(final ItemStack is) { + super(is); + + this.cm.registerSetting(Settings.SORT_BY, SortOrder.NAME); + this.cm.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + this.cm.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); + } + + @Override + public void getDrops(final List drops, final boolean wrenched) { + super.getDrops(drops, wrenched); + + for (final ItemStack is : this.viewCell) { + if (is != null) { + drops.add(is); + } + } + } + + @Override + public IConfigManager getConfigManager() { + return this.cm; + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.cm.readFromNBT(data); + this.viewCell.readFromNBT(data, "viewCell"); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.cm.writeToNBT(data); + this.viewCell.writeToNBT(data, "viewCell"); + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (!super.onPartActivate(player, pos)) { + if (!player.isSneaking()) { + if (Platform.isClient()) { + return true; + } + + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), this.getGui(player)); + + return true; + } + } + return false; + } + + public GuiBridge getGui(final EntityPlayer player) { + return GuiBridge.GUI_ME; + } + + @Override + public IMEMonitor getItemInventory() { + try { + return this.getProxy().getStorage().getItemInventory(); + } catch (final GridAccessException e) { + // err nope? + } + return null; + } + + @Override + public IMEMonitor getFluidInventory() { + try { + return this.getProxy().getStorage().getFluidInventory(); + } catch (final GridAccessException e) { + // err nope? + } + return null; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) {} + + @Override + public IInventory getViewCellStorage() { + return this.viewCell; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) { + this.getHost().markForSave(); + } } diff --git a/src/main/java/appeng/parts/reporting/PartConversionMonitor.java b/src/main/java/appeng/parts/reporting/PartConversionMonitor.java index 95c1f8ce081..2faf3536016 100644 --- a/src/main/java/appeng/parts/reporting/PartConversionMonitor.java +++ b/src/main/java/appeng/parts/reporting/PartConversionMonitor.java @@ -18,7 +18,6 @@ package appeng.parts.reporting; - import appeng.api.networking.energy.IEnergySource; import appeng.api.networking.security.PlayerSource; import appeng.api.storage.IMEMonitor; @@ -29,157 +28,139 @@ import appeng.util.InventoryAdaptor; import appeng.util.Platform; import appeng.util.item.AEItemStack; +import java.util.Collections; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.List; - - -public class PartConversionMonitor extends AbstractPartMonitor -{ - private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartConversionMonitor_Bright; - private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartConversionMonitor_Dark; - private static final CableBusTextures FRONT_DARK_ICON_LOCKED = CableBusTextures.PartConversionMonitor_Dark_Locked; - private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartConversionMonitor_Colored; - - @Reflected - public PartConversionMonitor( final ItemStack is ) - { - super( is ); - } - - @Override - public boolean onPartShiftActivate( final EntityPlayer player, final Vec3 pos ) - { - if( Platform.isClient() ) - { - return true; - } - - if( !this.getProxy().isActive() ) - { - return false; - } - - if( !Platform.hasPermissions( this.getLocation(), player ) ) - { - return false; - } - - boolean ModeB = false; - - ItemStack item = player.getCurrentEquippedItem(); - if( item == null && this.getDisplayed() != null ) - { - ModeB = true; - item = ( (IAEItemStack) this.getDisplayed() ).getItemStack(); - } - - if( item != null ) - { - try - { - if( !this.getProxy().isActive() ) - { - return false; - } - - final IEnergySource energy = this.getProxy().getEnergy(); - final IMEMonitor cell = this.getProxy().getStorage().getItemInventory(); - final IAEItemStack input = AEItemStack.create( item ); - - if( ModeB ) - { - for( int x = 0; x < player.inventory.getSizeInventory(); x++ ) - { - final ItemStack targetStack = player.inventory.getStackInSlot( x ); - if( input.equals( targetStack ) ) - { - final IAEItemStack insertItem = input.copy(); - insertItem.setStackSize( targetStack.stackSize ); - final IAEItemStack failedToInsert = Platform.poweredInsert( energy, cell, insertItem, new PlayerSource( player, this ) ); - player.inventory.setInventorySlotContents( x, failedToInsert == null ? null : failedToInsert.getItemStack() ); - } - } - } - else - { - final IAEItemStack failedToInsert = Platform.poweredInsert( energy, cell, input, new PlayerSource( player, this ) ); - player.inventory.setInventorySlotContents( player.inventory.currentItem, failedToInsert == null ? null : failedToInsert.getItemStack() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - return true; - } - - @Override - protected void extractItem( final EntityPlayer player ) - { - final IAEItemStack input = (IAEItemStack) this.getDisplayed(); - if( input != null ) - { - try - { - if( !this.getProxy().isActive() ) - { - return; - } - - final IEnergySource energy = this.getProxy().getEnergy(); - final IMEMonitor cell = this.getProxy().getStorage().getItemInventory(); - - final ItemStack is = input.getItemStack(); - input.setStackSize( is.getMaxStackSize() ); - - final IAEItemStack retrieved = Platform.poweredExtraction( energy, cell, input, new PlayerSource( player, this ) ); - if( retrieved != null ) - { - ItemStack newItems = retrieved.getItemStack(); - final InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); - newItems = adaptor.addItems( newItems ); - if( newItems != null ) - { - final TileEntity te = this.getTile(); - final List list = Collections.singletonList( newItems ); - Platform.spawnDrops( player.worldObj, te.xCoord + this.getSide().offsetX, te.yCoord + this.getSide().offsetY, te.zCoord + this.getSide().offsetZ, list ); - } - - if( player.openContainer != null ) - { - player.openContainer.detectAndSendChanges(); - } - } - } - catch( final GridAccessException e ) - { - // :P - } - } - } - - @Override - public CableBusTextures getFrontBright() - { - return FRONT_BRIGHT_ICON; - } - - @Override - public CableBusTextures getFrontColored() - { - return FRONT_COLORED_ICON; - } - - @Override - public CableBusTextures getFrontDark() - { - return this.isLocked() ? FRONT_DARK_ICON_LOCKED : FRONT_DARK_ICON; - } +public class PartConversionMonitor extends AbstractPartMonitor { + private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartConversionMonitor_Bright; + private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartConversionMonitor_Dark; + private static final CableBusTextures FRONT_DARK_ICON_LOCKED = CableBusTextures.PartConversionMonitor_Dark_Locked; + private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartConversionMonitor_Colored; + + @Reflected + public PartConversionMonitor(final ItemStack is) { + super(is); + } + + @Override + public boolean onPartShiftActivate(final EntityPlayer player, final Vec3 pos) { + if (Platform.isClient()) { + return true; + } + + if (!this.getProxy().isActive()) { + return false; + } + + if (!Platform.hasPermissions(this.getLocation(), player)) { + return false; + } + + boolean ModeB = false; + + ItemStack item = player.getCurrentEquippedItem(); + if (item == null && this.getDisplayed() != null) { + ModeB = true; + item = ((IAEItemStack) this.getDisplayed()).getItemStack(); + } + + if (item != null) { + try { + if (!this.getProxy().isActive()) { + return false; + } + + final IEnergySource energy = this.getProxy().getEnergy(); + final IMEMonitor cell = + this.getProxy().getStorage().getItemInventory(); + final IAEItemStack input = AEItemStack.create(item); + + if (ModeB) { + for (int x = 0; x < player.inventory.getSizeInventory(); x++) { + final ItemStack targetStack = player.inventory.getStackInSlot(x); + if (input.equals(targetStack)) { + final IAEItemStack insertItem = input.copy(); + insertItem.setStackSize(targetStack.stackSize); + final IAEItemStack failedToInsert = + Platform.poweredInsert(energy, cell, insertItem, new PlayerSource(player, this)); + player.inventory.setInventorySlotContents( + x, failedToInsert == null ? null : failedToInsert.getItemStack()); + } + } + } else { + final IAEItemStack failedToInsert = + Platform.poweredInsert(energy, cell, input, new PlayerSource(player, this)); + player.inventory.setInventorySlotContents( + player.inventory.currentItem, + failedToInsert == null ? null : failedToInsert.getItemStack()); + } + } catch (final GridAccessException e) { + // :P + } + } + return true; + } + + @Override + protected void extractItem(final EntityPlayer player) { + final IAEItemStack input = (IAEItemStack) this.getDisplayed(); + if (input != null) { + try { + if (!this.getProxy().isActive()) { + return; + } + + final IEnergySource energy = this.getProxy().getEnergy(); + final IMEMonitor cell = + this.getProxy().getStorage().getItemInventory(); + + final ItemStack is = input.getItemStack(); + input.setStackSize(is.getMaxStackSize()); + + final IAEItemStack retrieved = + Platform.poweredExtraction(energy, cell, input, new PlayerSource(player, this)); + if (retrieved != null) { + ItemStack newItems = retrieved.getItemStack(); + final InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor(player, ForgeDirection.UNKNOWN); + newItems = adaptor.addItems(newItems); + if (newItems != null) { + final TileEntity te = this.getTile(); + final List list = Collections.singletonList(newItems); + Platform.spawnDrops( + player.worldObj, + te.xCoord + this.getSide().offsetX, + te.yCoord + this.getSide().offsetY, + te.zCoord + this.getSide().offsetZ, + list); + } + + if (player.openContainer != null) { + player.openContainer.detectAndSendChanges(); + } + } + } catch (final GridAccessException e) { + // :P + } + } + } + + @Override + public CableBusTextures getFrontBright() { + return FRONT_BRIGHT_ICON; + } + + @Override + public CableBusTextures getFrontColored() { + return FRONT_COLORED_ICON; + } + + @Override + public CableBusTextures getFrontDark() { + return this.isLocked() ? FRONT_DARK_ICON_LOCKED : FRONT_DARK_ICON; + } } diff --git a/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java b/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java index 2f2fb897aa7..e52235f89a6 100644 --- a/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java @@ -18,106 +18,88 @@ package appeng.parts.reporting; - import appeng.client.texture.CableBusTextures; import appeng.core.sync.GuiBridge; import appeng.helpers.Reflected; import appeng.tile.inventory.AppEngInternalInventory; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.util.List; - - -public class PartCraftingTerminal extends AbstractPartTerminal -{ - private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartCraftingTerm_Bright; - private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartCraftingTerm_Dark; - private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartCraftingTerm_Colored; - - private final AppEngInternalInventory craftingGrid = new AppEngInternalInventory( this, 9 ); - - @Reflected - public PartCraftingTerminal( final ItemStack is ) - { - super( is ); - } - - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - super.getDrops( drops, wrenched ); - - for( final ItemStack is : this.craftingGrid ) - { - if( is != null ) - { - drops.add( is ); - } - } - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.craftingGrid.readFromNBT( data, "craftingGrid" ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.craftingGrid.writeToNBT( data, "craftingGrid" ); - } - - @Override - public GuiBridge getGui( final EntityPlayer p ) - { - int x = (int) p.posX; - int y = (int) p.posY; - int z = (int) p.posZ; - if( this.getHost().getTile() != null ) - { - x = this.getTile().xCoord; - y = this.getTile().yCoord; - z = this.getTile().zCoord; - } - - if( GuiBridge.GUI_CRAFTING_TERMINAL.hasPermissions( this.getHost().getTile(), x, y, z, this.getSide(), p ) ) - { - return GuiBridge.GUI_CRAFTING_TERMINAL; - } - return GuiBridge.GUI_ME; - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "crafting" ) ) - { - return this.craftingGrid; - } - return super.getInventoryByName( name ); - } - - @Override - public CableBusTextures getFrontBright() - { - return FRONT_BRIGHT_ICON; - } - - @Override - public CableBusTextures getFrontColored() - { - return FRONT_COLORED_ICON; - } - - @Override - public CableBusTextures getFrontDark() - { - return FRONT_DARK_ICON; - } +public class PartCraftingTerminal extends AbstractPartTerminal { + private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartCraftingTerm_Bright; + private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartCraftingTerm_Dark; + private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartCraftingTerm_Colored; + + private final AppEngInternalInventory craftingGrid = new AppEngInternalInventory(this, 9); + + @Reflected + public PartCraftingTerminal(final ItemStack is) { + super(is); + } + + @Override + public void getDrops(final List drops, final boolean wrenched) { + super.getDrops(drops, wrenched); + + for (final ItemStack is : this.craftingGrid) { + if (is != null) { + drops.add(is); + } + } + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.craftingGrid.readFromNBT(data, "craftingGrid"); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.craftingGrid.writeToNBT(data, "craftingGrid"); + } + + @Override + public GuiBridge getGui(final EntityPlayer p) { + int x = (int) p.posX; + int y = (int) p.posY; + int z = (int) p.posZ; + if (this.getHost().getTile() != null) { + x = this.getTile().xCoord; + y = this.getTile().yCoord; + z = this.getTile().zCoord; + } + + if (GuiBridge.GUI_CRAFTING_TERMINAL.hasPermissions(this.getHost().getTile(), x, y, z, this.getSide(), p)) { + return GuiBridge.GUI_CRAFTING_TERMINAL; + } + return GuiBridge.GUI_ME; + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("crafting")) { + return this.craftingGrid; + } + return super.getInventoryByName(name); + } + + @Override + public CableBusTextures getFrontBright() { + return FRONT_BRIGHT_ICON; + } + + @Override + public CableBusTextures getFrontColored() { + return FRONT_COLORED_ICON; + } + + @Override + public CableBusTextures getFrontDark() { + return FRONT_DARK_ICON; + } } diff --git a/src/main/java/appeng/parts/reporting/PartDarkPanel.java b/src/main/java/appeng/parts/reporting/PartDarkPanel.java index e22bb175a84..81328dc2857 100644 --- a/src/main/java/appeng/parts/reporting/PartDarkPanel.java +++ b/src/main/java/appeng/parts/reporting/PartDarkPanel.java @@ -18,23 +18,18 @@ package appeng.parts.reporting; - import appeng.helpers.Reflected; import net.minecraft.item.ItemStack; +public class PartDarkPanel extends AbstractPartPanel { -public class PartDarkPanel extends AbstractPartPanel -{ - - @Reflected - public PartDarkPanel( final ItemStack is ) - { - super( is ); - } + @Reflected + public PartDarkPanel(final ItemStack is) { + super(is); + } - @Override - protected int getBrightnessColor() - { - return this.getColor().mediumVariant; - } + @Override + protected int getBrightnessColor() { + return this.getColor().mediumVariant; + } } diff --git a/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java b/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java index f742b9cb480..5595094b5ac 100644 --- a/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java @@ -18,7 +18,6 @@ package appeng.parts.reporting; - import appeng.client.texture.CableBusTextures; import appeng.core.sync.GuiBridge; import appeng.util.Platform; @@ -26,54 +25,44 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.Vec3; +public class PartInterfaceTerminal extends AbstractPartDisplay { + private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartInterfaceTerm_Bright; + private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartInterfaceTerm_Dark; + private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartInterfaceTerm_Colored; -public class PartInterfaceTerminal extends AbstractPartDisplay -{ - private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartInterfaceTerm_Bright; - private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartInterfaceTerm_Dark; - private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartInterfaceTerm_Colored; - - public PartInterfaceTerminal( final ItemStack is ) - { - super( is ); - } + public PartInterfaceTerminal(final ItemStack is) { + super(is); + } - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( !super.onPartActivate( player, pos ) ) - { - if( !player.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (!super.onPartActivate(player, pos)) { + if (!player.isSneaking()) { + if (Platform.isClient()) { + return true; + } - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_INTERFACE_TERMINAL ); + Platform.openGUI(player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_INTERFACE_TERMINAL); - return true; - } - } + return true; + } + } - return false; - } + return false; + } - @Override - public CableBusTextures getFrontBright() - { - return FRONT_BRIGHT_ICON; - } + @Override + public CableBusTextures getFrontBright() { + return FRONT_BRIGHT_ICON; + } - @Override - public CableBusTextures getFrontColored() - { - return FRONT_COLORED_ICON; - } + @Override + public CableBusTextures getFrontColored() { + return FRONT_COLORED_ICON; + } - @Override - public CableBusTextures getFrontDark() - { - return FRONT_DARK_ICON; - } + @Override + public CableBusTextures getFrontDark() { + return FRONT_DARK_ICON; + } } diff --git a/src/main/java/appeng/parts/reporting/PartPanel.java b/src/main/java/appeng/parts/reporting/PartPanel.java index d12cd4dcfc8..56301b9d2c2 100644 --- a/src/main/java/appeng/parts/reporting/PartPanel.java +++ b/src/main/java/appeng/parts/reporting/PartPanel.java @@ -18,24 +18,18 @@ package appeng.parts.reporting; - import appeng.helpers.Reflected; import net.minecraft.item.ItemStack; +public class PartPanel extends AbstractPartPanel { -public class PartPanel extends AbstractPartPanel -{ - - @Reflected - public PartPanel( final ItemStack is ) - { - super( is ); - } - - @Override - protected int getBrightnessColor() - { - return this.getColor().whiteVariant; - } + @Reflected + public PartPanel(final ItemStack is) { + super(is); + } + @Override + protected int getBrightnessColor() { + return this.getColor().whiteVariant; + } } diff --git a/src/main/java/appeng/parts/reporting/PartPatternTerminal.java b/src/main/java/appeng/parts/reporting/PartPatternTerminal.java index c7e4e4602b8..c18e29fbf12 100644 --- a/src/main/java/appeng/parts/reporting/PartPatternTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartPatternTerminal.java @@ -18,138 +18,126 @@ package appeng.parts.reporting; - import appeng.api.implementations.ICraftingPatternItem; import appeng.api.networking.crafting.ICraftingPatternDetails; import appeng.api.storage.data.IAEItemStack; import appeng.client.texture.CableBusTextures; -import appeng.core.AELog; import appeng.core.sync.GuiBridge; import appeng.helpers.PatternHelper; import appeng.helpers.Reflected; import appeng.tile.inventory.AppEngInternalInventory; import appeng.tile.inventory.BiggerAppEngInventory; -import appeng.tile.inventory.IAEAppEngInventory; import appeng.tile.inventory.InvOperation; -import appeng.util.Platform; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.util.List; - - -public class PartPatternTerminal extends AbstractPartTerminal -{ - private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartPatternTerm_Bright; - private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartPatternTerm_Dark; - private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartPatternTerm_Colored; - - private final AppEngInternalInventory crafting = new BiggerAppEngInventory( this, 9 ){ - - }; - private final AppEngInternalInventory output = new BiggerAppEngInventory( this, 3 ){ - - }; - private final AppEngInternalInventory pattern = new AppEngInternalInventory( this, 2 ); - - private boolean craftingMode = true; - private boolean substitute = false; - - @Reflected - public PartPatternTerminal( final ItemStack is ) - { - super( is ); - } - - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - for( final ItemStack is : this.pattern ) - { - if( is != null ) - { - drops.add( is ); - } - } - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.setCraftingRecipe( data.getBoolean( "craftingMode" ) ); - this.setSubstitution( data.getBoolean( "substitute" ) ); - this.pattern.readFromNBT( data, "pattern" ); - this.output.readFromNBT( data, "outputList" ); - this.crafting.readFromNBT( data, "craftingGrid" ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setBoolean( "craftingMode", this.craftingMode ); - data.setBoolean( "substitute", this.substitute ); - this.pattern.writeToNBT( data, "pattern" ); - this.output.writeToNBT( data, "outputList" ); - this.crafting.writeToNBT( data, "craftingGrid" ); - } - - @Override - public GuiBridge getGui( final EntityPlayer p ) - { - int x = (int) p.posX; - int y = (int) p.posY; - int z = (int) p.posZ; - if( this.getHost().getTile() != null ) - { - x = this.getTile().xCoord; - y = this.getTile().yCoord; - z = this.getTile().zCoord; - } - - if( GuiBridge.GUI_PATTERN_TERMINAL.hasPermissions( this.getHost().getTile(), x, y, z, this.getSide(), p ) ) - { - return GuiBridge.GUI_PATTERN_TERMINAL; - } - return GuiBridge.GUI_ME; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - if (inv == this.pattern && slot == 1) { - - final ItemStack stack = this.pattern.getStackInSlot( 1 ); - - if (stack != null && stack.getItem() instanceof ICraftingPatternItem) { +public class PartPatternTerminal extends AbstractPartTerminal { + private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartPatternTerm_Bright; + private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartPatternTerm_Dark; + private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartPatternTerm_Colored; + + private final AppEngInternalInventory crafting = new BiggerAppEngInventory(this, 9) {}; + + private final AppEngInternalInventory output = new BiggerAppEngInventory(this, 3) {}; + + private final AppEngInternalInventory pattern = new AppEngInternalInventory(this, 2); + + private boolean craftingMode = true; + private boolean substitute = false; + + @Reflected + public PartPatternTerminal(final ItemStack is) { + super(is); + } + + @Override + public void getDrops(final List drops, final boolean wrenched) { + for (final ItemStack is : this.pattern) { + if (is != null) { + drops.add(is); + } + } + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.setCraftingRecipe(data.getBoolean("craftingMode")); + this.setSubstitution(data.getBoolean("substitute")); + this.pattern.readFromNBT(data, "pattern"); + this.output.readFromNBT(data, "outputList"); + this.crafting.readFromNBT(data, "craftingGrid"); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setBoolean("craftingMode", this.craftingMode); + data.setBoolean("substitute", this.substitute); + this.pattern.writeToNBT(data, "pattern"); + this.output.writeToNBT(data, "outputList"); + this.crafting.writeToNBT(data, "craftingGrid"); + } + + @Override + public GuiBridge getGui(final EntityPlayer p) { + int x = (int) p.posX; + int y = (int) p.posY; + int z = (int) p.posZ; + if (this.getHost().getTile() != null) { + x = this.getTile().xCoord; + y = this.getTile().yCoord; + z = this.getTile().zCoord; + } + + if (GuiBridge.GUI_PATTERN_TERMINAL.hasPermissions(this.getHost().getTile(), x, y, z, this.getSide(), p)) { + return GuiBridge.GUI_PATTERN_TERMINAL; + } + return GuiBridge.GUI_ME; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) { + if (inv == this.pattern && slot == 1) { + + final ItemStack stack = this.pattern.getStackInSlot(1); + + if (stack != null && stack.getItem() instanceof ICraftingPatternItem) { final ICraftingPatternItem pattern = (ICraftingPatternItem) stack.getItem(); final NBTTagCompound encodedValue = stack.getTagCompound(); - if (encodedValue != null) { - final ICraftingPatternDetails details = pattern.getPatternForItem( stack, this.getHost().getTile().getWorldObj() ); + if (encodedValue != null) { + final ICraftingPatternDetails details = pattern.getPatternForItem( + stack, this.getHost().getTile().getWorldObj()); final boolean substitute = encodedValue.getBoolean("substitute"); - final boolean isCrafting = encodedValue.getBoolean( "crafting" ); + final boolean isCrafting = encodedValue.getBoolean("crafting"); final IAEItemStack[] inItems; final IAEItemStack[] outItems; - + if (details == null) { inItems = PatternHelper.loadIAEItemStackFromNBT(encodedValue.getTagList("in", 10), true, null); - outItems = PatternHelper.loadIAEItemStackFromNBT(encodedValue.getTagList("out", 10), true, null); + outItems = + PatternHelper.loadIAEItemStackFromNBT(encodedValue.getTagList("out", 10), true, null); } else { inItems = details.getInputs(); outItems = details.getOutputs(); } - this.setCraftingRecipe(isCrafting); - this.setSubstitution(substitute); + this.setCraftingRecipe(isCrafting); + this.setSubstitution(substitute); for (int x = 0; x < this.crafting.getSizeInventory(); x++) { this.crafting.setInventorySlotContents(x, null); } - + for (int x = 0; x < this.output.getSizeInventory(); x++) { this.output.setInventorySlotContents(x, null); } @@ -159,98 +147,78 @@ public void onChangeInventory( final IInventory inv, final int slot, final InvOp this.crafting.setInventorySlotContents(x, inItems[x].getItemStack()); } } - - for (int x = 0; x < this.output.getSizeInventory() && x < outItems.length; x++) { - if (outItems[x] != null) { - this.output.setInventorySlotContents(x, outItems[x].getItemStack()); - } - } - - } - - } - } - else if( inv == this.crafting ) - { - this.fixCraftingRecipes(); - } - - this.getHost().markForSave(); - } - - private void fixCraftingRecipes() - { - if( this.craftingMode ) - { - for( int x = 0; x < this.crafting.getSizeInventory(); x++ ) - { - final ItemStack is = this.crafting.getStackInSlot( x ); - if( is != null ) - { - is.stackSize = 1; - } - } - } - } - - public boolean isCraftingRecipe() - { - return this.craftingMode; - } - - public void setCraftingRecipe( final boolean craftingMode ) - { - this.craftingMode = craftingMode; - this.fixCraftingRecipes(); - } - - public boolean isSubstitution() - { - return this.substitute; - } - - public void setSubstitution( boolean canSubstitute ) - { - this.substitute = canSubstitute; - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "crafting" ) ) - { - return this.crafting; - } - - if( name.equals( "output" ) ) - { - return this.output; - } - - if( name.equals( "pattern" ) ) - { - return this.pattern; - } - - return super.getInventoryByName( name ); - } - - @Override - public CableBusTextures getFrontBright() - { - return FRONT_BRIGHT_ICON; - } - - @Override - public CableBusTextures getFrontColored() - { - return FRONT_COLORED_ICON; - } - - @Override - public CableBusTextures getFrontDark() - { - return FRONT_DARK_ICON; - } + for (int x = 0; x < this.output.getSizeInventory() && x < outItems.length; x++) { + if (outItems[x] != null) { + this.output.setInventorySlotContents(x, outItems[x].getItemStack()); + } + } + } + } + } else if (inv == this.crafting) { + this.fixCraftingRecipes(); + } + + this.getHost().markForSave(); + } + + private void fixCraftingRecipes() { + if (this.craftingMode) { + for (int x = 0; x < this.crafting.getSizeInventory(); x++) { + final ItemStack is = this.crafting.getStackInSlot(x); + if (is != null) { + is.stackSize = 1; + } + } + } + } + + public boolean isCraftingRecipe() { + return this.craftingMode; + } + + public void setCraftingRecipe(final boolean craftingMode) { + this.craftingMode = craftingMode; + this.fixCraftingRecipes(); + } + + public boolean isSubstitution() { + return this.substitute; + } + + public void setSubstitution(boolean canSubstitute) { + this.substitute = canSubstitute; + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("crafting")) { + return this.crafting; + } + + if (name.equals("output")) { + return this.output; + } + + if (name.equals("pattern")) { + return this.pattern; + } + + return super.getInventoryByName(name); + } + + @Override + public CableBusTextures getFrontBright() { + return FRONT_BRIGHT_ICON; + } + + @Override + public CableBusTextures getFrontColored() { + return FRONT_COLORED_ICON; + } + + @Override + public CableBusTextures getFrontDark() { + return FRONT_DARK_ICON; + } } diff --git a/src/main/java/appeng/parts/reporting/PartPatternTerminalEx.java b/src/main/java/appeng/parts/reporting/PartPatternTerminalEx.java index b86fa51f21b..69488e9d883 100644 --- a/src/main/java/appeng/parts/reporting/PartPatternTerminalEx.java +++ b/src/main/java/appeng/parts/reporting/PartPatternTerminalEx.java @@ -10,114 +10,109 @@ import appeng.tile.inventory.AppEngInternalInventory; import appeng.tile.inventory.BiggerAppEngInventory; import appeng.tile.inventory.InvOperation; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.util.List; - public class PartPatternTerminalEx extends AbstractPartTerminal { private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartPatternTerm_Bright; private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartPatternTerm_Dark; private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartPatternTerm_Colored; - private final AppEngInternalInventory crafting = new BiggerAppEngInventory( this, 32 ); - private final AppEngInternalInventory output = new BiggerAppEngInventory( this, 32 ); - private final AppEngInternalInventory pattern = new AppEngInternalInventory( this, 2 ); + private final AppEngInternalInventory crafting = new BiggerAppEngInventory(this, 32); + private final AppEngInternalInventory output = new BiggerAppEngInventory(this, 32); + private final AppEngInternalInventory pattern = new AppEngInternalInventory(this, 2); private boolean substitute = false; private boolean inverted = false; private int activePage = 0; @Reflected - public PartPatternTerminalEx( final ItemStack is ) - { - super( is ); + public PartPatternTerminalEx(final ItemStack is) { + super(is); } @Override - public void getDrops(final List drops, final boolean wrenched ) - { - for( final ItemStack is : this.pattern ) - { - if( is != null ) - { - drops.add( is ); + public void getDrops(final List drops, final boolean wrenched) { + for (final ItemStack is : this.pattern) { + if (is != null) { + drops.add(is); } } } @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - - this.pattern.readFromNBT( data, "pattern" ); - this.output.readFromNBT( data, "outputList" ); - this.crafting.readFromNBT( data, "craftingGrid" ); + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); - this.setSubstitution( data.getBoolean( "substitute" ) ); - this.setInverted( data.getBoolean( "inverted" ) ); - this.setActivePage( data.getInteger( "activePage" ) ); + this.pattern.readFromNBT(data, "pattern"); + this.output.readFromNBT(data, "outputList"); + this.crafting.readFromNBT(data, "craftingGrid"); + this.setSubstitution(data.getBoolean("substitute")); + this.setInverted(data.getBoolean("inverted")); + this.setActivePage(data.getInteger("activePage")); } @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); - this.pattern.writeToNBT( data, "pattern" ); - this.output.writeToNBT( data, "outputList" ); - this.crafting.writeToNBT( data, "craftingGrid" ); + this.pattern.writeToNBT(data, "pattern"); + this.output.writeToNBT(data, "outputList"); + this.crafting.writeToNBT(data, "craftingGrid"); - data.setBoolean( "substitute", this.substitute ); - data.setBoolean( "inverted", this.inverted ); - data.setInteger( "activePage", this.activePage ); + data.setBoolean("substitute", this.substitute); + data.setBoolean("inverted", this.inverted); + data.setInteger("activePage", this.activePage); } @Override - public GuiBridge getGui(final EntityPlayer p ) - { + public GuiBridge getGui(final EntityPlayer p) { int x = (int) p.posX; int y = (int) p.posY; int z = (int) p.posZ; - if( this.getHost().getTile() != null ) - { + if (this.getHost().getTile() != null) { x = this.getTile().xCoord; y = this.getTile().yCoord; z = this.getTile().zCoord; } - if( GuiBridge.GUI_PATTERN_TERMINAL_EX.hasPermissions( this.getHost().getTile(), x, y, z, this.getSide(), p ) ) - { + if (GuiBridge.GUI_PATTERN_TERMINAL_EX.hasPermissions(this.getHost().getTile(), x, y, z, this.getSide(), p)) { return GuiBridge.GUI_PATTERN_TERMINAL_EX; } return GuiBridge.GUI_ME; } @Override - public void onChangeInventory(final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) { if (inv == this.pattern && slot == 1) { - final ItemStack stack = this.pattern.getStackInSlot( 1 ); + final ItemStack stack = this.pattern.getStackInSlot(1); if (stack != null && stack.getItem() instanceof ICraftingPatternItem) { final ICraftingPatternItem pattern = (ICraftingPatternItem) stack.getItem(); final NBTTagCompound encodedValue = stack.getTagCompound(); if (encodedValue != null) { - final ICraftingPatternDetails details = pattern.getPatternForItem( stack, this.getHost().getTile().getWorldObj() ); + final ICraftingPatternDetails details = pattern.getPatternForItem( + stack, this.getHost().getTile().getWorldObj()); final boolean substitute = encodedValue.getBoolean("substitute"); final IAEItemStack[] inItems; final IAEItemStack[] outItems; int inputsCount = 0; int outputCount = 0; - + if (details == null) { inItems = PatternHelper.loadIAEItemStackFromNBT(encodedValue.getTagList("in", 10), true, null); - outItems = PatternHelper.loadIAEItemStackFromNBT(encodedValue.getTagList("out", 10), false, null); + outItems = + PatternHelper.loadIAEItemStackFromNBT(encodedValue.getTagList("out", 10), false, null); } else { inItems = details.getInputs(); outItems = details.getOutputs(); @@ -125,13 +120,13 @@ public void onChangeInventory(final IInventory inv, final int slot, final InvOpe for (int x = 0; x < inItems.length; x++) { if (inItems[x] != null) { - inputsCount ++; + inputsCount++; } } for (int x = 0; x < outItems.length; x++) { if (outItems[x] != null) { - outputCount ++; + outputCount++; } } @@ -142,7 +137,7 @@ public void onChangeInventory(final IInventory inv, final int slot, final InvOpe for (int x = 0; x < this.crafting.getSizeInventory(); x++) { this.crafting.setInventorySlotContents(x, null); } - + for (int x = 0; x < this.output.getSizeInventory(); x++) { this.output.setInventorySlotContents(x, null); } @@ -152,7 +147,7 @@ public void onChangeInventory(final IInventory inv, final int slot, final InvOpe this.crafting.setInventorySlotContents(x, inItems[x].getItemStack()); } } - + if (inverted) { for (int x = 0; x < this.output.getSizeInventory() && x < outItems.length; x++) { if (outItems[x] != null) { @@ -161,85 +156,69 @@ public void onChangeInventory(final IInventory inv, final int slot, final InvOpe } } else { for (int x = 0; x < outItems.length && x < 8; x++) { - this.output.setInventorySlotContents(x >= 4? 12 + x : x, outItems[x].getItemStack()); + this.output.setInventorySlotContents(x >= 4 ? 12 + x : x, outItems[x].getItemStack()); } } - } - } } - + this.getHost().markForSave(); } - public boolean isSubstitution() - { + public boolean isSubstitution() { return this.substitute; } - public void setSubstitution( boolean canSubstitute ) - { + public void setSubstitution(boolean canSubstitute) { this.substitute = canSubstitute; } @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "crafting" ) ) - { + public IInventory getInventoryByName(final String name) { + if (name.equals("crafting")) { return this.crafting; } - if( name.equals( "output" ) ) - { + if (name.equals("output")) { return this.output; } - if( name.equals( "pattern" ) ) - { + if (name.equals("pattern")) { return this.pattern; } - return super.getInventoryByName( name ); + return super.getInventoryByName(name); } @Override - public CableBusTextures getFrontBright() - { + public CableBusTextures getFrontBright() { return FRONT_BRIGHT_ICON; } @Override - public CableBusTextures getFrontColored() - { + public CableBusTextures getFrontColored() { return FRONT_COLORED_ICON; } @Override - public CableBusTextures getFrontDark() - { + public CableBusTextures getFrontDark() { return FRONT_DARK_ICON; } - public boolean isInverted() - { + public boolean isInverted() { return inverted; } - public void setInverted(boolean inverted) - { + public void setInverted(boolean inverted) { this.inverted = inverted; } - public int getActivePage() - { + public int getActivePage() { return this.activePage; } - public void setActivePage(int activePage) - { + public void setActivePage(int activePage) { this.activePage = activePage; } - } diff --git a/src/main/java/appeng/parts/reporting/PartSemiDarkPanel.java b/src/main/java/appeng/parts/reporting/PartSemiDarkPanel.java index aee42e1a933..fe191f25b96 100644 --- a/src/main/java/appeng/parts/reporting/PartSemiDarkPanel.java +++ b/src/main/java/appeng/parts/reporting/PartSemiDarkPanel.java @@ -18,25 +18,22 @@ package appeng.parts.reporting; - import appeng.helpers.Reflected; import net.minecraft.item.ItemStack; +public class PartSemiDarkPanel extends AbstractPartPanel { -public class PartSemiDarkPanel extends AbstractPartPanel -{ - - @Reflected - public PartSemiDarkPanel( final ItemStack is ) - { - super( is ); - } + @Reflected + public PartSemiDarkPanel(final ItemStack is) { + super(is); + } - @Override - protected int getBrightnessColor() - { - final int light = this.getColor().whiteVariant; - final int dark = this.getColor().mediumVariant; - return ( ( ( ( ( light >> 16 ) & 0xff ) + ( ( dark >> 16 ) & 0xff ) ) / 2 ) << 16 ) | ( ( ( ( ( light >> 8 ) & 0xff ) + ( ( dark >> 8 ) & 0xff ) ) / 2 ) << 8 ) | ( ( ( ( light ) & 0xff ) + ( ( dark ) & 0xff ) ) / 2 ); - } + @Override + protected int getBrightnessColor() { + final int light = this.getColor().whiteVariant; + final int dark = this.getColor().mediumVariant; + return (((((light >> 16) & 0xff) + ((dark >> 16) & 0xff)) / 2) << 16) + | (((((light >> 8) & 0xff) + ((dark >> 8) & 0xff)) / 2) << 8) + | ((((light) & 0xff) + ((dark) & 0xff)) / 2); + } } diff --git a/src/main/java/appeng/parts/reporting/PartStorageMonitor.java b/src/main/java/appeng/parts/reporting/PartStorageMonitor.java index 764bf1319f7..3a9ccfca835 100644 --- a/src/main/java/appeng/parts/reporting/PartStorageMonitor.java +++ b/src/main/java/appeng/parts/reporting/PartStorageMonitor.java @@ -18,46 +18,40 @@ package appeng.parts.reporting; - import appeng.client.texture.CableBusTextures; import appeng.helpers.Reflected; import net.minecraft.item.ItemStack; - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class PartStorageMonitor extends AbstractPartMonitor -{ - private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartStorageMonitor_Bright; - private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartStorageMonitor_Dark; - private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartStorageMonitor_Colored; - private static final CableBusTextures FRONT_COLORED_ICON_LOCKED = CableBusTextures.PartStorageMonitor_Colored_Locked; - - @Reflected - public PartStorageMonitor( final ItemStack is ) - { - super( is ); - } - - @Override - public CableBusTextures getFrontBright() - { - return FRONT_BRIGHT_ICON; - } - - @Override - public CableBusTextures getFrontColored() - { - return this.isLocked() ? FRONT_COLORED_ICON_LOCKED : FRONT_COLORED_ICON; - } - - @Override - public CableBusTextures getFrontDark() - { - return FRONT_DARK_ICON; - } +public class PartStorageMonitor extends AbstractPartMonitor { + private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartStorageMonitor_Bright; + private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartStorageMonitor_Dark; + private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartStorageMonitor_Colored; + private static final CableBusTextures FRONT_COLORED_ICON_LOCKED = + CableBusTextures.PartStorageMonitor_Colored_Locked; + + @Reflected + public PartStorageMonitor(final ItemStack is) { + super(is); + } + + @Override + public CableBusTextures getFrontBright() { + return FRONT_BRIGHT_ICON; + } + + @Override + public CableBusTextures getFrontColored() { + return this.isLocked() ? FRONT_COLORED_ICON_LOCKED : FRONT_COLORED_ICON; + } + + @Override + public CableBusTextures getFrontDark() { + return FRONT_DARK_ICON; + } } diff --git a/src/main/java/appeng/parts/reporting/PartTerminal.java b/src/main/java/appeng/parts/reporting/PartTerminal.java index f3db2dcee81..2ec9311e4e4 100644 --- a/src/main/java/appeng/parts/reporting/PartTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartTerminal.java @@ -18,38 +18,31 @@ package appeng.parts.reporting; - import appeng.client.texture.CableBusTextures; import net.minecraft.item.ItemStack; +public class PartTerminal extends AbstractPartTerminal { -public class PartTerminal extends AbstractPartTerminal -{ - - public PartTerminal( final ItemStack is ) - { - super( is ); - } + public PartTerminal(final ItemStack is) { + super(is); + } - private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartTerminal_Bright; - private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartTerminal_Dark; - private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartTerminal_Colored; + private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartTerminal_Bright; + private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartTerminal_Dark; + private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartTerminal_Colored; - @Override - public CableBusTextures getFrontBright() - { - return FRONT_BRIGHT_ICON; - } + @Override + public CableBusTextures getFrontBright() { + return FRONT_BRIGHT_ICON; + } - @Override - public CableBusTextures getFrontColored() - { - return FRONT_COLORED_ICON; - } + @Override + public CableBusTextures getFrontColored() { + return FRONT_COLORED_ICON; + } - @Override - public CableBusTextures getFrontDark() - { - return FRONT_DARK_ICON; - } + @Override + public CableBusTextures getFrontDark() { + return FRONT_DARK_ICON; + } } diff --git a/src/main/java/appeng/recipes/AEItemResolver.java b/src/main/java/appeng/recipes/AEItemResolver.java index 356262a337e..93cfe0cc623 100644 --- a/src/main/java/appeng/recipes/AEItemResolver.java +++ b/src/main/java/appeng/recipes/AEItemResolver.java @@ -18,7 +18,6 @@ package appeng.recipes; - import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; import appeng.api.definitions.IItems; @@ -36,181 +35,151 @@ import appeng.items.parts.PartType; import net.minecraft.item.ItemStack; - -public class AEItemResolver implements ISubItemResolver -{ - - @Override - public Object resolveItemByName( final String nameSpace, final String itemName ) - { - - if( nameSpace.equals( AppEng.MOD_ID ) ) - { - final IDefinitions definitions = AEApi.instance().definitions(); - final IItems items = definitions.items(); - final IParts parts = definitions.parts(); - - if( itemName.startsWith( "PaintBall." ) ) - { - return this.paintBall( items.coloredPaintBall(), itemName.substring( itemName.indexOf( '.' ) + 1 ), false ); - } - - if( itemName.startsWith( "LumenPaintBall." ) ) - { - return this.paintBall( items.coloredLumenPaintBall(), itemName.substring( itemName.indexOf( '.' ) + 1 ), true ); - } - - if( itemName.equals( "CableGlass" ) ) - { - return new ResolverResultSet( "CableGlass", parts.cableGlass().allStacks( 1 ) ); - } - - if( itemName.startsWith( "CableGlass." ) ) - { - return this.cableItem( parts.cableGlass(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } - - if( itemName.equals( "CableCovered" ) ) - { - return new ResolverResultSet( "CableCovered", parts.cableCovered().allStacks( 1 ) ); - } - - if( itemName.startsWith( "CableCovered." ) ) - { - return this.cableItem( parts.cableCovered(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } - - if( itemName.equals( "CableSmart" ) ) - { - return new ResolverResultSet( "CableSmart", parts.cableSmart().allStacks( 1 ) ); - } - - if( itemName.startsWith( "CableSmart." ) ) - { - return this.cableItem( parts.cableSmart(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } - - if( itemName.equals( "CableDense" ) ) - { - return new ResolverResultSet( "CableDense", parts.cableDense().allStacks( 1 ) ); - } - - if( itemName.startsWith( "CableDense." ) ) - { - return this.cableItem( parts.cableDense(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } - - if( itemName.equals( "CableDenseCovered" ) ) - { - return new ResolverResultSet( "CableDenseCovered", parts.cableDenseCovered().allStacks( 1 ) ); - } - - if( itemName.startsWith( "CableDenseCovered." ) ) - { - return this.cableItem( parts.cableDenseCovered(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } - - if( itemName.equals( "CableUltraDenseSmart" ) ) - { - return new ResolverResultSet( "CableUltraDenseSmart", parts.cableUltraDenseSmart().allStacks( 1 ) ); - } - - if( itemName.startsWith( "CableUltraDenseSmart." ) ) - { - return this.cableItem( parts.cableUltraDenseSmart(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } - - if( itemName.equals( "CableUltraDenseCovered" ) ) - { - return new ResolverResultSet( "CableUltraDenseCovered", parts.cableUltraDenseCovered().allStacks( 1 ) ); - } - - if( itemName.startsWith( "CableUltraDenseCovered." ) ) - { - return this.cableItem( parts.cableUltraDenseCovered(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } - - if( itemName.startsWith( "ItemCrystalSeed." ) ) - { - if( itemName.equalsIgnoreCase( "ItemCrystalSeed.Certus" ) ) - { - return ItemCrystalSeed.getResolver( ItemCrystalSeed.CERTUS ); - } - if( itemName.equalsIgnoreCase( "ItemCrystalSeed.Nether" ) ) - { - return ItemCrystalSeed.getResolver( ItemCrystalSeed.NETHER ); - } - if( itemName.equalsIgnoreCase( "ItemCrystalSeed.Fluix" ) ) - { - return ItemCrystalSeed.getResolver( ItemCrystalSeed.FLUIX ); - } - - return null; - } - - if( itemName.startsWith( "ItemMaterial." ) ) - { - final String materialName = itemName.substring( itemName.indexOf( '.' ) + 1 ); - final MaterialType mt = MaterialType.valueOf( materialName ); - // itemName = itemName.substring( 0, itemName.indexOf( "." ) ); - if( mt.getItemInstance() == ItemMultiMaterial.instance && mt.getDamageValue() >= 0 && mt.isRegistered() ) - { - return new ResolverResult( "ItemMultiMaterial", mt.getDamageValue() ); - } - } - - if( itemName.startsWith( "ItemPart." ) ) - { - final String partName = itemName.substring( itemName.indexOf( '.' ) + 1 ); - final PartType pt = PartType.valueOf( partName ); - // itemName = itemName.substring( 0, itemName.indexOf( "." ) ); - final int dVal = ItemMultiPart.instance.getDamageByType( pt ); - if( dVal >= 0 ) - { - return new ResolverResult( "ItemMultiPart", dVal ); - } - } - } - - return null; - } - - private Object paintBall( final AEColoredItemDefinition partType, final String substring, final boolean lumen ) - { - AEColor col; - - try - { - col = AEColor.valueOf( substring ); - } - catch( final Throwable t ) - { - col = AEColor.Transparent; - } - - if( col == AEColor.Transparent ) - { - return null; - } - - final ItemStack is = partType.stack( col, 1 ); - return new ResolverResult( "ItemPaintBall", ( lumen ? 20 : 0 ) + is.getItemDamage() ); - } - - private Object cableItem( final AEColoredItemDefinition partType, final String substring ) - { - AEColor col; - - try - { - col = AEColor.valueOf( substring ); - } - catch( final Throwable t ) - { - col = AEColor.Transparent; - } - - final ItemStack is = partType.stack( col, 1 ); - return new ResolverResult( "ItemMultiPart", is.getItemDamage() ); - } +public class AEItemResolver implements ISubItemResolver { + + @Override + public Object resolveItemByName(final String nameSpace, final String itemName) { + + if (nameSpace.equals(AppEng.MOD_ID)) { + final IDefinitions definitions = AEApi.instance().definitions(); + final IItems items = definitions.items(); + final IParts parts = definitions.parts(); + + if (itemName.startsWith("PaintBall.")) { + return this.paintBall(items.coloredPaintBall(), itemName.substring(itemName.indexOf('.') + 1), false); + } + + if (itemName.startsWith("LumenPaintBall.")) { + return this.paintBall( + items.coloredLumenPaintBall(), itemName.substring(itemName.indexOf('.') + 1), true); + } + + if (itemName.equals("CableGlass")) { + return new ResolverResultSet("CableGlass", parts.cableGlass().allStacks(1)); + } + + if (itemName.startsWith("CableGlass.")) { + return this.cableItem(parts.cableGlass(), itemName.substring(itemName.indexOf('.') + 1)); + } + + if (itemName.equals("CableCovered")) { + return new ResolverResultSet( + "CableCovered", parts.cableCovered().allStacks(1)); + } + + if (itemName.startsWith("CableCovered.")) { + return this.cableItem(parts.cableCovered(), itemName.substring(itemName.indexOf('.') + 1)); + } + + if (itemName.equals("CableSmart")) { + return new ResolverResultSet("CableSmart", parts.cableSmart().allStacks(1)); + } + + if (itemName.startsWith("CableSmart.")) { + return this.cableItem(parts.cableSmart(), itemName.substring(itemName.indexOf('.') + 1)); + } + + if (itemName.equals("CableDense")) { + return new ResolverResultSet("CableDense", parts.cableDense().allStacks(1)); + } + + if (itemName.startsWith("CableDense.")) { + return this.cableItem(parts.cableDense(), itemName.substring(itemName.indexOf('.') + 1)); + } + + if (itemName.equals("CableDenseCovered")) { + return new ResolverResultSet( + "CableDenseCovered", parts.cableDenseCovered().allStacks(1)); + } + + if (itemName.startsWith("CableDenseCovered.")) { + return this.cableItem(parts.cableDenseCovered(), itemName.substring(itemName.indexOf('.') + 1)); + } + + if (itemName.equals("CableUltraDenseSmart")) { + return new ResolverResultSet( + "CableUltraDenseSmart", parts.cableUltraDenseSmart().allStacks(1)); + } + + if (itemName.startsWith("CableUltraDenseSmart.")) { + return this.cableItem(parts.cableUltraDenseSmart(), itemName.substring(itemName.indexOf('.') + 1)); + } + + if (itemName.equals("CableUltraDenseCovered")) { + return new ResolverResultSet( + "CableUltraDenseCovered", parts.cableUltraDenseCovered().allStacks(1)); + } + + if (itemName.startsWith("CableUltraDenseCovered.")) { + return this.cableItem(parts.cableUltraDenseCovered(), itemName.substring(itemName.indexOf('.') + 1)); + } + + if (itemName.startsWith("ItemCrystalSeed.")) { + if (itemName.equalsIgnoreCase("ItemCrystalSeed.Certus")) { + return ItemCrystalSeed.getResolver(ItemCrystalSeed.CERTUS); + } + if (itemName.equalsIgnoreCase("ItemCrystalSeed.Nether")) { + return ItemCrystalSeed.getResolver(ItemCrystalSeed.NETHER); + } + if (itemName.equalsIgnoreCase("ItemCrystalSeed.Fluix")) { + return ItemCrystalSeed.getResolver(ItemCrystalSeed.FLUIX); + } + + return null; + } + + if (itemName.startsWith("ItemMaterial.")) { + final String materialName = itemName.substring(itemName.indexOf('.') + 1); + final MaterialType mt = MaterialType.valueOf(materialName); + // itemName = itemName.substring( 0, itemName.indexOf( "." ) ); + if (mt.getItemInstance() == ItemMultiMaterial.instance + && mt.getDamageValue() >= 0 + && mt.isRegistered()) { + return new ResolverResult("ItemMultiMaterial", mt.getDamageValue()); + } + } + + if (itemName.startsWith("ItemPart.")) { + final String partName = itemName.substring(itemName.indexOf('.') + 1); + final PartType pt = PartType.valueOf(partName); + // itemName = itemName.substring( 0, itemName.indexOf( "." ) ); + final int dVal = ItemMultiPart.instance.getDamageByType(pt); + if (dVal >= 0) { + return new ResolverResult("ItemMultiPart", dVal); + } + } + } + + return null; + } + + private Object paintBall(final AEColoredItemDefinition partType, final String substring, final boolean lumen) { + AEColor col; + + try { + col = AEColor.valueOf(substring); + } catch (final Throwable t) { + col = AEColor.Transparent; + } + + if (col == AEColor.Transparent) { + return null; + } + + final ItemStack is = partType.stack(col, 1); + return new ResolverResult("ItemPaintBall", (lumen ? 20 : 0) + is.getItemDamage()); + } + + private Object cableItem(final AEColoredItemDefinition partType, final String substring) { + AEColor col; + + try { + col = AEColor.valueOf(substring); + } catch (final Throwable t) { + col = AEColor.Transparent; + } + + final ItemStack is = partType.stack(col, 1); + return new ResolverResult("ItemMultiPart", is.getItemDamage()); + } } diff --git a/src/main/java/appeng/recipes/CustomRecipeConfig.java b/src/main/java/appeng/recipes/CustomRecipeConfig.java index 08829ca9e66..36c1587c674 100644 --- a/src/main/java/appeng/recipes/CustomRecipeConfig.java +++ b/src/main/java/appeng/recipes/CustomRecipeConfig.java @@ -18,13 +18,11 @@ package appeng.recipes; - /** * @author thatsIch * @version rv3 - 22.08.2015 * @since rv3 22.08.2015 */ -public interface CustomRecipeConfig -{ - boolean isEnabled(); +public interface CustomRecipeConfig { + boolean isEnabled(); } diff --git a/src/main/java/appeng/recipes/CustomRecipeForgeConfiguration.java b/src/main/java/appeng/recipes/CustomRecipeForgeConfiguration.java index 0d92ed95255..179900613ec 100644 --- a/src/main/java/appeng/recipes/CustomRecipeForgeConfiguration.java +++ b/src/main/java/appeng/recipes/CustomRecipeForgeConfiguration.java @@ -18,32 +18,27 @@ package appeng.recipes; - import com.google.common.base.Preconditions; -import net.minecraftforge.common.config.Configuration; - import javax.annotation.Nonnull; - +import net.minecraftforge.common.config.Configuration; /** * @author thatsIch * @version rv3 - 23.08.2015 * @since rv3 23.08.2015 */ -public class CustomRecipeForgeConfiguration implements CustomRecipeConfig -{ - private final boolean isEnabled; +public class CustomRecipeForgeConfiguration implements CustomRecipeConfig { + private final boolean isEnabled; - public CustomRecipeForgeConfiguration( @Nonnull final Configuration config ) - { - Preconditions.checkNotNull( config ); + public CustomRecipeForgeConfiguration(@Nonnull final Configuration config) { + Preconditions.checkNotNull(config); - this.isEnabled = config.getBoolean( "enabled", "general", true, "If true, the custom recipes are enabled. Acts as a master switch." ); - } + this.isEnabled = config.getBoolean( + "enabled", "general", true, "If true, the custom recipes are enabled. Acts as a master switch."); + } - @Override - public final boolean isEnabled() - { - return this.isEnabled; - } + @Override + public final boolean isEnabled() { + return this.isEnabled; + } } diff --git a/src/main/java/appeng/recipes/GroupIngredient.java b/src/main/java/appeng/recipes/GroupIngredient.java index cbb483887b0..eac2a4f2267 100644 --- a/src/main/java/appeng/recipes/GroupIngredient.java +++ b/src/main/java/appeng/recipes/GroupIngredient.java @@ -18,143 +18,116 @@ package appeng.recipes; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; import appeng.api.recipes.IIngredient; import com.google.common.base.Preconditions; -import net.minecraft.item.ItemStack; -import net.minecraftforge.oredict.OreDictionary; - import java.util.Arrays; import java.util.LinkedList; import java.util.List; +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; - -public class GroupIngredient implements IIngredient -{ - - private final String name; - private final List ingredients; - private final int qty; - private ItemStack[] baked; - private boolean isInside = false; - - public GroupIngredient( final String myName, final List ingredients, final int qty ) throws RecipeError - { - Preconditions.checkNotNull( myName ); - Preconditions.checkNotNull( ingredients ); - Preconditions.checkState( !ingredients.isEmpty() ); - Preconditions.checkState( qty > 0 ); - - this.name = myName; - this.qty = qty; - - for( final IIngredient ingredient : ingredients ) - { - if( ingredient.isAir() ) - { - throw new RecipeError( "Cannot include air in a group." ); - } - } - - this.ingredients = ingredients; - } - - IIngredient copy( final int qty ) throws RecipeError - { - Preconditions.checkState( qty > 0 ); - return new GroupIngredient( this.name, this.ingredients, qty ); - } - - @Override - public ItemStack getItemStack() throws RegistrationError, MissingIngredientError - { - throw new RegistrationError( "Cannot pass group of items to a recipe which desires a single recipe item." ); - } - - @Override - public ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError - { - if( this.baked != null ) - { - return this.baked; - } - - if( this.isInside ) - { - return new ItemStack[0]; - } - - final List out = new LinkedList(); - this.isInside = true; - try - { - for( final IIngredient i : this.ingredients ) - { - try - { - out.addAll( Arrays.asList( i.getItemStackSet() ) ); - } - catch( final MissingIngredientError mir ) - { - // oh well this is a group! - } - } - } - finally - { - this.isInside = false; - } - - if( out.isEmpty() ) - { - throw new MissingIngredientError( this.toString() + " - group could not be resolved to any items." ); - } - - for( final ItemStack is : out ) - { - is.stackSize = this.qty; - } - - return out.toArray( new ItemStack[out.size()] ); - } - - @Override - public boolean isAir() - { - return false; - } - - @Override - public String getNameSpace() - { - return ""; - } - - @Override - public String getItemName() - { - return this.name; - } - - @Override - public int getDamageValue() - { - return OreDictionary.WILDCARD_VALUE; - } - - @Override - public int getQty() - { - return this.qty; - } - - @Override - public void bake() throws RegistrationError, MissingIngredientError - { - this.baked = null; - this.baked = this.getItemStackSet(); - } +public class GroupIngredient implements IIngredient { + + private final String name; + private final List ingredients; + private final int qty; + private ItemStack[] baked; + private boolean isInside = false; + + public GroupIngredient(final String myName, final List ingredients, final int qty) throws RecipeError { + Preconditions.checkNotNull(myName); + Preconditions.checkNotNull(ingredients); + Preconditions.checkState(!ingredients.isEmpty()); + Preconditions.checkState(qty > 0); + + this.name = myName; + this.qty = qty; + + for (final IIngredient ingredient : ingredients) { + if (ingredient.isAir()) { + throw new RecipeError("Cannot include air in a group."); + } + } + + this.ingredients = ingredients; + } + + IIngredient copy(final int qty) throws RecipeError { + Preconditions.checkState(qty > 0); + return new GroupIngredient(this.name, this.ingredients, qty); + } + + @Override + public ItemStack getItemStack() throws RegistrationError, MissingIngredientError { + throw new RegistrationError("Cannot pass group of items to a recipe which desires a single recipe item."); + } + + @Override + public ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError { + if (this.baked != null) { + return this.baked; + } + + if (this.isInside) { + return new ItemStack[0]; + } + + final List out = new LinkedList(); + this.isInside = true; + try { + for (final IIngredient i : this.ingredients) { + try { + out.addAll(Arrays.asList(i.getItemStackSet())); + } catch (final MissingIngredientError mir) { + // oh well this is a group! + } + } + } finally { + this.isInside = false; + } + + if (out.isEmpty()) { + throw new MissingIngredientError(this.toString() + " - group could not be resolved to any items."); + } + + for (final ItemStack is : out) { + is.stackSize = this.qty; + } + + return out.toArray(new ItemStack[out.size()]); + } + + @Override + public boolean isAir() { + return false; + } + + @Override + public String getNameSpace() { + return ""; + } + + @Override + public String getItemName() { + return this.name; + } + + @Override + public int getDamageValue() { + return OreDictionary.WILDCARD_VALUE; + } + + @Override + public int getQty() { + return this.qty; + } + + @Override + public void bake() throws RegistrationError, MissingIngredientError { + this.baked = null; + this.baked = this.getItemStackSet(); + } } diff --git a/src/main/java/appeng/recipes/Ingredient.java b/src/main/java/appeng/recipes/Ingredient.java index a7b3db09aeb..489f50d458e 100644 --- a/src/main/java/appeng/recipes/Ingredient.java +++ b/src/main/java/appeng/recipes/Ingredient.java @@ -18,7 +18,6 @@ package appeng.recipes; - import appeng.api.AEApi; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; @@ -28,247 +27,203 @@ import appeng.api.recipes.ResolverResultSet; import com.google.common.base.Preconditions; import cpw.mods.fml.common.registry.GameRegistry; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.oredict.OreDictionary; -import java.util.List; - - -public class Ingredient implements IIngredient -{ - - private final boolean isAir; - private final String nameSpace; - private final String itemName; - private final int meta; - private final int qty; - private NBTTagCompound nbt = null; - private ItemStack[] baked; - - public Ingredient( final RecipeHandler handler, final String input, final int qty ) throws RecipeError, MissedIngredientSet - { - Preconditions.checkNotNull( handler ); - Preconditions.checkNotNull( input ); - Preconditions.checkState( qty > 0 ); - - // works no matter wat! - this.qty = qty; - - if( input.equals( "_" ) ) - { - this.isAir = true; - this.nameSpace = ""; - this.itemName = ""; - this.meta = OreDictionary.WILDCARD_VALUE; - return; - } - - this.isAir = false; - final String[] parts = input.split( ":" ); - if( parts.length >= 2 ) - { - this.nameSpace = handler.alias( parts[0] ); - String tmpName = handler.alias( parts[1] ); - - if( parts.length != 3 ) - { - int sel = 0; - - if( this.nameSpace.equals( "oreDictionary" ) ) - { - if( parts.length == 3 ) - { - throw new RecipeError( "Cannot specify meta when using ore dictionary." ); - } - sel = OreDictionary.WILDCARD_VALUE; - } - else - { - try - { - final Object ro = AEApi.instance().registries().recipes().resolveItem( this.nameSpace, tmpName ); - if( ro instanceof ResolverResult ) - { - final ResolverResult rr = (ResolverResult) ro; - tmpName = rr.itemName; - sel = rr.damageValue; - this.nbt = rr.compound; - } - else if( ro instanceof ResolverResultSet ) - { - throw new MissedIngredientSet( (ResolverResultSet) ro ); - } - } - catch( final IllegalArgumentException e ) - { - throw new RecipeError( tmpName + " is not a valid ae2 item definition." ); - } - } - - this.meta = sel; - } - else - { - if( parts[2].equals( "*" ) ) - { - this.meta = OreDictionary.WILDCARD_VALUE; - } - else - { - try - { - this.meta = Integer.parseInt( parts[2] ); - } - catch( final NumberFormatException e ) - { - throw new RecipeError( "Invalid Metadata." ); - } - } - } - this.itemName = tmpName; - } - else - { - throw new RecipeError( input + " : Needs at least Namespace and Name." ); - } - - handler.getData().knownItem.add( this.toString() ); - } - - @Override - public String toString() - { - return this.nameSpace + ':' + this.itemName + ':' + this.meta; - } - - @Override - public ItemStack getItemStack() throws RegistrationError, MissingIngredientError - { - if( this.isAir ) - { - throw new RegistrationError( "Found blank item and expected a real item." ); - } - - if( this.nameSpace.equalsIgnoreCase( "oreDictionary" ) ) - { - throw new RegistrationError( "Recipe format expected a single item, but got a set of items." ); - } - - Block blk = GameRegistry.findBlock( this.nameSpace, this.itemName ); - if( blk == null ) - { - blk = GameRegistry.findBlock( this.nameSpace, "tile." + this.itemName ); - } - - if( blk != null ) - { - final Item it = Item.getItemFromBlock( blk ); - if( it != null ) - { - return this.makeItemStack( it, this.qty, this.meta, this.nbt ); - } - } - - Item it = GameRegistry.findItem( this.nameSpace, this.itemName ); - if( it == null ) - { - it = GameRegistry.findItem( this.nameSpace, "item." + this.itemName ); - } - - if( it != null ) - { - return this.makeItemStack( it, this.qty, this.meta, this.nbt ); - } - - /* - * Object o = Item.itemRegistry.getObject( nameSpace + ":" + itemName ); if ( o instanceof Item ) return new - * ItemStack( (Item) o, qty, meta ); - * if ( o instanceof Block ) return new ItemStack( (Block) o, qty, meta ); - * o = Item.itemRegistry.getObject( nameSpace + ":item." + itemName ); if ( o instanceof Item ) return new - * ItemStack( (Item) o, qty, meta ); - * o = Block.blockRegistry.getObject( nameSpace + ":tile." + itemName ); if ( o instanceof Block && (!(o - * instanceof BlockAir)) ) return new ItemStack( (Block) o, qty, meta ); - */ - - throw new MissingIngredientError( "Unable to find item: " + this.toString() ); - } - - private ItemStack makeItemStack( final Item it, final int quantity, final int damageValue, final NBTTagCompound compound ) - { - final ItemStack is = new ItemStack( it, quantity, damageValue ); - is.setTagCompound( compound ); - return is; - } - - @Override - public ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError - { - if( this.baked != null ) - { - return this.baked; - } - - if( this.nameSpace.equalsIgnoreCase( "oreDictionary" ) ) - { - final List ores = OreDictionary.getOres( this.itemName ); - final ItemStack[] set = ores.toArray( new ItemStack[ores.size()] ); - - // clone and set qty. - for( int x = 0; x < set.length; x++ ) - { - final ItemStack is = set[x].copy(); - is.stackSize = this.qty; - set[x] = is; - } - - if( set.length == 0 ) - { - throw new MissingIngredientError( this.itemName + " - ore dictionary could not be resolved to any items." ); - } - - return set; - } - - return new ItemStack[] { this.getItemStack() }; - } - - @Override - public String getNameSpace() - { - return this.nameSpace; - } - - @Override - public String getItemName() - { - return this.itemName; - } - - @Override - public int getDamageValue() - { - return this.meta; - } - - @Override - public int getQty() - { - return this.qty; - } - - @Override - public boolean isAir() - { - return this.isAir; - } - - @Override - public void bake() throws RegistrationError, MissingIngredientError - { - this.baked = null; - this.baked = this.getItemStackSet(); - } +public class Ingredient implements IIngredient { + + private final boolean isAir; + private final String nameSpace; + private final String itemName; + private final int meta; + private final int qty; + private NBTTagCompound nbt = null; + private ItemStack[] baked; + + public Ingredient(final RecipeHandler handler, final String input, final int qty) + throws RecipeError, MissedIngredientSet { + Preconditions.checkNotNull(handler); + Preconditions.checkNotNull(input); + Preconditions.checkState(qty > 0); + + // works no matter wat! + this.qty = qty; + + if (input.equals("_")) { + this.isAir = true; + this.nameSpace = ""; + this.itemName = ""; + this.meta = OreDictionary.WILDCARD_VALUE; + return; + } + + this.isAir = false; + final String[] parts = input.split(":"); + if (parts.length >= 2) { + this.nameSpace = handler.alias(parts[0]); + String tmpName = handler.alias(parts[1]); + + if (parts.length != 3) { + int sel = 0; + + if (this.nameSpace.equals("oreDictionary")) { + if (parts.length == 3) { + throw new RecipeError("Cannot specify meta when using ore dictionary."); + } + sel = OreDictionary.WILDCARD_VALUE; + } else { + try { + final Object ro = + AEApi.instance().registries().recipes().resolveItem(this.nameSpace, tmpName); + if (ro instanceof ResolverResult) { + final ResolverResult rr = (ResolverResult) ro; + tmpName = rr.itemName; + sel = rr.damageValue; + this.nbt = rr.compound; + } else if (ro instanceof ResolverResultSet) { + throw new MissedIngredientSet((ResolverResultSet) ro); + } + } catch (final IllegalArgumentException e) { + throw new RecipeError(tmpName + " is not a valid ae2 item definition."); + } + } + + this.meta = sel; + } else { + if (parts[2].equals("*")) { + this.meta = OreDictionary.WILDCARD_VALUE; + } else { + try { + this.meta = Integer.parseInt(parts[2]); + } catch (final NumberFormatException e) { + throw new RecipeError("Invalid Metadata."); + } + } + } + this.itemName = tmpName; + } else { + throw new RecipeError(input + " : Needs at least Namespace and Name."); + } + + handler.getData().knownItem.add(this.toString()); + } + + @Override + public String toString() { + return this.nameSpace + ':' + this.itemName + ':' + this.meta; + } + + @Override + public ItemStack getItemStack() throws RegistrationError, MissingIngredientError { + if (this.isAir) { + throw new RegistrationError("Found blank item and expected a real item."); + } + + if (this.nameSpace.equalsIgnoreCase("oreDictionary")) { + throw new RegistrationError("Recipe format expected a single item, but got a set of items."); + } + + Block blk = GameRegistry.findBlock(this.nameSpace, this.itemName); + if (blk == null) { + blk = GameRegistry.findBlock(this.nameSpace, "tile." + this.itemName); + } + + if (blk != null) { + final Item it = Item.getItemFromBlock(blk); + if (it != null) { + return this.makeItemStack(it, this.qty, this.meta, this.nbt); + } + } + + Item it = GameRegistry.findItem(this.nameSpace, this.itemName); + if (it == null) { + it = GameRegistry.findItem(this.nameSpace, "item." + this.itemName); + } + + if (it != null) { + return this.makeItemStack(it, this.qty, this.meta, this.nbt); + } + + /* + * Object o = Item.itemRegistry.getObject( nameSpace + ":" + itemName ); if ( o instanceof Item ) return new + * ItemStack( (Item) o, qty, meta ); + * if ( o instanceof Block ) return new ItemStack( (Block) o, qty, meta ); + * o = Item.itemRegistry.getObject( nameSpace + ":item." + itemName ); if ( o instanceof Item ) return new + * ItemStack( (Item) o, qty, meta ); + * o = Block.blockRegistry.getObject( nameSpace + ":tile." + itemName ); if ( o instanceof Block && (!(o + * instanceof BlockAir)) ) return new ItemStack( (Block) o, qty, meta ); + */ + + throw new MissingIngredientError("Unable to find item: " + this.toString()); + } + + private ItemStack makeItemStack( + final Item it, final int quantity, final int damageValue, final NBTTagCompound compound) { + final ItemStack is = new ItemStack(it, quantity, damageValue); + is.setTagCompound(compound); + return is; + } + + @Override + public ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError { + if (this.baked != null) { + return this.baked; + } + + if (this.nameSpace.equalsIgnoreCase("oreDictionary")) { + final List ores = OreDictionary.getOres(this.itemName); + final ItemStack[] set = ores.toArray(new ItemStack[ores.size()]); + + // clone and set qty. + for (int x = 0; x < set.length; x++) { + final ItemStack is = set[x].copy(); + is.stackSize = this.qty; + set[x] = is; + } + + if (set.length == 0) { + throw new MissingIngredientError( + this.itemName + " - ore dictionary could not be resolved to any items."); + } + + return set; + } + + return new ItemStack[] {this.getItemStack()}; + } + + @Override + public String getNameSpace() { + return this.nameSpace; + } + + @Override + public String getItemName() { + return this.itemName; + } + + @Override + public int getDamageValue() { + return this.meta; + } + + @Override + public int getQty() { + return this.qty; + } + + @Override + public boolean isAir() { + return this.isAir; + } + + @Override + public void bake() throws RegistrationError, MissingIngredientError { + this.baked = null; + this.baked = this.getItemStackSet(); + } } diff --git a/src/main/java/appeng/recipes/IngredientSet.java b/src/main/java/appeng/recipes/IngredientSet.java index 407c8aa90e8..e0698b5ea05 100644 --- a/src/main/java/appeng/recipes/IngredientSet.java +++ b/src/main/java/appeng/recipes/IngredientSet.java @@ -18,109 +18,92 @@ package appeng.recipes; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; import appeng.api.recipes.IIngredient; import appeng.api.recipes.ResolverResultSet; import com.google.common.base.Preconditions; -import net.minecraft.item.ItemStack; -import net.minecraftforge.oredict.OreDictionary; - import java.util.LinkedList; import java.util.List; +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; - -public class IngredientSet implements IIngredient -{ - - private final int qty; - private final String name; - private final List items; - private final boolean isInside = false; - private ItemStack[] baked; - - public IngredientSet( final ResolverResultSet rr, final int qty ) - { - Preconditions.checkNotNull( rr ); - Preconditions.checkNotNull( rr.name ); - Preconditions.checkNotNull( rr.results ); - Preconditions.checkState( qty > 0 ); - - this.name = rr.name; - this.items = rr.results; - this.qty = qty; - } - - @Override - public ItemStack getItemStack() throws RegistrationError, MissingIngredientError - { - throw new RegistrationError( "Cannot pass group of items to a recipe which desires a single recipe item." ); - } - - @Override - public ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError - { - if( this.baked != null ) - { - return this.baked; - } - - if( this.isInside ) - { - return new ItemStack[0]; - } - - final List out = new LinkedList(); - out.addAll( this.items ); - - if( out.isEmpty() ) - { - throw new MissingIngredientError( this.toString() + " - group could not be resolved to any items." ); - } - - for( final ItemStack is : out ) - { - is.stackSize = this.qty; - } - - return out.toArray( new ItemStack[out.size()] ); - } - - @Override - public boolean isAir() - { - return false; - } - - @Override - public String getNameSpace() - { - return ""; - } - - @Override - public String getItemName() - { - return this.name; - } - - @Override - public int getDamageValue() - { - return OreDictionary.WILDCARD_VALUE; - } - - @Override - public int getQty() - { - return this.qty; - } - - @Override - public void bake() throws RegistrationError, MissingIngredientError - { - this.baked = null; - this.baked = this.getItemStackSet(); - } +public class IngredientSet implements IIngredient { + + private final int qty; + private final String name; + private final List items; + private final boolean isInside = false; + private ItemStack[] baked; + + public IngredientSet(final ResolverResultSet rr, final int qty) { + Preconditions.checkNotNull(rr); + Preconditions.checkNotNull(rr.name); + Preconditions.checkNotNull(rr.results); + Preconditions.checkState(qty > 0); + + this.name = rr.name; + this.items = rr.results; + this.qty = qty; + } + + @Override + public ItemStack getItemStack() throws RegistrationError, MissingIngredientError { + throw new RegistrationError("Cannot pass group of items to a recipe which desires a single recipe item."); + } + + @Override + public ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError { + if (this.baked != null) { + return this.baked; + } + + if (this.isInside) { + return new ItemStack[0]; + } + + final List out = new LinkedList(); + out.addAll(this.items); + + if (out.isEmpty()) { + throw new MissingIngredientError(this.toString() + " - group could not be resolved to any items."); + } + + for (final ItemStack is : out) { + is.stackSize = this.qty; + } + + return out.toArray(new ItemStack[out.size()]); + } + + @Override + public boolean isAir() { + return false; + } + + @Override + public String getNameSpace() { + return ""; + } + + @Override + public String getItemName() { + return this.name; + } + + @Override + public int getDamageValue() { + return OreDictionary.WILDCARD_VALUE; + } + + @Override + public int getQty() { + return this.qty; + } + + @Override + public void bake() throws RegistrationError, MissingIngredientError { + this.baked = null; + this.baked = this.getItemStackSet(); + } } diff --git a/src/main/java/appeng/recipes/MissedIngredientSet.java b/src/main/java/appeng/recipes/MissedIngredientSet.java index 41f398e260c..dfcc02381d5 100644 --- a/src/main/java/appeng/recipes/MissedIngredientSet.java +++ b/src/main/java/appeng/recipes/MissedIngredientSet.java @@ -18,23 +18,18 @@ package appeng.recipes; - import appeng.api.recipes.ResolverResultSet; +public class MissedIngredientSet extends Throwable { -public class MissedIngredientSet extends Throwable -{ - - private static final long serialVersionUID = 2672951714376345807L; - private final ResolverResultSet resolverResultSet; + private static final long serialVersionUID = 2672951714376345807L; + private final ResolverResultSet resolverResultSet; - public MissedIngredientSet( final ResolverResultSet ro ) - { - this.resolverResultSet = ro; - } + public MissedIngredientSet(final ResolverResultSet ro) { + this.resolverResultSet = ro; + } - ResolverResultSet getResolverResultSet() - { - return this.resolverResultSet; - } + ResolverResultSet getResolverResultSet() { + return this.resolverResultSet; + } } diff --git a/src/main/java/appeng/recipes/RecipeData.java b/src/main/java/appeng/recipes/RecipeData.java index 36b8934f608..8ad0a3b55bc 100644 --- a/src/main/java/appeng/recipes/RecipeData.java +++ b/src/main/java/appeng/recipes/RecipeData.java @@ -18,21 +18,17 @@ package appeng.recipes; - import appeng.api.recipes.ICraftHandler; - import java.util.*; +public class RecipeData { -public class RecipeData -{ - - final Map aliases = new HashMap(); - final Map groups = new HashMap(); + final Map aliases = new HashMap(); + final Map groups = new HashMap(); - final List handlers = new LinkedList(); - final Set knownItem = new HashSet(); - boolean crash = true; - boolean exceptions = true; - boolean errorOnMissing = true; + final List handlers = new LinkedList(); + final Set knownItem = new HashSet(); + boolean crash = true; + boolean exceptions = true; + boolean errorOnMissing = true; } diff --git a/src/main/java/appeng/recipes/RecipeHandler.java b/src/main/java/appeng/recipes/RecipeHandler.java index 79f1d244b92..e4458cc6c68 100644 --- a/src/main/java/appeng/recipes/RecipeHandler.java +++ b/src/main/java/appeng/recipes/RecipeHandler.java @@ -18,7 +18,6 @@ package appeng.recipes; - import appeng.api.AEApi; import appeng.api.definitions.IBlocks; import appeng.api.definitions.IDefinitions; @@ -46,10 +45,6 @@ import cpw.mods.fml.common.LoaderState; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import javax.annotation.Nonnull; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; @@ -58,7 +53,9 @@ import java.util.Map.Entry; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; - +import javax.annotation.Nonnull; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; /** * @author AlgorithmX2 @@ -66,716 +63,536 @@ * @version rv3 - 10.08.2015 * @since rv0 */ -public class RecipeHandler implements IRecipeHandler -{ - private final RecipeData data; - private final List tokens = new LinkedList(); - - public RecipeHandler() - { - this.data = new RecipeData(); - } - - /** - * Called recursively from parent - * - * @param parent owner of this handler - */ - private RecipeHandler( final RecipeHandler parent ) - { - Preconditions.checkNotNull( parent ); - this.data = parent.data; - } - - private void addCrafting( final ICraftHandler ch ) - { - this.data.handlers.add( ch ); - } - - public String getName( @Nonnull final IIngredient i ) - { - try - { - for( final ItemStack is : i.getItemStackSet() ) - { - return this.getName( is ); - } - } - catch( final RecipeError ignored ) - { - } - catch( final Throwable t ) - { - t.printStackTrace(); - // :P - } - - return i.getNameSpace() + ':' + i.getItemName(); - } - - private String getName( final ItemStack is ) throws RecipeError - { - Preconditions.checkNotNull( is ); - - final UniqueIdentifier id = GameRegistry.findUniqueIdentifierFor( is.getItem() ); - String realName = id.modId + ':' + id.name; - - if( !id.modId.equals( AppEng.MOD_ID ) && !id.modId.equals( "minecraft" ) ) - { - throw new RecipeError( "Not applicable for website" ); - } - - final IDefinitions definitions = AEApi.instance().definitions(); - final IItems items = definitions.items(); - final IBlocks blocks = definitions.blocks(); - - final Optional maybeCrystalSeedItem = items.crystalSeed().maybeItem(); - final Optional maybeSkyStoneItem = blocks.skyStone().maybeItem(); - final Optional maybeCStorageItem = blocks.craftingStorage1k().maybeItem(); - final Optional maybeCUnitItem = blocks.craftingUnit().maybeItem(); - final Optional maybeSkyChestItem = blocks.skyChest().maybeItem(); - - if( maybeCrystalSeedItem.isPresent() && is.getItem() == maybeCrystalSeedItem.get() ) - { - final int dmg = is.getItemDamage(); - if( dmg < ItemCrystalSeed.NETHER ) - { - realName += ".Certus"; - } - else if( dmg < ItemCrystalSeed.FLUIX ) - { - realName += ".Nether"; - } - else if( dmg < ItemCrystalSeed.FINAL_STAGE ) - { - realName += ".Fluix"; - } - } - else if( maybeSkyStoneItem.isPresent() && is.getItem() == maybeSkyStoneItem.get() ) - { - switch( is.getItemDamage() ) - { - case 1: - realName += ".Block"; - break; - case 2: - realName += ".Brick"; - break; - case 3: - realName += ".SmallBrick"; - break; - default: - } - } - else if( maybeCStorageItem.isPresent() && is.getItem() == maybeCStorageItem.get() ) - { - switch( is.getItemDamage() ) - { - case 1: - realName += "4k"; - break; - case 2: - realName += "16k"; - break; - case 3: - realName += "64k"; - break; - default: - } - } - else if( maybeCUnitItem.isPresent() && is.getItem() == maybeCUnitItem.get() ) - { - switch( is.getItemDamage() ) - { - case 1: - realName = realName.replace( "Unit", "Accelerator" ); - break; - default: - } - } - else if( maybeSkyChestItem.isPresent() && is.getItem() == maybeSkyChestItem.get() ) - { - switch( is.getItemDamage() ) - { - case 1: - realName += ".Block"; - break; - default: - } - } - else if( is.getItem() instanceof ItemMultiMaterial ) - { - realName = realName.replace( "ItemMultiMaterial", "ItemMaterial" ); - realName += '.' + ( (ItemMultiMaterial) is.getItem() ).getTypeByStack( is ).name(); - } - else if( is.getItem() instanceof ItemMultiPart ) - { - realName = realName.replace( "ItemMultiPart", "ItemPart" ); - realName += '.' + ( (ItemMultiPart) is.getItem() ).getTypeByStack( is ).name(); - } - else if( is.getItemDamage() > 0 ) - { - realName += "." + is.getItemDamage(); - } - - return realName; - } - - String alias( final String in ) - { - Preconditions.checkNotNull( in ); - - final String out = this.data.aliases.get( in ); - - if( out != null ) - { - return out; - } - - return in; - } - - @Override - public void parseRecipes( final IRecipeLoader loader, final String path ) - { - Preconditions.checkNotNull( loader ); - Preconditions.checkNotNull( path ); - - try - { - BufferedReader reader = null; - try - { - reader = loader.getFile( path ); - } - catch( final Exception err ) - { - AELog.warn( "Error Loading Recipe File:" + path ); - if( this.data.exceptions ) - { - AELog.debug( err ); - } - return; - } - - boolean inQuote = false; - boolean inComment = false; - - String token = ""; - int line = 0; - - int val = -1; - while( ( val = reader.read() ) != -1 ) - { - final char c = (char) val; - - if( c == '\n' ) - { - line++; - } - - if( inComment ) - { - if( c == '\n' || c == '\r' ) - { - inComment = false; - } - } - else if( inQuote ) - { - switch( c ) - { - case '"': - inQuote = !inQuote; - break; - default: - token += c; - } - } - else - { - switch( c ) - { - case '"': - inQuote = !inQuote; - break; - case ',': - - if( token.length() > 0 ) - { - this.tokens.add( token ); - this.tokens.add( "," ); - } - token = ""; - break; - - case '=': - - this.processTokens( loader, path, line ); - - if( token.length() > 0 ) - { - this.tokens.add( token ); - } - token = ""; - - break; - - case '#': - inComment = true; - // then add a token if you can... - - case '\n': - case '\t': - case '\r': - case ' ': - - if( token.length() > 0 ) - { - this.tokens.add( token ); - } - token = ""; - - break; - default: - token += c; - } - } - } - - if( token.length() > 0 ) - { - this.tokens.add( token ); - } - - reader.close(); - this.processTokens( loader, path, line ); - } - catch( final Throwable e ) - { - AELog.debug( e ); - if( this.data.crash ) - { - throw new IllegalStateException( e ); - } - } - } - - @Override - public void injectRecipes() - { - if( cpw.mods.fml.common.Loader.instance().hasReachedState( LoaderState.POSTINITIALIZATION ) ) - { - throw new IllegalStateException( "Recipes must now be loaded in Init." ); - } - - final Map processed = new HashMap(); - try - { - for( final ICraftHandler ch : this.data.handlers ) - { - try - { - ch.register(); - - final Class clz = ch.getClass(); - final Integer i = processed.get( clz ); - if( i == null ) - { - processed.put( clz, 1 ); - } - else - { - processed.put( clz, i + 1 ); - } - } - catch( final RegistrationError e ) - { - AELog.warn( "Unable to register a recipe: " + e.getMessage() ); - if( this.data.exceptions ) - { - AELog.debug( e ); - } - if( this.data.crash ) - { - throw e; - } - } - catch( final MissingIngredientError e ) - { - if( this.data.errorOnMissing ) - { - AELog.warn( "Unable to register a recipe:" + e.getMessage() ); - if( this.data.exceptions ) - { - AELog.debug( e ); - } - if( this.data.crash ) - { - throw e; - } - } - } - } - } - catch( final Throwable e ) - { - if( this.data.exceptions ) - { - AELog.debug( e ); - } - if( this.data.crash ) - { - throw new IllegalStateException( e ); - } - } - - for( final Entry e : processed.entrySet() ) - { - AELog.info( "Recipes Loading: " + e.getKey().getSimpleName() + ": " + e.getValue() + " loaded." ); - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.WebsiteRecipes ) ) - { - try - { - final ZipOutputStream out = new ZipOutputStream( new FileOutputStream( "recipes.zip" ) ); - - final HashMultimap combined = HashMultimap.create(); - - for( final String s : this.data.knownItem ) - { - try - { - - final IIngredient i = new Ingredient( this, s, 1 ); - - for( final ItemStack is : i.getItemStackSet() ) - { - final String realName = this.getName( is ); - final List recipes = this.findRecipe( is ); - if( !recipes.isEmpty() ) - { - combined.putAll( realName, recipes ); - } - } - } - catch( final RecipeError ignored ) - { - - } - catch( final MissedIngredientSet ignored ) - { - - } - catch( final RegistrationError ignored ) - { - - } - catch( final MissingIngredientError ignored ) - { - - } - } - - for( final String realName : combined.keySet() ) - { - int offset = 0; - - for( final IWebsiteSerializer ws : combined.get( realName ) ) - { - final String rew = ws.getPattern( this ); - if( rew != null && rew.length() > 0 ) - { - out.putNextEntry( new ZipEntry( realName + '_' + offset + ".txt" ) ); - offset++; - out.write( rew.getBytes() ); - } - } - } - - out.close(); - } - catch( final FileNotFoundException e1 ) - { - AELog.debug( e1 ); - } - catch( final IOException e1 ) - { - AELog.debug( e1 ); - } - } - } - - private List findRecipe( final ItemStack output ) - { - final List out = new LinkedList(); - - for( final ICraftHandler ch : this.data.handlers ) - { - try - { - if( ch instanceof IWebsiteSerializer && ( (IWebsiteSerializer) ch ).canCraft( output ) ) - { - out.add( (IWebsiteSerializer) ch ); - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - } - - return out; - } - - RecipeData getData() - { - return this.data; - } - - private void processTokens( final IRecipeLoader loader, final String file, final int line ) throws RecipeError - { - try - { - final IRecipeHandlerRegistry cr = AEApi.instance().registries().recipes(); - - if( this.tokens.isEmpty() ) - { - return; - } - - final int split = this.tokens.indexOf( "->" ); - if( split != -1 ) - { - final String operation = this.tokens.remove( 0 ).toLowerCase( Locale.ENGLISH ); - - if( operation.equals( "alias" ) ) - { - if( this.tokens.size() == 3 && this.tokens.indexOf( "->" ) == 1 ) - { - this.data.aliases.put( this.tokens.get( 0 ), this.tokens.get( 2 ) ); - } - else - { - throw new RecipeError( "Alias must have exactly 1 input and 1 output." ); - } - } - else if( operation.equals( "group" ) ) - { - final List pre = this.tokens.subList( 0, split - 1 ); - final List post = this.tokens.subList( split, this.tokens.size() ); - - final List> inputs = this.parseLines( pre ); - - if( inputs.size() == 1 && inputs.get( 0 ).size() > 0 && post.size() == 1 ) - { - this.data.groups.put( post.get( 0 ), new GroupIngredient( post.get( 0 ), inputs.get( 0 ), 1 ) ); - } - else - { - throw new RecipeError( "Group must have exactly 1 output, and 1 or more inputs." ); - } - } - else if( operation.equals( "ore" ) ) - { - final List pre = this.tokens.subList( 0, split - 1 ); - final List post = this.tokens.subList( split, this.tokens.size() ); - - final List> inputs = this.parseLines( pre ); - - if( inputs.size() == 1 && inputs.get( 0 ).size() > 0 && post.size() == 1 ) - { - final ICraftHandler ch = new OreRegistration( inputs.get( 0 ), post.get( 0 ) ); - this.addCrafting( ch ); - } - else - { - throw new RecipeError( "Group must have exactly 1 output, and 1 or more inputs in a single row." ); - } - } - else - { - final List pre = this.tokens.subList( 0, split - 1 ); - final List post = this.tokens.subList( split, this.tokens.size() ); - - final List> inputs = this.parseLines( pre ); - final List> outputs = this.parseLines( post ); - - final ICraftHandler ch = cr.getCraftHandlerFor( operation ); - - if( ch != null ) - { - ch.setup( inputs, outputs ); - this.addCrafting( ch ); - } - else - { - throw new RecipeError( "Invalid crafting type: " + operation ); - } - } - } - else - { - final String operation = this.tokens.remove( 0 ).toLowerCase(); - - if( operation.equals( "exceptions" ) && ( this.tokens.get( 0 ).equals( "true" ) || this.tokens.get( 0 ).equals( "false" ) ) ) - { - if( this.tokens.size() == 1 ) - { - this.data.exceptions = this.tokens.get( 0 ).equals( "true" ); - } - else - { - throw new RecipeError( "exceptions must be true or false explicitly." ); - } - } - else if( operation.equals( "crash" ) && ( this.tokens.get( 0 ).equals( "true" ) || this.tokens.get( 0 ).equals( "false" ) ) ) - { - if( this.tokens.size() == 1 ) - { - this.data.crash = this.tokens.get( 0 ).equals( "true" ); - } - else - { - throw new RecipeError( "crash must be true or false explicitly." ); - } - } - else if( operation.equals( "erroronmissing" ) ) - { - if( this.tokens.size() == 1 && ( this.tokens.get( 0 ).equals( "true" ) || this.tokens.get( 0 ).equals( "false" ) ) ) - { - this.data.errorOnMissing = this.tokens.get( 0 ).equals( "true" ); - } - else - { - throw new RecipeError( "erroronmissing must be true or false explicitly." ); - } - } - else if( operation.equals( "import" ) ) - { - if( this.tokens.size() == 1 ) - { - ( new RecipeHandler( this ) ).parseRecipes( loader, this.tokens.get( 0 ) ); - } - else - { - throw new RecipeError( "Import must have exactly 1 input." ); - } - } - else - { - throw new RecipeError( operation + ": " + this.tokens.toString() + "; recipe without an output." ); - } - } - } - catch( final RecipeError e ) - { - AELog.warn( "Recipe Error '" + e.getMessage() + "' near line:" + line + " in " + file + " with: " + this.tokens.toString() ); - if( this.data.exceptions ) - { - AELog.debug( e ); - } - if( this.data.crash ) - { - throw e; - } - } - - this.tokens.clear(); - } - - private List> parseLines( final Iterable subList ) throws RecipeError - { - final List> out = new LinkedList>(); - List cList = new LinkedList(); - - boolean hasQty = false; - int qty = 1; - - for( final String v : subList ) - { - if( v.equals( "," ) ) - { - if( hasQty ) - { - throw new RecipeError( "Qty found with no item." ); - } - if( !cList.isEmpty() ) - { - out.add( cList ); - } - cList = new LinkedList(); - } - else - { - if( this.isNumber( v ) ) - { - if( hasQty ) - { - throw new RecipeError( "Qty found with no item." ); - } - hasQty = true; - qty = Integer.parseInt( v ); - } - else - { - if( hasQty ) - { - cList.add( this.findIngredient( v, qty ) ); - hasQty = false; - } - else - { - cList.add( this.findIngredient( v, 1 ) ); - } - } - } - } - - if( !cList.isEmpty() ) - { - out.add( cList ); - } - - return out; - } - - private IIngredient findIngredient( final String v, final int qty ) throws RecipeError - { - final GroupIngredient gi = this.data.groups.get( v ); - - if( gi != null ) - { - return gi.copy( qty ); - } - - try - { - return new Ingredient( this, v, qty ); - } - catch( final MissedIngredientSet grp ) - { - return new IngredientSet( grp.getResolverResultSet(), qty ); - } - } - - private boolean isNumber( final CharSequence v ) - { - if( v.length() <= 0 ) - { - return false; - } - - final int l = v.length(); - for( int x = 0; x < l; x++ ) - { - if( !Character.isDigit( v.charAt( x ) ) ) - { - return false; - } - } - - return true; - } +public class RecipeHandler implements IRecipeHandler { + private final RecipeData data; + private final List tokens = new LinkedList(); + + public RecipeHandler() { + this.data = new RecipeData(); + } + + /** + * Called recursively from parent + * + * @param parent owner of this handler + */ + private RecipeHandler(final RecipeHandler parent) { + Preconditions.checkNotNull(parent); + this.data = parent.data; + } + + private void addCrafting(final ICraftHandler ch) { + this.data.handlers.add(ch); + } + + public String getName(@Nonnull final IIngredient i) { + try { + for (final ItemStack is : i.getItemStackSet()) { + return this.getName(is); + } + } catch (final RecipeError ignored) { + } catch (final Throwable t) { + t.printStackTrace(); + // :P + } + + return i.getNameSpace() + ':' + i.getItemName(); + } + + private String getName(final ItemStack is) throws RecipeError { + Preconditions.checkNotNull(is); + + final UniqueIdentifier id = GameRegistry.findUniqueIdentifierFor(is.getItem()); + String realName = id.modId + ':' + id.name; + + if (!id.modId.equals(AppEng.MOD_ID) && !id.modId.equals("minecraft")) { + throw new RecipeError("Not applicable for website"); + } + + final IDefinitions definitions = AEApi.instance().definitions(); + final IItems items = definitions.items(); + final IBlocks blocks = definitions.blocks(); + + final Optional maybeCrystalSeedItem = items.crystalSeed().maybeItem(); + final Optional maybeSkyStoneItem = blocks.skyStone().maybeItem(); + final Optional maybeCStorageItem = blocks.craftingStorage1k().maybeItem(); + final Optional maybeCUnitItem = blocks.craftingUnit().maybeItem(); + final Optional maybeSkyChestItem = blocks.skyChest().maybeItem(); + + if (maybeCrystalSeedItem.isPresent() && is.getItem() == maybeCrystalSeedItem.get()) { + final int dmg = is.getItemDamage(); + if (dmg < ItemCrystalSeed.NETHER) { + realName += ".Certus"; + } else if (dmg < ItemCrystalSeed.FLUIX) { + realName += ".Nether"; + } else if (dmg < ItemCrystalSeed.FINAL_STAGE) { + realName += ".Fluix"; + } + } else if (maybeSkyStoneItem.isPresent() && is.getItem() == maybeSkyStoneItem.get()) { + switch (is.getItemDamage()) { + case 1: + realName += ".Block"; + break; + case 2: + realName += ".Brick"; + break; + case 3: + realName += ".SmallBrick"; + break; + default: + } + } else if (maybeCStorageItem.isPresent() && is.getItem() == maybeCStorageItem.get()) { + switch (is.getItemDamage()) { + case 1: + realName += "4k"; + break; + case 2: + realName += "16k"; + break; + case 3: + realName += "64k"; + break; + default: + } + } else if (maybeCUnitItem.isPresent() && is.getItem() == maybeCUnitItem.get()) { + switch (is.getItemDamage()) { + case 1: + realName = realName.replace("Unit", "Accelerator"); + break; + default: + } + } else if (maybeSkyChestItem.isPresent() && is.getItem() == maybeSkyChestItem.get()) { + switch (is.getItemDamage()) { + case 1: + realName += ".Block"; + break; + default: + } + } else if (is.getItem() instanceof ItemMultiMaterial) { + realName = realName.replace("ItemMultiMaterial", "ItemMaterial"); + realName += + '.' + ((ItemMultiMaterial) is.getItem()).getTypeByStack(is).name(); + } else if (is.getItem() instanceof ItemMultiPart) { + realName = realName.replace("ItemMultiPart", "ItemPart"); + realName += '.' + ((ItemMultiPart) is.getItem()).getTypeByStack(is).name(); + } else if (is.getItemDamage() > 0) { + realName += "." + is.getItemDamage(); + } + + return realName; + } + + String alias(final String in) { + Preconditions.checkNotNull(in); + + final String out = this.data.aliases.get(in); + + if (out != null) { + return out; + } + + return in; + } + + @Override + public void parseRecipes(final IRecipeLoader loader, final String path) { + Preconditions.checkNotNull(loader); + Preconditions.checkNotNull(path); + + try { + BufferedReader reader = null; + try { + reader = loader.getFile(path); + } catch (final Exception err) { + AELog.warn("Error Loading Recipe File:" + path); + if (this.data.exceptions) { + AELog.debug(err); + } + return; + } + + boolean inQuote = false; + boolean inComment = false; + + String token = ""; + int line = 0; + + int val = -1; + while ((val = reader.read()) != -1) { + final char c = (char) val; + + if (c == '\n') { + line++; + } + + if (inComment) { + if (c == '\n' || c == '\r') { + inComment = false; + } + } else if (inQuote) { + switch (c) { + case '"': + inQuote = !inQuote; + break; + default: + token += c; + } + } else { + switch (c) { + case '"': + inQuote = !inQuote; + break; + case ',': + if (token.length() > 0) { + this.tokens.add(token); + this.tokens.add(","); + } + token = ""; + break; + + case '=': + this.processTokens(loader, path, line); + + if (token.length() > 0) { + this.tokens.add(token); + } + token = ""; + + break; + + case '#': + inComment = true; + // then add a token if you can... + + case '\n': + case '\t': + case '\r': + case ' ': + if (token.length() > 0) { + this.tokens.add(token); + } + token = ""; + + break; + default: + token += c; + } + } + } + + if (token.length() > 0) { + this.tokens.add(token); + } + + reader.close(); + this.processTokens(loader, path, line); + } catch (final Throwable e) { + AELog.debug(e); + if (this.data.crash) { + throw new IllegalStateException(e); + } + } + } + + @Override + public void injectRecipes() { + if (cpw.mods.fml.common.Loader.instance().hasReachedState(LoaderState.POSTINITIALIZATION)) { + throw new IllegalStateException("Recipes must now be loaded in Init."); + } + + final Map processed = new HashMap(); + try { + for (final ICraftHandler ch : this.data.handlers) { + try { + ch.register(); + + final Class clz = ch.getClass(); + final Integer i = processed.get(clz); + if (i == null) { + processed.put(clz, 1); + } else { + processed.put(clz, i + 1); + } + } catch (final RegistrationError e) { + AELog.warn("Unable to register a recipe: " + e.getMessage()); + if (this.data.exceptions) { + AELog.debug(e); + } + if (this.data.crash) { + throw e; + } + } catch (final MissingIngredientError e) { + if (this.data.errorOnMissing) { + AELog.warn("Unable to register a recipe:" + e.getMessage()); + if (this.data.exceptions) { + AELog.debug(e); + } + if (this.data.crash) { + throw e; + } + } + } + } + } catch (final Throwable e) { + if (this.data.exceptions) { + AELog.debug(e); + } + if (this.data.crash) { + throw new IllegalStateException(e); + } + } + + for (final Entry e : processed.entrySet()) { + AELog.info("Recipes Loading: " + e.getKey().getSimpleName() + ": " + e.getValue() + " loaded."); + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.WebsiteRecipes)) { + try { + final ZipOutputStream out = new ZipOutputStream(new FileOutputStream("recipes.zip")); + + final HashMultimap combined = HashMultimap.create(); + + for (final String s : this.data.knownItem) { + try { + + final IIngredient i = new Ingredient(this, s, 1); + + for (final ItemStack is : i.getItemStackSet()) { + final String realName = this.getName(is); + final List recipes = this.findRecipe(is); + if (!recipes.isEmpty()) { + combined.putAll(realName, recipes); + } + } + } catch (final RecipeError ignored) { + + } catch (final MissedIngredientSet ignored) { + + } catch (final RegistrationError ignored) { + + } catch (final MissingIngredientError ignored) { + + } + } + + for (final String realName : combined.keySet()) { + int offset = 0; + + for (final IWebsiteSerializer ws : combined.get(realName)) { + final String rew = ws.getPattern(this); + if (rew != null && rew.length() > 0) { + out.putNextEntry(new ZipEntry(realName + '_' + offset + ".txt")); + offset++; + out.write(rew.getBytes()); + } + } + } + + out.close(); + } catch (final FileNotFoundException e1) { + AELog.debug(e1); + } catch (final IOException e1) { + AELog.debug(e1); + } + } + } + + private List findRecipe(final ItemStack output) { + final List out = new LinkedList(); + + for (final ICraftHandler ch : this.data.handlers) { + try { + if (ch instanceof IWebsiteSerializer && ((IWebsiteSerializer) ch).canCraft(output)) { + out.add((IWebsiteSerializer) ch); + } + } catch (final Throwable t) { + AELog.debug(t); + } + } + + return out; + } + + RecipeData getData() { + return this.data; + } + + private void processTokens(final IRecipeLoader loader, final String file, final int line) throws RecipeError { + try { + final IRecipeHandlerRegistry cr = AEApi.instance().registries().recipes(); + + if (this.tokens.isEmpty()) { + return; + } + + final int split = this.tokens.indexOf("->"); + if (split != -1) { + final String operation = this.tokens.remove(0).toLowerCase(Locale.ENGLISH); + + if (operation.equals("alias")) { + if (this.tokens.size() == 3 && this.tokens.indexOf("->") == 1) { + this.data.aliases.put(this.tokens.get(0), this.tokens.get(2)); + } else { + throw new RecipeError("Alias must have exactly 1 input and 1 output."); + } + } else if (operation.equals("group")) { + final List pre = this.tokens.subList(0, split - 1); + final List post = this.tokens.subList(split, this.tokens.size()); + + final List> inputs = this.parseLines(pre); + + if (inputs.size() == 1 && inputs.get(0).size() > 0 && post.size() == 1) { + this.data.groups.put(post.get(0), new GroupIngredient(post.get(0), inputs.get(0), 1)); + } else { + throw new RecipeError("Group must have exactly 1 output, and 1 or more inputs."); + } + } else if (operation.equals("ore")) { + final List pre = this.tokens.subList(0, split - 1); + final List post = this.tokens.subList(split, this.tokens.size()); + + final List> inputs = this.parseLines(pre); + + if (inputs.size() == 1 && inputs.get(0).size() > 0 && post.size() == 1) { + final ICraftHandler ch = new OreRegistration(inputs.get(0), post.get(0)); + this.addCrafting(ch); + } else { + throw new RecipeError( + "Group must have exactly 1 output, and 1 or more inputs in a single row."); + } + } else { + final List pre = this.tokens.subList(0, split - 1); + final List post = this.tokens.subList(split, this.tokens.size()); + + final List> inputs = this.parseLines(pre); + final List> outputs = this.parseLines(post); + + final ICraftHandler ch = cr.getCraftHandlerFor(operation); + + if (ch != null) { + ch.setup(inputs, outputs); + this.addCrafting(ch); + } else { + throw new RecipeError("Invalid crafting type: " + operation); + } + } + } else { + final String operation = this.tokens.remove(0).toLowerCase(); + + if (operation.equals("exceptions") + && (this.tokens.get(0).equals("true") + || this.tokens.get(0).equals("false"))) { + if (this.tokens.size() == 1) { + this.data.exceptions = this.tokens.get(0).equals("true"); + } else { + throw new RecipeError("exceptions must be true or false explicitly."); + } + } else if (operation.equals("crash") + && (this.tokens.get(0).equals("true") + || this.tokens.get(0).equals("false"))) { + if (this.tokens.size() == 1) { + this.data.crash = this.tokens.get(0).equals("true"); + } else { + throw new RecipeError("crash must be true or false explicitly."); + } + } else if (operation.equals("erroronmissing")) { + if (this.tokens.size() == 1 + && (this.tokens.get(0).equals("true") + || this.tokens.get(0).equals("false"))) { + this.data.errorOnMissing = this.tokens.get(0).equals("true"); + } else { + throw new RecipeError("erroronmissing must be true or false explicitly."); + } + } else if (operation.equals("import")) { + if (this.tokens.size() == 1) { + (new RecipeHandler(this)).parseRecipes(loader, this.tokens.get(0)); + } else { + throw new RecipeError("Import must have exactly 1 input."); + } + } else { + throw new RecipeError(operation + ": " + this.tokens.toString() + "; recipe without an output."); + } + } + } catch (final RecipeError e) { + AELog.warn("Recipe Error '" + e.getMessage() + "' near line:" + line + " in " + file + " with: " + + this.tokens.toString()); + if (this.data.exceptions) { + AELog.debug(e); + } + if (this.data.crash) { + throw e; + } + } + + this.tokens.clear(); + } + + private List> parseLines(final Iterable subList) throws RecipeError { + final List> out = new LinkedList>(); + List cList = new LinkedList(); + + boolean hasQty = false; + int qty = 1; + + for (final String v : subList) { + if (v.equals(",")) { + if (hasQty) { + throw new RecipeError("Qty found with no item."); + } + if (!cList.isEmpty()) { + out.add(cList); + } + cList = new LinkedList(); + } else { + if (this.isNumber(v)) { + if (hasQty) { + throw new RecipeError("Qty found with no item."); + } + hasQty = true; + qty = Integer.parseInt(v); + } else { + if (hasQty) { + cList.add(this.findIngredient(v, qty)); + hasQty = false; + } else { + cList.add(this.findIngredient(v, 1)); + } + } + } + } + + if (!cList.isEmpty()) { + out.add(cList); + } + + return out; + } + + private IIngredient findIngredient(final String v, final int qty) throws RecipeError { + final GroupIngredient gi = this.data.groups.get(v); + + if (gi != null) { + return gi.copy(qty); + } + + try { + return new Ingredient(this, v, qty); + } catch (final MissedIngredientSet grp) { + return new IngredientSet(grp.getResolverResultSet(), qty); + } + } + + private boolean isNumber(final CharSequence v) { + if (v.length() <= 0) { + return false; + } + + final int l = v.length(); + for (int x = 0; x < l; x++) { + if (!Character.isDigit(v.charAt(x))) { + return false; + } + } + + return true; + } } diff --git a/src/main/java/appeng/recipes/game/DisassembleRecipe.java b/src/main/java/appeng/recipes/game/DisassembleRecipe.java index 1f5456f191b..a6a2ccc3471 100644 --- a/src/main/java/appeng/recipes/game/DisassembleRecipe.java +++ b/src/main/java/appeng/recipes/game/DisassembleRecipe.java @@ -18,7 +18,6 @@ package appeng.recipes.game; - import appeng.api.AEApi; import appeng.api.definitions.*; import appeng.api.storage.IMEInventory; @@ -26,144 +25,129 @@ import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; import com.google.common.base.Optional; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.world.World; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.HashMap; -import java.util.Map; - - -public final class DisassembleRecipe implements IRecipe -{ - private static final ItemStack MISMATCHED_STACK = null; - - private final Map cellMappings; - private final Map nonCellMappings; - - public DisassembleRecipe() - { - final IDefinitions definitions = AEApi.instance().definitions(); - final IBlocks blocks = definitions.blocks(); - final IItems items = definitions.items(); - final IMaterials mats = definitions.materials(); - - this.cellMappings = new HashMap( 4 ); - this.nonCellMappings = new HashMap( 5 ); - - this.cellMappings.put( items.cell1k(), mats.cell1kPart() ); - this.cellMappings.put( items.cell4k(), mats.cell4kPart() ); - this.cellMappings.put( items.cell16k(), mats.cell16kPart() ); - this.cellMappings.put( items.cell64k(), mats.cell64kPart() ); - - this.nonCellMappings.put( items.encodedPattern(), mats.blankPattern() ); - this.nonCellMappings.put( blocks.craftingStorage1k(), mats.cell1kPart() ); - this.nonCellMappings.put( blocks.craftingStorage4k(), mats.cell4kPart() ); - this.nonCellMappings.put( blocks.craftingStorage16k(), mats.cell16kPart() ); - this.nonCellMappings.put( blocks.craftingStorage64k(), mats.cell64kPart() ); - } - - @Override - public boolean matches( final InventoryCrafting inv, final World w ) - { - return this.getOutput( inv ) != null; - } - - @Nullable - private ItemStack getOutput( final IInventory inventory ) - { - int itemCount = 0; - ItemStack output = MISMATCHED_STACK; - - for( int slotIndex = 0; slotIndex < inventory.getSizeInventory(); slotIndex++ ) - { - final ItemStack stackInSlot = inventory.getStackInSlot( slotIndex ); - if( stackInSlot != null ) - { - // needs a single input in the recipe - itemCount++; - if( itemCount > 1 ) - { - return MISMATCHED_STACK; - } - - // handle storage cells - for( final ItemStack storageCellStack : this.getCellOutput( stackInSlot ).asSet() ) - { - // make sure the storage cell stackInSlot empty... - final IMEInventory cellInv = AEApi.instance().registries().cell().getCellInventory( stackInSlot, null, StorageChannel.ITEMS ); - if( cellInv != null ) - { - final IItemList list = cellInv.getAvailableItems( StorageChannel.ITEMS.createList() ); - if( !list.isEmpty() ) - { - return null; - } - } - - output = storageCellStack; - } - - // handle crafting storage blocks - for( final ItemStack craftingStorageStack : this.getNonCellOutput( stackInSlot ).asSet() ) - { - output = craftingStorageStack; - } - } - } - - return output; - } - - @Nonnull - private Optional getCellOutput( final ItemStack compared ) - { - for( final Map.Entry entry : this.cellMappings.entrySet() ) - { - if( entry.getKey().isSameAs( compared ) ) - { - return entry.getValue().maybeStack( 1 ); - } - } - - return Optional.absent(); - } - - @Nonnull - private Optional getNonCellOutput( final ItemStack compared ) - { - for( final Map.Entry entry : this.nonCellMappings.entrySet() ) - { - if( entry.getKey().isSameAs( compared ) ) - { - return entry.getValue().maybeStack( 1 ); - } - } - - return Optional.absent(); - } - - @Nullable - @Override - public ItemStack getCraftingResult( final InventoryCrafting inv ) - { - return this.getOutput( inv ); - } - - @Override - public int getRecipeSize() - { - return 1; - } - - @Nullable - @Override - public ItemStack getRecipeOutput() // no default output.. - { - return null; - } -} \ No newline at end of file +public final class DisassembleRecipe implements IRecipe { + private static final ItemStack MISMATCHED_STACK = null; + + private final Map cellMappings; + private final Map nonCellMappings; + + public DisassembleRecipe() { + final IDefinitions definitions = AEApi.instance().definitions(); + final IBlocks blocks = definitions.blocks(); + final IItems items = definitions.items(); + final IMaterials mats = definitions.materials(); + + this.cellMappings = new HashMap(4); + this.nonCellMappings = new HashMap(5); + + this.cellMappings.put(items.cell1k(), mats.cell1kPart()); + this.cellMappings.put(items.cell4k(), mats.cell4kPart()); + this.cellMappings.put(items.cell16k(), mats.cell16kPart()); + this.cellMappings.put(items.cell64k(), mats.cell64kPart()); + + this.nonCellMappings.put(items.encodedPattern(), mats.blankPattern()); + this.nonCellMappings.put(blocks.craftingStorage1k(), mats.cell1kPart()); + this.nonCellMappings.put(blocks.craftingStorage4k(), mats.cell4kPart()); + this.nonCellMappings.put(blocks.craftingStorage16k(), mats.cell16kPart()); + this.nonCellMappings.put(blocks.craftingStorage64k(), mats.cell64kPart()); + } + + @Override + public boolean matches(final InventoryCrafting inv, final World w) { + return this.getOutput(inv) != null; + } + + @Nullable + private ItemStack getOutput(final IInventory inventory) { + int itemCount = 0; + ItemStack output = MISMATCHED_STACK; + + for (int slotIndex = 0; slotIndex < inventory.getSizeInventory(); slotIndex++) { + final ItemStack stackInSlot = inventory.getStackInSlot(slotIndex); + if (stackInSlot != null) { + // needs a single input in the recipe + itemCount++; + if (itemCount > 1) { + return MISMATCHED_STACK; + } + + // handle storage cells + for (final ItemStack storageCellStack : + this.getCellOutput(stackInSlot).asSet()) { + // make sure the storage cell stackInSlot empty... + final IMEInventory cellInv = AEApi.instance() + .registries() + .cell() + .getCellInventory(stackInSlot, null, StorageChannel.ITEMS); + if (cellInv != null) { + final IItemList list = + cellInv.getAvailableItems(StorageChannel.ITEMS.createList()); + if (!list.isEmpty()) { + return null; + } + } + + output = storageCellStack; + } + + // handle crafting storage blocks + for (final ItemStack craftingStorageStack : + this.getNonCellOutput(stackInSlot).asSet()) { + output = craftingStorageStack; + } + } + } + + return output; + } + + @Nonnull + private Optional getCellOutput(final ItemStack compared) { + for (final Map.Entry entry : this.cellMappings.entrySet()) { + if (entry.getKey().isSameAs(compared)) { + return entry.getValue().maybeStack(1); + } + } + + return Optional.absent(); + } + + @Nonnull + private Optional getNonCellOutput(final ItemStack compared) { + for (final Map.Entry entry : this.nonCellMappings.entrySet()) { + if (entry.getKey().isSameAs(compared)) { + return entry.getValue().maybeStack(1); + } + } + + return Optional.absent(); + } + + @Nullable + @Override + public ItemStack getCraftingResult(final InventoryCrafting inv) { + return this.getOutput(inv); + } + + @Override + public int getRecipeSize() { + return 1; + } + + @Nullable + @Override + public ItemStack getRecipeOutput() // no default output.. + { + return null; + } +} diff --git a/src/main/java/appeng/recipes/game/FacadeRecipe.java b/src/main/java/appeng/recipes/game/FacadeRecipe.java index 63698f76084..3d571ea55e0 100644 --- a/src/main/java/appeng/recipes/game/FacadeRecipe.java +++ b/src/main/java/appeng/recipes/game/FacadeRecipe.java @@ -18,12 +18,12 @@ package appeng.recipes.game; - import appeng.api.AEApi; import appeng.api.definitions.IComparableDefinition; import appeng.api.definitions.IDefinitions; import appeng.items.parts.ItemFacade; import com.google.common.base.Optional; +import javax.annotation.Nullable; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.Item; @@ -31,67 +31,60 @@ import net.minecraft.item.crafting.IRecipe; import net.minecraft.world.World; -import javax.annotation.Nullable; - - -public final class FacadeRecipe implements IRecipe -{ - private final IComparableDefinition anchor; - private final Optional maybeFacade; +public final class FacadeRecipe implements IRecipe { + private final IComparableDefinition anchor; + private final Optional maybeFacade; - public FacadeRecipe() - { - final IDefinitions definitions = AEApi.instance().definitions(); + public FacadeRecipe() { + final IDefinitions definitions = AEApi.instance().definitions(); - this.maybeFacade = definitions.items().facade().maybeItem(); - this.anchor = definitions.parts().cableAnchor(); - } + this.maybeFacade = definitions.items().facade().maybeItem(); + this.anchor = definitions.parts().cableAnchor(); + } - @Override - public boolean matches( final InventoryCrafting inv, final World w ) - { - return this.getOutput( inv, false ) != null; - } + @Override + public boolean matches(final InventoryCrafting inv, final World w) { + return this.getOutput(inv, false) != null; + } - @Nullable - private ItemStack getOutput( final IInventory inv, final boolean createFacade ) - { - if( inv.getStackInSlot( 0 ) == null && inv.getStackInSlot( 2 ) == null && inv.getStackInSlot( 6 ) == null && inv.getStackInSlot( 8 ) == null ) - { - if( this.anchor.isSameAs( inv.getStackInSlot( 1 ) ) && this.anchor.isSameAs( inv.getStackInSlot( 3 ) ) && this.anchor.isSameAs( inv.getStackInSlot( 5 ) ) && this.anchor.isSameAs( inv.getStackInSlot( 7 ) ) ) - { - for( final Item facadeItemDefinition : this.maybeFacade.asSet() ) - { - final ItemFacade facade = (ItemFacade) facadeItemDefinition; + @Nullable + private ItemStack getOutput(final IInventory inv, final boolean createFacade) { + if (inv.getStackInSlot(0) == null + && inv.getStackInSlot(2) == null + && inv.getStackInSlot(6) == null + && inv.getStackInSlot(8) == null) { + if (this.anchor.isSameAs(inv.getStackInSlot(1)) + && this.anchor.isSameAs(inv.getStackInSlot(3)) + && this.anchor.isSameAs(inv.getStackInSlot(5)) + && this.anchor.isSameAs(inv.getStackInSlot(7))) { + for (final Item facadeItemDefinition : this.maybeFacade.asSet()) { + final ItemFacade facade = (ItemFacade) facadeItemDefinition; - final ItemStack facades = facade.createFacadeForItem( inv.getStackInSlot( 4 ), !createFacade ); - if( facades != null && createFacade ) - { - facades.stackSize = 4; - } - return facades; - } - } - } + final ItemStack facades = facade.createFacadeForItem(inv.getStackInSlot(4), !createFacade); + if (facades != null && createFacade) { + facades.stackSize = 4; + } + return facades; + } + } + } - return null; - } + return null; + } - @Override - public ItemStack getCraftingResult( final InventoryCrafting inv ) - { - return this.getOutput( inv, true ); - } + @Override + public ItemStack getCraftingResult(final InventoryCrafting inv) { + return this.getOutput(inv, true); + } - @Override - public int getRecipeSize() - { - return 9; - } + @Override + public int getRecipeSize() { + return 9; + } - @Override - public ItemStack getRecipeOutput() // no default output.. - { - return null; - } -} \ No newline at end of file + @Override + public ItemStack getRecipeOutput() // no default output.. + { + return null; + } +} diff --git a/src/main/java/appeng/recipes/game/IRecipeBakeable.java b/src/main/java/appeng/recipes/game/IRecipeBakeable.java index f4d9617e42c..aabeb8a3beb 100644 --- a/src/main/java/appeng/recipes/game/IRecipeBakeable.java +++ b/src/main/java/appeng/recipes/game/IRecipeBakeable.java @@ -18,11 +18,8 @@ package appeng.recipes.game; - import appeng.api.exceptions.RegistrationError; - -public interface IRecipeBakeable -{ - void bake() throws RegistrationError; +public interface IRecipeBakeable { + void bake() throws RegistrationError; } diff --git a/src/main/java/appeng/recipes/game/ShapedRecipe.java b/src/main/java/appeng/recipes/game/ShapedRecipe.java index 83e0bd8e9ac..41db3873aef 100644 --- a/src/main/java/appeng/recipes/game/ShapedRecipe.java +++ b/src/main/java/appeng/recipes/game/ShapedRecipe.java @@ -18,309 +18,244 @@ package appeng.recipes.game; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; import appeng.api.recipes.IIngredient; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - - -public class ShapedRecipe implements IRecipe, IRecipeBakeable -{ - // Added in for future ease of change, but hard coded for now. - private static final int MAX_CRAFT_GRID_WIDTH = 3; - private static final int MAX_CRAFT_GRID_HEIGHT = 3; - - private ItemStack output = null; - private Object[] input = null; - private int width = 0; - private int height = 0; - private boolean mirrored = true; - private boolean disable = false; - - public ShapedRecipe( final ItemStack result, Object... recipe ) - { - this.output = result.copy(); - - final StringBuilder shape = new StringBuilder(); - int idx = 0; - - if( recipe[idx] instanceof Boolean ) - { - this.mirrored = (Boolean) recipe[idx]; - if( recipe[idx + 1] instanceof Object[] ) - { - recipe = (Object[]) recipe[idx + 1]; - } - else - { - idx = 1; - } - } - - if( recipe[idx] instanceof String[] ) - { - final String[] parts = ( (String[]) recipe[idx] ); - idx++; - - for( final String s : parts ) - { - this.width = s.length(); - shape.append( s ); - } - - this.height = parts.length; - } - else - { - while( recipe[idx] instanceof String ) - { - final String s = (String) recipe[idx]; - idx++; - shape.append( s ); - this.width = s.length(); - this.height++; - } - } - - if( this.width * this.height != shape.length() ) - { - final StringBuilder ret = new StringBuilder( "Invalid shaped ore recipe: " ); - for( final Object tmp : recipe ) - { - ret.append( tmp ).append( ", " ); - } - ret.append( this.output ); - throw new IllegalStateException( ret.toString() ); - } - - final Map itemMap = new HashMap(); - - for( ; idx < recipe.length; idx += 2 ) - { - final Character chr = (Character) recipe[idx]; - final Object in = recipe[idx + 1]; - - if( in instanceof IIngredient ) - { - itemMap.put( chr, (IIngredient) in ); - } - else - { - final StringBuilder ret = new StringBuilder( "Invalid shaped ore recipe: " ); - for( final Object tmp : recipe ) - { - ret.append( tmp ).append( ", " ); - } - ret.append( this.output ); - throw new IllegalStateException( ret.toString() ); - } - } - - this.input = new Object[this.width * this.height]; - int x = 0; - for( final char chr : shape.toString().toCharArray() ) - { - this.input[x] = itemMap.get( chr ); - x++; - } - } - - public boolean isEnabled() - { - return !this.disable; - } - - @Override - public boolean matches( final InventoryCrafting inv, final World world ) - { - if( this.disable ) - { - return false; - } - - for( int x = 0; x <= MAX_CRAFT_GRID_WIDTH - this.width; x++ ) - { - for( int y = 0; y <= MAX_CRAFT_GRID_HEIGHT - this.height; ++y ) - { - if( this.checkMatch( inv, x, y, false ) ) - { - return true; - } - - if( this.mirrored && this.checkMatch( inv, x, y, true ) ) - { - return true; - } - } - } - - return false; - } - - @Override - public ItemStack getCraftingResult( final InventoryCrafting var1 ) - { - return this.output.copy(); - } - - @Override - public int getRecipeSize() - { - return this.input.length; - } - - @Override - public ItemStack getRecipeOutput() - { - return this.output; - } - - @SuppressWarnings( "unchecked" ) - private boolean checkMatch( final InventoryCrafting inv, final int startX, final int startY, final boolean mirror ) - { - if( this.disable ) - { - return false; - } - - for( int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++ ) - { - for( int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++ ) - { - final int subX = x - startX; - final int subY = y - startY; - Object target = null; - - if( subX >= 0 && subY >= 0 && subX < this.width && subY < this.height ) - { - if( mirror ) - { - target = this.input[this.width - subX - 1 + subY * this.width]; - } - else - { - target = this.input[subX + subY * this.width]; - } - } - - final ItemStack slot = inv.getStackInRowAndColumn( x, y ); - - if( target instanceof IIngredient ) - { - boolean matched = false; - - try - { - for( final ItemStack item : ( (IIngredient) target ).getItemStackSet() ) - { - matched = matched || this.checkItemEquals( item, slot ); - } - } - catch( final RegistrationError e ) - { - // :P - } - catch( final MissingIngredientError e ) - { - // :P - } - - if( !matched ) - { - return false; - } - } - else if( target instanceof ArrayList ) - { - boolean matched = false; - - for( final ItemStack item : (Iterable) target ) - { - matched = matched || this.checkItemEquals( item, slot ); - } - - if( !matched ) - { - return false; - } - } - else if( target == null && slot != null ) - { - return false; - } - } - } - - return true; - } - - private boolean checkItemEquals( final ItemStack target, final ItemStack input ) - { - if( input == null && target != null || input != null && target == null ) - { - return false; - } - return ( target.getItem() == input.getItem() && ( target.getItemDamage() == OreDictionary.WILDCARD_VALUE || target.getItemDamage() == input.getItemDamage() ) ); - } - - public ShapedRecipe setMirrored( final boolean mirror ) - { - this.mirrored = mirror; - return this; - } - - /** - * Returns the input for this recipe, any mod accessing this value should never manipulate the values in this array - * as it will effect the recipe itself. - * - * @return The recipes input vales. - */ - public Object[] getInput() - { - return this.input; - } - - public int getWidth() - { - return this.width; - } - - public int getHeight() - { - return this.height; - } - - public Object[] getIngredients() - { - return this.input; - } - - @Override - public void bake() throws RegistrationError - { - try - { - this.disable = false; - for( final Object o : this.input ) - { - if( o instanceof IIngredient ) - { - ( (IIngredient) o ).bake(); - } - } - } - catch( final MissingIngredientError err ) - { - this.disable = true; - } - } -} \ No newline at end of file +public class ShapedRecipe implements IRecipe, IRecipeBakeable { + // Added in for future ease of change, but hard coded for now. + private static final int MAX_CRAFT_GRID_WIDTH = 3; + private static final int MAX_CRAFT_GRID_HEIGHT = 3; + + private ItemStack output = null; + private Object[] input = null; + private int width = 0; + private int height = 0; + private boolean mirrored = true; + private boolean disable = false; + + public ShapedRecipe(final ItemStack result, Object... recipe) { + this.output = result.copy(); + + final StringBuilder shape = new StringBuilder(); + int idx = 0; + + if (recipe[idx] instanceof Boolean) { + this.mirrored = (Boolean) recipe[idx]; + if (recipe[idx + 1] instanceof Object[]) { + recipe = (Object[]) recipe[idx + 1]; + } else { + idx = 1; + } + } + + if (recipe[idx] instanceof String[]) { + final String[] parts = ((String[]) recipe[idx]); + idx++; + + for (final String s : parts) { + this.width = s.length(); + shape.append(s); + } + + this.height = parts.length; + } else { + while (recipe[idx] instanceof String) { + final String s = (String) recipe[idx]; + idx++; + shape.append(s); + this.width = s.length(); + this.height++; + } + } + + if (this.width * this.height != shape.length()) { + final StringBuilder ret = new StringBuilder("Invalid shaped ore recipe: "); + for (final Object tmp : recipe) { + ret.append(tmp).append(", "); + } + ret.append(this.output); + throw new IllegalStateException(ret.toString()); + } + + final Map itemMap = new HashMap(); + + for (; idx < recipe.length; idx += 2) { + final Character chr = (Character) recipe[idx]; + final Object in = recipe[idx + 1]; + + if (in instanceof IIngredient) { + itemMap.put(chr, (IIngredient) in); + } else { + final StringBuilder ret = new StringBuilder("Invalid shaped ore recipe: "); + for (final Object tmp : recipe) { + ret.append(tmp).append(", "); + } + ret.append(this.output); + throw new IllegalStateException(ret.toString()); + } + } + + this.input = new Object[this.width * this.height]; + int x = 0; + for (final char chr : shape.toString().toCharArray()) { + this.input[x] = itemMap.get(chr); + x++; + } + } + + public boolean isEnabled() { + return !this.disable; + } + + @Override + public boolean matches(final InventoryCrafting inv, final World world) { + if (this.disable) { + return false; + } + + for (int x = 0; x <= MAX_CRAFT_GRID_WIDTH - this.width; x++) { + for (int y = 0; y <= MAX_CRAFT_GRID_HEIGHT - this.height; ++y) { + if (this.checkMatch(inv, x, y, false)) { + return true; + } + + if (this.mirrored && this.checkMatch(inv, x, y, true)) { + return true; + } + } + } + + return false; + } + + @Override + public ItemStack getCraftingResult(final InventoryCrafting var1) { + return this.output.copy(); + } + + @Override + public int getRecipeSize() { + return this.input.length; + } + + @Override + public ItemStack getRecipeOutput() { + return this.output; + } + + @SuppressWarnings("unchecked") + private boolean checkMatch(final InventoryCrafting inv, final int startX, final int startY, final boolean mirror) { + if (this.disable) { + return false; + } + + for (int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++) { + for (int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++) { + final int subX = x - startX; + final int subY = y - startY; + Object target = null; + + if (subX >= 0 && subY >= 0 && subX < this.width && subY < this.height) { + if (mirror) { + target = this.input[this.width - subX - 1 + subY * this.width]; + } else { + target = this.input[subX + subY * this.width]; + } + } + + final ItemStack slot = inv.getStackInRowAndColumn(x, y); + + if (target instanceof IIngredient) { + boolean matched = false; + + try { + for (final ItemStack item : ((IIngredient) target).getItemStackSet()) { + matched = matched || this.checkItemEquals(item, slot); + } + } catch (final RegistrationError e) { + // :P + } catch (final MissingIngredientError e) { + // :P + } + + if (!matched) { + return false; + } + } else if (target instanceof ArrayList) { + boolean matched = false; + + for (final ItemStack item : (Iterable) target) { + matched = matched || this.checkItemEquals(item, slot); + } + + if (!matched) { + return false; + } + } else if (target == null && slot != null) { + return false; + } + } + } + + return true; + } + + private boolean checkItemEquals(final ItemStack target, final ItemStack input) { + if (input == null && target != null || input != null && target == null) { + return false; + } + return (target.getItem() == input.getItem() + && (target.getItemDamage() == OreDictionary.WILDCARD_VALUE + || target.getItemDamage() == input.getItemDamage())); + } + + public ShapedRecipe setMirrored(final boolean mirror) { + this.mirrored = mirror; + return this; + } + + /** + * Returns the input for this recipe, any mod accessing this value should never manipulate the values in this array + * as it will effect the recipe itself. + * + * @return The recipes input vales. + */ + public Object[] getInput() { + return this.input; + } + + public int getWidth() { + return this.width; + } + + public int getHeight() { + return this.height; + } + + public Object[] getIngredients() { + return this.input; + } + + @Override + public void bake() throws RegistrationError { + try { + this.disable = false; + for (final Object o : this.input) { + if (o instanceof IIngredient) { + ((IIngredient) o).bake(); + } + } + } catch (final MissingIngredientError err) { + this.disable = true; + } + } +} diff --git a/src/main/java/appeng/recipes/game/ShapelessRecipe.java b/src/main/java/appeng/recipes/game/ShapelessRecipe.java index 43b0165d063..0a1c7bc85e3 100644 --- a/src/main/java/appeng/recipes/game/ShapelessRecipe.java +++ b/src/main/java/appeng/recipes/game/ShapelessRecipe.java @@ -18,164 +18,130 @@ package appeng.recipes.game; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; import appeng.api.recipes.IIngredient; +import java.util.ArrayList; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; -import java.util.ArrayList; - - -public class ShapelessRecipe implements IRecipe, IRecipeBakeable -{ - - private final ArrayList input = new ArrayList(); - private ItemStack output = null; - private boolean disable = false; - - public ShapelessRecipe( final ItemStack result, final Object... recipe ) - { - this.output = result.copy(); - for( final Object in : recipe ) - { - if( in instanceof IIngredient ) - { - this.input.add( in ); - } - else - { - final StringBuilder ret = new StringBuilder( "Invalid shapeless ore recipe: " ); - for( final Object tmp : recipe ) - { - ret.append( tmp ).append( ", " ); - } - ret.append( this.output ); - throw new IllegalArgumentException( ret.toString() ); - } - } - } - - public boolean isEnabled() - { - return !this.disable; - } - - @SuppressWarnings( "unchecked" ) - @Override - public boolean matches( final InventoryCrafting var1, final World world ) - { - if( this.disable ) - { - return false; - } - - final ArrayList required = new ArrayList( this.input ); - - for( int x = 0; x < var1.getSizeInventory(); x++ ) - { - final ItemStack slot = var1.getStackInSlot( x ); - - if( slot != null ) - { - boolean inRecipe = false; - - for( final Object next : required ) - { - boolean match = false; - - if( next instanceof IIngredient ) - { - try - { - for( final ItemStack item : ( (IIngredient) next ).getItemStackSet() ) - { - match = match || this.checkItemEquals( item, slot ); - } - } - catch( final RegistrationError e ) - { - // :P - } - catch( final MissingIngredientError e ) - { - // :P - } - } - - if( match ) - { - inRecipe = true; - required.remove( next ); - break; - } - } - - if( !inRecipe ) - { - return false; - } - } - } - - return required.isEmpty(); - } - - @Override - public ItemStack getCraftingResult( final InventoryCrafting var1 ) - { - return this.output.copy(); - } - - @Override - public int getRecipeSize() - { - return this.input.size(); - } - - @Override - public ItemStack getRecipeOutput() - { - return this.output; - } - - private boolean checkItemEquals( final ItemStack target, final ItemStack input ) - { - return ( target.getItem() == input.getItem() && ( target.getItemDamage() == OreDictionary.WILDCARD_VALUE || target.getItemDamage() == input.getItemDamage() ) ); - } - - /** - * Returns the input for this recipe, any mod accessing this value should never manipulate the values in this array - * as it will effect the recipe itself. - * - * @return The recipes input vales. - */ - public ArrayList getInput() - { - return this.input; - } - - @Override - public void bake() throws RegistrationError - { - try - { - this.disable = false; - for( final Object o : this.input ) - { - if( o instanceof IIngredient ) - { - ( (IIngredient) o ).bake(); - } - } - } - catch( final MissingIngredientError e ) - { - this.disable = true; - } - } -} \ No newline at end of file +public class ShapelessRecipe implements IRecipe, IRecipeBakeable { + + private final ArrayList input = new ArrayList(); + private ItemStack output = null; + private boolean disable = false; + + public ShapelessRecipe(final ItemStack result, final Object... recipe) { + this.output = result.copy(); + for (final Object in : recipe) { + if (in instanceof IIngredient) { + this.input.add(in); + } else { + final StringBuilder ret = new StringBuilder("Invalid shapeless ore recipe: "); + for (final Object tmp : recipe) { + ret.append(tmp).append(", "); + } + ret.append(this.output); + throw new IllegalArgumentException(ret.toString()); + } + } + } + + public boolean isEnabled() { + return !this.disable; + } + + @SuppressWarnings("unchecked") + @Override + public boolean matches(final InventoryCrafting var1, final World world) { + if (this.disable) { + return false; + } + + final ArrayList required = new ArrayList(this.input); + + for (int x = 0; x < var1.getSizeInventory(); x++) { + final ItemStack slot = var1.getStackInSlot(x); + + if (slot != null) { + boolean inRecipe = false; + + for (final Object next : required) { + boolean match = false; + + if (next instanceof IIngredient) { + try { + for (final ItemStack item : ((IIngredient) next).getItemStackSet()) { + match = match || this.checkItemEquals(item, slot); + } + } catch (final RegistrationError e) { + // :P + } catch (final MissingIngredientError e) { + // :P + } + } + + if (match) { + inRecipe = true; + required.remove(next); + break; + } + } + + if (!inRecipe) { + return false; + } + } + } + + return required.isEmpty(); + } + + @Override + public ItemStack getCraftingResult(final InventoryCrafting var1) { + return this.output.copy(); + } + + @Override + public int getRecipeSize() { + return this.input.size(); + } + + @Override + public ItemStack getRecipeOutput() { + return this.output; + } + + private boolean checkItemEquals(final ItemStack target, final ItemStack input) { + return (target.getItem() == input.getItem() + && (target.getItemDamage() == OreDictionary.WILDCARD_VALUE + || target.getItemDamage() == input.getItemDamage())); + } + + /** + * Returns the input for this recipe, any mod accessing this value should never manipulate the values in this array + * as it will effect the recipe itself. + * + * @return The recipes input vales. + */ + public ArrayList getInput() { + return this.input; + } + + @Override + public void bake() throws RegistrationError { + try { + this.disable = false; + for (final Object o : this.input) { + if (o instanceof IIngredient) { + ((IIngredient) o).bake(); + } + } + } catch (final MissingIngredientError e) { + this.disable = true; + } + } +} diff --git a/src/main/java/appeng/recipes/handlers/Crusher.java b/src/main/java/appeng/recipes/handlers/Crusher.java index 24f532e28b7..2e58eaed04c 100644 --- a/src/main/java/appeng/recipes/handlers/Crusher.java +++ b/src/main/java/appeng/recipes/handlers/Crusher.java @@ -18,7 +18,6 @@ package appeng.recipes.handlers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; @@ -30,62 +29,48 @@ import appeng.integration.abstraction.IRC; import appeng.recipes.RecipeHandler; import appeng.util.Platform; -import net.minecraft.item.ItemStack; - import java.util.List; +import net.minecraft.item.ItemStack; +public class Crusher implements ICraftHandler, IWebsiteSerializer { -public class Crusher implements ICraftHandler, IWebsiteSerializer -{ - - private IIngredient pro_input; - private IIngredient[] pro_output; + private IIngredient pro_input; + private IIngredient[] pro_output; - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - if( input.get( 0 ).size() == 1 && outs == 1 ) - { - this.pro_input = input.get( 0 ).get( 0 ); - this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); - return; - } - } - throw new RecipeError( "Crusher must have a single input, and single output." ); - } + @Override + public void setup(final List> input, final List> output) throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + if (input.get(0).size() == 1 && outs == 1) { + this.pro_input = input.get(0).get(0); + this.pro_output = output.get(0).toArray(new IIngredient[outs]); + return; + } + } + throw new RecipeError("Crusher must have a single input, and single output."); + } - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.RC ) ) - { - final IRC rc = (IRC) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.RC ); - for( final ItemStack is : this.pro_input.getItemStackSet() ) - { - try - { - rc.rockCrusher( is, this.pro_output[0].getItemStack() ); - } - catch( final java.lang.RuntimeException err ) - { - AELog.info( "RC not happy - " + err.getMessage() ); - } - } - } - } + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.RC)) { + final IRC rc = (IRC) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.RC); + for (final ItemStack is : this.pro_input.getItemStackSet()) { + try { + rc.rockCrusher(is, this.pro_output[0].getItemStack()); + } catch (final java.lang.RuntimeException err) { + AELog.info("RC not happy - " + err.getMessage()); + } + } + } + } - @Override - public String getPattern( final RecipeHandler h ) - { - return null; - } + @Override + public String getPattern(final RecipeHandler h) { + return null; + } - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } + @Override + public boolean canCraft(final ItemStack output) throws RegistrationError, MissingIngredientError { + return Platform.isSameItemPrecise(this.pro_output[0].getItemStack(), output); + } } diff --git a/src/main/java/appeng/recipes/handlers/Grind.java b/src/main/java/appeng/recipes/handlers/Grind.java index 358402830f7..8d3126e8727 100644 --- a/src/main/java/appeng/recipes/handlers/Grind.java +++ b/src/main/java/appeng/recipes/handlers/Grind.java @@ -18,7 +18,6 @@ package appeng.recipes.handlers; - import appeng.api.AEApi; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; @@ -29,56 +28,43 @@ import appeng.core.features.AEFeature; import appeng.recipes.RecipeHandler; import appeng.util.Platform; -import net.minecraft.item.ItemStack; - import java.util.List; +import net.minecraft.item.ItemStack; +public class Grind implements ICraftHandler, IWebsiteSerializer { -public class Grind implements ICraftHandler, IWebsiteSerializer -{ - - private IIngredient pro_input; - private IIngredient[] pro_output; + private IIngredient pro_input; + private IIngredient[] pro_output; - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - if( input.get( 0 ).size() == 1 && outs == 1 ) - { - this.pro_input = input.get( 0 ).get( 0 ); - this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); - return; - } - } - throw new RecipeError( "Grind must have a single input, and single output." ); - } + @Override + public void setup(final List> input, final List> output) throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + if (input.get(0).size() == 1 && outs == 1) { + this.pro_input = input.get(0).get(0); + this.pro_output = output.get(0).toArray(new IIngredient[outs]); + return; + } + } + throw new RecipeError("Grind must have a single input, and single output."); + } - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if ( AEConfig.instance.isFeatureEnabled( AEFeature.GrindStone ) ) - { - for (final ItemStack is : this.pro_input.getItemStackSet()) - { - AEApi.instance().registries().grinder().addRecipe(is, this.pro_output[0].getItemStack(), 8); - } - } - } + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (AEConfig.instance.isFeatureEnabled(AEFeature.GrindStone)) { + for (final ItemStack is : this.pro_input.getItemStackSet()) { + AEApi.instance().registries().grinder().addRecipe(is, this.pro_output[0].getItemStack(), 8); + } + } + } - @Override - public String getPattern( final RecipeHandler h ) - { - return "grind\n" + - h.getName( this.pro_input ) + '\n' + - h.getName( this.pro_output[0] ); - } + @Override + public String getPattern(final RecipeHandler h) { + return "grind\n" + h.getName(this.pro_input) + '\n' + h.getName(this.pro_output[0]); + } - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } + @Override + public boolean canCraft(final ItemStack output) throws RegistrationError, MissingIngredientError { + return Platform.isSameItemPrecise(this.pro_output[0].getItemStack(), output); + } } diff --git a/src/main/java/appeng/recipes/handlers/GrindFZ.java b/src/main/java/appeng/recipes/handlers/GrindFZ.java index 571474a1239..a5d7c251605 100644 --- a/src/main/java/appeng/recipes/handlers/GrindFZ.java +++ b/src/main/java/appeng/recipes/handlers/GrindFZ.java @@ -18,7 +18,6 @@ package appeng.recipes.handlers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; @@ -30,62 +29,48 @@ import appeng.integration.abstraction.IFZ; import appeng.recipes.RecipeHandler; import appeng.util.Platform; -import net.minecraft.item.ItemStack; - import java.util.List; +import net.minecraft.item.ItemStack; +public class GrindFZ implements ICraftHandler, IWebsiteSerializer { -public class GrindFZ implements ICraftHandler, IWebsiteSerializer -{ - - private IIngredient pro_input; - private IIngredient[] pro_output; + private IIngredient pro_input; + private IIngredient[] pro_output; - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - if( input.get( 0 ).size() == 1 && outs == 1 ) - { - this.pro_input = input.get( 0 ).get( 0 ); - this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); - return; - } - } - throw new RecipeError( "Grind must have a single input, and single output." ); - } + @Override + public void setup(final List> input, final List> output) throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + if (input.get(0).size() == 1 && outs == 1) { + this.pro_input = input.get(0).get(0); + this.pro_output = output.get(0).toArray(new IIngredient[outs]); + return; + } + } + throw new RecipeError("Grind must have a single input, and single output."); + } - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.FZ ) ) - { - final IFZ fz = (IFZ) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.FZ ); - for( final ItemStack is : this.pro_input.getItemStackSet() ) - { - try - { - fz.grinderRecipe( is, this.pro_output[0].getItemStack() ); - } - catch( final java.lang.RuntimeException err ) - { - AELog.info( "FZ not happy - " + err.getMessage() ); - } - } - } - } + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.FZ)) { + final IFZ fz = (IFZ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.FZ); + for (final ItemStack is : this.pro_input.getItemStackSet()) { + try { + fz.grinderRecipe(is, this.pro_output[0].getItemStack()); + } catch (final java.lang.RuntimeException err) { + AELog.info("FZ not happy - " + err.getMessage()); + } + } + } + } - @Override - public String getPattern( final RecipeHandler h ) - { - return null; - } + @Override + public String getPattern(final RecipeHandler h) { + return null; + } - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } + @Override + public boolean canCraft(final ItemStack output) throws RegistrationError, MissingIngredientError { + return Platform.isSameItemPrecise(this.pro_output[0].getItemStack(), output); + } } diff --git a/src/main/java/appeng/recipes/handlers/HCCrusher.java b/src/main/java/appeng/recipes/handlers/HCCrusher.java index c4bc9766eba..349dd2e6447 100644 --- a/src/main/java/appeng/recipes/handlers/HCCrusher.java +++ b/src/main/java/appeng/recipes/handlers/HCCrusher.java @@ -18,7 +18,6 @@ package appeng.recipes.handlers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; @@ -28,73 +27,60 @@ import appeng.recipes.RecipeHandler; import appeng.util.Platform; import cpw.mods.fml.common.event.FMLInterModComms; +import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.util.List; - - -public class HCCrusher implements ICraftHandler, IWebsiteSerializer -{ - - private IIngredient pro_input; - private IIngredient[] pro_output; - - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - if( input.get( 0 ).size() == 1 && outs == 1 ) - { - this.pro_input = input.get( 0 ).get( 0 ); - this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); - return; - } - } - throw new RecipeError( "Crusher must have a single input, and single output." ); - } - - @Override - public void register() throws RegistrationError, MissingIngredientError - { - for( final ItemStack beginStack : this.pro_input.getItemStackSet() ) - { - try - { - final NBTTagCompound toRegister = new NBTTagCompound(); - - final ItemStack endStack = this.pro_output[0].getItemStack(); - - final NBTTagCompound itemFrom = new NBTTagCompound(); - final NBTTagCompound itemTo = new NBTTagCompound(); - - beginStack.writeToNBT( itemFrom ); - endStack.writeToNBT( itemTo ); - - toRegister.setTag( "itemFrom", itemFrom ); - toRegister.setTag( "itemTo", itemTo ); - toRegister.setFloat( "pressureRatio", 1.0F ); - - FMLInterModComms.sendMessage( "HydCraft", "registerCrushingRecipe", toRegister ); - } - catch( final java.lang.RuntimeException err ) - { - AELog.info( "Hydraulicraft not happy - " + err.getMessage() ); - } - } - } - - @Override - public String getPattern( final RecipeHandler h ) - { - return null; - } - - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } +public class HCCrusher implements ICraftHandler, IWebsiteSerializer { + + private IIngredient pro_input; + private IIngredient[] pro_output; + + @Override + public void setup(final List> input, final List> output) throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + if (input.get(0).size() == 1 && outs == 1) { + this.pro_input = input.get(0).get(0); + this.pro_output = output.get(0).toArray(new IIngredient[outs]); + return; + } + } + throw new RecipeError("Crusher must have a single input, and single output."); + } + + @Override + public void register() throws RegistrationError, MissingIngredientError { + for (final ItemStack beginStack : this.pro_input.getItemStackSet()) { + try { + final NBTTagCompound toRegister = new NBTTagCompound(); + + final ItemStack endStack = this.pro_output[0].getItemStack(); + + final NBTTagCompound itemFrom = new NBTTagCompound(); + final NBTTagCompound itemTo = new NBTTagCompound(); + + beginStack.writeToNBT(itemFrom); + endStack.writeToNBT(itemTo); + + toRegister.setTag("itemFrom", itemFrom); + toRegister.setTag("itemTo", itemTo); + toRegister.setFloat("pressureRatio", 1.0F); + + FMLInterModComms.sendMessage("HydCraft", "registerCrushingRecipe", toRegister); + } catch (final java.lang.RuntimeException err) { + AELog.info("Hydraulicraft not happy - " + err.getMessage()); + } + } + } + + @Override + public String getPattern(final RecipeHandler h) { + return null; + } + + @Override + public boolean canCraft(final ItemStack output) throws RegistrationError, MissingIngredientError { + return Platform.isSameItemPrecise(this.pro_output[0].getItemStack(), output); + } } diff --git a/src/main/java/appeng/recipes/handlers/IWebsiteSerializer.java b/src/main/java/appeng/recipes/handlers/IWebsiteSerializer.java index 8006f28796a..dab7ac37c73 100644 --- a/src/main/java/appeng/recipes/handlers/IWebsiteSerializer.java +++ b/src/main/java/appeng/recipes/handlers/IWebsiteSerializer.java @@ -18,17 +18,14 @@ package appeng.recipes.handlers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; import appeng.recipes.RecipeHandler; import net.minecraft.item.ItemStack; +public interface IWebsiteSerializer { -public interface IWebsiteSerializer -{ - - String getPattern( RecipeHandler han ); + String getPattern(RecipeHandler han); - boolean canCraft( ItemStack output ) throws RegistrationError, MissingIngredientError; + boolean canCraft(ItemStack output) throws RegistrationError, MissingIngredientError; } diff --git a/src/main/java/appeng/recipes/handlers/Inscribe.java b/src/main/java/appeng/recipes/handlers/Inscribe.java index 479548a644d..f32f466e8a7 100644 --- a/src/main/java/appeng/recipes/handlers/Inscribe.java +++ b/src/main/java/appeng/recipes/handlers/Inscribe.java @@ -18,19 +18,16 @@ package appeng.recipes.handlers; - import appeng.api.AEApi; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; import appeng.api.features.IInscriberRecipe; import appeng.api.features.InscriberProcessType; import appeng.core.features.registries.entries.InscriberRecipe; -import net.minecraft.item.ItemStack; - import java.util.ArrayList; import java.util.Collections; import java.util.List; - +import net.minecraft.item.ItemStack; /** * recipe translation for inscribe process @@ -40,30 +37,28 @@ * @version rv2 * @since rv0 */ -public final class Inscribe extends InscriberProcess -{ - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( this.getImprintable() == null ) - { - return; - } - if( this.getOutput() == null ) - { - return; - } +public final class Inscribe extends InscriberProcess { + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (this.getImprintable() == null) { + return; + } + if (this.getOutput() == null) { + return; + } - final ItemStack[] realInput = this.getImprintable().getItemStackSet(); - final List inputs = new ArrayList( realInput.length ); - Collections.addAll( inputs, realInput ); - final ItemStack top = ( this.getTopOptional() == null ) ? null : this.getTopOptional().getItemStack(); - final ItemStack bot = ( this.getBotOptional() == null ) ? null : this.getBotOptional().getItemStack(); - final ItemStack output = this.getOutput().getItemStack(); - final InscriberProcessType type = InscriberProcessType.Inscribe; + final ItemStack[] realInput = this.getImprintable().getItemStackSet(); + final List inputs = new ArrayList(realInput.length); + Collections.addAll(inputs, realInput); + final ItemStack top = + (this.getTopOptional() == null) ? null : this.getTopOptional().getItemStack(); + final ItemStack bot = + (this.getBotOptional() == null) ? null : this.getBotOptional().getItemStack(); + final ItemStack output = this.getOutput().getItemStack(); + final InscriberProcessType type = InscriberProcessType.Inscribe; - final IInscriberRecipe recipe = new InscriberRecipe( inputs, output, top, bot, type ); + final IInscriberRecipe recipe = new InscriberRecipe(inputs, output, top, bot, type); - AEApi.instance().registries().inscriber().addRecipe( recipe ); - } + AEApi.instance().registries().inscriber().addRecipe(recipe); + } } diff --git a/src/main/java/appeng/recipes/handlers/InscriberProcess.java b/src/main/java/appeng/recipes/handlers/InscriberProcess.java index 5c42bc8f251..cb1e1459d59 100644 --- a/src/main/java/appeng/recipes/handlers/InscriberProcess.java +++ b/src/main/java/appeng/recipes/handlers/InscriberProcess.java @@ -1,6 +1,5 @@ package appeng.recipes.handlers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; @@ -8,11 +7,9 @@ import appeng.api.recipes.IIngredient; import appeng.recipes.RecipeHandler; import appeng.util.Platform; -import net.minecraft.item.ItemStack; - -import javax.annotation.Nullable; import java.util.List; - +import javax.annotation.Nullable; +import net.minecraft.item.ItemStack; /** * basic inscriber process for recipes @@ -22,105 +19,86 @@ * @version rv2 * @since rv0 */ -public abstract class InscriberProcess implements ICraftHandler, IWebsiteSerializer -{ - @Nullable - private IIngredient imprintable; - - @Nullable - private IIngredient topOptional; - - @Nullable - private IIngredient botOptional; - - @Nullable - private IIngredient output; - - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( output.size() == 1 && output.get( 0 ).size() == 1 ) - { - if( input.size() == 1 && input.get( 0 ).size() > 1 ) - { - this.imprintable = input.get( 0 ).get( 0 ); - - this.topOptional = input.get( 0 ).get( 1 ); - - if( input.get( 0 ).size() > 2 ) - { - this.botOptional = input.get( 0 ).get( 2 ); - } - - this.output = output.get( 0 ).get( 0 ); - } - else - { - throw new RecipeError( "Inscriber recipes cannot have rows, and must have more then one input." ); - } - } - else - { - throw new RecipeError( "Inscriber recipes must produce a single output." ); - } - } - - @Override - public boolean canCraft( final ItemStack reqOutput ) throws RegistrationError, MissingIngredientError - { - return this.output != null && Platform.isSameItemPrecise( this.output.getItemStack(), reqOutput ); - } - - @Override - public String getPattern( final RecipeHandler handler ) - { - String pattern = "inscriber "; - - if( this.output != null ) - { - pattern += this.output.getQty() + '\n'; - pattern += handler.getName( this.output ) + '\n'; - } - - if( this.topOptional != null ) - { - pattern += handler.getName( this.topOptional ) + '\n'; - } - - if( this.imprintable != null ) - { - pattern += handler.getName( this.imprintable ); - } - - if( this.botOptional != null ) - { - pattern += '\n' + handler.getName( this.botOptional ); - } - - return pattern; - } - - @Nullable - protected IIngredient getImprintable() - { - return this.imprintable; - } - - @Nullable - protected IIngredient getTopOptional() - { - return this.topOptional; - } - - @Nullable - protected IIngredient getBotOptional() - { - return this.botOptional; - } - - @Nullable - protected IIngredient getOutput() - { - return this.output; - } +public abstract class InscriberProcess implements ICraftHandler, IWebsiteSerializer { + @Nullable + private IIngredient imprintable; + + @Nullable + private IIngredient topOptional; + + @Nullable + private IIngredient botOptional; + + @Nullable + private IIngredient output; + + @Override + public void setup(final List> input, final List> output) throws RecipeError { + if (output.size() == 1 && output.get(0).size() == 1) { + if (input.size() == 1 && input.get(0).size() > 1) { + this.imprintable = input.get(0).get(0); + + this.topOptional = input.get(0).get(1); + + if (input.get(0).size() > 2) { + this.botOptional = input.get(0).get(2); + } + + this.output = output.get(0).get(0); + } else { + throw new RecipeError("Inscriber recipes cannot have rows, and must have more then one input."); + } + } else { + throw new RecipeError("Inscriber recipes must produce a single output."); + } + } + + @Override + public boolean canCraft(final ItemStack reqOutput) throws RegistrationError, MissingIngredientError { + return this.output != null && Platform.isSameItemPrecise(this.output.getItemStack(), reqOutput); + } + + @Override + public String getPattern(final RecipeHandler handler) { + String pattern = "inscriber "; + + if (this.output != null) { + pattern += this.output.getQty() + '\n'; + pattern += handler.getName(this.output) + '\n'; + } + + if (this.topOptional != null) { + pattern += handler.getName(this.topOptional) + '\n'; + } + + if (this.imprintable != null) { + pattern += handler.getName(this.imprintable); + } + + if (this.botOptional != null) { + pattern += '\n' + handler.getName(this.botOptional); + } + + return pattern; + } + + @Nullable + protected IIngredient getImprintable() { + return this.imprintable; + } + + @Nullable + protected IIngredient getTopOptional() { + return this.topOptional; + } + + @Nullable + protected IIngredient getBotOptional() { + return this.botOptional; + } + + @Nullable + protected IIngredient getOutput() { + return this.output; + } } diff --git a/src/main/java/appeng/recipes/handlers/Macerator.java b/src/main/java/appeng/recipes/handlers/Macerator.java index 32cc61fccda..0172b6b3988 100644 --- a/src/main/java/appeng/recipes/handlers/Macerator.java +++ b/src/main/java/appeng/recipes/handlers/Macerator.java @@ -18,7 +18,6 @@ package appeng.recipes.handlers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; @@ -30,62 +29,48 @@ import appeng.integration.abstraction.IIC2; import appeng.recipes.RecipeHandler; import appeng.util.Platform; -import net.minecraft.item.ItemStack; - import java.util.List; +import net.minecraft.item.ItemStack; +public class Macerator implements ICraftHandler, IWebsiteSerializer { -public class Macerator implements ICraftHandler, IWebsiteSerializer -{ - - private IIngredient pro_input; - private IIngredient[] pro_output; + private IIngredient pro_input; + private IIngredient[] pro_output; - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - if( input.get( 0 ).size() == 1 && outs == 1 ) - { - this.pro_input = input.get( 0 ).get( 0 ); - this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); - return; - } - } - throw new RecipeError( "Grind must have a single input, and single output." ); - } + @Override + public void setup(final List> input, final List> output) throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + if (input.get(0).size() == 1 && outs == 1) { + this.pro_input = input.get(0).get(0); + this.pro_output = output.get(0).toArray(new IIngredient[outs]); + return; + } + } + throw new RecipeError("Grind must have a single input, and single output."); + } - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.IC2 ) ) - { - final IIC2 ic2 = (IIC2) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.IC2 ); - for( final ItemStack is : this.pro_input.getItemStackSet() ) - { - try - { - ic2.maceratorRecipe( is, this.pro_output[0].getItemStack() ); - } - catch( final java.lang.RuntimeException err ) - { - AELog.info( "IC2 not happy - " + err.getMessage() ); - } - } - } - } + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.IC2)) { + final IIC2 ic2 = (IIC2) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.IC2); + for (final ItemStack is : this.pro_input.getItemStackSet()) { + try { + ic2.maceratorRecipe(is, this.pro_output[0].getItemStack()); + } catch (final java.lang.RuntimeException err) { + AELog.info("IC2 not happy - " + err.getMessage()); + } + } + } + } - @Override - public String getPattern( final RecipeHandler h ) - { - return null; - } + @Override + public String getPattern(final RecipeHandler h) { + return null; + } - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } + @Override + public boolean canCraft(final ItemStack output) throws RegistrationError, MissingIngredientError { + return Platform.isSameItemPrecise(this.pro_output[0].getItemStack(), output); + } } diff --git a/src/main/java/appeng/recipes/handlers/MekCrusher.java b/src/main/java/appeng/recipes/handlers/MekCrusher.java index 4245defb097..618cdf64d6f 100644 --- a/src/main/java/appeng/recipes/handlers/MekCrusher.java +++ b/src/main/java/appeng/recipes/handlers/MekCrusher.java @@ -18,7 +18,6 @@ package appeng.recipes.handlers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; @@ -30,63 +29,49 @@ import appeng.integration.abstraction.IMekanism; import appeng.recipes.RecipeHandler; import appeng.util.Platform; -import net.minecraft.item.ItemStack; - import java.util.List; +import net.minecraft.item.ItemStack; +public class MekCrusher implements ICraftHandler, IWebsiteSerializer { -public class MekCrusher implements ICraftHandler, IWebsiteSerializer -{ - - private IIngredient pro_input; - private IIngredient[] pro_output; + private IIngredient pro_input; + private IIngredient[] pro_output; - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - if( input.get( 0 ).size() == 1 && outs == 1 ) - { - this.pro_input = input.get( 0 ).get( 0 ); - this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); - return; - } - } + @Override + public void setup(final List> input, final List> output) throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + if (input.get(0).size() == 1 && outs == 1) { + this.pro_input = input.get(0).get(0); + this.pro_output = output.get(0).toArray(new IIngredient[outs]); + return; + } + } - throw new RecipeError( "MekCrusher must have a single input, and single output." ); - } + throw new RecipeError("MekCrusher must have a single input, and single output."); + } - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.Mekanism ) ) - { - final IMekanism rc = (IMekanism) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.Mekanism ); - for( final ItemStack is : this.pro_input.getItemStackSet() ) - { - try - { - rc.addCrusherRecipe( is, this.pro_output[0].getItemStack() ); - } - catch( final java.lang.RuntimeException err ) - { - AELog.info( "Mekanism not happy - " + err.getMessage() ); - } - } - } - } + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.Mekanism)) { + final IMekanism rc = (IMekanism) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.Mekanism); + for (final ItemStack is : this.pro_input.getItemStackSet()) { + try { + rc.addCrusherRecipe(is, this.pro_output[0].getItemStack()); + } catch (final java.lang.RuntimeException err) { + AELog.info("Mekanism not happy - " + err.getMessage()); + } + } + } + } - @Override - public String getPattern( final RecipeHandler h ) - { - return null; - } + @Override + public String getPattern(final RecipeHandler h) { + return null; + } - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } + @Override + public boolean canCraft(final ItemStack output) throws RegistrationError, MissingIngredientError { + return Platform.isSameItemPrecise(this.pro_output[0].getItemStack(), output); + } } diff --git a/src/main/java/appeng/recipes/handlers/MekEnrichment.java b/src/main/java/appeng/recipes/handlers/MekEnrichment.java index a11c78cc729..3b2ce2c408c 100644 --- a/src/main/java/appeng/recipes/handlers/MekEnrichment.java +++ b/src/main/java/appeng/recipes/handlers/MekEnrichment.java @@ -18,7 +18,6 @@ package appeng.recipes.handlers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; @@ -30,62 +29,48 @@ import appeng.integration.abstraction.IMekanism; import appeng.recipes.RecipeHandler; import appeng.util.Platform; -import net.minecraft.item.ItemStack; - import java.util.List; +import net.minecraft.item.ItemStack; +public class MekEnrichment implements ICraftHandler, IWebsiteSerializer { -public class MekEnrichment implements ICraftHandler, IWebsiteSerializer -{ - - private IIngredient pro_input; - private IIngredient[] pro_output; + private IIngredient pro_input; + private IIngredient[] pro_output; - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - if( input.get( 0 ).size() == 1 && outs == 1 ) - { - this.pro_input = input.get( 0 ).get( 0 ); - this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); - return; - } - } - throw new RecipeError( "MekCrusher must have a single input, and single output." ); - } + @Override + public void setup(final List> input, final List> output) throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + if (input.get(0).size() == 1 && outs == 1) { + this.pro_input = input.get(0).get(0); + this.pro_output = output.get(0).toArray(new IIngredient[outs]); + return; + } + } + throw new RecipeError("MekCrusher must have a single input, and single output."); + } - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.Mekanism ) ) - { - final IMekanism rc = (IMekanism) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.Mekanism ); - for( final ItemStack is : this.pro_input.getItemStackSet() ) - { - try - { - rc.addEnrichmentChamberRecipe( is, this.pro_output[0].getItemStack() ); - } - catch( final java.lang.RuntimeException err ) - { - AELog.info( "Mekanism not happy - " + err.getMessage() ); - } - } - } - } + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.Mekanism)) { + final IMekanism rc = (IMekanism) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.Mekanism); + for (final ItemStack is : this.pro_input.getItemStackSet()) { + try { + rc.addEnrichmentChamberRecipe(is, this.pro_output[0].getItemStack()); + } catch (final java.lang.RuntimeException err) { + AELog.info("Mekanism not happy - " + err.getMessage()); + } + } + } + } - @Override - public String getPattern( final RecipeHandler h ) - { - return null; - } + @Override + public String getPattern(final RecipeHandler h) { + return null; + } - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } + @Override + public boolean canCraft(final ItemStack output) throws RegistrationError, MissingIngredientError { + return Platform.isSameItemPrecise(this.pro_output[0].getItemStack(), output); + } } diff --git a/src/main/java/appeng/recipes/handlers/OreRegistration.java b/src/main/java/appeng/recipes/handlers/OreRegistration.java index 4ff5f0d1a2d..3d10c2f7831 100644 --- a/src/main/java/appeng/recipes/handlers/OreRegistration.java +++ b/src/main/java/appeng/recipes/handlers/OreRegistration.java @@ -18,45 +18,34 @@ package appeng.recipes.handlers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; import appeng.api.recipes.ICraftHandler; import appeng.api.recipes.IIngredient; +import java.util.List; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; -import java.util.List; - - -public class OreRegistration implements ICraftHandler -{ - - private final List inputs; - private final String name; +public class OreRegistration implements ICraftHandler { - public OreRegistration( final List in, final String out ) - { - this.inputs = in; - this.name = out; - } + private final List inputs; + private final String name; - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { + public OreRegistration(final List in, final String out) { + this.inputs = in; + this.name = out; + } - } + @Override + public void setup(final List> input, final List> output) throws RecipeError {} - @Override - public void register() throws RegistrationError, MissingIngredientError - { - for( final IIngredient i : this.inputs ) - { - for( final ItemStack is : i.getItemStackSet() ) - { - OreDictionary.registerOre( this.name, is ); - } - } - } + @Override + public void register() throws RegistrationError, MissingIngredientError { + for (final IIngredient i : this.inputs) { + for (final ItemStack is : i.getItemStackSet()) { + OreDictionary.registerOre(this.name, is); + } + } + } } diff --git a/src/main/java/appeng/recipes/handlers/Press.java b/src/main/java/appeng/recipes/handlers/Press.java index 5ce4059fed6..b15c127ea3d 100644 --- a/src/main/java/appeng/recipes/handlers/Press.java +++ b/src/main/java/appeng/recipes/handlers/Press.java @@ -18,19 +18,16 @@ package appeng.recipes.handlers; - import appeng.api.AEApi; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; import appeng.api.features.IInscriberRecipe; import appeng.api.features.InscriberProcessType; import appeng.core.features.registries.entries.InscriberRecipe; -import net.minecraft.item.ItemStack; - import java.util.ArrayList; import java.util.Collections; import java.util.List; - +import net.minecraft.item.ItemStack; /** * recipe translation for pressing in the inscriber @@ -40,30 +37,28 @@ * @version rv2 * @since rv0 */ -public final class Press extends InscriberProcess -{ - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( this.getImprintable() == null ) - { - return; - } - if( this.getOutput() == null ) - { - return; - } +public final class Press extends InscriberProcess { + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (this.getImprintable() == null) { + return; + } + if (this.getOutput() == null) { + return; + } - final ItemStack[] realInput = this.getImprintable().getItemStackSet(); - final List inputs = new ArrayList( realInput.length ); - Collections.addAll( inputs, realInput ); - final ItemStack top = ( this.getTopOptional() == null ) ? null : this.getTopOptional().getItemStack(); - final ItemStack bot = ( this.getBotOptional() == null ) ? null : this.getBotOptional().getItemStack(); - final ItemStack output = this.getOutput().getItemStack(); - final InscriberProcessType type = InscriberProcessType.Press; + final ItemStack[] realInput = this.getImprintable().getItemStackSet(); + final List inputs = new ArrayList(realInput.length); + Collections.addAll(inputs, realInput); + final ItemStack top = + (this.getTopOptional() == null) ? null : this.getTopOptional().getItemStack(); + final ItemStack bot = + (this.getBotOptional() == null) ? null : this.getBotOptional().getItemStack(); + final ItemStack output = this.getOutput().getItemStack(); + final InscriberProcessType type = InscriberProcessType.Press; - final IInscriberRecipe recipe = new InscriberRecipe( inputs, output, top, bot, type ); + final IInscriberRecipe recipe = new InscriberRecipe(inputs, output, top, bot, type); - AEApi.instance().registries().inscriber().addRecipe( recipe ); - } + AEApi.instance().registries().inscriber().addRecipe(recipe); + } } diff --git a/src/main/java/appeng/recipes/handlers/Pulverizer.java b/src/main/java/appeng/recipes/handlers/Pulverizer.java index 7a024b19d88..b1221261e1a 100644 --- a/src/main/java/appeng/recipes/handlers/Pulverizer.java +++ b/src/main/java/appeng/recipes/handlers/Pulverizer.java @@ -18,7 +18,6 @@ package appeng.recipes.handlers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; @@ -27,60 +26,50 @@ import appeng.recipes.RecipeHandler; import appeng.util.Platform; import cpw.mods.fml.common.event.FMLInterModComms; +import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.util.List; - - -public class Pulverizer implements ICraftHandler, IWebsiteSerializer -{ +public class Pulverizer implements ICraftHandler, IWebsiteSerializer { - private IIngredient pro_input; - private IIngredient[] pro_output; + private IIngredient pro_input; + private IIngredient[] pro_output; - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - if( input.get( 0 ).size() == 1 && outs == 1 ) - { - this.pro_input = input.get( 0 ).get( 0 ); - this.pro_output = output.get( 0 ).toArray( new IIngredient[outs] ); - return; - } - } - throw new RecipeError( "Grind must have a single input, and single output." ); - } + @Override + public void setup(final List> input, final List> output) throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + if (input.get(0).size() == 1 && outs == 1) { + this.pro_input = input.get(0).get(0); + this.pro_output = output.get(0).toArray(new IIngredient[outs]); + return; + } + } + throw new RecipeError("Grind must have a single input, and single output."); + } - @Override - public void register() throws RegistrationError, MissingIngredientError - { - final NBTTagCompound toSend = new NBTTagCompound(); - toSend.setInteger( "energy", 800 ); - toSend.setTag( "primaryOutput", new NBTTagCompound() ); + @Override + public void register() throws RegistrationError, MissingIngredientError { + final NBTTagCompound toSend = new NBTTagCompound(); + toSend.setInteger("energy", 800); + toSend.setTag("primaryOutput", new NBTTagCompound()); - this.pro_output[0].getItemStack().writeToNBT( toSend.getCompoundTag( "primaryOutput" ) ); + this.pro_output[0].getItemStack().writeToNBT(toSend.getCompoundTag("primaryOutput")); - for( final ItemStack is : this.pro_input.getItemStackSet() ) - { - toSend.setTag( "input", new NBTTagCompound() ); - is.writeToNBT( toSend.getCompoundTag( "input" ) ); - FMLInterModComms.sendMessage( "ThermalExpansion", "PulverizerRecipe", toSend ); - } - } + for (final ItemStack is : this.pro_input.getItemStackSet()) { + toSend.setTag("input", new NBTTagCompound()); + is.writeToNBT(toSend.getCompoundTag("input")); + FMLInterModComms.sendMessage("ThermalExpansion", "PulverizerRecipe", toSend); + } + } - @Override - public String getPattern( final RecipeHandler h ) - { - return null; - } + @Override + public String getPattern(final RecipeHandler h) { + return null; + } - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } + @Override + public boolean canCraft(final ItemStack output) throws RegistrationError, MissingIngredientError { + return Platform.isSameItemPrecise(this.pro_output[0].getItemStack(), output); + } } diff --git a/src/main/java/appeng/recipes/handlers/Shaped.java b/src/main/java/appeng/recipes/handlers/Shaped.java index fef54c1dbbd..82840a10bf6 100644 --- a/src/main/java/appeng/recipes/handlers/Shaped.java +++ b/src/main/java/appeng/recipes/handlers/Shaped.java @@ -18,7 +18,6 @@ package appeng.recipes.handlers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; @@ -29,147 +28,112 @@ import appeng.recipes.game.ShapedRecipe; import appeng.util.Platform; import cpw.mods.fml.common.registry.GameRegistry; -import net.minecraft.item.ItemStack; - import java.util.ArrayList; import java.util.List; +import net.minecraft.item.ItemStack; - -public class Shaped implements ICraftHandler, IWebsiteSerializer -{ - - private List> inputs; - private IIngredient output; - private int rows; - private int cols; - - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( output.size() == 1 && output.get( 0 ).size() == 1 ) - { - this.rows = input.size(); - if( this.rows > 0 && input.size() <= 3 ) - { - this.cols = input.get( 0 ).size(); - if( this.cols <= 3 && this.cols >= 1 ) - { - for( final List anInput : input ) - { - if( anInput.size() != this.cols ) - { - throw new RecipeError( "all rows in a shaped crafting recipe must contain the same number of ingredients." ); - } - } - - this.inputs = input; - this.output = output.get( 0 ).get( 0 ); - } - else - { - throw new RecipeError( "Crafting recipes must have 1-3 columns." ); - } - } - else - { - throw new RecipeError( "shaped crafting recipes must have 1-3 rows." ); - } - } - else - { - throw new RecipeError( "Crafting must produce a single output." ); - } - } - - @Override - public void register() throws RegistrationError, MissingIngredientError - { - char first = 'A'; - final List args = new ArrayList(); - - for( int y = 0; y < this.rows; y++ ) - { - final StringBuilder row = new StringBuilder(); - for( int x = 0; x < this.cols; x++ ) - { - if( this.inputs.get( y ).get( x ).isAir() ) - { - row.append( ' ' ); - } - else - { - row.append( first ); - args.add( first ); - args.add( this.inputs.get( y ).get( x ) ); - - first++; - } - } - args.add( y, row.toString() ); - } - - final ItemStack outIS = this.output.getItemStack(); - - try - { - GameRegistry.addRecipe( new ShapedRecipe( outIS, args.toArray( new Object[args.size()] ) ) ); - } - catch( final Throwable e ) - { - AELog.debug( e ); - throw new RegistrationError( "Error while adding shaped recipe." ); - } - } - - @Override - public String getPattern( final RecipeHandler h ) - { - String o = "shaped " + this.output.getQty() + ' ' + this.cols + 'x' + this.rows + '\n'; - - o += h.getName( this.output ) + '\n'; - - for( int y = 0; y < this.rows; y++ ) - { - for( int x = 0; x < this.cols; x++ ) - { - final IIngredient i = this.inputs.get( y ).get( x ); - - if( i.isAir() ) - { - o += "air" + ( x + 1 == this.cols ? "\n" : " " ); - } - else - { - o += h.getName( i ) + ( x + 1 == this.cols ? "\n" : " " ); - } - } - } - - return o.trim(); - } - - @Override - public boolean canCraft( final ItemStack reqOutput ) throws RegistrationError, MissingIngredientError - { - for( int y = 0; y < this.rows; y++ ) - { - for( int x = 0; x < this.cols; x++ ) - { - final IIngredient i = this.inputs.get( y ).get( x ); - - if( !i.isAir() ) - { - for( final ItemStack r : i.getItemStackSet() ) - { - if( Platform.isSameItemPrecise( r, reqOutput ) ) - { - return false; - } - } - } - } - } - - return Platform.isSameItemPrecise( this.output.getItemStack(), reqOutput ); - } +public class Shaped implements ICraftHandler, IWebsiteSerializer { + + private List> inputs; + private IIngredient output; + private int rows; + private int cols; + + @Override + public void setup(final List> input, final List> output) throws RecipeError { + if (output.size() == 1 && output.get(0).size() == 1) { + this.rows = input.size(); + if (this.rows > 0 && input.size() <= 3) { + this.cols = input.get(0).size(); + if (this.cols <= 3 && this.cols >= 1) { + for (final List anInput : input) { + if (anInput.size() != this.cols) { + throw new RecipeError( + "all rows in a shaped crafting recipe must contain the same number of ingredients."); + } + } + + this.inputs = input; + this.output = output.get(0).get(0); + } else { + throw new RecipeError("Crafting recipes must have 1-3 columns."); + } + } else { + throw new RecipeError("shaped crafting recipes must have 1-3 rows."); + } + } else { + throw new RecipeError("Crafting must produce a single output."); + } + } + + @Override + public void register() throws RegistrationError, MissingIngredientError { + char first = 'A'; + final List args = new ArrayList(); + + for (int y = 0; y < this.rows; y++) { + final StringBuilder row = new StringBuilder(); + for (int x = 0; x < this.cols; x++) { + if (this.inputs.get(y).get(x).isAir()) { + row.append(' '); + } else { + row.append(first); + args.add(first); + args.add(this.inputs.get(y).get(x)); + + first++; + } + } + args.add(y, row.toString()); + } + + final ItemStack outIS = this.output.getItemStack(); + + try { + GameRegistry.addRecipe(new ShapedRecipe(outIS, args.toArray(new Object[args.size()]))); + } catch (final Throwable e) { + AELog.debug(e); + throw new RegistrationError("Error while adding shaped recipe."); + } + } + + @Override + public String getPattern(final RecipeHandler h) { + String o = "shaped " + this.output.getQty() + ' ' + this.cols + 'x' + this.rows + '\n'; + + o += h.getName(this.output) + '\n'; + + for (int y = 0; y < this.rows; y++) { + for (int x = 0; x < this.cols; x++) { + final IIngredient i = this.inputs.get(y).get(x); + + if (i.isAir()) { + o += "air" + (x + 1 == this.cols ? "\n" : " "); + } else { + o += h.getName(i) + (x + 1 == this.cols ? "\n" : " "); + } + } + } + + return o.trim(); + } + + @Override + public boolean canCraft(final ItemStack reqOutput) throws RegistrationError, MissingIngredientError { + for (int y = 0; y < this.rows; y++) { + for (int x = 0; x < this.cols; x++) { + final IIngredient i = this.inputs.get(y).get(x); + + if (!i.isAir()) { + for (final ItemStack r : i.getItemStackSet()) { + if (Platform.isSameItemPrecise(r, reqOutput)) { + return false; + } + } + } + } + } + + return Platform.isSameItemPrecise(this.output.getItemStack(), reqOutput); + } } diff --git a/src/main/java/appeng/recipes/handlers/Shapeless.java b/src/main/java/appeng/recipes/handlers/Shapeless.java index 97ca0495873..1930bf0053c 100644 --- a/src/main/java/appeng/recipes/handlers/Shapeless.java +++ b/src/main/java/appeng/recipes/handlers/Shapeless.java @@ -18,7 +18,6 @@ package appeng.recipes.handlers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; @@ -29,112 +28,84 @@ import appeng.recipes.game.ShapelessRecipe; import appeng.util.Platform; import cpw.mods.fml.common.registry.GameRegistry; -import net.minecraft.item.ItemStack; - import java.util.ArrayList; import java.util.List; +import net.minecraft.item.ItemStack; - -public class Shapeless implements ICraftHandler, IWebsiteSerializer -{ - - private List inputs; - private IIngredient output; - - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( output.size() == 1 && output.get( 0 ).size() == 1 ) - { - if( input.size() == 1 ) - { - this.inputs = input.get( 0 ); - this.output = output.get( 0 ).get( 0 ); - } - else - { - throw new RecipeError( "Shapeless crafting recipes cannot have rows." ); - } - } - else - { - throw new RecipeError( "Crafting must produce a single output." ); - } - } - - @Override - public void register() throws RegistrationError, MissingIngredientError - { - final List args = new ArrayList(); - for( final IIngredient i : this.inputs ) - { - args.add( i ); - } - - final ItemStack outIS = this.output.getItemStack(); - - try - { - GameRegistry.addRecipe( new ShapelessRecipe( outIS, args.toArray( new Object[args.size()] ) ) ); - } - catch( final Throwable e ) - { - AELog.debug( e ); - throw new RegistrationError( "Error while adding shapeless recipe." ); - } - } - - @Override - public String getPattern( final RecipeHandler h ) - { - final StringBuilder o = new StringBuilder( "shapeless " + this.output.getQty() + '\n' ); - - o.append( h.getName( this.output ) ).append( '\n' ); - - for( int y = 0; y < this.inputs.size(); y++ ) - { - final IIngredient i = this.inputs.get( y ); - - if( i.isAir() ) - { - o.append( "air" ); - } - else - { - o.append( h.getName( i ) ); - } - - if( y + 1 == this.inputs.size() ) - { - o.append( '\n' ); - } - else - { - o.append( ' ' ); - } - } - - return o.toString().trim(); - } - - @Override - public boolean canCraft( final ItemStack reqOutput ) throws RegistrationError, MissingIngredientError - { - - for( final IIngredient i : this.inputs ) - { - if( !i.isAir() ) - { - for( final ItemStack r : i.getItemStackSet() ) - { - if( Platform.isSameItemPrecise( r, reqOutput ) ) - { - return false; - } - } - } - } - - return Platform.isSameItemPrecise( this.output.getItemStack(), reqOutput ); - } +public class Shapeless implements ICraftHandler, IWebsiteSerializer { + + private List inputs; + private IIngredient output; + + @Override + public void setup(final List> input, final List> output) throws RecipeError { + if (output.size() == 1 && output.get(0).size() == 1) { + if (input.size() == 1) { + this.inputs = input.get(0); + this.output = output.get(0).get(0); + } else { + throw new RecipeError("Shapeless crafting recipes cannot have rows."); + } + } else { + throw new RecipeError("Crafting must produce a single output."); + } + } + + @Override + public void register() throws RegistrationError, MissingIngredientError { + final List args = new ArrayList(); + for (final IIngredient i : this.inputs) { + args.add(i); + } + + final ItemStack outIS = this.output.getItemStack(); + + try { + GameRegistry.addRecipe(new ShapelessRecipe(outIS, args.toArray(new Object[args.size()]))); + } catch (final Throwable e) { + AELog.debug(e); + throw new RegistrationError("Error while adding shapeless recipe."); + } + } + + @Override + public String getPattern(final RecipeHandler h) { + final StringBuilder o = new StringBuilder("shapeless " + this.output.getQty() + '\n'); + + o.append(h.getName(this.output)).append('\n'); + + for (int y = 0; y < this.inputs.size(); y++) { + final IIngredient i = this.inputs.get(y); + + if (i.isAir()) { + o.append("air"); + } else { + o.append(h.getName(i)); + } + + if (y + 1 == this.inputs.size()) { + o.append('\n'); + } else { + o.append(' '); + } + } + + return o.toString().trim(); + } + + @Override + public boolean canCraft(final ItemStack reqOutput) throws RegistrationError, MissingIngredientError { + + for (final IIngredient i : this.inputs) { + if (!i.isAir()) { + for (final ItemStack r : i.getItemStackSet()) { + if (Platform.isSameItemPrecise(r, reqOutput)) { + return false; + } + } + } + } + + return Platform.isSameItemPrecise(this.output.getItemStack(), reqOutput); + } } diff --git a/src/main/java/appeng/recipes/handlers/Smelt.java b/src/main/java/appeng/recipes/handlers/Smelt.java index cd72445e170..ed22bf54b01 100644 --- a/src/main/java/appeng/recipes/handlers/Smelt.java +++ b/src/main/java/appeng/recipes/handlers/Smelt.java @@ -18,7 +18,6 @@ package appeng.recipes.handlers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; @@ -27,61 +26,48 @@ import appeng.recipes.RecipeHandler; import appeng.util.Platform; import cpw.mods.fml.common.registry.GameRegistry; -import net.minecraft.item.ItemStack; - import java.util.List; +import net.minecraft.item.ItemStack; +public class Smelt implements ICraftHandler, IWebsiteSerializer { -public class Smelt implements ICraftHandler, IWebsiteSerializer -{ - - private IIngredient in; - private IIngredient out; + private IIngredient in; + private IIngredient out; - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final List inputList = input.get( 0 ); - final List outputList = output.get( 0 ); - if( inputList.size() == 1 && outputList.size() == 1 ) - { - this.in = inputList.get( 0 ); - this.out = outputList.get( 0 ); - return; - } - } - throw new RecipeError( "Smelting recipe can only have a single input and output." ); - } + @Override + public void setup(final List> input, final List> output) throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final List inputList = input.get(0); + final List outputList = output.get(0); + if (inputList.size() == 1 && outputList.size() == 1) { + this.in = inputList.get(0); + this.out = outputList.get(0); + return; + } + } + throw new RecipeError("Smelting recipe can only have a single input and output."); + } - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( this.in.getItemStack().getItem() == null ) - { - throw new RegistrationError( this.in.toString() + ": Smelting Input is not a valid item." ); - } + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (this.in.getItemStack().getItem() == null) { + throw new RegistrationError(this.in.toString() + ": Smelting Input is not a valid item."); + } - if( this.out.getItemStack().getItem() == null ) - { - throw new RegistrationError( this.out.toString() + ": Smelting Output is not a valid item." ); - } + if (this.out.getItemStack().getItem() == null) { + throw new RegistrationError(this.out.toString() + ": Smelting Output is not a valid item."); + } - GameRegistry.addSmelting( this.in.getItemStack(), this.out.getItemStack(), 0 ); - } + GameRegistry.addSmelting(this.in.getItemStack(), this.out.getItemStack(), 0); + } - @Override - public String getPattern( final RecipeHandler h ) - { - return "smelt " + this.out.getQty() + '\n' + - h.getName( this.out ) + '\n' + - h.getName( this.in ); - } + @Override + public String getPattern(final RecipeHandler h) { + return "smelt " + this.out.getQty() + '\n' + h.getName(this.out) + '\n' + h.getName(this.in); + } - @Override - public boolean canCraft( final ItemStack reqOutput ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.out.getItemStack(), reqOutput ); - } + @Override + public boolean canCraft(final ItemStack reqOutput) throws RegistrationError, MissingIngredientError { + return Platform.isSameItemPrecise(this.out.getItemStack(), reqOutput); + } } diff --git a/src/main/java/appeng/recipes/loader/ConfigLoader.java b/src/main/java/appeng/recipes/loader/ConfigLoader.java index 58701e0867d..6748d5cae4e 100644 --- a/src/main/java/appeng/recipes/loader/ConfigLoader.java +++ b/src/main/java/appeng/recipes/loader/ConfigLoader.java @@ -18,42 +18,37 @@ package appeng.recipes.loader; - import appeng.api.recipes.IRecipeLoader; import com.google.common.base.Preconditions; - -import javax.annotation.Nonnull; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; - +import javax.annotation.Nonnull; /** * Loads the recipes from the config folder */ -public final class ConfigLoader implements IRecipeLoader -{ - private final File generatedRecipesDir; - private final File userRecipesDir; - - public ConfigLoader( final File generatedRecipesDir, final File userRecipesDir ) - { - this.generatedRecipesDir = generatedRecipesDir; - this.userRecipesDir = userRecipesDir; - } - - @Override - public BufferedReader getFile( @Nonnull final String relativeFilePath ) throws Exception - { - Preconditions.checkNotNull( relativeFilePath ); - Preconditions.checkArgument( !relativeFilePath.isEmpty(), "Supplying an empty String will result creating a reader of a folder." ); - - final File generatedFile = new File( this.generatedRecipesDir, relativeFilePath ); - final File userFile = new File( this.userRecipesDir, relativeFilePath ); - - final File toBeLoaded = ( userFile.exists() && userFile.isFile() ) ? userFile : generatedFile; - - return new BufferedReader( new InputStreamReader( new FileInputStream( toBeLoaded ), "UTF-8" ) ); - } +public final class ConfigLoader implements IRecipeLoader { + private final File generatedRecipesDir; + private final File userRecipesDir; + + public ConfigLoader(final File generatedRecipesDir, final File userRecipesDir) { + this.generatedRecipesDir = generatedRecipesDir; + this.userRecipesDir = userRecipesDir; + } + + @Override + public BufferedReader getFile(@Nonnull final String relativeFilePath) throws Exception { + Preconditions.checkNotNull(relativeFilePath); + Preconditions.checkArgument( + !relativeFilePath.isEmpty(), "Supplying an empty String will result creating a reader of a folder."); + + final File generatedFile = new File(this.generatedRecipesDir, relativeFilePath); + final File userFile = new File(this.userRecipesDir, relativeFilePath); + + final File toBeLoaded = (userFile.exists() && userFile.isFile()) ? userFile : generatedFile; + + return new BufferedReader(new InputStreamReader(new FileInputStream(toBeLoaded), "UTF-8")); + } } diff --git a/src/main/java/appeng/recipes/loader/JarLoader.java b/src/main/java/appeng/recipes/loader/JarLoader.java index cb6b657583e..8f2b2ded9e3 100644 --- a/src/main/java/appeng/recipes/loader/JarLoader.java +++ b/src/main/java/appeng/recipes/loader/JarLoader.java @@ -18,31 +18,26 @@ package appeng.recipes.loader; - import appeng.api.recipes.IRecipeLoader; import com.google.common.base.Preconditions; - -import javax.annotation.Nonnull; import java.io.BufferedReader; import java.io.InputStreamReader; +import javax.annotation.Nonnull; +public class JarLoader implements IRecipeLoader { -public class JarLoader implements IRecipeLoader -{ - - private final String rootPath; + private final String rootPath; - public JarLoader( final String s ) - { - this.rootPath = s; - } + public JarLoader(final String s) { + this.rootPath = s; + } - @Override - public BufferedReader getFile( @Nonnull final String s ) throws Exception - { - Preconditions.checkNotNull( s ); - Preconditions.checkArgument( !s.isEmpty() ); + @Override + public BufferedReader getFile(@Nonnull final String s) throws Exception { + Preconditions.checkNotNull(s); + Preconditions.checkArgument(!s.isEmpty()); - return new BufferedReader( new InputStreamReader( this.getClass().getResourceAsStream( this.rootPath + s ), "UTF-8" ) ); - } + return new BufferedReader( + new InputStreamReader(this.getClass().getResourceAsStream(this.rootPath + s), "UTF-8")); + } } diff --git a/src/main/java/appeng/recipes/loader/RecipeResourceCopier.java b/src/main/java/appeng/recipes/loader/RecipeResourceCopier.java index 39ac1574e81..a3cc473736c 100644 --- a/src/main/java/appeng/recipes/loader/RecipeResourceCopier.java +++ b/src/main/java/appeng/recipes/loader/RecipeResourceCopier.java @@ -18,11 +18,7 @@ package appeng.recipes.loader; - import com.google.common.base.Preconditions; -import org.apache.commons.io.FileUtils; - -import javax.annotation.Nonnull; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -37,7 +33,8 @@ import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; - +import javax.annotation.Nonnull; +import org.apache.commons.io.FileUtils; /** * copies recipes in jars onto file system includes the readme, needs to be modified if other files needs to be handled @@ -46,211 +43,194 @@ * @version rv3 - 11.05.2015 * @since rv3 11.05.2015 */ -public class RecipeResourceCopier -{ - /** - * Most expected size of recipes found - */ - private static final int INITIAL_RESOURCE_CAPACITY = 20; - private static final Pattern DOT_COMPILE_PATTERN = Pattern.compile( ".", Pattern.LITERAL ); - private static final String FILE_PROTOCOL = "file"; - private static final String CLASS_EXTENSION = ".class"; - private static final String JAR_PROTOCOL = "jar"; - private static final String UTF_8_ENCODING = "UTF-8"; - - /** - * copy source in the jar - */ - private final String root; - - /** - * @param root source root folder of the recipes inside the jar. - * @throws NullPointerException if root is null - */ - public RecipeResourceCopier( @Nonnull final String root ) - { - Preconditions.checkNotNull( root ); - - this.root = root; - } - - /** - * copies recipes found in the root to destination. - * - * @param identifier only copy files which end with the identifier - * @param destination destination folder to which the recipes are copied to - * @throws URISyntaxException {@see #getResourceListing} - * @throws IOException {@see #getResourceListing} and if copying the detected resource to file is not possible - * @throws NullPointerException if either parameter is null - * @throws IllegalArgumentException if destination is not a directory - */ - public void copyTo( @Nonnull final String identifier, @Nonnull final File destination ) throws URISyntaxException, IOException - { - Preconditions.checkNotNull( destination ); - Preconditions.checkArgument( destination.isDirectory() ); - - this.copyTo( identifier, destination, this.root ); - } - - /** - * @param destination destination folder to which the recipes are copied to - * @param directory the folder to copy. - * @throws URISyntaxException {@see #getResourceListing} - * @throws IOException {@see #getResourceListing} and if copying the detected resource to file is not possible - * @see {RecipeResourceCopier#copyTo(File)} - */ - private void copyTo( @Nonnull final String identifier, @Nonnull final File destination, @Nonnull final String directory ) - throws URISyntaxException, IOException - { - assert identifier != null; - assert destination != null; - assert directory != null; - - final Class copierClass = this.getClass(); - final String[] listing = this.getResourceListing( copierClass, directory ); - for( final String list : listing ) - { - if( list.endsWith( identifier ) ) - { - // generate folder before the file is copied so no empty folders will be generated - FileUtils.forceMkdir( destination ); - - this.copyFile( destination, directory, list ); - } - else if( !list.contains( "." ) ) - { - final File subDirectory = new File( destination, list ); - - this.copyTo( identifier, subDirectory, directory + list + "/" ); - } - } - } - - /** - * Copies a single file inside a folder to the destination. - * - * @param destination folder to which the file is copied to - * @param directory the directory containing the file - * @param fileName the file to copy - * @throws IOException if copying the file is not possible - */ - private void copyFile( @Nonnull final File destination, @Nonnull final String directory, @Nonnull final String fileName ) throws IOException - { - assert destination != null; - assert directory != null; - assert fileName != null; - - final Class copierClass = this.getClass(); - final InputStream inStream = copierClass.getResourceAsStream( '/' + directory + fileName ); - final File outFile = new File( destination, fileName ); - - if( !outFile.exists() && inStream != null ) - { - FileUtils.copyInputStreamToFile( inStream, outFile ); - inStream.close(); - } - } - - /** - * List directory contents for a resource folder. Not recursive. This is basically a brute-force implementation. Works for regular files and also JARs. - * - * @param clazz Any java class that lives in the same place as the resources you want. - * @param path Should end with "/", but not start with one. - * @return Just the name of each member item, not the full paths. - * @throws URISyntaxException if it is a file path and the URL can not be converted to URI - * @throws IOException if jar path can not be decoded - * @throws UnsupportedOperationException if it is neither in jar nor in file path - */ - @Nonnull - private String[] getResourceListing( @Nonnull final Class clazz, @Nonnull final String path ) throws URISyntaxException, IOException - { - assert clazz != null; - assert path != null; - - final ClassLoader classLoader = clazz.getClassLoader(); - if( classLoader == null ) - { - throw new IllegalStateException( "ClassLoader was not found. It was probably loaded at a inappropriate time" ); - } - - URL dirURL = classLoader.getResource( path ); - if( dirURL != null ) - { - final String protocol = dirURL.getProtocol(); - if( protocol.equals( FILE_PROTOCOL ) ) - { - // A file path: easy enough - - final URI uriOfURL = dirURL.toURI(); - final File fileOfURI = new File( uriOfURL ); - final String[] filesAndDirectoriesOfURI = fileOfURI.list(); - - if( filesAndDirectoriesOfURI == null ) - { - throw new IllegalStateException( "Files and Directories were illegal. Either an abstract pathname does not denote a directory, or an I/O error occured." ); - } - else - { - return filesAndDirectoriesOfURI; - } - } - } - - if( dirURL == null ) - { - /* - * In case of a jar file, we can't actually find a directory. - * Have to assume the same jar as clazz. - */ - final String className = clazz.getName(); - final Matcher matcher = DOT_COMPILE_PATTERN.matcher( className ); - final String me = matcher.replaceAll( "/" ) + CLASS_EXTENSION; - dirURL = classLoader.getResource( me ); - } - - if( dirURL != null ) - { - final String protocol = dirURL.getProtocol(); - if( protocol.equals( JAR_PROTOCOL ) ) - { - /* A JAR path */ - final String dirPath = dirURL.getPath(); - final String jarPath = dirPath.substring( 5, dirPath.indexOf( '!' ) ); // strip out only - // the JAR file - final JarFile jar = new JarFile( URLDecoder.decode( jarPath, UTF_8_ENCODING ) ); - try - { - final Enumeration entries = jar.entries(); // gives ALL entries in jar - final Collection result = new HashSet( INITIAL_RESOURCE_CAPACITY ); // avoid duplicates - - // in case it is a - // subdirectory - while( entries.hasMoreElements() ) - { - final JarEntry entry = entries.nextElement(); - final String entryFullName = entry.getName(); - if( entryFullName.startsWith( path ) ) - { // filter according to the path - String entryName = entryFullName.substring( path.length() ); - final int checkSubDir = entryName.indexOf( '/' ); - if( checkSubDir >= 0 ) - { - // if it is a subdirectory, we just return the directory name - entryName = entryName.substring( 0, checkSubDir ); - } - result.add( entryName ); - } - } - - return result.toArray( new String[result.size()] ); - } - finally - { - jar.close(); - } - } - } - - throw new UnsupportedOperationException( "Cannot list files for URL " + dirURL ); - } +public class RecipeResourceCopier { + /** + * Most expected size of recipes found + */ + private static final int INITIAL_RESOURCE_CAPACITY = 20; + + private static final Pattern DOT_COMPILE_PATTERN = Pattern.compile(".", Pattern.LITERAL); + private static final String FILE_PROTOCOL = "file"; + private static final String CLASS_EXTENSION = ".class"; + private static final String JAR_PROTOCOL = "jar"; + private static final String UTF_8_ENCODING = "UTF-8"; + + /** + * copy source in the jar + */ + private final String root; + + /** + * @param root source root folder of the recipes inside the jar. + * @throws NullPointerException if root is null + */ + public RecipeResourceCopier(@Nonnull final String root) { + Preconditions.checkNotNull(root); + + this.root = root; + } + + /** + * copies recipes found in the root to destination. + * + * @param identifier only copy files which end with the identifier + * @param destination destination folder to which the recipes are copied to + * @throws URISyntaxException {@see #getResourceListing} + * @throws IOException {@see #getResourceListing} and if copying the detected resource to file is not possible + * @throws NullPointerException if either parameter is null + * @throws IllegalArgumentException if destination is not a directory + */ + public void copyTo(@Nonnull final String identifier, @Nonnull final File destination) + throws URISyntaxException, IOException { + Preconditions.checkNotNull(destination); + Preconditions.checkArgument(destination.isDirectory()); + + this.copyTo(identifier, destination, this.root); + } + + /** + * @param destination destination folder to which the recipes are copied to + * @param directory the folder to copy. + * @throws URISyntaxException {@see #getResourceListing} + * @throws IOException {@see #getResourceListing} and if copying the detected resource to file is not possible + * @see {RecipeResourceCopier#copyTo(File)} + */ + private void copyTo( + @Nonnull final String identifier, @Nonnull final File destination, @Nonnull final String directory) + throws URISyntaxException, IOException { + assert identifier != null; + assert destination != null; + assert directory != null; + + final Class copierClass = this.getClass(); + final String[] listing = this.getResourceListing(copierClass, directory); + for (final String list : listing) { + if (list.endsWith(identifier)) { + // generate folder before the file is copied so no empty folders will be generated + FileUtils.forceMkdir(destination); + + this.copyFile(destination, directory, list); + } else if (!list.contains(".")) { + final File subDirectory = new File(destination, list); + + this.copyTo(identifier, subDirectory, directory + list + "/"); + } + } + } + + /** + * Copies a single file inside a folder to the destination. + * + * @param destination folder to which the file is copied to + * @param directory the directory containing the file + * @param fileName the file to copy + * @throws IOException if copying the file is not possible + */ + private void copyFile( + @Nonnull final File destination, @Nonnull final String directory, @Nonnull final String fileName) + throws IOException { + assert destination != null; + assert directory != null; + assert fileName != null; + + final Class copierClass = this.getClass(); + final InputStream inStream = copierClass.getResourceAsStream('/' + directory + fileName); + final File outFile = new File(destination, fileName); + + if (!outFile.exists() && inStream != null) { + FileUtils.copyInputStreamToFile(inStream, outFile); + inStream.close(); + } + } + + /** + * List directory contents for a resource folder. Not recursive. This is basically a brute-force implementation. Works for regular files and also JARs. + * + * @param clazz Any java class that lives in the same place as the resources you want. + * @param path Should end with "/", but not start with one. + * @return Just the name of each member item, not the full paths. + * @throws URISyntaxException if it is a file path and the URL can not be converted to URI + * @throws IOException if jar path can not be decoded + * @throws UnsupportedOperationException if it is neither in jar nor in file path + */ + @Nonnull + private String[] getResourceListing(@Nonnull final Class clazz, @Nonnull final String path) + throws URISyntaxException, IOException { + assert clazz != null; + assert path != null; + + final ClassLoader classLoader = clazz.getClassLoader(); + if (classLoader == null) { + throw new IllegalStateException( + "ClassLoader was not found. It was probably loaded at a inappropriate time"); + } + + URL dirURL = classLoader.getResource(path); + if (dirURL != null) { + final String protocol = dirURL.getProtocol(); + if (protocol.equals(FILE_PROTOCOL)) { + // A file path: easy enough + + final URI uriOfURL = dirURL.toURI(); + final File fileOfURI = new File(uriOfURL); + final String[] filesAndDirectoriesOfURI = fileOfURI.list(); + + if (filesAndDirectoriesOfURI == null) { + throw new IllegalStateException( + "Files and Directories were illegal. Either an abstract pathname does not denote a directory, or an I/O error occured."); + } else { + return filesAndDirectoriesOfURI; + } + } + } + + if (dirURL == null) { + /* + * In case of a jar file, we can't actually find a directory. + * Have to assume the same jar as clazz. + */ + final String className = clazz.getName(); + final Matcher matcher = DOT_COMPILE_PATTERN.matcher(className); + final String me = matcher.replaceAll("/") + CLASS_EXTENSION; + dirURL = classLoader.getResource(me); + } + + if (dirURL != null) { + final String protocol = dirURL.getProtocol(); + if (protocol.equals(JAR_PROTOCOL)) { + /* A JAR path */ + final String dirPath = dirURL.getPath(); + final String jarPath = dirPath.substring(5, dirPath.indexOf('!')); // strip out only + // the JAR file + final JarFile jar = new JarFile(URLDecoder.decode(jarPath, UTF_8_ENCODING)); + try { + final Enumeration entries = jar.entries(); // gives ALL entries in jar + final Collection result = + new HashSet(INITIAL_RESOURCE_CAPACITY); // avoid duplicates + + // in case it is a + // subdirectory + while (entries.hasMoreElements()) { + final JarEntry entry = entries.nextElement(); + final String entryFullName = entry.getName(); + if (entryFullName.startsWith(path)) { // filter according to the path + String entryName = entryFullName.substring(path.length()); + final int checkSubDir = entryName.indexOf('/'); + if (checkSubDir >= 0) { + // if it is a subdirectory, we just return the directory name + entryName = entryName.substring(0, checkSubDir); + } + result.add(entryName); + } + } + + return result.toArray(new String[result.size()]); + } finally { + jar.close(); + } + } + } + + throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); + } } diff --git a/src/main/java/appeng/recipes/ores/IOreListener.java b/src/main/java/appeng/recipes/ores/IOreListener.java index 404883719c0..011f9751e88 100644 --- a/src/main/java/appeng/recipes/ores/IOreListener.java +++ b/src/main/java/appeng/recipes/ores/IOreListener.java @@ -18,19 +18,16 @@ package appeng.recipes.ores; - import net.minecraft.item.ItemStack; +public interface IOreListener { -public interface IOreListener -{ - - /** - * Called with various items registered in the dictionary. - * AppEng.oreDictionary.observe(...) to register them. - * - * @param name name of ore - * @param item item with name - */ - void oreRegistered( String name, ItemStack item ); + /** + * Called with various items registered in the dictionary. + * AppEng.oreDictionary.observe(...) to register them. + * + * @param name name of ore + * @param item item with name + */ + void oreRegistered(String name, ItemStack item); } diff --git a/src/main/java/appeng/recipes/ores/OreDictionaryHandler.java b/src/main/java/appeng/recipes/ores/OreDictionaryHandler.java index ebfff01a1ad..6bdd8db8a6a 100644 --- a/src/main/java/appeng/recipes/ores/OreDictionaryHandler.java +++ b/src/main/java/appeng/recipes/ores/OreDictionaryHandler.java @@ -18,103 +18,82 @@ package appeng.recipes.ores; - import appeng.core.AELog; import appeng.recipes.game.IRecipeBakeable; import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import java.util.ArrayList; +import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraftforge.oredict.OreDictionary; -import java.util.ArrayList; -import java.util.List; - - -public class OreDictionaryHandler -{ - - public static final OreDictionaryHandler INSTANCE = new OreDictionaryHandler(); - - private final List oreListeners = new ArrayList(); - - private boolean enableRebaking = false; - - @SubscribeEvent - public void onOreDictionaryRegister( final OreDictionary.OreRegisterEvent event ) - { - if( event.Name == null || event.Ore == null ) - { - return; - } - - if( this.shouldCare( event.Name ) ) - { - for( final IOreListener v : this.oreListeners ) - { - v.oreRegistered( event.Name, event.Ore ); - } - } - - if( this.enableRebaking ) - { - this.bakeRecipes(); - } - } - - /** - * Just limit what items are sent to the final listeners, I got sick of strange items showing up... - * - * @param name name about cared item - * @return true if it should care - */ - private boolean shouldCare( final String name ) - { - return true; - } - - public void bakeRecipes() - { - this.enableRebaking = true; - - for( final Object o : CraftingManager.getInstance().getRecipeList() ) - { - if( o instanceof IRecipeBakeable ) - { - try - { - ( (IRecipeBakeable) o ).bake(); - } - catch( final Throwable e ) - { - AELog.debug( e ); - } - } - } - } - - /** - * Adds a new IOreListener and immediately notifies it of any previous ores, any ores added latter will be added at - * that point. - * - * @param n to be added ore listener - */ - public void observe( final IOreListener n ) - { - this.oreListeners.add( n ); - - // notify the listener of any ore already in existence. - for( final String name : OreDictionary.getOreNames() ) - { - if( name != null && this.shouldCare( name ) ) - { - for( final ItemStack item : OreDictionary.getOres( name ) ) - { - if( item != null ) - { - n.oreRegistered( name, item ); - } - } - } - } - } +public class OreDictionaryHandler { + + public static final OreDictionaryHandler INSTANCE = new OreDictionaryHandler(); + + private final List oreListeners = new ArrayList(); + + private boolean enableRebaking = false; + + @SubscribeEvent + public void onOreDictionaryRegister(final OreDictionary.OreRegisterEvent event) { + if (event.Name == null || event.Ore == null) { + return; + } + + if (this.shouldCare(event.Name)) { + for (final IOreListener v : this.oreListeners) { + v.oreRegistered(event.Name, event.Ore); + } + } + + if (this.enableRebaking) { + this.bakeRecipes(); + } + } + + /** + * Just limit what items are sent to the final listeners, I got sick of strange items showing up... + * + * @param name name about cared item + * @return true if it should care + */ + private boolean shouldCare(final String name) { + return true; + } + + public void bakeRecipes() { + this.enableRebaking = true; + + for (final Object o : CraftingManager.getInstance().getRecipeList()) { + if (o instanceof IRecipeBakeable) { + try { + ((IRecipeBakeable) o).bake(); + } catch (final Throwable e) { + AELog.debug(e); + } + } + } + } + + /** + * Adds a new IOreListener and immediately notifies it of any previous ores, any ores added latter will be added at + * that point. + * + * @param n to be added ore listener + */ + public void observe(final IOreListener n) { + this.oreListeners.add(n); + + // notify the listener of any ore already in existence. + for (final String name : OreDictionary.getOreNames()) { + if (name != null && this.shouldCare(name)) { + for (final ItemStack item : OreDictionary.getOres(name)) { + if (item != null) { + n.oreRegistered(name, item); + } + } + } + } + } } diff --git a/src/main/java/appeng/server/AECommand.java b/src/main/java/appeng/server/AECommand.java index 33e937d3011..bc20244f761 100644 --- a/src/main/java/appeng/server/AECommand.java +++ b/src/main/java/appeng/server/AECommand.java @@ -18,119 +18,91 @@ package appeng.server; - import com.google.common.base.Joiner; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.command.WrongUsageException; import net.minecraft.server.MinecraftServer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - - -public final class AECommand extends CommandBase -{ - private final MinecraftServer srv; +public final class AECommand extends CommandBase { + private final MinecraftServer srv; - public AECommand( final MinecraftServer server ) - { - this.srv = server; - } + public AECommand(final MinecraftServer server) { + this.srv = server; + } - @Override - public int getRequiredPermissionLevel() - { - return 0; - } + @Override + public int getRequiredPermissionLevel() { + return 0; + } - /** - * wtf? - */ - @Override - public int compareTo( final Object arg0 ) - { - return 1; - } + /** + * wtf? + */ + @Override + public int compareTo(final Object arg0) { + return 1; + } - @Override - public String getCommandName() - { - return "ae2"; - } + @Override + public String getCommandName() { + return "ae2"; + } - @Override - public String getCommandUsage( final ICommandSender icommandsender ) - { - return "commands.ae2.usage"; - } + @Override + public String getCommandUsage(final ICommandSender icommandsender) { + return "commands.ae2.usage"; + } - @Override - public List addTabCompletionOptions(ICommandSender sender, String[] ss) { - List l = new ArrayList<>(); - String test = ss.length == 0 ? "" : ss[0].trim(); - if (ss.length == 0 - || ss.length == 1 && (test.isEmpty() || Arrays.stream(Commands.values()).anyMatch(c -> c.toString().startsWith(test)))) - Arrays.stream(Commands.values()) - .map(Commands::toString) - .filter(c -> test.isEmpty() || c.startsWith(test)) - .forEach(l::add); - return l; - } + @Override + public List addTabCompletionOptions(ICommandSender sender, String[] ss) { + List l = new ArrayList<>(); + String test = ss.length == 0 ? "" : ss[0].trim(); + if (ss.length == 0 + || ss.length == 1 + && (test.isEmpty() + || Arrays.stream(Commands.values()) + .anyMatch(c -> c.toString().startsWith(test)))) + Arrays.stream(Commands.values()) + .map(Commands::toString) + .filter(c -> test.isEmpty() || c.startsWith(test)) + .forEach(l::add); + return l; + } - @Override - public void processCommand( final ICommandSender sender, final String[] args ) - { - if( args.length == 0 ) - { - throw new WrongUsageException( "commands.ae2.usage" ); - } - else if( "help".equals( args[0] ) ) - { - try - { - if( args.length > 1 ) - { - final Commands c = Commands.valueOf( args[1] ); - throw new WrongUsageException( c.command.getHelp( this.srv ) ); - } - } - catch( final WrongUsageException wrong ) - { - throw wrong; - } - catch( final Throwable er ) - { - throw new WrongUsageException( "commands.ae2.usage" ); - } - } - else if( "list".equals( args[0] ) ) - { - throw new WrongUsageException( Joiner.on( ", " ).join( Commands.values() ) ); - } - else - { - try - { - final Commands c = Commands.valueOf( args[0] ); - if( sender.canCommandSenderUseCommand( c.level, this.getCommandName() ) ) - { - c.command.call( this.srv, args, sender ); - } - else - { - throw new WrongUsageException( "commands.ae2.permissions" ); - } - } - catch( final WrongUsageException wrong ) - { - throw wrong; - } - catch( final Throwable er ) - { - throw new WrongUsageException( "commands.ae2.usage" ); - } - } - } + @Override + public void processCommand(final ICommandSender sender, final String[] args) { + if (args.length == 0) { + throw new WrongUsageException("commands.ae2.usage"); + } else if ("help".equals(args[0])) { + try { + if (args.length > 1) { + final Commands c = Commands.valueOf(args[1]); + throw new WrongUsageException(c.command.getHelp(this.srv)); + } + } catch (final WrongUsageException wrong) { + throw wrong; + } catch (final Throwable er) { + throw new WrongUsageException("commands.ae2.usage"); + } + } else if ("list".equals(args[0])) { + throw new WrongUsageException(Joiner.on(", ").join(Commands.values())); + } else { + try { + final Commands c = Commands.valueOf(args[0]); + if (sender.canCommandSenderUseCommand(c.level, this.getCommandName())) { + c.command.call(this.srv, args, sender); + } else { + throw new WrongUsageException("commands.ae2.permissions"); + } + } catch (final WrongUsageException wrong) { + throw wrong; + } catch (final Throwable er) { + throw new WrongUsageException("commands.ae2.usage"); + } + } + } } diff --git a/src/main/java/appeng/server/AccessType.java b/src/main/java/appeng/server/AccessType.java index 0d45762ae99..b1880e99e29 100644 --- a/src/main/java/appeng/server/AccessType.java +++ b/src/main/java/appeng/server/AccessType.java @@ -18,36 +18,34 @@ package appeng.server; - -public enum AccessType -{ - /** - * allows basic access to manipulate the block via gui, or other. - */ - BLOCK_ACCESS, - - /** - * Can player deposit items into the network. - */ - NETWORK_DEPOSIT, - - /** - * can player withdraw items from the network. - */ - NETWORK_WITHDRAW, - - /** - * can player issue crafting requests? - */ - NETWORK_CRAFT, - - /** - * can player add new blocks to the network. - */ - NETWORK_BUILD, - - /** - * can player manipulate security settings. - */ - NETWORK_SECURITY +public enum AccessType { + /** + * allows basic access to manipulate the block via gui, or other. + */ + BLOCK_ACCESS, + + /** + * Can player deposit items into the network. + */ + NETWORK_DEPOSIT, + + /** + * can player withdraw items from the network. + */ + NETWORK_WITHDRAW, + + /** + * can player issue crafting requests? + */ + NETWORK_CRAFT, + + /** + * can player add new blocks to the network. + */ + NETWORK_BUILD, + + /** + * can player manipulate security settings. + */ + NETWORK_SECURITY } diff --git a/src/main/java/appeng/server/Commands.java b/src/main/java/appeng/server/Commands.java index 722c632900e..9f007c1c9d5 100644 --- a/src/main/java/appeng/server/Commands.java +++ b/src/main/java/appeng/server/Commands.java @@ -18,30 +18,26 @@ package appeng.server; - import appeng.server.subcommands.*; -public enum Commands -{ - Chunklogger( 4, new ChunkLogger() ), - Supporters( 0, new Supporters() ), - profile(2, new Profile() ), - toggleFullAccess(2, new ToggleFullAccess()), - toggleDebugPaths(2, new ToggleDebugPathfinding()), - toggleDebugTiming(2, new ToggleDebugTiming()); +public enum Commands { + Chunklogger(4, new ChunkLogger()), + Supporters(0, new Supporters()), + profile(2, new Profile()), + toggleFullAccess(2, new ToggleFullAccess()), + toggleDebugPaths(2, new ToggleDebugPathfinding()), + toggleDebugTiming(2, new ToggleDebugTiming()); - public final int level; - public final ISubCommand command; + public final int level; + public final ISubCommand command; - Commands( final int level, final ISubCommand w ) - { - this.level = level; - this.command = w; - } + Commands(final int level, final ISubCommand w) { + this.level = level; + this.command = w; + } - @Override - public String toString() - { - return this.name(); - } + @Override + public String toString() { + return this.name(); + } } diff --git a/src/main/java/appeng/server/ISubCommand.java b/src/main/java/appeng/server/ISubCommand.java index 4abd9ddec48..fc25d00d12e 100644 --- a/src/main/java/appeng/server/ISubCommand.java +++ b/src/main/java/appeng/server/ISubCommand.java @@ -18,15 +18,12 @@ package appeng.server; - import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; +public interface ISubCommand { -public interface ISubCommand -{ - - String getHelp( MinecraftServer srv ); + String getHelp(MinecraftServer srv); - void call( MinecraftServer srv, String[] args, ICommandSender sender ); + void call(MinecraftServer srv, String[] args, ICommandSender sender); } diff --git a/src/main/java/appeng/server/ServerHelper.java b/src/main/java/appeng/server/ServerHelper.java index 3feeec91839..f31d7f6454d 100644 --- a/src/main/java/appeng/server/ServerHelper.java +++ b/src/main/java/appeng/server/ServerHelper.java @@ -18,7 +18,6 @@ package appeng.server; - import appeng.api.parts.CableRenderMode; import appeng.block.AEBaseBlock; import appeng.client.ActionKey; @@ -29,6 +28,9 @@ import appeng.items.tools.ToolNetworkTool; import appeng.util.Platform; import cpw.mods.fml.common.FMLCommonHandler; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; @@ -38,166 +40,138 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - - -public class ServerHelper extends CommonHelper -{ - - private EntityPlayer renderModeBased; - - @Override - public void init() - { - - } - - @Override - public World getWorld() - { - throw new UnsupportedOperationException( "This is a server..." ); - } - - @Override - public void bindTileEntitySpecialRenderer( final Class tile, final AEBaseBlock blk ) - { - throw new UnsupportedOperationException( "This is a server..." ); - } - - @Override - public List getPlayers() - { - if( !Platform.isClient() ) - { - final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - - if( server != null ) - { - return server.getConfigurationManager().playerEntityList; - } - } - - return new ArrayList(); - } - - @Override - public void sendToAllNearExcept( final EntityPlayer p, final double x, final double y, final double z, final double dist, final World w, final AppEngPacket packet ) - { - if( Platform.isClient() ) - { - return; - } - - for( final EntityPlayer o : this.getPlayers() ) - { - final EntityPlayerMP entityplayermp = (EntityPlayerMP) o; - - if( entityplayermp != p && entityplayermp.worldObj == w ) - { - final double dX = x - entityplayermp.posX; - final double dY = y - entityplayermp.posY; - final double dZ = z - entityplayermp.posZ; - - if( dX * dX + dY * dY + dZ * dZ < dist * dist ) - { - NetworkHandler.instance.sendTo( packet, entityplayermp ); - } - } - } - } - - @Override - public void spawnEffect( final EffectType type, final World worldObj, final double posX, final double posY, final double posZ, final Object o ) - { - // :P - } - - @Override - public boolean shouldAddParticles( final Random r ) - { - return false; - } - - @Override - public MovingObjectPosition getMOP() - { - return null; - } - - @Override - public void doRenderItem( final ItemStack sis, final World tile ) - { - - } - - @Override - public void postInit() - { - - } - - @Override - public CableRenderMode getRenderMode() - { - if( this.renderModeBased == null ) - { - return CableRenderMode.Standard; - } - - return this.renderModeForPlayer( this.renderModeBased ); - } - - protected CableRenderMode renderModeForPlayer( final EntityPlayer player ) - { - if( player != null ) - { - for( int x = 0; x < InventoryPlayer.getHotbarSize(); x++ ) - { - final ItemStack is = player.inventory.getStackInSlot( x ); - - if( is != null && is.getItem() instanceof ToolNetworkTool ) - { - final NBTTagCompound c = is.getTagCompound(); - if( c != null && c.getBoolean( "hideFacades" ) ) - { - return CableRenderMode.CableView; - } - } - } - } - - return CableRenderMode.Standard; - } - - @Override - public void triggerUpdates() - { - - } - - @Override - public void updateRenderMode( final EntityPlayer player ) - { - this.renderModeBased = player; - } - - @Override - public void missingCoreMod() - { - throw new IllegalStateException( "Unable to Load Core Mod, please verify that AE2 is properly install in the mods folder, with a .jar extension." ); - } - - @Override - public boolean isKeyPressed( ActionKey key ) - { - return false; - } - - @Override - public boolean isActionKey( ActionKey key, int pressedKeyCode ) - { - return false; - } +public class ServerHelper extends CommonHelper { + + private EntityPlayer renderModeBased; + + @Override + public void init() {} + + @Override + public World getWorld() { + throw new UnsupportedOperationException("This is a server..."); + } + + @Override + public void bindTileEntitySpecialRenderer(final Class tile, final AEBaseBlock blk) { + throw new UnsupportedOperationException("This is a server..."); + } + + @Override + public List getPlayers() { + if (!Platform.isClient()) { + final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + + if (server != null) { + return server.getConfigurationManager().playerEntityList; + } + } + + return new ArrayList(); + } + + @Override + public void sendToAllNearExcept( + final EntityPlayer p, + final double x, + final double y, + final double z, + final double dist, + final World w, + final AppEngPacket packet) { + if (Platform.isClient()) { + return; + } + + for (final EntityPlayer o : this.getPlayers()) { + final EntityPlayerMP entityplayermp = (EntityPlayerMP) o; + + if (entityplayermp != p && entityplayermp.worldObj == w) { + final double dX = x - entityplayermp.posX; + final double dY = y - entityplayermp.posY; + final double dZ = z - entityplayermp.posZ; + + if (dX * dX + dY * dY + dZ * dZ < dist * dist) { + NetworkHandler.instance.sendTo(packet, entityplayermp); + } + } + } + } + + @Override + public void spawnEffect( + final EffectType type, + final World worldObj, + final double posX, + final double posY, + final double posZ, + final Object o) { + // :P + } + + @Override + public boolean shouldAddParticles(final Random r) { + return false; + } + + @Override + public MovingObjectPosition getMOP() { + return null; + } + + @Override + public void doRenderItem(final ItemStack sis, final World tile) {} + + @Override + public void postInit() {} + + @Override + public CableRenderMode getRenderMode() { + if (this.renderModeBased == null) { + return CableRenderMode.Standard; + } + + return this.renderModeForPlayer(this.renderModeBased); + } + + protected CableRenderMode renderModeForPlayer(final EntityPlayer player) { + if (player != null) { + for (int x = 0; x < InventoryPlayer.getHotbarSize(); x++) { + final ItemStack is = player.inventory.getStackInSlot(x); + + if (is != null && is.getItem() instanceof ToolNetworkTool) { + final NBTTagCompound c = is.getTagCompound(); + if (c != null && c.getBoolean("hideFacades")) { + return CableRenderMode.CableView; + } + } + } + } + + return CableRenderMode.Standard; + } + + @Override + public void triggerUpdates() {} + + @Override + public void updateRenderMode(final EntityPlayer player) { + this.renderModeBased = player; + } + + @Override + public void missingCoreMod() { + throw new IllegalStateException( + "Unable to Load Core Mod, please verify that AE2 is properly install in the mods folder, with a .jar extension."); + } + + @Override + public boolean isKeyPressed(ActionKey key) { + return false; + } + + @Override + public boolean isActionKey(ActionKey key, int pressedKeyCode) { + return false; + } } diff --git a/src/main/java/appeng/server/subcommands/ChunkLogger.java b/src/main/java/appeng/server/subcommands/ChunkLogger.java index 1a9d3ed7eac..ff7c1be6cdf 100644 --- a/src/main/java/appeng/server/subcommands/ChunkLogger.java +++ b/src/main/java/appeng/server/subcommands/ChunkLogger.java @@ -18,7 +18,6 @@ package appeng.server.subcommands; - import appeng.core.AEConfig; import appeng.core.AELog; import appeng.core.features.AEFeature; @@ -30,71 +29,55 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.world.ChunkEvent; +public class ChunkLogger implements ISubCommand { -public class ChunkLogger implements ISubCommand -{ - - private boolean enabled = false; + private boolean enabled = false; - @SubscribeEvent - public void onChunkLoadEvent( final ChunkEvent.Load event ) - { - if( !event.world.isRemote ) - { - AELog.info( "Chunk Loaded: " + event.getChunk().xPosition + ", " + event.getChunk().zPosition ); - this.displayStack(); - } - } + @SubscribeEvent + public void onChunkLoadEvent(final ChunkEvent.Load event) { + if (!event.world.isRemote) { + AELog.info("Chunk Loaded: " + event.getChunk().xPosition + ", " + event.getChunk().zPosition); + this.displayStack(); + } + } - private void displayStack() - { - if( AEConfig.instance.isFeatureEnabled( AEFeature.ChunkLoggerTrace ) ) - { - boolean output = false; - for( final StackTraceElement e : Thread.currentThread().getStackTrace() ) - { - if( output ) - { - AELog.info( " " + e.getClassName() + '.' + e.getMethodName() + " (" + e.getLineNumber() + ')' ); - } - else - { - output = e.getClassName().contains( "EventBus" ) && e.getMethodName().contains( "post" ); - } - } - } - } + private void displayStack() { + if (AEConfig.instance.isFeatureEnabled(AEFeature.ChunkLoggerTrace)) { + boolean output = false; + for (final StackTraceElement e : Thread.currentThread().getStackTrace()) { + if (output) { + AELog.info(" " + e.getClassName() + '.' + e.getMethodName() + " (" + e.getLineNumber() + ')'); + } else { + output = e.getClassName().contains("EventBus") + && e.getMethodName().contains("post"); + } + } + } + } - @SubscribeEvent - public void onChunkUnloadEvent( final ChunkEvent.Unload unload ) - { - if( !unload.world.isRemote ) - { - AELog.info( "Chunk Unloaded: " + unload.getChunk().xPosition + ", " + unload.getChunk().zPosition ); - this.displayStack(); - } - } + @SubscribeEvent + public void onChunkUnloadEvent(final ChunkEvent.Unload unload) { + if (!unload.world.isRemote) { + AELog.info("Chunk Unloaded: " + unload.getChunk().xPosition + ", " + unload.getChunk().zPosition); + this.displayStack(); + } + } - @Override - public String getHelp( final MinecraftServer srv ) - { - return "commands.ae2.ChunkLogger"; - } + @Override + public String getHelp(final MinecraftServer srv) { + return "commands.ae2.ChunkLogger"; + } - @Override - public void call( final MinecraftServer srv, final String[] data, final ICommandSender sender ) - { - this.enabled = !this.enabled; + @Override + public void call(final MinecraftServer srv, final String[] data, final ICommandSender sender) { + this.enabled = !this.enabled; - if( this.enabled ) - { - MinecraftForge.EVENT_BUS.register( this ); - sender.addChatMessage( new ChatComponentTranslation( "commands.ae2.ChunkLoggerOn" ) ); - } - else - { - MinecraftForge.EVENT_BUS.unregister( this ); - sender.addChatMessage( new ChatComponentTranslation( "commands.ae2.ChunkLoggerOff" ) ); - } - } + if (this.enabled) { + MinecraftForge.EVENT_BUS.register(this); + sender.addChatMessage(new ChatComponentTranslation("commands.ae2.ChunkLoggerOn")); + } else { + MinecraftForge.EVENT_BUS.unregister(this); + sender.addChatMessage(new ChatComponentTranslation("commands.ae2.ChunkLoggerOff")); + } + } } diff --git a/src/main/java/appeng/server/subcommands/Profile.java b/src/main/java/appeng/server/subcommands/Profile.java index e8bb64dbf31..3d3b7a74b8e 100644 --- a/src/main/java/appeng/server/subcommands/Profile.java +++ b/src/main/java/appeng/server/subcommands/Profile.java @@ -1,8 +1,6 @@ package appeng.server.subcommands; -import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; -import appeng.api.networking.IGridNode; import appeng.me.Grid; import appeng.server.ISubCommand; import net.minecraft.command.ICommandSender; @@ -21,54 +19,42 @@ public String getHelp(MinecraftServer srv) { @Override public void call(MinecraftServer srv, String[] args, ICommandSender sender) { - if (args.length < 4) - sender.addChatMessage( new ChatComponentTranslation( "commands.ae2.Profiler" ) ); - try - { + if (args.length < 4) sender.addChatMessage(new ChatComponentTranslation("commands.ae2.Profiler")); + try { int x = Integer.decode(args[1]); int y = Integer.decode(args[2]); int z = Integer.decode(args[3]); TileEntity tile; - if (args.length > 4) - { + if (args.length > 4) { int dim = Integer.decode(args[4]); WorldServer ws = srv.worldServerForDimension(dim); - if (ws == null) - { - sender.addChatMessage( new ChatComponentTranslation("commands.ae2.ProfilerFailedDim")); + if (ws == null) { + sender.addChatMessage(new ChatComponentTranslation("commands.ae2.ProfilerFailedDim")); return; } - tile = ws.getTileEntity(x,y,z); - } - else - tile = sender.getEntityWorld().getTileEntity(x,y,z); + tile = ws.getTileEntity(x, y, z); + } else tile = sender.getEntityWorld().getTileEntity(x, y, z); - if (!(tile instanceof IGridHost) || ((IGridHost)tile).getGridNode(ForgeDirection.UNKNOWN) == null) - { - sender.addChatMessage( new ChatComponentTranslation("commands.ae2.ProfilerFailed")); + if (!(tile instanceof IGridHost) || ((IGridHost) tile).getGridNode(ForgeDirection.UNKNOWN) == null) { + sender.addChatMessage(new ChatComponentTranslation("commands.ae2.ProfilerFailed")); return; } - Grid grid = (Grid)((IGridHost)tile).getGridNode(ForgeDirection.UNKNOWN).getGrid(); - if (grid == null) - { - sender.addChatMessage( new ChatComponentTranslation("commands.ae2.ProfilerGridDown")); + Grid grid = (Grid) + ((IGridHost) tile).getGridNode(ForgeDirection.UNKNOWN).getGrid(); + if (grid == null) { + sender.addChatMessage(new ChatComponentTranslation("commands.ae2.ProfilerGridDown")); return; } - if (!grid.isProfiling()) - { - sender.addChatMessage( new ChatComponentTranslation("commands.ae2.ProfilerStart")); + if (!grid.isProfiling()) { + sender.addChatMessage(new ChatComponentTranslation("commands.ae2.ProfilerStart")); grid.startProfiling(); - } - else - { + } else { IChatComponent message = new ChatComponentTranslation("commands.ae2.ProfilerStop"); message.appendText(String.format(" %d", grid.stopProfiling())); sender.addChatMessage(message); } - } - catch (NumberFormatException ex) - { - sender.addChatMessage( new ChatComponentTranslation("commands.ae2.ProfilerFailed")); + } catch (NumberFormatException ex) { + sender.addChatMessage(new ChatComponentTranslation("commands.ae2.ProfilerFailed")); return; } } diff --git a/src/main/java/appeng/server/subcommands/Supporters.java b/src/main/java/appeng/server/subcommands/Supporters.java index a0391969c66..8fb0806b288 100644 --- a/src/main/java/appeng/server/subcommands/Supporters.java +++ b/src/main/java/appeng/server/subcommands/Supporters.java @@ -18,27 +18,25 @@ package appeng.server.subcommands; - import appeng.server.ISubCommand; import com.google.common.base.Joiner; import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentText; +public class Supporters implements ISubCommand { -public class Supporters implements ISubCommand -{ - - @Override - public String getHelp( final MinecraftServer srv ) - { - return "commands.ae2.Supporters"; - } + @Override + public String getHelp(final MinecraftServer srv) { + return "commands.ae2.Supporters"; + } - @Override - public void call( final MinecraftServer srv, final String[] data, final ICommandSender sender ) - { - final String[] who = { "Stig Halvorsen", "Josh Ricker", "Jenny \"Othlon\" Sutherland", "Hristo Bogdanov", "BevoLJ" }; - sender.addChatMessage( new ChatComponentText( "Special thanks to " + Joiner.on( ", " ).join( who ) ) ); - } + @Override + public void call(final MinecraftServer srv, final String[] data, final ICommandSender sender) { + final String[] who = { + "Stig Halvorsen", "Josh Ricker", "Jenny \"Othlon\" Sutherland", "Hristo Bogdanov", "BevoLJ" + }; + sender.addChatMessage( + new ChatComponentText("Special thanks to " + Joiner.on(", ").join(who))); + } } diff --git a/src/main/java/appeng/server/subcommands/ToggleDebugPathfinding.java b/src/main/java/appeng/server/subcommands/ToggleDebugPathfinding.java index bf92101f831..2f982a826a9 100644 --- a/src/main/java/appeng/server/subcommands/ToggleDebugPathfinding.java +++ b/src/main/java/appeng/server/subcommands/ToggleDebugPathfinding.java @@ -11,9 +11,11 @@ public class ToggleDebugPathfinding implements ISubCommand { public String getHelp(MinecraftServer srv) { return "commands.ae2.ToggleDebugPathfinding"; } + @Override public void call(MinecraftServer srv, String[] args, ICommandSender sender) { AEConfig.instance.debugPathFinding = !AEConfig.instance.debugPathFinding; - sender.addChatMessage(new ChatComponentText("Logging pathfinding is now " + (AEConfig.instance.debugPathFinding? "on" : "off"))); + sender.addChatMessage(new ChatComponentText( + "Logging pathfinding is now " + (AEConfig.instance.debugPathFinding ? "on" : "off"))); } } diff --git a/src/main/java/appeng/server/subcommands/ToggleDebugTiming.java b/src/main/java/appeng/server/subcommands/ToggleDebugTiming.java index 93fdcaf08a7..3c02f37a18a 100644 --- a/src/main/java/appeng/server/subcommands/ToggleDebugTiming.java +++ b/src/main/java/appeng/server/subcommands/ToggleDebugTiming.java @@ -6,14 +6,16 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentText; -public class ToggleDebugTiming implements ISubCommand { +public class ToggleDebugTiming implements ISubCommand { @Override public String getHelp(MinecraftServer srv) { return "commands.ae2.ToggleDebugTiming"; } + @Override public void call(MinecraftServer srv, String[] args, ICommandSender sender) { - AEConfig.instance.debugLogTiming = !AEConfig.instance.debugLogTiming; - sender.addChatMessage(new ChatComponentText("Debug timing is now " + (AEConfig.instance.debugLogTiming? "on" : "off"))); + AEConfig.instance.debugLogTiming = !AEConfig.instance.debugLogTiming; + sender.addChatMessage( + new ChatComponentText("Debug timing is now " + (AEConfig.instance.debugLogTiming ? "on" : "off"))); } } diff --git a/src/main/java/appeng/server/subcommands/ToggleFullAccess.java b/src/main/java/appeng/server/subcommands/ToggleFullAccess.java index 8d396a26aed..e25a3c4d485 100644 --- a/src/main/java/appeng/server/subcommands/ToggleFullAccess.java +++ b/src/main/java/appeng/server/subcommands/ToggleFullAccess.java @@ -8,7 +8,7 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentText; -public class ToggleFullAccess implements ISubCommand { +public class ToggleFullAccess implements ISubCommand { @Override public String getHelp(MinecraftServer srv) { return "commands.ae2.ToggleFullAccess"; @@ -16,21 +16,19 @@ public String getHelp(MinecraftServer srv) { @Override public void call(MinecraftServer srv, String[] args, ICommandSender sender) { - if (sender instanceof EntityPlayerMP) - { + if (sender instanceof EntityPlayerMP) { GameProfile profile = ((EntityPlayerMP) sender).getGameProfile(); - if (!SecurityCache.isPlayerOP(profile)) - { + if (!SecurityCache.isPlayerOP(profile)) { SecurityCache.registerOpPlayer(profile); - sender.addChatMessage(new ChatComponentText("Player " + profile.getName() + " has full admin access now")); - } - else - { + sender.addChatMessage( + new ChatComponentText("Player " + profile.getName() + " has full admin access now")); + } else { SecurityCache.unregisterOpPlayer(profile); - sender.addChatMessage(new ChatComponentText("Player " + profile.getName() + " has admin access revoked")); + sender.addChatMessage( + new ChatComponentText("Player " + profile.getName() + " has admin access revoked")); } - } - else - sender.addChatMessage(new ChatComponentText("The command is intended to be used in game, not from the server console")); + } else + sender.addChatMessage( + new ChatComponentText("The command is intended to be used in game, not from the server console")); } } diff --git a/src/main/java/appeng/services/CompassService.java b/src/main/java/appeng/services/CompassService.java index da64b7dd4ee..10cea36d365 100644 --- a/src/main/java/appeng/services/CompassService.java +++ b/src/main/java/appeng/services/CompassService.java @@ -18,7 +18,6 @@ package appeng.services; - import appeng.api.AEApi; import appeng.api.util.DimensionalCoord; import appeng.services.compass.CompassReader; @@ -26,332 +25,287 @@ import appeng.util.Platform; import com.google.common.base.Preconditions; import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import net.minecraft.block.Block; -import net.minecraft.world.World; -import net.minecraft.world.chunk.Chunk; -import net.minecraftforge.event.world.WorldEvent; - -import javax.annotation.Nonnull; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.concurrent.*; +import javax.annotation.Nonnull; +import net.minecraft.block.Block; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; +import net.minecraftforge.event.world.WorldEvent; - -public final class CompassService -{ - private static final int CHUNK_SIZE = 16; - - private final Map worldSet = new HashMap( 10 ); - private final ExecutorService executor; - - /** - * AE2 Folder for each world - */ - private final File worldCompassFolder; - - private int jobSize; - - public CompassService( @Nonnull final File worldCompassFolder, @Nonnull final ThreadFactory factory ) - { - Preconditions.checkNotNull( worldCompassFolder ); - - this.worldCompassFolder = worldCompassFolder; - this.executor = Executors.newSingleThreadExecutor( factory ); - this.jobSize = 0; - } - - public Future getCompassDirection( final DimensionalCoord coord, final int maxRange, final ICompassCallback cc ) - { - this.jobSize++; - return this.executor.submit( new CMDirectionRequest( coord, maxRange, cc ) ); - } - - /** - * Ensure the a compass service is removed once a world gets unloaded by forge. - * - * @param event the event containing the unloaded world. - */ - @SubscribeEvent - public void unloadWorld( final WorldEvent.Unload event ) - { - if( Platform.isServer() && this.worldSet.containsKey( event.world ) ) - { - final CompassReader compassReader = this.worldSet.remove( event.world ); - - compassReader.close(); - } - } - - private int jobSize() - { - return this.jobSize; - } - - private void cleanUp() - { - for( final CompassReader cr : this.worldSet.values() ) - { - cr.close(); - } - } - - public void updateArea( final World w, final int chunkX, final int chunkZ ) - { - final int x = chunkX << 4; - final int z = chunkZ << 4; - - this.updateArea( w, x, CHUNK_SIZE, z ); - this.updateArea( w, x, CHUNK_SIZE + 32, z ); - this.updateArea( w, x, CHUNK_SIZE + 64, z ); - this.updateArea( w, x, CHUNK_SIZE + 96, z ); - - this.updateArea( w, x, CHUNK_SIZE + 128, z ); - this.updateArea( w, x, CHUNK_SIZE + 160, z ); - this.updateArea( w, x, CHUNK_SIZE + 192, z ); - this.updateArea( w, x, CHUNK_SIZE + 224, z ); - } - - public Future updateArea( final World w, final int x, final int y, final int z ) - { - this.jobSize++; - - final int cx = x >> 4; - final int cdy = y >> 5; - final int cz = z >> 4; - - final int low_y = cdy << 5; - final int hi_y = low_y + 32; - - // lower level... - final Chunk c = w.getChunkFromBlockCoords( x, z ); - - for( final Block skyStoneBlock : AEApi.instance().definitions().blocks().skyStone().maybeBlock().asSet() ) - { - for( int i = 0; i < CHUNK_SIZE; i++ ) - { - for( int j = 0; j < CHUNK_SIZE; j++ ) - { - for( int k = low_y; k < hi_y; k++ ) - { - final Block blk = c.getBlock( i, k, j ); - if( blk == skyStoneBlock && c.getBlockMetadata( i, k, j ) == 0 ) - { - return this.executor.submit( new CMUpdatePost( w, cx, cz, cdy, true ) ); - } - } - } - } - } - - return this.executor.submit( new CMUpdatePost( w, cx, cz, cdy, false ) ); - } - - public void kill() - { - this.executor.shutdown(); - - try - { - this.executor.awaitTermination( 6, TimeUnit.MINUTES ); - this.jobSize = 0; - - for( final CompassReader cr : this.worldSet.values() ) - { - cr.close(); - } - - this.worldSet.clear(); - } - catch( final InterruptedException e ) - { - // wrap this up.. - } - } - - private CompassReader getReader( final World w ) - { - CompassReader cr = this.worldSet.get( w ); - - if( cr == null ) - { - cr = new CompassReader( w.provider.dimensionId, this.worldCompassFolder ); - this.worldSet.put( w, cr ); - } - - return cr; - } - - private int dist( final int ax, final int az, final int bx, final int bz ) - { - final int up = ( bz - az ) * CHUNK_SIZE; - final int side = ( bx - ax ) * CHUNK_SIZE; - - return up * up + side * side; - } - - private double rad( final int ax, final int az, final int bx, final int bz ) - { - final int up = bz - az; - final int side = bx - ax; - - return Math.atan2( -up, side ) - Math.PI / 2.0; - } - - private class CMUpdatePost implements Runnable - { - - public final World world; - - public final int chunkX; - public final int chunkZ; - public final int doubleChunkY; // 32 blocks instead of 16. - public final boolean value; - - public CMUpdatePost( final World w, final int cx, final int cz, final int dcy, final boolean val ) - { - this.world = w; - this.chunkX = cx; - this.doubleChunkY = dcy; - this.chunkZ = cz; - this.value = val; - } - - @Override - public void run() - { - CompassService.this.jobSize--; - - final CompassReader cr = CompassService.this.getReader( this.world ); - cr.setHasBeacon( this.chunkX, this.chunkZ, this.doubleChunkY, this.value ); - - if( CompassService.this.jobSize() < 2 ) - { - CompassService.this.cleanUp(); - } - } - } - - - private class CMDirectionRequest implements Runnable - { - - public final int maxRange; - public final DimensionalCoord coord; - public final ICompassCallback callback; - - public CMDirectionRequest( final DimensionalCoord coord, final int getMaxRange, final ICompassCallback cc ) - { - this.coord = coord; - this.maxRange = getMaxRange; - this.callback = cc; - } - - @Override - public void run() - { - CompassService.this.jobSize--; - - final int cx = this.coord.x >> 4; - final int cz = this.coord.z >> 4; - - final CompassReader cr = CompassService.this.getReader( this.coord.getWorld() ); - - // Am I standing on it? - if( cr.hasBeacon( cx, cz ) ) - { - this.callback.calculatedDirection( true, true, -999, 0 ); - - if( CompassService.this.jobSize() < 2 ) - { - CompassService.this.cleanUp(); - } - - return; - } - - // spiral outward... - for( int offset = 1; offset < this.maxRange; offset++ ) - { - final int minX = cx - offset; - final int minZ = cz - offset; - final int maxX = cx + offset; - final int maxZ = cz + offset; - - int closest = Integer.MAX_VALUE; - int chosen_x = cx; - int chosen_z = cz; - - for( int z = minZ; z <= maxZ; z++ ) - { - if( cr.hasBeacon( minX, z ) ) - { - final int closeness = CompassService.this.dist( cx, cz, minX, z ); - if( closeness < closest ) - { - closest = closeness; - chosen_x = minX; - chosen_z = z; - } - } - - if( cr.hasBeacon( maxX, z ) ) - { - final int closeness = CompassService.this.dist( cx, cz, maxX, z ); - if( closeness < closest ) - { - closest = closeness; - chosen_x = maxX; - chosen_z = z; - } - } - } - - for( int x = minX + 1; x < maxX; x++ ) - { - if( cr.hasBeacon( x, minZ ) ) - { - final int closeness = CompassService.this.dist( cx, cz, x, minZ ); - if( closeness < closest ) - { - closest = closeness; - chosen_x = x; - chosen_z = minZ; - } - } - - if( cr.hasBeacon( x, maxZ ) ) - { - final int closeness = CompassService.this.dist( cx, cz, x, maxZ ); - if( closeness < closest ) - { - closest = closeness; - chosen_x = x; - chosen_z = maxZ; - } - } - } - - if( closest < Integer.MAX_VALUE ) - { - this.callback.calculatedDirection( true, false, CompassService.this.rad( cx, cz, chosen_x, chosen_z ), CompassService.this.dist( cx, cz, chosen_x, chosen_z ) ); - - if( CompassService.this.jobSize() < 2 ) - { - CompassService.this.cleanUp(); - } - - return; - } - } - - // didn't find shit... - this.callback.calculatedDirection( false, true, -999, 999 ); - - if( CompassService.this.jobSize() < 2 ) - { - CompassService.this.cleanUp(); - } - } - } +public final class CompassService { + private static final int CHUNK_SIZE = 16; + + private final Map worldSet = new HashMap(10); + private final ExecutorService executor; + + /** + * AE2 Folder for each world + */ + private final File worldCompassFolder; + + private int jobSize; + + public CompassService(@Nonnull final File worldCompassFolder, @Nonnull final ThreadFactory factory) { + Preconditions.checkNotNull(worldCompassFolder); + + this.worldCompassFolder = worldCompassFolder; + this.executor = Executors.newSingleThreadExecutor(factory); + this.jobSize = 0; + } + + public Future getCompassDirection(final DimensionalCoord coord, final int maxRange, final ICompassCallback cc) { + this.jobSize++; + return this.executor.submit(new CMDirectionRequest(coord, maxRange, cc)); + } + + /** + * Ensure the a compass service is removed once a world gets unloaded by forge. + * + * @param event the event containing the unloaded world. + */ + @SubscribeEvent + public void unloadWorld(final WorldEvent.Unload event) { + if (Platform.isServer() && this.worldSet.containsKey(event.world)) { + final CompassReader compassReader = this.worldSet.remove(event.world); + + compassReader.close(); + } + } + + private int jobSize() { + return this.jobSize; + } + + private void cleanUp() { + for (final CompassReader cr : this.worldSet.values()) { + cr.close(); + } + } + + public void updateArea(final World w, final int chunkX, final int chunkZ) { + final int x = chunkX << 4; + final int z = chunkZ << 4; + + this.updateArea(w, x, CHUNK_SIZE, z); + this.updateArea(w, x, CHUNK_SIZE + 32, z); + this.updateArea(w, x, CHUNK_SIZE + 64, z); + this.updateArea(w, x, CHUNK_SIZE + 96, z); + + this.updateArea(w, x, CHUNK_SIZE + 128, z); + this.updateArea(w, x, CHUNK_SIZE + 160, z); + this.updateArea(w, x, CHUNK_SIZE + 192, z); + this.updateArea(w, x, CHUNK_SIZE + 224, z); + } + + public Future updateArea(final World w, final int x, final int y, final int z) { + this.jobSize++; + + final int cx = x >> 4; + final int cdy = y >> 5; + final int cz = z >> 4; + + final int low_y = cdy << 5; + final int hi_y = low_y + 32; + + // lower level... + final Chunk c = w.getChunkFromBlockCoords(x, z); + + for (final Block skyStoneBlock : + AEApi.instance().definitions().blocks().skyStone().maybeBlock().asSet()) { + for (int i = 0; i < CHUNK_SIZE; i++) { + for (int j = 0; j < CHUNK_SIZE; j++) { + for (int k = low_y; k < hi_y; k++) { + final Block blk = c.getBlock(i, k, j); + if (blk == skyStoneBlock && c.getBlockMetadata(i, k, j) == 0) { + return this.executor.submit(new CMUpdatePost(w, cx, cz, cdy, true)); + } + } + } + } + } + + return this.executor.submit(new CMUpdatePost(w, cx, cz, cdy, false)); + } + + public void kill() { + this.executor.shutdown(); + + try { + this.executor.awaitTermination(6, TimeUnit.MINUTES); + this.jobSize = 0; + + for (final CompassReader cr : this.worldSet.values()) { + cr.close(); + } + + this.worldSet.clear(); + } catch (final InterruptedException e) { + // wrap this up.. + } + } + + private CompassReader getReader(final World w) { + CompassReader cr = this.worldSet.get(w); + + if (cr == null) { + cr = new CompassReader(w.provider.dimensionId, this.worldCompassFolder); + this.worldSet.put(w, cr); + } + + return cr; + } + + private int dist(final int ax, final int az, final int bx, final int bz) { + final int up = (bz - az) * CHUNK_SIZE; + final int side = (bx - ax) * CHUNK_SIZE; + + return up * up + side * side; + } + + private double rad(final int ax, final int az, final int bx, final int bz) { + final int up = bz - az; + final int side = bx - ax; + + return Math.atan2(-up, side) - Math.PI / 2.0; + } + + private class CMUpdatePost implements Runnable { + + public final World world; + + public final int chunkX; + public final int chunkZ; + public final int doubleChunkY; // 32 blocks instead of 16. + public final boolean value; + + public CMUpdatePost(final World w, final int cx, final int cz, final int dcy, final boolean val) { + this.world = w; + this.chunkX = cx; + this.doubleChunkY = dcy; + this.chunkZ = cz; + this.value = val; + } + + @Override + public void run() { + CompassService.this.jobSize--; + + final CompassReader cr = CompassService.this.getReader(this.world); + cr.setHasBeacon(this.chunkX, this.chunkZ, this.doubleChunkY, this.value); + + if (CompassService.this.jobSize() < 2) { + CompassService.this.cleanUp(); + } + } + } + + private class CMDirectionRequest implements Runnable { + + public final int maxRange; + public final DimensionalCoord coord; + public final ICompassCallback callback; + + public CMDirectionRequest(final DimensionalCoord coord, final int getMaxRange, final ICompassCallback cc) { + this.coord = coord; + this.maxRange = getMaxRange; + this.callback = cc; + } + + @Override + public void run() { + CompassService.this.jobSize--; + + final int cx = this.coord.x >> 4; + final int cz = this.coord.z >> 4; + + final CompassReader cr = CompassService.this.getReader(this.coord.getWorld()); + + // Am I standing on it? + if (cr.hasBeacon(cx, cz)) { + this.callback.calculatedDirection(true, true, -999, 0); + + if (CompassService.this.jobSize() < 2) { + CompassService.this.cleanUp(); + } + + return; + } + + // spiral outward... + for (int offset = 1; offset < this.maxRange; offset++) { + final int minX = cx - offset; + final int minZ = cz - offset; + final int maxX = cx + offset; + final int maxZ = cz + offset; + + int closest = Integer.MAX_VALUE; + int chosen_x = cx; + int chosen_z = cz; + + for (int z = minZ; z <= maxZ; z++) { + if (cr.hasBeacon(minX, z)) { + final int closeness = CompassService.this.dist(cx, cz, minX, z); + if (closeness < closest) { + closest = closeness; + chosen_x = minX; + chosen_z = z; + } + } + + if (cr.hasBeacon(maxX, z)) { + final int closeness = CompassService.this.dist(cx, cz, maxX, z); + if (closeness < closest) { + closest = closeness; + chosen_x = maxX; + chosen_z = z; + } + } + } + + for (int x = minX + 1; x < maxX; x++) { + if (cr.hasBeacon(x, minZ)) { + final int closeness = CompassService.this.dist(cx, cz, x, minZ); + if (closeness < closest) { + closest = closeness; + chosen_x = x; + chosen_z = minZ; + } + } + + if (cr.hasBeacon(x, maxZ)) { + final int closeness = CompassService.this.dist(cx, cz, x, maxZ); + if (closeness < closest) { + closest = closeness; + chosen_x = x; + chosen_z = maxZ; + } + } + } + + if (closest < Integer.MAX_VALUE) { + this.callback.calculatedDirection( + true, + false, + CompassService.this.rad(cx, cz, chosen_x, chosen_z), + CompassService.this.dist(cx, cz, chosen_x, chosen_z)); + + if (CompassService.this.jobSize() < 2) { + CompassService.this.cleanUp(); + } + + return; + } + } + + // didn't find shit... + this.callback.calculatedDirection(false, true, -999, 999); + + if (CompassService.this.jobSize() < 2) { + CompassService.this.cleanUp(); + } + } + } } diff --git a/src/main/java/appeng/services/VersionChecker.java b/src/main/java/appeng/services/VersionChecker.java index a6703e2d554..a917944fdf7 100644 --- a/src/main/java/appeng/services/VersionChecker.java +++ b/src/main/java/appeng/services/VersionChecker.java @@ -18,7 +18,6 @@ package appeng.services; - import appeng.core.AEConfig; import appeng.core.AELog; import appeng.core.AppEng; @@ -28,11 +27,9 @@ import com.google.common.base.Preconditions; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.event.FMLInterModComms; -import net.minecraft.nbt.NBTTagCompound; - -import javax.annotation.Nonnull; import java.util.Date; - +import javax.annotation.Nonnull; +import net.minecraft.nbt.NBTTagCompound; /** * Tries to connect to GitHub to retrieve the most current build. @@ -56,142 +53,125 @@ * Only after all that cases, if the external version is higher than the local, * use Version Checker Mod and post several information needed for it to update the mod. */ -public final class VersionChecker implements Runnable -{ - private static final int SEC_TO_HOUR = 3600; - private static final int MS_TO_SEC = 1000; - private final VersionCheckerConfig config; - - public VersionChecker( @Nonnull final VersionCheckerConfig config ) - { - Preconditions.checkNotNull( config ); - - this.config = config; - } - - @Override - public void run() - { - try - { - Thread.yield(); - - // persist the config - this.config.save(); - - // retrieve data - final String rawLastCheck = this.config.lastCheck(); - - // process data - final long lastCheck = Long.parseLong( rawLastCheck ); - final Date now = new Date(); - final long nowInMs = now.getTime(); - final long intervalInMs = this.config.interval() * SEC_TO_HOUR * MS_TO_SEC; - final long lastAfterInterval = lastCheck + intervalInMs; - - this.processInterval( nowInMs, lastAfterInterval ); - } - catch( Exception exception ) - { - // Log any unhandled exception to prevent the JVM from reporting them as unhandled. - AELog.debug( exception ); - } - - AELog.info( "Stopping AE2 VersionChecker" ); - } - - /** - * checks if enough time since last check has expired - * - * @param nowInMs now in milli seconds - * @param lastAfterInterval last version check including the interval defined in the config - */ - private void processInterval( final long nowInMs, final long lastAfterInterval ) - { - if( nowInMs > lastAfterInterval ) - { - final String rawModVersion = AEConfig.VERSION; - final VersionParser parser = new VersionParser(); - final VersionFetcher modFetcher = new ModVersionFetcher( rawModVersion, parser ); - final ReleaseFetcher githubFetcher = new ReleaseFetcher( this.config, parser ); - - final Version modVersion = modFetcher.get(); - final FormattedRelease githubRelease = githubFetcher.get(); - - this.processVersions( modVersion, githubRelease ); - } - else - { - AELog.info( "Last check was just recently." ); - } - } - - /** - * Checks if the retrieved version is newer as the current mod version. - * Will notify player if config is enabled. - * - * @param modVersion version of mod - * @param githubRelease release retrieved through github - */ - private void processVersions( @Nonnull final Version modVersion, @Nonnull final FormattedRelease githubRelease ) - { - final Version githubVersion = githubRelease.version(); - final String modFormatted = modVersion.formatted(); - final String ghFormatted = githubVersion.formatted(); - - if( githubVersion.isNewerAs( modVersion ) ) - { - final String changelog = githubRelease.changelog(); - - if( this.config.shouldNotifyPlayer() ) - { - AELog.info( "Newer version is available: " + ghFormatted + " (found) > " + modFormatted + " (current)" ); - - if( this.config.shouldPostChangelog() ) - { - AELog.info( "Changelog: " + changelog ); - } - } - - this.interactWithVersionCheckerMod( modFormatted, ghFormatted, changelog ); - } - else - { - AELog.info( "No newer version is available: " + ghFormatted + "(found) < " + modFormatted + " (current)" ); - } - } - - /** - * Checks if the version checker mod is installed and handles it depending on that information - * - * @param modFormatted mod version formatted as rv2-beta-8 - * @param ghFormatted retrieved github version formatted as rv2-beta-8 - * @param changelog retrieved github changelog - */ - private void interactWithVersionCheckerMod( @Nonnull final String modFormatted, @Nonnull final String ghFormatted, @Nonnull final String changelog ) - { - if( Loader.isModLoaded( "VersionChecker" ) ) - { - final NBTTagCompound versionInf = new NBTTagCompound(); - versionInf.setString( "modDisplayName", AppEng.MOD_NAME ); - versionInf.setString( "oldVersion", modFormatted ); - versionInf.setString( "newVersion", ghFormatted ); - versionInf.setString( "updateUrl", "https://github.com/xsun2001/Applied-Energistics-2-Unofficial/releases/download/rv3.beta.13/appliedenergistics2" + ghFormatted + ".jar" ); - versionInf.setBoolean( "isDirectLink", true ); - - if( !changelog.isEmpty() ) - { - versionInf.setString( "changeLog", changelog ); - } - - versionInf.setString( "newFileName", "appliedenergistics2-" + ghFormatted + ".jar" ); - FMLInterModComms.sendRuntimeMessage( AppEng.instance(), "VersionChecker", "addUpdate", versionInf ); - - AELog.info( "Reported new version to VersionChecker mod." ); - } - else - { - AELog.info( "VersionChecker mod is not installed; Proceeding." ); - } - } +public final class VersionChecker implements Runnable { + private static final int SEC_TO_HOUR = 3600; + private static final int MS_TO_SEC = 1000; + private final VersionCheckerConfig config; + + public VersionChecker(@Nonnull final VersionCheckerConfig config) { + Preconditions.checkNotNull(config); + + this.config = config; + } + + @Override + public void run() { + try { + Thread.yield(); + + // persist the config + this.config.save(); + + // retrieve data + final String rawLastCheck = this.config.lastCheck(); + + // process data + final long lastCheck = Long.parseLong(rawLastCheck); + final Date now = new Date(); + final long nowInMs = now.getTime(); + final long intervalInMs = this.config.interval() * SEC_TO_HOUR * MS_TO_SEC; + final long lastAfterInterval = lastCheck + intervalInMs; + + this.processInterval(nowInMs, lastAfterInterval); + } catch (Exception exception) { + // Log any unhandled exception to prevent the JVM from reporting them as unhandled. + AELog.debug(exception); + } + + AELog.info("Stopping AE2 VersionChecker"); + } + + /** + * checks if enough time since last check has expired + * + * @param nowInMs now in milli seconds + * @param lastAfterInterval last version check including the interval defined in the config + */ + private void processInterval(final long nowInMs, final long lastAfterInterval) { + if (nowInMs > lastAfterInterval) { + final String rawModVersion = AEConfig.VERSION; + final VersionParser parser = new VersionParser(); + final VersionFetcher modFetcher = new ModVersionFetcher(rawModVersion, parser); + final ReleaseFetcher githubFetcher = new ReleaseFetcher(this.config, parser); + + final Version modVersion = modFetcher.get(); + final FormattedRelease githubRelease = githubFetcher.get(); + + this.processVersions(modVersion, githubRelease); + } else { + AELog.info("Last check was just recently."); + } + } + + /** + * Checks if the retrieved version is newer as the current mod version. + * Will notify player if config is enabled. + * + * @param modVersion version of mod + * @param githubRelease release retrieved through github + */ + private void processVersions(@Nonnull final Version modVersion, @Nonnull final FormattedRelease githubRelease) { + final Version githubVersion = githubRelease.version(); + final String modFormatted = modVersion.formatted(); + final String ghFormatted = githubVersion.formatted(); + + if (githubVersion.isNewerAs(modVersion)) { + final String changelog = githubRelease.changelog(); + + if (this.config.shouldNotifyPlayer()) { + AELog.info("Newer version is available: " + ghFormatted + " (found) > " + modFormatted + " (current)"); + + if (this.config.shouldPostChangelog()) { + AELog.info("Changelog: " + changelog); + } + } + + this.interactWithVersionCheckerMod(modFormatted, ghFormatted, changelog); + } else { + AELog.info("No newer version is available: " + ghFormatted + "(found) < " + modFormatted + " (current)"); + } + } + + /** + * Checks if the version checker mod is installed and handles it depending on that information + * + * @param modFormatted mod version formatted as rv2-beta-8 + * @param ghFormatted retrieved github version formatted as rv2-beta-8 + * @param changelog retrieved github changelog + */ + private void interactWithVersionCheckerMod( + @Nonnull final String modFormatted, @Nonnull final String ghFormatted, @Nonnull final String changelog) { + if (Loader.isModLoaded("VersionChecker")) { + final NBTTagCompound versionInf = new NBTTagCompound(); + versionInf.setString("modDisplayName", AppEng.MOD_NAME); + versionInf.setString("oldVersion", modFormatted); + versionInf.setString("newVersion", ghFormatted); + versionInf.setString( + "updateUrl", + "https://github.com/xsun2001/Applied-Energistics-2-Unofficial/releases/download/rv3.beta.13/appliedenergistics2" + + ghFormatted + ".jar"); + versionInf.setBoolean("isDirectLink", true); + + if (!changelog.isEmpty()) { + versionInf.setString("changeLog", changelog); + } + + versionInf.setString("newFileName", "appliedenergistics2-" + ghFormatted + ".jar"); + FMLInterModComms.sendRuntimeMessage(AppEng.instance(), "VersionChecker", "addUpdate", versionInf); + + AELog.info("Reported new version to VersionChecker mod."); + } else { + AELog.info("VersionChecker mod is not installed; Proceeding."); + } + } } diff --git a/src/main/java/appeng/services/compass/CompassException.java b/src/main/java/appeng/services/compass/CompassException.java index e61c09c2d9a..d4d4917dae4 100644 --- a/src/main/java/appeng/services/compass/CompassException.java +++ b/src/main/java/appeng/services/compass/CompassException.java @@ -18,16 +18,13 @@ package appeng.services.compass; +public class CompassException extends RuntimeException { -public class CompassException extends RuntimeException -{ + private static final long serialVersionUID = 8825268683203860877L; - private static final long serialVersionUID = 8825268683203860877L; + private final Throwable inner; - private final Throwable inner; - - public CompassException( final Throwable t ) - { - this.inner = t; - } + public CompassException(final Throwable t) { + this.inner = t; + } } diff --git a/src/main/java/appeng/services/compass/CompassReader.java b/src/main/java/appeng/services/compass/CompassReader.java index 3b247328422..a8aa0d01800 100644 --- a/src/main/java/appeng/services/compass/CompassReader.java +++ b/src/main/java/appeng/services/compass/CompassReader.java @@ -18,68 +18,57 @@ package appeng.services.compass; - import com.google.common.base.Preconditions; - -import javax.annotation.Nonnull; import java.io.File; import java.util.HashMap; import java.util.Map; +import javax.annotation.Nonnull; +public final class CompassReader { + private final Map regions = new HashMap(100); + private final int dimensionId; + private final File worldCompassFolder; -public final class CompassReader -{ - private final Map regions = new HashMap( 100 ); - private final int dimensionId; - private final File worldCompassFolder; - - public CompassReader( final int dimensionId, @Nonnull final File worldCompassFolder ) - { - Preconditions.checkNotNull( worldCompassFolder ); - Preconditions.checkArgument( worldCompassFolder.isDirectory() ); + public CompassReader(final int dimensionId, @Nonnull final File worldCompassFolder) { + Preconditions.checkNotNull(worldCompassFolder); + Preconditions.checkArgument(worldCompassFolder.isDirectory()); - this.dimensionId = dimensionId; - this.worldCompassFolder = worldCompassFolder; - } + this.dimensionId = dimensionId; + this.worldCompassFolder = worldCompassFolder; + } - public void close() - { - for( final CompassRegion r : this.regions.values() ) - { - r.close(); - } + public void close() { + for (final CompassRegion r : this.regions.values()) { + r.close(); + } - this.regions.clear(); - } + this.regions.clear(); + } - public void setHasBeacon( final int cx, final int cz, final int cdy, final boolean hasBeacon ) - { - final CompassRegion r = this.getRegion( cx, cz ); + public void setHasBeacon(final int cx, final int cz, final int cdy, final boolean hasBeacon) { + final CompassRegion r = this.getRegion(cx, cz); - r.setHasBeacon( cx, cz, cdy, hasBeacon ); - } + r.setHasBeacon(cx, cz, cdy, hasBeacon); + } - public boolean hasBeacon( final int cx, final int cz ) - { - final CompassRegion r = this.getRegion( cx, cz ); + public boolean hasBeacon(final int cx, final int cz) { + final CompassRegion r = this.getRegion(cx, cz); - return r.hasBeacon( cx, cz ); - } + return r.hasBeacon(cx, cz); + } - private CompassRegion getRegion( final int cx, final int cz ) - { - long pos = cx >> 10; - pos <<= 32; - pos |= ( cz >> 10 ); + private CompassRegion getRegion(final int cx, final int cz) { + long pos = cx >> 10; + pos <<= 32; + pos |= (cz >> 10); - CompassRegion cr = this.regions.get( pos ); + CompassRegion cr = this.regions.get(pos); - if( cr == null ) - { - cr = new CompassRegion( cx, cz, this.dimensionId, this.worldCompassFolder ); - this.regions.put( pos, cr ); - } + if (cr == null) { + cr = new CompassRegion(cx, cz, this.dimensionId, this.worldCompassFolder); + this.regions.put(pos, cr); + } - return cr; - } + return cr; + } } diff --git a/src/main/java/appeng/services/compass/CompassRegion.java b/src/main/java/appeng/services/compass/CompassRegion.java index ad9fb3636dc..a4c5fb809b7 100644 --- a/src/main/java/appeng/services/compass/CompassRegion.java +++ b/src/main/java/appeng/services/compass/CompassRegion.java @@ -18,192 +18,149 @@ package appeng.services.compass; - import appeng.core.worlddata.MeteorDataNameEncoder; import com.google.common.base.Preconditions; - -import javax.annotation.Nonnull; import java.io.File; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; +import javax.annotation.Nonnull; - -public final class CompassRegion -{ - private final int lowX; - private final int lowZ; - private final int world; - private final File worldCompassFolder; - private final MeteorDataNameEncoder encoder; - - private boolean hasFile = false; - private RandomAccessFile raf = null; - private ByteBuffer buffer; - - public CompassRegion( final int cx, final int cz, final int worldID, @Nonnull final File worldCompassFolder ) - { - Preconditions.checkNotNull( worldCompassFolder ); - Preconditions.checkArgument( worldCompassFolder.isDirectory() ); - - this.world = worldID; - this.worldCompassFolder = worldCompassFolder; - this.encoder = new MeteorDataNameEncoder( 0 ); - - final int region_x = cx >> 10; - final int region_z = cz >> 10; - - this.lowX = region_x << 10; - this.lowZ = region_z << 10; - - this.openFile( false ); - } - - void close() - { - try - { - if( this.hasFile ) - { - this.buffer = null; - this.raf.close(); - this.raf = null; - this.hasFile = false; - } - } - catch( final Throwable t ) - { - throw new CompassException( t ); - } - } - - boolean hasBeacon( int cx, int cz ) - { - if( this.hasFile ) - { - cx &= 0x3FF; - cz &= 0x3FF; - - final int val = this.read( cx, cz ); - if( val != 0 ) - { - return true; - } - } - - return false; - } - - void setHasBeacon( int cx, int cz, final int cdy, final boolean hasBeacon ) - { - cx &= 0x3FF; - cz &= 0x3FF; - - this.openFile( hasBeacon ); - - if( this.hasFile ) - { - int val = this.read( cx, cz ); - final int originalVal = val; - - if( hasBeacon ) - { - val |= 1 << cdy; - } - else - { - val &= ~( 1 << cdy ); - } - - if( originalVal != val ) - { - this.write( cx, cz, val ); - } - } - } - - @Override - protected void finalize() throws Throwable - { - try - { - if( this.raf != null ) - { - this.raf.close(); - } - } - finally - { - super.finalize(); - } - - } - - private void openFile( final boolean create ) - { - if( this.hasFile ) - { - return; - } - - final File file = this.getFile(); - if( create || this.isFileExistent( file ) ) - { - try - { - this.raf = new RandomAccessFile( file, "rw" ); - final FileChannel fc = this.raf.getChannel(); - this.buffer = fc.map( FileChannel.MapMode.READ_WRITE, 0, 0x400 * 0x400 );// fc.size() ); - this.hasFile = true; - } - catch( final Throwable t ) - { - throw new CompassException( t ); - } - } - } - - private File getFile() - { - final String fileName = this.encoder.encode( this.world, this.lowX, this.lowZ ); - - return new File( this.worldCompassFolder, fileName ); - } - - private boolean isFileExistent( final File file ) - { - return file.exists() && file.isFile(); - } - - private int read( final int cx, final int cz ) - { - try - { - return this.buffer.get( cx + cz * 0x400 ); - // raf.seek( cx + cz * 0x400 ); - // return raf.readByte(); - } - catch( final IndexOutOfBoundsException outOfBounds ) - { - return 0; - } - catch( final Throwable t ) - { - throw new CompassException( t ); - } - } - - private void write( final int cx, final int cz, final int val ) - { - try - { - this.buffer.put( cx + cz * 0x400, (byte) val ); - // raf.seek( cx + cz * 0x400 ); - // raf.writeByte( val ); - } - catch( final Throwable t ) - { - throw new CompassException( t ); - } - } +public final class CompassRegion { + private final int lowX; + private final int lowZ; + private final int world; + private final File worldCompassFolder; + private final MeteorDataNameEncoder encoder; + + private boolean hasFile = false; + private RandomAccessFile raf = null; + private ByteBuffer buffer; + + public CompassRegion(final int cx, final int cz, final int worldID, @Nonnull final File worldCompassFolder) { + Preconditions.checkNotNull(worldCompassFolder); + Preconditions.checkArgument(worldCompassFolder.isDirectory()); + + this.world = worldID; + this.worldCompassFolder = worldCompassFolder; + this.encoder = new MeteorDataNameEncoder(0); + + final int region_x = cx >> 10; + final int region_z = cz >> 10; + + this.lowX = region_x << 10; + this.lowZ = region_z << 10; + + this.openFile(false); + } + + void close() { + try { + if (this.hasFile) { + this.buffer = null; + this.raf.close(); + this.raf = null; + this.hasFile = false; + } + } catch (final Throwable t) { + throw new CompassException(t); + } + } + + boolean hasBeacon(int cx, int cz) { + if (this.hasFile) { + cx &= 0x3FF; + cz &= 0x3FF; + + final int val = this.read(cx, cz); + if (val != 0) { + return true; + } + } + + return false; + } + + void setHasBeacon(int cx, int cz, final int cdy, final boolean hasBeacon) { + cx &= 0x3FF; + cz &= 0x3FF; + + this.openFile(hasBeacon); + + if (this.hasFile) { + int val = this.read(cx, cz); + final int originalVal = val; + + if (hasBeacon) { + val |= 1 << cdy; + } else { + val &= ~(1 << cdy); + } + + if (originalVal != val) { + this.write(cx, cz, val); + } + } + } + + @Override + protected void finalize() throws Throwable { + try { + if (this.raf != null) { + this.raf.close(); + } + } finally { + super.finalize(); + } + } + + private void openFile(final boolean create) { + if (this.hasFile) { + return; + } + + final File file = this.getFile(); + if (create || this.isFileExistent(file)) { + try { + this.raf = new RandomAccessFile(file, "rw"); + final FileChannel fc = this.raf.getChannel(); + this.buffer = fc.map(FileChannel.MapMode.READ_WRITE, 0, 0x400 * 0x400); // fc.size() ); + this.hasFile = true; + } catch (final Throwable t) { + throw new CompassException(t); + } + } + } + + private File getFile() { + final String fileName = this.encoder.encode(this.world, this.lowX, this.lowZ); + + return new File(this.worldCompassFolder, fileName); + } + + private boolean isFileExistent(final File file) { + return file.exists() && file.isFile(); + } + + private int read(final int cx, final int cz) { + try { + return this.buffer.get(cx + cz * 0x400); + // raf.seek( cx + cz * 0x400 ); + // return raf.readByte(); + } catch (final IndexOutOfBoundsException outOfBounds) { + return 0; + } catch (final Throwable t) { + throw new CompassException(t); + } + } + + private void write(final int cx, final int cz, final int val) { + try { + this.buffer.put(cx + cz * 0x400, (byte) val); + // raf.seek( cx + cz * 0x400 ); + // raf.writeByte( val ); + } catch (final Throwable t) { + throw new CompassException(t); + } + } } diff --git a/src/main/java/appeng/services/compass/CompassThreadFactory.java b/src/main/java/appeng/services/compass/CompassThreadFactory.java index 086451727a6..c8a4eebf114 100644 --- a/src/main/java/appeng/services/compass/CompassThreadFactory.java +++ b/src/main/java/appeng/services/compass/CompassThreadFactory.java @@ -18,25 +18,20 @@ package appeng.services.compass; - import com.google.common.base.Preconditions; - -import javax.annotation.Nonnull; import java.util.concurrent.ThreadFactory; - +import javax.annotation.Nonnull; /** * @author thatsIch * @version rv3 - 31.05.2015 * @since rv3 31.05.2015 */ -public final class CompassThreadFactory implements ThreadFactory -{ - @Override - public Thread newThread( @Nonnull final Runnable job ) - { - Preconditions.checkNotNull( job ); +public final class CompassThreadFactory implements ThreadFactory { + @Override + public Thread newThread(@Nonnull final Runnable job) { + Preconditions.checkNotNull(job); - return new Thread( job, "AE Compass Service" ); - } + return new Thread(job, "AE Compass Service"); + } } diff --git a/src/main/java/appeng/services/compass/ICompassCallback.java b/src/main/java/appeng/services/compass/ICompassCallback.java index 8eb5d1500b8..1906379f7ee 100644 --- a/src/main/java/appeng/services/compass/ICompassCallback.java +++ b/src/main/java/appeng/services/compass/ICompassCallback.java @@ -18,17 +18,15 @@ package appeng.services.compass; +public interface ICompassCallback { -public interface ICompassCallback -{ - - /** - * Called from another thread. - * - * @param hasResult true if found a target - * @param spin true if should spin - * @param radians radians - * @param dist distance - */ - void calculatedDirection( boolean hasResult, boolean spin, double radians, double dist ); + /** + * Called from another thread. + * + * @param hasResult true if found a target + * @param spin true if should spin + * @param radians radians + * @param dist distance + */ + void calculatedDirection(boolean hasResult, boolean spin, double radians, double dist); } diff --git a/src/main/java/appeng/services/export/CheckType.java b/src/main/java/appeng/services/export/CheckType.java index 7b37e04bf0b..c11c70121ce 100644 --- a/src/main/java/appeng/services/export/CheckType.java +++ b/src/main/java/appeng/services/export/CheckType.java @@ -18,7 +18,6 @@ package appeng.services.export; - /** * Defines a concrete result type when using the {@link Checker#isEqual(Object)} from the {@link Checker} class. * @@ -27,15 +26,14 @@ * @see Checker * @since rv3 - 25.09.2015 */ -enum CheckType -{ - /** - * If checking resulted in both objects being equal - */ - EQUAL, +enum CheckType { + /** + * If checking resulted in both objects being equal + */ + EQUAL, - /** - * If checking resulted in both objects being unequal - */ - UNEQUAL + /** + * If checking resulted in both objects being unequal + */ + UNEQUAL } diff --git a/src/main/java/appeng/services/export/Checker.java b/src/main/java/appeng/services/export/Checker.java index 8486bf06267..21bcc99d209 100644 --- a/src/main/java/appeng/services/export/Checker.java +++ b/src/main/java/appeng/services/export/Checker.java @@ -18,10 +18,8 @@ package appeng.services.export; - import javax.annotation.Nonnull; - /** * Checks against a specific type with its own check type for clear outcome. *

@@ -31,13 +29,12 @@ * @version rv3 - 01.09.2015 * @since rv3 - 01.09.2015 */ -interface Checker -{ - /** - * @param checkedAgainst the object it is checked against - * @return non null being either equal or unequal - * @since rv3 - 01.09.2015 - */ - @Nonnull - CheckType isEqual( @Nonnull final T checkedAgainst ); +interface Checker { + /** + * @param checkedAgainst the object it is checked against + * @return non null being either equal or unequal + * @since rv3 - 01.09.2015 + */ + @Nonnull + CheckType isEqual(@Nonnull final T checkedAgainst); } diff --git a/src/main/java/appeng/services/export/ExportConfig.java b/src/main/java/appeng/services/export/ExportConfig.java index 8d57e6cc012..9192aa50cac 100644 --- a/src/main/java/appeng/services/export/ExportConfig.java +++ b/src/main/java/appeng/services/export/ExportConfig.java @@ -18,65 +18,62 @@ package appeng.services.export; - import javax.annotation.Nonnull; - /** * @author thatsIch * @version rv3 - 14.08.2015 * @since rv3 14.08.2015 */ -public interface ExportConfig -{ - /** - * config switch to disable the exporting. - * if the recipes system is not used - * there is no reason to export them. - * Still can be useful for debugging purpose, - * thus not tying it to the recipe system directly. - * - * @return true if exporting is enabled - */ - boolean isExportingItemNamesEnabled(); +public interface ExportConfig { + /** + * config switch to disable the exporting. + * if the recipes system is not used + * there is no reason to export them. + * Still can be useful for debugging purpose, + * thus not tying it to the recipe system directly. + * + * @return true if exporting is enabled + */ + boolean isExportingItemNamesEnabled(); - /** - * config switch for using the digest cache. - * - * @return true if cache is enabled - */ - boolean isCacheEnabled(); + /** + * config switch for using the digest cache. + * + * @return true if cache is enabled + */ + boolean isCacheEnabled(); - /** - * config switch to always refresh the CSV. Might be useful to activate on debugging. - * - * @return true if force refresh is enabled - */ - boolean isForceRefreshEnabled(); + /** + * config switch to always refresh the CSV. Might be useful to activate on debugging. + * + * @return true if force refresh is enabled + */ + boolean isForceRefreshEnabled(); - /** - * config switch to export more information mostly used for debugging - * - * @return true if additional information are enabled - */ - boolean isAdditionalInformationEnabled(); + /** + * config switch to export more information mostly used for debugging + * + * @return true if additional information are enabled + */ + boolean isAdditionalInformationEnabled(); - /** - * Will get the cache from last session. Can be used to reduce I/O operations though containing itself calculation. - * - * @return a digest from the last calculation - */ - String getCache(); + /** + * Will get the cache from last session. Can be used to reduce I/O operations though containing itself calculation. + * + * @return a digest from the last calculation + */ + String getCache(); - /** - * sets the cache for the next session to reduce calculation overhead - * - * @param digest new digest for the cache - */ - void setCache( @Nonnull String digest ); + /** + * sets the cache for the next session to reduce calculation overhead + * + * @param digest new digest for the cache + */ + void setCache(@Nonnull String digest); - /** - * Will delegate the saving - */ - void save(); + /** + * Will delegate the saving + */ + void save(); } diff --git a/src/main/java/appeng/services/export/ExportMode.java b/src/main/java/appeng/services/export/ExportMode.java index 1c8a559f554..d11e7f39564 100644 --- a/src/main/java/appeng/services/export/ExportMode.java +++ b/src/main/java/appeng/services/export/ExportMode.java @@ -18,7 +18,6 @@ package appeng.services.export; - /** * Defines the different modes which need to be distinguished upon exporting. *

@@ -28,15 +27,14 @@ * @version rv3 - 23.09.2015 * @since rv3 - 23.09.2015 */ -enum ExportMode -{ - /** - * Will provide general users with information required for recipe making - */ - MINIMAL, +enum ExportMode { + /** + * Will provide general users with information required for recipe making + */ + MINIMAL, - /** - * Will provide advanced users with information with debugging functionality - */ - VERBOSE + /** + * Will provide advanced users with information with debugging functionality + */ + VERBOSE } diff --git a/src/main/java/appeng/services/export/ExportProcess.java b/src/main/java/appeng/services/export/ExportProcess.java index 269fcc74d32..96d66a7a6c9 100644 --- a/src/main/java/appeng/services/export/ExportProcess.java +++ b/src/main/java/appeng/services/export/ExportProcess.java @@ -18,7 +18,6 @@ package appeng.services.export; - import appeng.core.AELog; import com.google.common.base.Preconditions; import com.google.common.base.Stopwatch; @@ -26,13 +25,11 @@ import cpw.mods.fml.common.ModContainer; import cpw.mods.fml.common.registry.FMLControlledNamespacedRegistry; import cpw.mods.fml.common.registry.GameData; -import net.minecraft.item.Item; - -import javax.annotation.Nonnull; import java.io.File; import java.util.List; import java.util.concurrent.TimeUnit; - +import javax.annotation.Nonnull; +import net.minecraft.item.Item; /** * Main entry point for exporting the CSV file @@ -43,85 +40,76 @@ * @version rv3 - 14.08.2015 * @since rv3 14.08.2015 */ -public class ExportProcess implements Runnable -{ - private static final String FORCE_REFRESH_MESSAGE = "Force Refresh enabled. Will ignore cache and export CSV content."; - private static final String CACHE_ENABLED_MESSAGE = "Cache is enabled. Checking for new mod configurations."; - private static final String EQUAL_CONTENT_MESSAGE = "Same mod configuration was found. Not updating CSV content."; - private static final String UNEQUAL_CONTENT_MESSAGE = "New mod configuration was found. Commencing exporting."; - private static final String CACHE_DISABLED_MESSAGE = "Cache is disabled. Commencing exporting."; - private static final String EXPORT_START_MESSAGE = "Item Exporting ( started )"; - private static final String EXPORT_END_MESSAGE = "Item Exporting ( ended after %s ms)"; - - @Nonnull - private final File exportDirectory; - @Nonnull - private final Checker> modChecker; - @Nonnull - private final ExportConfig config; - - /** - * @param exportDirectory directory where the final CSV file will be exported to - * @param config configuration to manipulate the export process - */ - public ExportProcess( @Nonnull final File exportDirectory, @Nonnull final ExportConfig config ) - { - this.exportDirectory = Preconditions.checkNotNull( exportDirectory ); - this.config = Preconditions.checkNotNull( config ); - - this.modChecker = new ModListChecker( config ); - } - - /** - * Will check and export if various config settings will lead to exporting the CSV file. - */ - @Override - public void run() - { - // no priority to this thread - Thread.yield(); - - // logic when to cancel the export process - if( this.config.isForceRefreshEnabled() ) - { - AELog.info( FORCE_REFRESH_MESSAGE ); - } - else - { - if( this.config.isCacheEnabled() ) - { - AELog.info( CACHE_ENABLED_MESSAGE ); - - final Loader loader = Loader.instance(); - final List mods = loader.getActiveModList(); - - if( this.modChecker.isEqual( mods ) == CheckType.EQUAL ) - { - AELog.info( EQUAL_CONTENT_MESSAGE ); - - return; - } - else - { - AELog.info( UNEQUAL_CONTENT_MESSAGE ); - } - } - else - { - AELog.info( CACHE_DISABLED_MESSAGE ); - } - } - - AELog.info( EXPORT_START_MESSAGE ); - final Stopwatch watch = Stopwatch.createStarted(); - - final FMLControlledNamespacedRegistry itemRegistry = GameData.getItemRegistry(); - - final ExportMode mode = this.config.isAdditionalInformationEnabled() ? ExportMode.VERBOSE : ExportMode.MINIMAL; - final Exporter exporter = new MinecraftItemCSVExporter( this.exportDirectory, itemRegistry, mode ); - - exporter.export(); - - AELog.info( EXPORT_END_MESSAGE, watch.elapsed( TimeUnit.MILLISECONDS ) ); - } +public class ExportProcess implements Runnable { + private static final String FORCE_REFRESH_MESSAGE = + "Force Refresh enabled. Will ignore cache and export CSV content."; + private static final String CACHE_ENABLED_MESSAGE = "Cache is enabled. Checking for new mod configurations."; + private static final String EQUAL_CONTENT_MESSAGE = "Same mod configuration was found. Not updating CSV content."; + private static final String UNEQUAL_CONTENT_MESSAGE = "New mod configuration was found. Commencing exporting."; + private static final String CACHE_DISABLED_MESSAGE = "Cache is disabled. Commencing exporting."; + private static final String EXPORT_START_MESSAGE = "Item Exporting ( started )"; + private static final String EXPORT_END_MESSAGE = "Item Exporting ( ended after %s ms)"; + + @Nonnull + private final File exportDirectory; + + @Nonnull + private final Checker> modChecker; + + @Nonnull + private final ExportConfig config; + + /** + * @param exportDirectory directory where the final CSV file will be exported to + * @param config configuration to manipulate the export process + */ + public ExportProcess(@Nonnull final File exportDirectory, @Nonnull final ExportConfig config) { + this.exportDirectory = Preconditions.checkNotNull(exportDirectory); + this.config = Preconditions.checkNotNull(config); + + this.modChecker = new ModListChecker(config); + } + + /** + * Will check and export if various config settings will lead to exporting the CSV file. + */ + @Override + public void run() { + // no priority to this thread + Thread.yield(); + + // logic when to cancel the export process + if (this.config.isForceRefreshEnabled()) { + AELog.info(FORCE_REFRESH_MESSAGE); + } else { + if (this.config.isCacheEnabled()) { + AELog.info(CACHE_ENABLED_MESSAGE); + + final Loader loader = Loader.instance(); + final List mods = loader.getActiveModList(); + + if (this.modChecker.isEqual(mods) == CheckType.EQUAL) { + AELog.info(EQUAL_CONTENT_MESSAGE); + + return; + } else { + AELog.info(UNEQUAL_CONTENT_MESSAGE); + } + } else { + AELog.info(CACHE_DISABLED_MESSAGE); + } + } + + AELog.info(EXPORT_START_MESSAGE); + final Stopwatch watch = Stopwatch.createStarted(); + + final FMLControlledNamespacedRegistry itemRegistry = GameData.getItemRegistry(); + + final ExportMode mode = this.config.isAdditionalInformationEnabled() ? ExportMode.VERBOSE : ExportMode.MINIMAL; + final Exporter exporter = new MinecraftItemCSVExporter(this.exportDirectory, itemRegistry, mode); + + exporter.export(); + + AELog.info(EXPORT_END_MESSAGE, watch.elapsed(TimeUnit.MILLISECONDS)); + } } diff --git a/src/main/java/appeng/services/export/Exporter.java b/src/main/java/appeng/services/export/Exporter.java index 4bd5aa64833..664070571f1 100644 --- a/src/main/java/appeng/services/export/Exporter.java +++ b/src/main/java/appeng/services/export/Exporter.java @@ -18,7 +18,6 @@ package appeng.services.export; - /** * General purpose interface to define an export operation with side effects * @@ -26,10 +25,9 @@ * @version rv3 - 19.08.2015 * @since rv3 19.08.2015 */ -interface Exporter -{ - /** - * Will export something defined by the Exporter with side effects - */ - void export(); +interface Exporter { + /** + * Will export something defined by the Exporter with side effects + */ + void export(); } diff --git a/src/main/java/appeng/services/export/ForgeExportConfig.java b/src/main/java/appeng/services/export/ForgeExportConfig.java index 8380408794b..24dd32dc69b 100644 --- a/src/main/java/appeng/services/export/ForgeExportConfig.java +++ b/src/main/java/appeng/services/export/ForgeExportConfig.java @@ -18,14 +18,11 @@ package appeng.services.export; - import com.google.common.base.Preconditions; +import javax.annotation.Nonnull; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; -import javax.annotation.Nonnull; - - /** * Offers configuration switches for the user to change the export process * @@ -33,96 +30,102 @@ * @version rv3 - 14.08.2015 * @since rv3 14.08.2015 */ -public final class ForgeExportConfig implements ExportConfig -{ - private static final String GENERAL_CATEGORY = "general"; - private static final String CACHE_CATEGORY = "cache"; - - private static final String EXPORT_ITEM_NAMES_KEY = "exportItemNames"; - private static final boolean EXPORT_ITEM_NAMES_DEFAULT = true; - private static final String EXPORT_ITEM_NAMES_DESCRIPTION = "If true, all registered items will be exported containing the internal minecraft name and the localized name to actually find the item you are using. This also contains the item representation of the blocks, but are missing items, which are too much to display e.g. FMP."; - - private static final String ENABLE_FORCE_REFRESH_KEY = "enableForceRefresh"; - private static final boolean ENABLE_FORCE_REFRESH_DEFAULT = false; - private static final String ENABLE_FORCE_REFRESH_DESCRIPTION = "If true, the CSV exporting will always happen. This will not use the cache to reduce the computation."; - - private static final String ENABLE_CACHE_KEY = "enableCache"; - private static final boolean ENABLE_CACHE_DEFAULT = true; - private static final String ENABLE_CACHE_DESCRIPTION = "Caching can save processing time, if there are a lot of items."; - - private static final String ENABLE_ADDITIONAL_INFO_KEY = "enableAdditionalInfo"; - private static final boolean ENABLE_ADDITIONAL_INFO_DEFAULT = false; - private static final String ENABLE_ADDITIONAL_INFO_DESCRIPTION = "Will output more detailed information into the CSV like corresponding items"; - - private static final String DIGEST_KEY = "digest"; - private static final String DIGEST_DEFAULT = ""; - private static final String DIGEST_DESCRIPTION = "Digest of all the mods and versions to check if a re-export of the item names is required."; - - private final boolean exportItemNamesEnabled; - private final boolean cacheEnabled; - private final boolean forceRefreshEnabled; - private final boolean additionalInformationEnabled; - private final String cache; - private final Configuration config; - - /** - * Constructor using the configuration. Apparently there are some race conditions if constructing configurations on multiple file accesses - * - * @param config to be wrapped configuration. - */ - public ForgeExportConfig( @Nonnull final Configuration config ) - { - this.config = Preconditions.checkNotNull( config ); - - this.exportItemNamesEnabled = this.config.getBoolean( EXPORT_ITEM_NAMES_KEY, GENERAL_CATEGORY, EXPORT_ITEM_NAMES_DEFAULT, EXPORT_ITEM_NAMES_DESCRIPTION ); - this.cacheEnabled = this.config.getBoolean( ENABLE_CACHE_KEY, CACHE_CATEGORY, ENABLE_CACHE_DEFAULT, ENABLE_CACHE_DESCRIPTION ); - this.additionalInformationEnabled = this.config.getBoolean( ENABLE_ADDITIONAL_INFO_KEY, GENERAL_CATEGORY, ENABLE_ADDITIONAL_INFO_DEFAULT, ENABLE_ADDITIONAL_INFO_DESCRIPTION ); - this.cache = this.config.getString( DIGEST_KEY, CACHE_CATEGORY, DIGEST_DEFAULT, DIGEST_DESCRIPTION ); - this.forceRefreshEnabled = this.config.getBoolean( ENABLE_FORCE_REFRESH_KEY, GENERAL_CATEGORY, ENABLE_FORCE_REFRESH_DEFAULT, ENABLE_FORCE_REFRESH_DESCRIPTION ); - } - - @Override - public boolean isExportingItemNamesEnabled() - { - return this.exportItemNamesEnabled; - } - - @Override - public boolean isCacheEnabled() - { - return this.cacheEnabled; - } - - @Override - public boolean isForceRefreshEnabled() - { - return this.forceRefreshEnabled; - } - - @Override - public boolean isAdditionalInformationEnabled() - { - return this.additionalInformationEnabled; - } - - @Override - public String getCache() - { - return this.cache; - } - - @Override - public void setCache( @Nonnull final String digest ) - { - final Property digestProperty = this.config.get( CACHE_CATEGORY, DIGEST_KEY, DIGEST_DEFAULT ); - digestProperty.set( digest ); - - this.config.save(); - } - - @Override - public void save() - { - this.config.save(); - } +public final class ForgeExportConfig implements ExportConfig { + private static final String GENERAL_CATEGORY = "general"; + private static final String CACHE_CATEGORY = "cache"; + + private static final String EXPORT_ITEM_NAMES_KEY = "exportItemNames"; + private static final boolean EXPORT_ITEM_NAMES_DEFAULT = true; + private static final String EXPORT_ITEM_NAMES_DESCRIPTION = + "If true, all registered items will be exported containing the internal minecraft name and the localized name to actually find the item you are using. This also contains the item representation of the blocks, but are missing items, which are too much to display e.g. FMP."; + + private static final String ENABLE_FORCE_REFRESH_KEY = "enableForceRefresh"; + private static final boolean ENABLE_FORCE_REFRESH_DEFAULT = false; + private static final String ENABLE_FORCE_REFRESH_DESCRIPTION = + "If true, the CSV exporting will always happen. This will not use the cache to reduce the computation."; + + private static final String ENABLE_CACHE_KEY = "enableCache"; + private static final boolean ENABLE_CACHE_DEFAULT = true; + private static final String ENABLE_CACHE_DESCRIPTION = + "Caching can save processing time, if there are a lot of items."; + + private static final String ENABLE_ADDITIONAL_INFO_KEY = "enableAdditionalInfo"; + private static final boolean ENABLE_ADDITIONAL_INFO_DEFAULT = false; + private static final String ENABLE_ADDITIONAL_INFO_DESCRIPTION = + "Will output more detailed information into the CSV like corresponding items"; + + private static final String DIGEST_KEY = "digest"; + private static final String DIGEST_DEFAULT = ""; + private static final String DIGEST_DESCRIPTION = + "Digest of all the mods and versions to check if a re-export of the item names is required."; + + private final boolean exportItemNamesEnabled; + private final boolean cacheEnabled; + private final boolean forceRefreshEnabled; + private final boolean additionalInformationEnabled; + private final String cache; + private final Configuration config; + + /** + * Constructor using the configuration. Apparently there are some race conditions if constructing configurations on multiple file accesses + * + * @param config to be wrapped configuration. + */ + public ForgeExportConfig(@Nonnull final Configuration config) { + this.config = Preconditions.checkNotNull(config); + + this.exportItemNamesEnabled = this.config.getBoolean( + EXPORT_ITEM_NAMES_KEY, GENERAL_CATEGORY, EXPORT_ITEM_NAMES_DEFAULT, EXPORT_ITEM_NAMES_DESCRIPTION); + this.cacheEnabled = this.config.getBoolean( + ENABLE_CACHE_KEY, CACHE_CATEGORY, ENABLE_CACHE_DEFAULT, ENABLE_CACHE_DESCRIPTION); + this.additionalInformationEnabled = this.config.getBoolean( + ENABLE_ADDITIONAL_INFO_KEY, + GENERAL_CATEGORY, + ENABLE_ADDITIONAL_INFO_DEFAULT, + ENABLE_ADDITIONAL_INFO_DESCRIPTION); + this.cache = this.config.getString(DIGEST_KEY, CACHE_CATEGORY, DIGEST_DEFAULT, DIGEST_DESCRIPTION); + this.forceRefreshEnabled = this.config.getBoolean( + ENABLE_FORCE_REFRESH_KEY, + GENERAL_CATEGORY, + ENABLE_FORCE_REFRESH_DEFAULT, + ENABLE_FORCE_REFRESH_DESCRIPTION); + } + + @Override + public boolean isExportingItemNamesEnabled() { + return this.exportItemNamesEnabled; + } + + @Override + public boolean isCacheEnabled() { + return this.cacheEnabled; + } + + @Override + public boolean isForceRefreshEnabled() { + return this.forceRefreshEnabled; + } + + @Override + public boolean isAdditionalInformationEnabled() { + return this.additionalInformationEnabled; + } + + @Override + public String getCache() { + return this.cache; + } + + @Override + public void setCache(@Nonnull final String digest) { + final Property digestProperty = this.config.get(CACHE_CATEGORY, DIGEST_KEY, DIGEST_DEFAULT); + digestProperty.set(digest); + + this.config.save(); + } + + @Override + public void save() { + this.config.save(); + } } diff --git a/src/main/java/appeng/services/export/MinecraftItemCSVExporter.java b/src/main/java/appeng/services/export/MinecraftItemCSVExporter.java index 6207b0ef297..81c3a297fac 100644 --- a/src/main/java/appeng/services/export/MinecraftItemCSVExporter.java +++ b/src/main/java/appeng/services/export/MinecraftItemCSVExporter.java @@ -18,7 +18,6 @@ package appeng.services.export; - import appeng.core.AELog; import com.google.common.base.Function; import com.google.common.base.Joiner; @@ -26,6 +25,11 @@ import com.google.common.collect.Lists; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.registry.FMLControlledNamespacedRegistry; +import java.io.*; +import java.nio.charset.Charset; +import java.util.List; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; @@ -34,13 +38,6 @@ import net.minecraft.util.StatCollector; import org.apache.commons.io.FileUtils; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.io.*; -import java.nio.charset.Charset; -import java.util.List; - - /** * handles the exporting including processing, transformation and persisting the information * @@ -48,239 +45,224 @@ * @version rv3 - 14.08.2015 * @since rv3 14.08.2015 */ -final class MinecraftItemCSVExporter implements Exporter -{ - private static final String ITEM_CSV_FILE_NAME = "items.csv"; - private static final String MINIMAL_HEADER = "Mod:Item:MetaData, Localized Name"; - private static final String VERBOSE_HEADER = MINIMAL_HEADER + ", Unlocalized Name, Is Air?, Class Name"; - private static final String EXPORT_SUCCESSFUL_MESSAGE = "Exported successfully %d items into %s"; - private static final String EXPORT_UNSUCCESSFUL_MESSAGE = "Exporting was unsuccessful."; - - @Nonnull - private final File exportDirectory; - @Nonnull - private final FMLControlledNamespacedRegistry itemRegistry; - @Nonnull - private final ExportMode mode; - - /** - * @param exportDirectory directory of the resulting export file. Non-null required. - * @param itemRegistry the registry with minecraft items. Needs to be populated at that time, thus the exporting can - * only happen in init (pre-init is the - * phase when all items are determined) - * @param mode mode in which the export should be operated. Resulting CSV will change depending on this. - */ - MinecraftItemCSVExporter( @Nonnull final File exportDirectory, @Nonnull final FMLControlledNamespacedRegistry itemRegistry, @Nonnull final ExportMode mode ) - { - this.exportDirectory = Preconditions.checkNotNull( exportDirectory ); - Preconditions.checkArgument( !exportDirectory.isFile() ); - this.itemRegistry = Preconditions.checkNotNull( itemRegistry ); - this.mode = Preconditions.checkNotNull( mode ); - } - - @Override - public void export() - { - final Iterable items = this.itemRegistry.typeSafeIterable(); - final List itemList = Lists.newArrayList( items ); - - final List lines = Lists.transform( itemList, new ItemRowExtractFunction( this.itemRegistry, this.mode ) ); - - final Joiner newLineJoiner = Joiner.on( '\n' ); - final Joiner newLineJoinerIgnoringNull = newLineJoiner.skipNulls(); - final String joined = newLineJoinerIgnoringNull.join( lines ); - - final File file = new File( this.exportDirectory, ITEM_CSV_FILE_NAME ); - - try - { - FileUtils.forceMkdir( this.exportDirectory ); - - final Writer writer = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( file ), Charset.forName( "UTF-8" ) ) ); - - final String header = this.mode == ExportMode.MINIMAL ? MINIMAL_HEADER : VERBOSE_HEADER; - writer.write( header ); - writer.write( "\n" ); - writer.write( joined ); - writer.flush(); - writer.close(); - - AELog.info( EXPORT_SUCCESSFUL_MESSAGE, lines.size(), ITEM_CSV_FILE_NAME ); - } - catch( final IOException e ) - { - AELog.warn( EXPORT_UNSUCCESSFUL_MESSAGE ); - AELog.debug( e ); - } - } - - /** - * Extracts item name with meta and the display name - */ - private static final class TypeExtractFunction implements Function - { - private static final String EXTRACTING_NULL_MESSAGE = "extracting type null"; - private static final String EXTRACTING_ITEM_MESSAGE = "extracting type %s:%d"; - - @Nonnull - private final String itemName; - @Nonnull - private final ExportMode mode; - - private TypeExtractFunction( @Nonnull final String itemName, @Nonnull final ExportMode mode ) - { - this.itemName = Preconditions.checkNotNull( itemName ); - Preconditions.checkArgument( !itemName.isEmpty() ); - - this.mode = Preconditions.checkNotNull( mode ); - } - - @Nullable - @Override - public String apply( @Nullable final ItemStack input ) - { - if( input == null ) - { - AELog.debug( EXTRACTING_NULL_MESSAGE ); - - return null; - } - else - { - AELog.debug( EXTRACTING_ITEM_MESSAGE, input.getDisplayName(), input.getItemDamage() ); - } - - final List joinedBlockAttributes = Lists.newArrayListWithCapacity( 5 ); - final int meta = input.getItemDamage(); - final String metaName = this.itemName + ':' + meta; - final String localization = input.getDisplayName(); - - joinedBlockAttributes.add( metaName ); - joinedBlockAttributes.add( localization ); - - if( this.mode == ExportMode.VERBOSE ) - { - final Item item = input.getItem(); - final String unlocalizedItem = input.getUnlocalizedName(); - final Block block = Block.getBlockFromItem( item ); - final boolean isBlock = !block.equals( Blocks.air ); - final Class stackClass = input.getClass(); - final String stackClassName = stackClass.getName(); - - joinedBlockAttributes.add( unlocalizedItem ); - joinedBlockAttributes.add( Boolean.toString( isBlock ) ); - joinedBlockAttributes.add( stackClassName ); - } - - final Joiner csvJoiner = Joiner.on( ", " ); - final Joiner csvJoinerIgnoringNulls = csvJoiner.skipNulls(); - - return csvJoinerIgnoringNulls.join( joinedBlockAttributes ); - } - } - - - /** - * transforms an item into a row representation of the CSV file - */ - private static final class ItemRowExtractFunction implements Function - { - /** - * this extension is required to apply the {@link StatCollector} - */ - private static final String LOCALIZATION_NAME_EXTENSION = ".name"; - private static final String EXPORTING_NOTHING_MESSAGE = "Exporting nothing"; - private static final String EXPORTING_SUBTYPES_MESSAGE = "Exporting input %s with subtypes: %b"; - private static final String EXPORTING_SUBTYPES_FAILED_MESSAGE = "Could not export subtypes of: %s"; - - @Nonnull - private final FMLControlledNamespacedRegistry itemRegistry; - @Nonnull - private final ExportMode mode; - - /** - * @param itemRegistry used to retrieve the name of the item - * @param mode extracts more or less information from item depending on mode - */ - ItemRowExtractFunction( @Nonnull final FMLControlledNamespacedRegistry itemRegistry, @Nonnull final ExportMode mode ) - { - this.itemRegistry = Preconditions.checkNotNull( itemRegistry ); - this.mode = Preconditions.checkNotNull( mode ); - } - - @Nullable - @Override - public String apply( @Nullable final Item input ) - { - if (!FMLCommonHandler.instance().getSide().isClient()) return null; - if( input == null ) - { - AELog.debug( EXPORTING_NOTHING_MESSAGE ); - - return null; - } - else - { - AELog.debug( EXPORTING_SUBTYPES_MESSAGE, input.getUnlocalizedName(), input.getHasSubtypes() ); - } - - final String itemName = this.itemRegistry.getNameForObject( input ); - final boolean hasSubtypes = input.getHasSubtypes(); - if( hasSubtypes ) - { - final CreativeTabs creativeTab = input.getCreativeTab(); - final List stacks = Lists.newArrayList(); - - // modifies the stacks list and adds the different sub types to it - try - { - input.getSubItems( input, creativeTab, stacks ); - } - catch( final Exception ignored ) - { - AELog.warn( EXPORTING_SUBTYPES_FAILED_MESSAGE, input.getUnlocalizedName() ); - AELog.debug( ignored ); - - // ignore if mods do bullshit in their code - return null; - } - - // list can be empty, no clue why - if( stacks.isEmpty() ) - { - return null; - } - - final Joiner newLineJoiner = Joiner.on( '\n' ); - final Joiner typeJoiner = newLineJoiner.skipNulls(); - final List transformedTypes = Lists.transform( stacks, new TypeExtractFunction( itemName, this.mode ) ); - - return typeJoiner.join( transformedTypes ); - } - - final List joinedBlockAttributes = Lists.newArrayListWithCapacity( 5 ); - final String unlocalizedItem = input.getUnlocalizedName(); - final String localization = StatCollector.translateToLocal( unlocalizedItem + LOCALIZATION_NAME_EXTENSION ); - - joinedBlockAttributes.add( itemName ); - joinedBlockAttributes.add( localization ); - - if( this.mode == ExportMode.VERBOSE ) - { - final Block block = Block.getBlockFromItem( input ); - final boolean isBlock = !block.equals( Blocks.air ); - final Class itemClass = input.getClass(); - final String itemClassName = itemClass.getName(); - - joinedBlockAttributes.add( unlocalizedItem ); - joinedBlockAttributes.add( Boolean.toString( isBlock ) ); - joinedBlockAttributes.add( itemClassName ); - } - - final Joiner csvJoiner = Joiner.on( ", " ); - final Joiner csvJoinerIgnoringNulls = csvJoiner.skipNulls(); - - return csvJoinerIgnoringNulls.join( joinedBlockAttributes ); - } - } +final class MinecraftItemCSVExporter implements Exporter { + private static final String ITEM_CSV_FILE_NAME = "items.csv"; + private static final String MINIMAL_HEADER = "Mod:Item:MetaData, Localized Name"; + private static final String VERBOSE_HEADER = MINIMAL_HEADER + ", Unlocalized Name, Is Air?, Class Name"; + private static final String EXPORT_SUCCESSFUL_MESSAGE = "Exported successfully %d items into %s"; + private static final String EXPORT_UNSUCCESSFUL_MESSAGE = "Exporting was unsuccessful."; + + @Nonnull + private final File exportDirectory; + + @Nonnull + private final FMLControlledNamespacedRegistry itemRegistry; + + @Nonnull + private final ExportMode mode; + + /** + * @param exportDirectory directory of the resulting export file. Non-null required. + * @param itemRegistry the registry with minecraft items. Needs to be populated at that time, thus the exporting can + * only happen in init (pre-init is the + * phase when all items are determined) + * @param mode mode in which the export should be operated. Resulting CSV will change depending on this. + */ + MinecraftItemCSVExporter( + @Nonnull final File exportDirectory, + @Nonnull final FMLControlledNamespacedRegistry itemRegistry, + @Nonnull final ExportMode mode) { + this.exportDirectory = Preconditions.checkNotNull(exportDirectory); + Preconditions.checkArgument(!exportDirectory.isFile()); + this.itemRegistry = Preconditions.checkNotNull(itemRegistry); + this.mode = Preconditions.checkNotNull(mode); + } + + @Override + public void export() { + final Iterable items = this.itemRegistry.typeSafeIterable(); + final List itemList = Lists.newArrayList(items); + + final List lines = Lists.transform(itemList, new ItemRowExtractFunction(this.itemRegistry, this.mode)); + + final Joiner newLineJoiner = Joiner.on('\n'); + final Joiner newLineJoinerIgnoringNull = newLineJoiner.skipNulls(); + final String joined = newLineJoinerIgnoringNull.join(lines); + + final File file = new File(this.exportDirectory, ITEM_CSV_FILE_NAME); + + try { + FileUtils.forceMkdir(this.exportDirectory); + + final Writer writer = + new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8"))); + + final String header = this.mode == ExportMode.MINIMAL ? MINIMAL_HEADER : VERBOSE_HEADER; + writer.write(header); + writer.write("\n"); + writer.write(joined); + writer.flush(); + writer.close(); + + AELog.info(EXPORT_SUCCESSFUL_MESSAGE, lines.size(), ITEM_CSV_FILE_NAME); + } catch (final IOException e) { + AELog.warn(EXPORT_UNSUCCESSFUL_MESSAGE); + AELog.debug(e); + } + } + + /** + * Extracts item name with meta and the display name + */ + private static final class TypeExtractFunction implements Function { + private static final String EXTRACTING_NULL_MESSAGE = "extracting type null"; + private static final String EXTRACTING_ITEM_MESSAGE = "extracting type %s:%d"; + + @Nonnull + private final String itemName; + + @Nonnull + private final ExportMode mode; + + private TypeExtractFunction(@Nonnull final String itemName, @Nonnull final ExportMode mode) { + this.itemName = Preconditions.checkNotNull(itemName); + Preconditions.checkArgument(!itemName.isEmpty()); + + this.mode = Preconditions.checkNotNull(mode); + } + + @Nullable + @Override + public String apply(@Nullable final ItemStack input) { + if (input == null) { + AELog.debug(EXTRACTING_NULL_MESSAGE); + + return null; + } else { + AELog.debug(EXTRACTING_ITEM_MESSAGE, input.getDisplayName(), input.getItemDamage()); + } + + final List joinedBlockAttributes = Lists.newArrayListWithCapacity(5); + final int meta = input.getItemDamage(); + final String metaName = this.itemName + ':' + meta; + final String localization = input.getDisplayName(); + + joinedBlockAttributes.add(metaName); + joinedBlockAttributes.add(localization); + + if (this.mode == ExportMode.VERBOSE) { + final Item item = input.getItem(); + final String unlocalizedItem = input.getUnlocalizedName(); + final Block block = Block.getBlockFromItem(item); + final boolean isBlock = !block.equals(Blocks.air); + final Class stackClass = input.getClass(); + final String stackClassName = stackClass.getName(); + + joinedBlockAttributes.add(unlocalizedItem); + joinedBlockAttributes.add(Boolean.toString(isBlock)); + joinedBlockAttributes.add(stackClassName); + } + + final Joiner csvJoiner = Joiner.on(", "); + final Joiner csvJoinerIgnoringNulls = csvJoiner.skipNulls(); + + return csvJoinerIgnoringNulls.join(joinedBlockAttributes); + } + } + + /** + * transforms an item into a row representation of the CSV file + */ + private static final class ItemRowExtractFunction implements Function { + /** + * this extension is required to apply the {@link StatCollector} + */ + private static final String LOCALIZATION_NAME_EXTENSION = ".name"; + + private static final String EXPORTING_NOTHING_MESSAGE = "Exporting nothing"; + private static final String EXPORTING_SUBTYPES_MESSAGE = "Exporting input %s with subtypes: %b"; + private static final String EXPORTING_SUBTYPES_FAILED_MESSAGE = "Could not export subtypes of: %s"; + + @Nonnull + private final FMLControlledNamespacedRegistry itemRegistry; + + @Nonnull + private final ExportMode mode; + + /** + * @param itemRegistry used to retrieve the name of the item + * @param mode extracts more or less information from item depending on mode + */ + ItemRowExtractFunction( + @Nonnull final FMLControlledNamespacedRegistry itemRegistry, @Nonnull final ExportMode mode) { + this.itemRegistry = Preconditions.checkNotNull(itemRegistry); + this.mode = Preconditions.checkNotNull(mode); + } + + @Nullable + @Override + public String apply(@Nullable final Item input) { + if (!FMLCommonHandler.instance().getSide().isClient()) return null; + if (input == null) { + AELog.debug(EXPORTING_NOTHING_MESSAGE); + + return null; + } else { + AELog.debug(EXPORTING_SUBTYPES_MESSAGE, input.getUnlocalizedName(), input.getHasSubtypes()); + } + + final String itemName = this.itemRegistry.getNameForObject(input); + final boolean hasSubtypes = input.getHasSubtypes(); + if (hasSubtypes) { + final CreativeTabs creativeTab = input.getCreativeTab(); + final List stacks = Lists.newArrayList(); + + // modifies the stacks list and adds the different sub types to it + try { + input.getSubItems(input, creativeTab, stacks); + } catch (final Exception ignored) { + AELog.warn(EXPORTING_SUBTYPES_FAILED_MESSAGE, input.getUnlocalizedName()); + AELog.debug(ignored); + + // ignore if mods do bullshit in their code + return null; + } + + // list can be empty, no clue why + if (stacks.isEmpty()) { + return null; + } + + final Joiner newLineJoiner = Joiner.on('\n'); + final Joiner typeJoiner = newLineJoiner.skipNulls(); + final List transformedTypes = + Lists.transform(stacks, new TypeExtractFunction(itemName, this.mode)); + + return typeJoiner.join(transformedTypes); + } + + final List joinedBlockAttributes = Lists.newArrayListWithCapacity(5); + final String unlocalizedItem = input.getUnlocalizedName(); + final String localization = StatCollector.translateToLocal(unlocalizedItem + LOCALIZATION_NAME_EXTENSION); + + joinedBlockAttributes.add(itemName); + joinedBlockAttributes.add(localization); + + if (this.mode == ExportMode.VERBOSE) { + final Block block = Block.getBlockFromItem(input); + final boolean isBlock = !block.equals(Blocks.air); + final Class itemClass = input.getClass(); + final String itemClassName = itemClass.getName(); + + joinedBlockAttributes.add(unlocalizedItem); + joinedBlockAttributes.add(Boolean.toString(isBlock)); + joinedBlockAttributes.add(itemClassName); + } + + final Joiner csvJoiner = Joiner.on(", "); + final Joiner csvJoinerIgnoringNulls = csvJoiner.skipNulls(); + + return csvJoinerIgnoringNulls.join(joinedBlockAttributes); + } + } } diff --git a/src/main/java/appeng/services/export/ModListChecker.java b/src/main/java/appeng/services/export/ModListChecker.java index 8c5e4443b86..6368ea75aa3 100644 --- a/src/main/java/appeng/services/export/ModListChecker.java +++ b/src/main/java/appeng/services/export/ModListChecker.java @@ -18,14 +18,11 @@ package appeng.services.export; - import com.google.common.base.Preconditions; import cpw.mods.fml.common.ModContainer; -import org.apache.commons.codec.digest.DigestUtils; - -import javax.annotation.Nonnull; import java.util.List; - +import javax.annotation.Nonnull; +import org.apache.commons.codec.digest.DigestUtils; /** * Checks the cached digest against the current mods including their versions. @@ -35,55 +32,48 @@ * @version rv3 - 01.09.2015 * @since rv3 - 01.09.2015 */ -final class ModListChecker implements Checker> -{ - private final String configHashValue; +final class ModListChecker implements Checker> { + private final String configHashValue; - @Nonnull - private final ExportConfig config; + @Nonnull + private final ExportConfig config; - /** - * @param config uses the config to retrieve the old hash of the mod list - */ - ModListChecker( @Nonnull final ExportConfig config ) - { - this.config = Preconditions.checkNotNull( config ); - this.configHashValue = Preconditions.checkNotNull( config.getCache() ); - } + /** + * @param config uses the config to retrieve the old hash of the mod list + */ + ModListChecker(@Nonnull final ExportConfig config) { + this.config = Preconditions.checkNotNull(config); + this.configHashValue = Preconditions.checkNotNull(config.getCache()); + } - /** - * Compiles a list of all mods and their versions to a digest which is updated, if it differs from the config. This is used to elevate the need to export - * the csv once again, if no change was detected. - * - * @param modContainers all mods and their versions to check if a difference exists between the current instance and the previous instance - * @return CheckType.EQUAL if no change was detected - */ - @Nonnull - @Override - public CheckType isEqual( @Nonnull final List modContainers ) - { - Preconditions.checkNotNull( modContainers ); + /** + * Compiles a list of all mods and their versions to a digest which is updated, if it differs from the config. This is used to elevate the need to export + * the csv once again, if no change was detected. + * + * @param modContainers all mods and their versions to check if a difference exists between the current instance and the previous instance + * @return CheckType.EQUAL if no change was detected + */ + @Nonnull + @Override + public CheckType isEqual(@Nonnull final List modContainers) { + Preconditions.checkNotNull(modContainers); - final StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); - for( final ModContainer container : modContainers ) - { - builder.append( container.getModId() ); - builder.append( container.getVersion() ); - } + for (final ModContainer container : modContainers) { + builder.append(container.getModId()); + builder.append(container.getVersion()); + } - final String allModsAndVersions = builder.toString(); - final String hex = DigestUtils.md5Hex( allModsAndVersions ); + final String allModsAndVersions = builder.toString(); + final String hex = DigestUtils.md5Hex(allModsAndVersions); - if( hex.equals( this.configHashValue ) ) - { - return CheckType.EQUAL; - } - else - { - this.config.setCache( hex ); + if (hex.equals(this.configHashValue)) { + return CheckType.EQUAL; + } else { + this.config.setCache(hex); - return CheckType.UNEQUAL; - } - } + return CheckType.UNEQUAL; + } + } } diff --git a/src/main/java/appeng/services/export/package-info.java b/src/main/java/appeng/services/export/package-info.java index 8d212f17a89..bf12342a17b 100644 --- a/src/main/java/appeng/services/export/package-info.java +++ b/src/main/java/appeng/services/export/package-info.java @@ -29,5 +29,4 @@ * @version rv3 - 14.08.2015 * @since rv3 14.08.2015 */ - -package appeng.services.export; \ No newline at end of file +package appeng.services.export; diff --git a/src/main/java/appeng/services/version/BaseVersion.java b/src/main/java/appeng/services/version/BaseVersion.java index 8ea584719c0..1fd3c77d5c3 100644 --- a/src/main/java/appeng/services/version/BaseVersion.java +++ b/src/main/java/appeng/services/version/BaseVersion.java @@ -18,109 +18,91 @@ package appeng.services.version; - import com.google.common.base.Preconditions; - import javax.annotation.Nonnegative; import javax.annotation.Nonnull; - /** * Base version of {@link Version}. *

* Provides a unified way to test for equality and print a formatted string */ -public abstract class BaseVersion implements Version -{ - @Nonnegative - private final int revision; - @Nonnull - private final Channel channel; - @Nonnegative - private final int build; - - /** - * @param revision revision in natural number - * @param channel channel - * @param build build in natural number - * @throws AssertionError if assertion are enabled and revision or build are not natural numbers - */ - public BaseVersion( @Nonnegative final int revision, @Nonnull final Channel channel, @Nonnegative final int build ) - { - Preconditions.checkArgument( revision >= 0 ); - Preconditions.checkNotNull( channel ); - Preconditions.checkArgument( build >= 0 ); - - this.revision = revision; - this.channel = channel; - this.build = build; - } - - @Override - public final int revision() - { - return this.revision; - } - - @Override - public final Channel channel() - { - return this.channel; - } - - @Override - public final int build() - { - return this.build; - } - - @Override - public String formatted() - { - return "rv" + this.revision + '-' + this.channel.name().toLowerCase() + '-' + this.build; - } - - @Override - public final int hashCode() - { - int result = this.revision; - result = 31 * result + this.channel.hashCode(); - result = 31 * result + this.build; - return result; - } - - @Override - public final boolean equals( final Object o ) - { - if( this == o ) - { - return true; - } - if( !( o instanceof Version ) ) - { - return false; - } - - final Version that = (Version) o; - - if( this.revision != that.revision() ) - { - return false; - } - if( this.build != that.build() ) - { - return false; - } - return this.channel == that.channel(); - } - - @Override - public final String toString() - { - return "Version{" + - "revision=" + this.revision + - ", channel=" + this.channel + - ", build=" + this.build + - '}'; - } +public abstract class BaseVersion implements Version { + @Nonnegative + private final int revision; + + @Nonnull + private final Channel channel; + + @Nonnegative + private final int build; + + /** + * @param revision revision in natural number + * @param channel channel + * @param build build in natural number + * @throws AssertionError if assertion are enabled and revision or build are not natural numbers + */ + public BaseVersion(@Nonnegative final int revision, @Nonnull final Channel channel, @Nonnegative final int build) { + Preconditions.checkArgument(revision >= 0); + Preconditions.checkNotNull(channel); + Preconditions.checkArgument(build >= 0); + + this.revision = revision; + this.channel = channel; + this.build = build; + } + + @Override + public final int revision() { + return this.revision; + } + + @Override + public final Channel channel() { + return this.channel; + } + + @Override + public final int build() { + return this.build; + } + + @Override + public String formatted() { + return "rv" + this.revision + '-' + this.channel.name().toLowerCase() + '-' + this.build; + } + + @Override + public final int hashCode() { + int result = this.revision; + result = 31 * result + this.channel.hashCode(); + result = 31 * result + this.build; + return result; + } + + @Override + public final boolean equals(final Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Version)) { + return false; + } + + final Version that = (Version) o; + + if (this.revision != that.revision()) { + return false; + } + if (this.build != that.build()) { + return false; + } + return this.channel == that.channel(); + } + + @Override + public final String toString() { + return "Version{" + "revision=" + this.revision + ", channel=" + this.channel + ", build=" + this.build + '}'; + } } diff --git a/src/main/java/appeng/services/version/Channel.java b/src/main/java/appeng/services/version/Channel.java index 397ed8365b2..35cf2148c16 100644 --- a/src/main/java/appeng/services/version/Channel.java +++ b/src/main/java/appeng/services/version/Channel.java @@ -18,14 +18,12 @@ package appeng.services.version; - /** * Represents the release channel of Applied Energistics. The mod is either in Alpha, Beta or Stable channel. * Any more might be confusing to the end-user */ -public enum Channel -{ - Alpha, - Beta, - Stable +public enum Channel { + Alpha, + Beta, + Stable } diff --git a/src/main/java/appeng/services/version/DefaultVersion.java b/src/main/java/appeng/services/version/DefaultVersion.java index bcd4bd6bda2..96e1b1c9056 100644 --- a/src/main/java/appeng/services/version/DefaultVersion.java +++ b/src/main/java/appeng/services/version/DefaultVersion.java @@ -18,39 +18,31 @@ package appeng.services.version; - import javax.annotation.Nonnegative; import javax.annotation.Nonnull; - /** * AE prints version like rv2-beta-8 * GitHub prints version like rv2.beta.8 */ -public final class DefaultVersion extends BaseVersion -{ - /** - * @param revision natural number - * @param channel either alpha, beta or release - * @param build natural number - */ - public DefaultVersion( @Nonnegative final int revision, @Nonnull final Channel channel, @Nonnegative final int build ) - { - super( revision, channel, build ); - } +public final class DefaultVersion extends BaseVersion { + /** + * @param revision natural number + * @param channel either alpha, beta or release + * @param build natural number + */ + public DefaultVersion( + @Nonnegative final int revision, @Nonnull final Channel channel, @Nonnegative final int build) { + super(revision, channel, build); + } - @Override - public boolean isNewerAs( final Version maybeOlder ) - { - if( this.revision() == maybeOlder.revision() ) - { - if( this.channel().compareTo( maybeOlder.channel() ) == 0 ) - { - return this.build() > maybeOlder.build(); - } - return this.channel().compareTo( maybeOlder.channel() ) > 0; - } - else - return this.revision() > maybeOlder.revision(); - } + @Override + public boolean isNewerAs(final Version maybeOlder) { + if (this.revision() == maybeOlder.revision()) { + if (this.channel().compareTo(maybeOlder.channel()) == 0) { + return this.build() > maybeOlder.build(); + } + return this.channel().compareTo(maybeOlder.channel()) > 0; + } else return this.revision() > maybeOlder.revision(); + } } diff --git a/src/main/java/appeng/services/version/DoNotCheckVersion.java b/src/main/java/appeng/services/version/DoNotCheckVersion.java index 9edff745e17..97fa55b991f 100644 --- a/src/main/java/appeng/services/version/DoNotCheckVersion.java +++ b/src/main/java/appeng/services/version/DoNotCheckVersion.java @@ -18,26 +18,21 @@ package appeng.services.version; - /** * Exceptional template for {@link Version}, when the mod does not want a check */ -public final class DoNotCheckVersion extends BaseVersion -{ - public DoNotCheckVersion() - { - super( Integer.MAX_VALUE, Channel.Stable, Integer.MAX_VALUE ); - } +public final class DoNotCheckVersion extends BaseVersion { + public DoNotCheckVersion() { + super(Integer.MAX_VALUE, Channel.Stable, Integer.MAX_VALUE); + } - @Override - public boolean isNewerAs( final Version maybeOlder ) - { - return true; - } + @Override + public boolean isNewerAs(final Version maybeOlder) { + return true; + } - @Override - public String formatted() - { - return "dev build"; - } + @Override + public String formatted() { + return "dev build"; + } } diff --git a/src/main/java/appeng/services/version/MissingVersion.java b/src/main/java/appeng/services/version/MissingVersion.java index c7fef3a8772..54aff638450 100644 --- a/src/main/java/appeng/services/version/MissingVersion.java +++ b/src/main/java/appeng/services/version/MissingVersion.java @@ -18,30 +18,25 @@ package appeng.services.version; - /** * Exceptional template when the {@link Version} could not be retrieved */ -public final class MissingVersion extends BaseVersion -{ - public MissingVersion() - { - super( 0, Channel.Alpha, 0 ); - } +public final class MissingVersion extends BaseVersion { + public MissingVersion() { + super(0, Channel.Alpha, 0); + } - /** - * @param maybeOlder ignored - * @return false - */ - @Override - public boolean isNewerAs( final Version maybeOlder ) - { - return false; - } + /** + * @param maybeOlder ignored + * @return false + */ + @Override + public boolean isNewerAs(final Version maybeOlder) { + return false; + } - @Override - public String formatted() - { - return "missing"; - } + @Override + public String formatted() { + return "missing"; + } } diff --git a/src/main/java/appeng/services/version/ModVersionFetcher.java b/src/main/java/appeng/services/version/ModVersionFetcher.java index 36b4fbeaf5d..b8d68fea4ab 100644 --- a/src/main/java/appeng/services/version/ModVersionFetcher.java +++ b/src/main/java/appeng/services/version/ModVersionFetcher.java @@ -18,58 +18,49 @@ package appeng.services.version; - import appeng.core.AELog; import appeng.services.version.exceptions.VersionCheckerException; - import javax.annotation.Nonnull; - /** * Wrapper for {@link VersionParser} to check if the check is happening in developer environment or in a pull request. *

* In that case ignore the check. */ -public final class ModVersionFetcher implements VersionFetcher -{ - private static final Version EXCEPTIONAL_VERSION = new MissingVersion(); +public final class ModVersionFetcher implements VersionFetcher { + private static final Version EXCEPTIONAL_VERSION = new MissingVersion(); + + @Nonnull + private final String rawModVersion; - @Nonnull - private final String rawModVersion; - @Nonnull - private final VersionParser parser; + @Nonnull + private final VersionParser parser; - public ModVersionFetcher( @Nonnull final String rawModVersion, @Nonnull final VersionParser parser ) - { - this.rawModVersion = rawModVersion; - this.parser = parser; - } + public ModVersionFetcher(@Nonnull final String rawModVersion, @Nonnull final VersionParser parser) { + this.rawModVersion = rawModVersion; + this.parser = parser; + } - /** - * Parses only, if not checked in developer environment or in a pull request - * - * @return {@link DoNotCheckVersion} if in developer environment or pull request, {@link MissingVersion} in case of - * a parser exception or else the parsed {@link Version}. - */ - @Override - public Version get() - { - if( this.rawModVersion.equals( "@version@" ) || this.rawModVersion.contains( "pr" ) ) - { - return new DoNotCheckVersion(); - } + /** + * Parses only, if not checked in developer environment or in a pull request + * + * @return {@link DoNotCheckVersion} if in developer environment or pull request, {@link MissingVersion} in case of + * a parser exception or else the parsed {@link Version}. + */ + @Override + public Version get() { + if (this.rawModVersion.equals("@version@") || this.rawModVersion.contains("pr")) { + return new DoNotCheckVersion(); + } - try - { - final Version version = this.parser.parse( this.rawModVersion ); + try { + final Version version = this.parser.parse(this.rawModVersion); - return version; - } - catch( final VersionCheckerException e ) - { - AELog.debug( e ); + return version; + } catch (final VersionCheckerException e) { + AELog.debug(e); - return EXCEPTIONAL_VERSION; - } - } + return EXCEPTIONAL_VERSION; + } + } } diff --git a/src/main/java/appeng/services/version/Version.java b/src/main/java/appeng/services/version/Version.java index 1e3c1925188..9d669a86388 100644 --- a/src/main/java/appeng/services/version/Version.java +++ b/src/main/java/appeng/services/version/Version.java @@ -18,43 +18,41 @@ package appeng.services.version; - /** * Stores version information, which are easily compared */ -public interface Version -{ - /** - * @return revision of this version - */ - int revision(); +public interface Version { + /** + * @return revision of this version + */ + int revision(); - /** - * @return channel of this version - */ - Channel channel(); + /** + * @return channel of this version + */ + Channel channel(); - /** - * @return build of this version - */ - int build(); + /** + * @return build of this version + */ + int build(); - /** - * A version is never if these criteria are met: - * if the current revision is higher than the compared revision OR - * if revision are equal and the current channel is higher than the compared channel (Stable > Beta > Alpha) OR - * if revision, channel are equal and the build is higher than the compared build - * - * @return true if criteria are met - */ - boolean isNewerAs( Version maybeOlder ); + /** + * A version is never if these criteria are met: + * if the current revision is higher than the compared revision OR + * if revision are equal and the current channel is higher than the compared channel (Stable > Beta > Alpha) OR + * if revision, channel are equal and the build is higher than the compared build + * + * @return true if criteria are met + */ + boolean isNewerAs(Version maybeOlder); - /** - * Prints the revision, channel and build into a common displayed way - *

- * rv2-beta-8 - * - * @return formatted version - */ - String formatted(); + /** + * Prints the revision, channel and build into a common displayed way + *

+ * rv2-beta-8 + * + * @return formatted version + */ + String formatted(); } diff --git a/src/main/java/appeng/services/version/VersionCheckerConfig.java b/src/main/java/appeng/services/version/VersionCheckerConfig.java index 7c9968c778d..0a1ebfe531f 100644 --- a/src/main/java/appeng/services/version/VersionCheckerConfig.java +++ b/src/main/java/appeng/services/version/VersionCheckerConfig.java @@ -18,110 +18,120 @@ package appeng.services.version; - import com.google.common.base.Preconditions; -import net.minecraftforge.common.config.Configuration; - -import javax.annotation.Nonnull; import java.io.File; import java.util.Date; - +import javax.annotation.Nonnull; +import net.minecraftforge.common.config.Configuration; /** * Separate config file to handle the version checker */ -public final class VersionCheckerConfig -{ - private static final int DEFAULT_INTERVAL_HOURS = 24; - private static final int MIN_INTERVAL_HOURS = 0; - private static final int MAX_INTERVAL_HOURS = 7 * 24; - - @Nonnull - private final Configuration config; - - private final boolean isEnabled; - - @Nonnull - private final String lastCheck; - private final int interval; - - @Nonnull - private final String level; - - private final boolean shouldNotifyPlayer; - private final boolean shouldPostChangelog; - - /** - * @param file requires fully qualified file in which the config is saved - */ - public VersionCheckerConfig( @Nonnull final File file ) - { - Preconditions.checkNotNull( file ); - Preconditions.checkState( !file.isDirectory() ); - - this.config = new Configuration( file ); - - // initializes default values by caching - this.isEnabled = this.config.getBoolean( "enabled", "general", true, "If true, the version checker is enabled. Acts as a master switch." ); - - this.lastCheck = this.config.getString( "lastCheck", "cache", "0", "The number of milliseconds since January 1, 1970, 00:00:00 GMT of the last successful check." ); - this.interval = this.config.getInt( "interval", "cache", DEFAULT_INTERVAL_HOURS, MIN_INTERVAL_HOURS, MAX_INTERVAL_HOURS, "Waits as many hours, until it checks again." ); - - this.level = this.config.getString( "level", "channel", "Beta", "Determines the channel level which should be checked for updates. Can be either Stable, Beta or Alpha." ); - - this.shouldNotifyPlayer = this.config.getBoolean( "notify", "client", true, "If true, the player is getting a notification, that a new version is available." ); - this.shouldPostChangelog = this.config.getBoolean( "changelog", "client", true, "If true, the player is getting a notification including changelog. Only happens if notification are enabled." ); - } - - public boolean isVersionCheckingEnabled() - { - return this.isEnabled; - } - - public String lastCheck() - { - return this.lastCheck; - } - - /** - * Stores the current date in milli seconds into the "lastCheck" field of the config and makes it persistent. - */ - public void updateLastCheck() - { - final Date now = new Date(); - final long nowInMs = now.getTime(); - final String nowAsString = Long.toString( nowInMs ); - - this.config.get( "cache", "lastCheck", "0" ).set( nowAsString ); - - this.config.save(); - } - - public int interval() - { - return this.interval; - } - - public String level() - { - return this.level; - } - - public boolean shouldNotifyPlayer() - { - return this.shouldNotifyPlayer; - } - - public boolean shouldPostChangelog() - { - return this.shouldPostChangelog; - } - - public void save() - { - if( this.config.hasChanged() ) - { - this.config.save(); - } - } +public final class VersionCheckerConfig { + private static final int DEFAULT_INTERVAL_HOURS = 24; + private static final int MIN_INTERVAL_HOURS = 0; + private static final int MAX_INTERVAL_HOURS = 7 * 24; + + @Nonnull + private final Configuration config; + + private final boolean isEnabled; + + @Nonnull + private final String lastCheck; + + private final int interval; + + @Nonnull + private final String level; + + private final boolean shouldNotifyPlayer; + private final boolean shouldPostChangelog; + + /** + * @param file requires fully qualified file in which the config is saved + */ + public VersionCheckerConfig(@Nonnull final File file) { + Preconditions.checkNotNull(file); + Preconditions.checkState(!file.isDirectory()); + + this.config = new Configuration(file); + + // initializes default values by caching + this.isEnabled = this.config.getBoolean( + "enabled", "general", true, "If true, the version checker is enabled. Acts as a master switch."); + + this.lastCheck = this.config.getString( + "lastCheck", + "cache", + "0", + "The number of milliseconds since January 1, 1970, 00:00:00 GMT of the last successful check."); + this.interval = this.config.getInt( + "interval", + "cache", + DEFAULT_INTERVAL_HOURS, + MIN_INTERVAL_HOURS, + MAX_INTERVAL_HOURS, + "Waits as many hours, until it checks again."); + + this.level = this.config.getString( + "level", + "channel", + "Beta", + "Determines the channel level which should be checked for updates. Can be either Stable, Beta or Alpha."); + + this.shouldNotifyPlayer = this.config.getBoolean( + "notify", + "client", + true, + "If true, the player is getting a notification, that a new version is available."); + this.shouldPostChangelog = this.config.getBoolean( + "changelog", + "client", + true, + "If true, the player is getting a notification including changelog. Only happens if notification are enabled."); + } + + public boolean isVersionCheckingEnabled() { + return this.isEnabled; + } + + public String lastCheck() { + return this.lastCheck; + } + + /** + * Stores the current date in milli seconds into the "lastCheck" field of the config and makes it persistent. + */ + public void updateLastCheck() { + final Date now = new Date(); + final long nowInMs = now.getTime(); + final String nowAsString = Long.toString(nowInMs); + + this.config.get("cache", "lastCheck", "0").set(nowAsString); + + this.config.save(); + } + + public int interval() { + return this.interval; + } + + public String level() { + return this.level; + } + + public boolean shouldNotifyPlayer() { + return this.shouldNotifyPlayer; + } + + public boolean shouldPostChangelog() { + return this.shouldPostChangelog; + } + + public void save() { + if (this.config.hasChanged()) { + this.config.save(); + } + } } diff --git a/src/main/java/appeng/services/version/VersionFetcher.java b/src/main/java/appeng/services/version/VersionFetcher.java index c30faddf0c0..b343ac0f98c 100644 --- a/src/main/java/appeng/services/version/VersionFetcher.java +++ b/src/main/java/appeng/services/version/VersionFetcher.java @@ -18,11 +18,9 @@ package appeng.services.version; - /** * Processes base information to retrieve a {@link Version} */ -public interface VersionFetcher -{ - Version get(); +public interface VersionFetcher { + Version get(); } diff --git a/src/main/java/appeng/services/version/VersionParser.java b/src/main/java/appeng/services/version/VersionParser.java index d5d73cf80ec..6b7cfdb650c 100644 --- a/src/main/java/appeng/services/version/VersionParser.java +++ b/src/main/java/appeng/services/version/VersionParser.java @@ -18,163 +18,148 @@ package appeng.services.version; - import appeng.services.version.exceptions.*; import com.google.common.base.Preconditions; - -import javax.annotation.Nonnull; import java.util.Scanner; import java.util.regex.Pattern; - +import javax.annotation.Nonnull; /** * can parse a version in form of rv2-beta-8 or rv2.beta.8 */ -public final class VersionParser -{ - private static final Pattern PATTERN_DOT = Pattern.compile( "\\." ); - private static final Pattern PATTERN_DASH = Pattern.compile( "-" ); - private static final Pattern PATTERN_REVISION = Pattern.compile( "[^0-9]+" ); - private static final Pattern PATTERN_BUILD = Pattern.compile( "[^0-9]+" ); - private static final Pattern PATTERN_NATURAL = Pattern.compile( "[0-9]+" ); - private static final Pattern PATTERN_VALID_REVISION = Pattern.compile( "^rv\\d+$" ); - - /** - * Parses the {@link Version} out of a String - * - * @param raw String in form of rv2-beta-8 or rv2.beta.8 - * @return {@link Version} encoded in the raw String - * @throws VersionCheckerException if parsing the raw string was not successful. - */ - public Version parse( @Nonnull final String raw ) throws VersionCheckerException - { - Preconditions.checkNotNull( raw ); - - final String transformed = this.transformDelimiter( raw ); - final String[] split = transformed.split( "_" ); - - return this.parseVersion( split ); - } - - /** - * Replaces all "." and "-" into "_" to make them uniform - * - * @param raw raw version string containing "." or "-" - * @return transformed raw, where "." and "-" are replaced by "_" - * @throws MissingSeparatorException if not containing valid separators - */ - private String transformDelimiter( @Nonnull final String raw ) throws MissingSeparatorException - { - if( !( raw.contains( "." ) || raw.contains( "-" ) ) ) - { - throw new MissingSeparatorException(); - } - - final String withoutDot = PATTERN_DOT.matcher( raw ).replaceAll( "_" ); - final String withoutDash = PATTERN_DASH.matcher( withoutDot ).replaceAll( "_" ); - - return withoutDash; - } - - /** - * parses the {@link Version} out of the split. - * The split must have a length of 3, - * representing revision, channel and build. - * - * @param splitRaw raw version split with length of 3 - * @return {@link Version} represented by the splitRaw - * @throws InvalidVersionException when length not 3 - * @throws InvalidRevisionException {@link VersionParser#parseRevision(String)} - * @throws InvalidChannelException {@link VersionParser#parseChannel(String)} - * @throws InvalidBuildException {@link VersionParser#parseBuild(String)} - */ - private Version parseVersion( @Nonnull final String[] splitRaw ) - throws InvalidVersionException, InvalidRevisionException, InvalidChannelException, InvalidBuildException - { - if( splitRaw.length != 3 ) - { - throw new InvalidVersionException(); - } - - final String rawRevision = splitRaw[0]; - final String rawChannel = splitRaw[1]; - final String rawBuild = splitRaw[2]; - - final int revision = this.parseRevision( rawRevision ); - final Channel channel = this.parseChannel( rawChannel ); - final int build = this.parseBuild( rawBuild ); - - return new DefaultVersion( revision, channel, build ); - } - - /** - * A revision starts with the keyword "rv", followed by a natural number - * - * @param rawRevision String containing the revision number - * @return revision number - * @throws InvalidRevisionException if not matching "rv" followed by a natural number. - */ - private int parseRevision( @Nonnull final String rawRevision ) throws InvalidRevisionException - { - if( !PATTERN_VALID_REVISION.matcher( rawRevision ).matches() ) - { - throw new InvalidRevisionException(); - } - - final Scanner scanner = new Scanner( rawRevision ); - - final int revision = scanner.useDelimiter( PATTERN_REVISION ).nextInt(); - - scanner.close(); - - return revision; - } - - /** - * A channel is atm either one of {@link Channel#Alpha}, {@link Channel#Beta} or {@link Channel#Stable} - * - * @param rawChannel String containing the channel - * @return matching {@link Channel} to the String - * @throws InvalidChannelException if not one of {@link Channel} values. - */ - private Channel parseChannel( @Nonnull final String rawChannel ) throws InvalidChannelException - { - if( !( rawChannel.equalsIgnoreCase( Channel.Alpha.name() ) || rawChannel.equalsIgnoreCase( Channel.Beta.name() ) || rawChannel.equalsIgnoreCase( Channel.Stable.name() ) ) ) - { - throw new InvalidChannelException(); - } - - for( final Channel channel : Channel.values() ) - { - if( channel.name().equalsIgnoreCase( rawChannel ) ) - { - return channel; - } - } - - throw new InvalidChannelException(); - } - - /** - * A build is just a natural number - * - * @param rawBuild String containing the build number - * @return build number - * @throws InvalidBuildException if not a natural number. - */ - private int parseBuild( @Nonnull final String rawBuild ) throws InvalidBuildException - { - if( !PATTERN_NATURAL.matcher( rawBuild ).matches() ) - { - throw new InvalidBuildException(); - } - - final Scanner scanner = new Scanner( rawBuild ); - - final int build = scanner.useDelimiter( PATTERN_BUILD ).nextInt(); - - scanner.close(); - - return build; - } +public final class VersionParser { + private static final Pattern PATTERN_DOT = Pattern.compile("\\."); + private static final Pattern PATTERN_DASH = Pattern.compile("-"); + private static final Pattern PATTERN_REVISION = Pattern.compile("[^0-9]+"); + private static final Pattern PATTERN_BUILD = Pattern.compile("[^0-9]+"); + private static final Pattern PATTERN_NATURAL = Pattern.compile("[0-9]+"); + private static final Pattern PATTERN_VALID_REVISION = Pattern.compile("^rv\\d+$"); + + /** + * Parses the {@link Version} out of a String + * + * @param raw String in form of rv2-beta-8 or rv2.beta.8 + * @return {@link Version} encoded in the raw String + * @throws VersionCheckerException if parsing the raw string was not successful. + */ + public Version parse(@Nonnull final String raw) throws VersionCheckerException { + Preconditions.checkNotNull(raw); + + final String transformed = this.transformDelimiter(raw); + final String[] split = transformed.split("_"); + + return this.parseVersion(split); + } + + /** + * Replaces all "." and "-" into "_" to make them uniform + * + * @param raw raw version string containing "." or "-" + * @return transformed raw, where "." and "-" are replaced by "_" + * @throws MissingSeparatorException if not containing valid separators + */ + private String transformDelimiter(@Nonnull final String raw) throws MissingSeparatorException { + if (!(raw.contains(".") || raw.contains("-"))) { + throw new MissingSeparatorException(); + } + + final String withoutDot = PATTERN_DOT.matcher(raw).replaceAll("_"); + final String withoutDash = PATTERN_DASH.matcher(withoutDot).replaceAll("_"); + + return withoutDash; + } + + /** + * parses the {@link Version} out of the split. + * The split must have a length of 3, + * representing revision, channel and build. + * + * @param splitRaw raw version split with length of 3 + * @return {@link Version} represented by the splitRaw + * @throws InvalidVersionException when length not 3 + * @throws InvalidRevisionException {@link VersionParser#parseRevision(String)} + * @throws InvalidChannelException {@link VersionParser#parseChannel(String)} + * @throws InvalidBuildException {@link VersionParser#parseBuild(String)} + */ + private Version parseVersion(@Nonnull final String[] splitRaw) + throws InvalidVersionException, InvalidRevisionException, InvalidChannelException, InvalidBuildException { + if (splitRaw.length != 3) { + throw new InvalidVersionException(); + } + + final String rawRevision = splitRaw[0]; + final String rawChannel = splitRaw[1]; + final String rawBuild = splitRaw[2]; + + final int revision = this.parseRevision(rawRevision); + final Channel channel = this.parseChannel(rawChannel); + final int build = this.parseBuild(rawBuild); + + return new DefaultVersion(revision, channel, build); + } + + /** + * A revision starts with the keyword "rv", followed by a natural number + * + * @param rawRevision String containing the revision number + * @return revision number + * @throws InvalidRevisionException if not matching "rv" followed by a natural number. + */ + private int parseRevision(@Nonnull final String rawRevision) throws InvalidRevisionException { + if (!PATTERN_VALID_REVISION.matcher(rawRevision).matches()) { + throw new InvalidRevisionException(); + } + + final Scanner scanner = new Scanner(rawRevision); + + final int revision = scanner.useDelimiter(PATTERN_REVISION).nextInt(); + + scanner.close(); + + return revision; + } + + /** + * A channel is atm either one of {@link Channel#Alpha}, {@link Channel#Beta} or {@link Channel#Stable} + * + * @param rawChannel String containing the channel + * @return matching {@link Channel} to the String + * @throws InvalidChannelException if not one of {@link Channel} values. + */ + private Channel parseChannel(@Nonnull final String rawChannel) throws InvalidChannelException { + if (!(rawChannel.equalsIgnoreCase(Channel.Alpha.name()) + || rawChannel.equalsIgnoreCase(Channel.Beta.name()) + || rawChannel.equalsIgnoreCase(Channel.Stable.name()))) { + throw new InvalidChannelException(); + } + + for (final Channel channel : Channel.values()) { + if (channel.name().equalsIgnoreCase(rawChannel)) { + return channel; + } + } + + throw new InvalidChannelException(); + } + + /** + * A build is just a natural number + * + * @param rawBuild String containing the build number + * @return build number + * @throws InvalidBuildException if not a natural number. + */ + private int parseBuild(@Nonnull final String rawBuild) throws InvalidBuildException { + if (!PATTERN_NATURAL.matcher(rawBuild).matches()) { + throw new InvalidBuildException(); + } + + final Scanner scanner = new Scanner(rawBuild); + + final int build = scanner.useDelimiter(PATTERN_BUILD).nextInt(); + + scanner.close(); + + return build; + } } diff --git a/src/main/java/appeng/services/version/exceptions/InvalidBuildException.java b/src/main/java/appeng/services/version/exceptions/InvalidBuildException.java index b704901609f..6d3d9bbff07 100644 --- a/src/main/java/appeng/services/version/exceptions/InvalidBuildException.java +++ b/src/main/java/appeng/services/version/exceptions/InvalidBuildException.java @@ -18,16 +18,13 @@ package appeng.services.version.exceptions; - /** * Indicates a invalid build number, which is any string except a natural number. */ -public class InvalidBuildException extends VersionCheckerException -{ - private static final long serialVersionUID = 3015432444672364991L; +public class InvalidBuildException extends VersionCheckerException { + private static final long serialVersionUID = 3015432444672364991L; - public InvalidBuildException() - { - super( "Invalid Build: Needs to be a natural number." ); - } + public InvalidBuildException() { + super("Invalid Build: Needs to be a natural number."); + } } diff --git a/src/main/java/appeng/services/version/exceptions/InvalidChannelException.java b/src/main/java/appeng/services/version/exceptions/InvalidChannelException.java index 824d1f87d83..b9e35b77ebc 100644 --- a/src/main/java/appeng/services/version/exceptions/InvalidChannelException.java +++ b/src/main/java/appeng/services/version/exceptions/InvalidChannelException.java @@ -18,19 +18,15 @@ package appeng.services.version.exceptions; - import appeng.services.version.Channel; - /** * Indicates an invalid {@link Channel} value. */ -public class InvalidChannelException extends VersionCheckerException -{ - private static final long serialVersionUID = -1306378515002341620L; +public class InvalidChannelException extends VersionCheckerException { + private static final long serialVersionUID = -1306378515002341620L; - public InvalidChannelException() - { - super( "Invalid Channel: Needs to be one of the following values; alpha, beta, or stable." ); - } + public InvalidChannelException() { + super("Invalid Channel: Needs to be one of the following values; alpha, beta, or stable."); + } } diff --git a/src/main/java/appeng/services/version/exceptions/InvalidRevisionException.java b/src/main/java/appeng/services/version/exceptions/InvalidRevisionException.java index 02a155ce019..897b6a1ec92 100644 --- a/src/main/java/appeng/services/version/exceptions/InvalidRevisionException.java +++ b/src/main/java/appeng/services/version/exceptions/InvalidRevisionException.java @@ -18,17 +18,14 @@ package appeng.services.version.exceptions; - /** * Indicates a invalid revision, which does not match the pattern "rv" followed by a natural number. */ -public class InvalidRevisionException extends VersionCheckerException -{ +public class InvalidRevisionException extends VersionCheckerException { - private static final long serialVersionUID = 4828906902143875942L; + private static final long serialVersionUID = 4828906902143875942L; - public InvalidRevisionException() - { - super( "Invalid Revision: Needs to be 'rv' followd by a natural number." ); - } + public InvalidRevisionException() { + super("Invalid Revision: Needs to be 'rv' followd by a natural number."); + } } diff --git a/src/main/java/appeng/services/version/exceptions/InvalidVersionException.java b/src/main/java/appeng/services/version/exceptions/InvalidVersionException.java index 1985bc7609f..c8bf008cccd 100644 --- a/src/main/java/appeng/services/version/exceptions/InvalidVersionException.java +++ b/src/main/java/appeng/services/version/exceptions/InvalidVersionException.java @@ -18,17 +18,14 @@ package appeng.services.version.exceptions; - /** * Indicates an invalid version, which does not consists of 3 parts matching /(rv\d+)-(alpha|beta|stable)-(b\d+)/. */ -public class InvalidVersionException extends VersionCheckerException -{ +public class InvalidVersionException extends VersionCheckerException { - private static final long serialVersionUID = 4828906902143875942L; + private static final long serialVersionUID = 4828906902143875942L; - public InvalidVersionException() - { - super( "Invalid Version Format: Need to consist of exactly 3 parts separated by a dash." ); - } + public InvalidVersionException() { + super("Invalid Version Format: Need to consist of exactly 3 parts separated by a dash."); + } } diff --git a/src/main/java/appeng/services/version/exceptions/MissingSeparatorException.java b/src/main/java/appeng/services/version/exceptions/MissingSeparatorException.java index 7c1af0f086b..3360c430a62 100644 --- a/src/main/java/appeng/services/version/exceptions/MissingSeparatorException.java +++ b/src/main/java/appeng/services/version/exceptions/MissingSeparatorException.java @@ -18,18 +18,15 @@ package appeng.services.version.exceptions; - /** * Indicates a version without a valid separator. *

* Valid separators are a dash ("-") or dot (".") */ -public class MissingSeparatorException extends VersionCheckerException -{ - private static final long serialVersionUID = 8366370192017020750L; +public class MissingSeparatorException extends VersionCheckerException { + private static final long serialVersionUID = 8366370192017020750L; - public MissingSeparatorException() - { - super( "Invalid Revision: Needs to match 'rv' followed by a natural number." ); - } + public MissingSeparatorException() { + super("Invalid Revision: Needs to match 'rv' followed by a natural number."); + } } diff --git a/src/main/java/appeng/services/version/exceptions/VersionCheckerException.java b/src/main/java/appeng/services/version/exceptions/VersionCheckerException.java index caf373b7e3a..7358dd7e712 100644 --- a/src/main/java/appeng/services/version/exceptions/VersionCheckerException.java +++ b/src/main/java/appeng/services/version/exceptions/VersionCheckerException.java @@ -18,19 +18,15 @@ package appeng.services.version.exceptions; - import javax.annotation.Nonnull; - /** * A super class for any exception thrown by the version checker for easier handling. */ -public class VersionCheckerException extends Exception -{ - private static final long serialVersionUID = 4582501864800542884L; +public class VersionCheckerException extends Exception { + private static final long serialVersionUID = 4582501864800542884L; - public VersionCheckerException( @Nonnull String string ) - { - super( string ); - } + public VersionCheckerException(@Nonnull String string) { + super(string); + } } diff --git a/src/main/java/appeng/services/version/github/DefaultFormattedRelease.java b/src/main/java/appeng/services/version/github/DefaultFormattedRelease.java index b2269d19ea9..a4c8ad34467 100644 --- a/src/main/java/appeng/services/version/github/DefaultFormattedRelease.java +++ b/src/main/java/appeng/services/version/github/DefaultFormattedRelease.java @@ -18,37 +18,31 @@ package appeng.services.version.github; - import appeng.services.version.Version; - import javax.annotation.Nonnull; - /** * Default template when a {@link FormattedRelease} is needed. */ -public final class DefaultFormattedRelease implements FormattedRelease -{ - @Nonnull - private final Version version; - @Nonnull - private final String changelog; - - public DefaultFormattedRelease( @Nonnull final Version version, @Nonnull final String changelog ) - { - this.version = version; - this.changelog = changelog; - } - - @Override - public String changelog() - { - return this.changelog; - } - - @Override - public Version version() - { - return this.version; - } +public final class DefaultFormattedRelease implements FormattedRelease { + @Nonnull + private final Version version; + + @Nonnull + private final String changelog; + + public DefaultFormattedRelease(@Nonnull final Version version, @Nonnull final String changelog) { + this.version = version; + this.changelog = changelog; + } + + @Override + public String changelog() { + return this.changelog; + } + + @Override + public Version version() { + return this.version; + } } diff --git a/src/main/java/appeng/services/version/github/FormattedRelease.java b/src/main/java/appeng/services/version/github/FormattedRelease.java index fef5ae2fa04..2e2fdb40ff5 100644 --- a/src/main/java/appeng/services/version/github/FormattedRelease.java +++ b/src/main/java/appeng/services/version/github/FormattedRelease.java @@ -18,22 +18,19 @@ package appeng.services.version.github; - import appeng.services.version.Version; - /** * Represents the acquired, processed information through github about a release of Applied Energistics 2 */ -public interface FormattedRelease -{ - /** - * @return changelog - */ - String changelog(); +public interface FormattedRelease { + /** + * @return changelog + */ + String changelog(); - /** - * @return processed version - */ - Version version(); + /** + * @return processed version + */ + Version version(); } diff --git a/src/main/java/appeng/services/version/github/MissingFormattedRelease.java b/src/main/java/appeng/services/version/github/MissingFormattedRelease.java index b7ebd93cab7..95fe4c01f95 100644 --- a/src/main/java/appeng/services/version/github/MissingFormattedRelease.java +++ b/src/main/java/appeng/services/version/github/MissingFormattedRelease.java @@ -18,41 +18,34 @@ package appeng.services.version.github; - import appeng.services.version.MissingVersion; import appeng.services.version.Version; - import javax.annotation.Nonnull; - /** * Exceptional template, when no meaningful {@link FormattedRelease} could be obtained */ -public final class MissingFormattedRelease implements FormattedRelease -{ - @Nonnull - private final Version version; - - public MissingFormattedRelease() - { - this.version = new MissingVersion(); - } - - /** - * @return empty string - */ - @Override - public String changelog() - { - return ""; - } - - /** - * @return {@link MissingVersion} - */ - @Override - public Version version() - { - return this.version; - } +public final class MissingFormattedRelease implements FormattedRelease { + @Nonnull + private final Version version; + + public MissingFormattedRelease() { + this.version = new MissingVersion(); + } + + /** + * @return empty string + */ + @Override + public String changelog() { + return ""; + } + + /** + * @return {@link MissingVersion} + */ + @Override + public Version version() { + return this.version; + } } diff --git a/src/main/java/appeng/services/version/github/Release.java b/src/main/java/appeng/services/version/github/Release.java index 26eecd8c83a..db61d4ec3aa 100644 --- a/src/main/java/appeng/services/version/github/Release.java +++ b/src/main/java/appeng/services/version/github/Release.java @@ -18,19 +18,17 @@ package appeng.services.version.github; - /** * Template class for Gson to write values from the Json Object into an actual class */ -public class Release -{ - /** - * name of the tag it is saved - */ - public String tag_name; +public class Release { + /** + * name of the tag it is saved + */ + public String tag_name; - /** - * Contains the changelog - */ - public String body; + /** + * Contains the changelog + */ + public String body; } diff --git a/src/main/java/appeng/services/version/github/ReleaseFetcher.java b/src/main/java/appeng/services/version/github/ReleaseFetcher.java index a072cc4e03d..b87bf7aa722 100644 --- a/src/main/java/appeng/services/version/github/ReleaseFetcher.java +++ b/src/main/java/appeng/services/version/github/ReleaseFetcher.java @@ -18,7 +18,6 @@ package appeng.services.version.github; - import appeng.core.AELog; import appeng.services.version.Channel; import appeng.services.version.Version; @@ -27,93 +26,77 @@ import appeng.services.version.exceptions.VersionCheckerException; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; -import org.apache.commons.io.IOUtils; - -import javax.annotation.Nonnull; import java.io.IOException; import java.lang.reflect.Type; import java.net.MalformedURLException; import java.net.URL; import java.util.List; +import javax.annotation.Nonnull; +import org.apache.commons.io.IOUtils; + +public final class ReleaseFetcher { + private static final String GITHUB_RELEASES_URL = + "https://api.github.com/repos/xsun2001/Applied-Energistics-2-Unofficial/releases"; + private static final FormattedRelease EXCEPTIONAL_RELEASE = new MissingFormattedRelease(); + + @Nonnull + private final VersionCheckerConfig config; + + @Nonnull + private final VersionParser parser; + + public ReleaseFetcher(@Nonnull final VersionCheckerConfig config, @Nonnull final VersionParser parser) { + this.config = config; + this.parser = parser; + } + + public FormattedRelease get() { + final Gson gson = new Gson(); + final Type type = new ReleasesTypeToken().getType(); + + try { + final URL releasesURL = new URL(GITHUB_RELEASES_URL); + final String rawReleases = this.getRawReleases(releasesURL); + + this.config.updateLastCheck(); + + final List releases = gson.fromJson(rawReleases, type); + final FormattedRelease latestFitRelease = this.getLatestFitRelease(releases); + + return latestFitRelease; + } catch (final VersionCheckerException e) { + AELog.debug(e); + } catch (MalformedURLException e) { + AELog.debug(e); + } catch (IOException e) { + AELog.debug(e); + } + + return EXCEPTIONAL_RELEASE; + } + + private String getRawReleases(final URL url) throws IOException { + return IOUtils.toString(url); + } + + private FormattedRelease getLatestFitRelease(final Iterable releases) throws VersionCheckerException { + final String levelInConfig = this.config.level(); + final Channel level = Channel.valueOf(levelInConfig); + final int levelOrdinal = level.ordinal(); + + for (final Release release : releases) { + final String rawVersion = release.tag_name; + final String changelog = release.body; + + final Version version = this.parser.parse(rawVersion); + + if (version.channel().ordinal() >= levelOrdinal) { + return new DefaultFormattedRelease(version, changelog); + } + } + return EXCEPTIONAL_RELEASE; + } -public final class ReleaseFetcher -{ - private static final String GITHUB_RELEASES_URL = "https://api.github.com/repos/xsun2001/Applied-Energistics-2-Unofficial/releases"; - private static final FormattedRelease EXCEPTIONAL_RELEASE = new MissingFormattedRelease(); - - @Nonnull - private final VersionCheckerConfig config; - @Nonnull - private final VersionParser parser; - - public ReleaseFetcher( @Nonnull final VersionCheckerConfig config, @Nonnull final VersionParser parser ) - { - this.config = config; - this.parser = parser; - } - - public FormattedRelease get() - { - final Gson gson = new Gson(); - final Type type = new ReleasesTypeToken().getType(); - - try - { - final URL releasesURL = new URL( GITHUB_RELEASES_URL ); - final String rawReleases = this.getRawReleases( releasesURL ); - - this.config.updateLastCheck(); - - final List releases = gson.fromJson( rawReleases, type ); - final FormattedRelease latestFitRelease = this.getLatestFitRelease( releases ); - - return latestFitRelease; - } - catch( final VersionCheckerException e ) - { - AELog.debug( e ); - } - catch( MalformedURLException e ) - { - AELog.debug( e ); - } - catch( IOException e ) - { - AELog.debug( e ); - } - - return EXCEPTIONAL_RELEASE; - } - - private String getRawReleases( final URL url ) throws IOException - { - return IOUtils.toString( url ); - } - - private FormattedRelease getLatestFitRelease( final Iterable releases ) throws VersionCheckerException - { - final String levelInConfig = this.config.level(); - final Channel level = Channel.valueOf( levelInConfig ); - final int levelOrdinal = level.ordinal(); - - for( final Release release : releases ) - { - final String rawVersion = release.tag_name; - final String changelog = release.body; - - final Version version = this.parser.parse( rawVersion ); - - if( version.channel().ordinal() >= levelOrdinal ) - { - return new DefaultFormattedRelease( version, changelog ); - } - } - - return EXCEPTIONAL_RELEASE; - } - - private static final class ReleasesTypeToken extends TypeToken> - { - } + private static final class ReleasesTypeToken extends TypeToken> {} } diff --git a/src/main/java/appeng/spatial/BiomeGenStorage.java b/src/main/java/appeng/spatial/BiomeGenStorage.java index 79e9e077a70..aaaeacdc5d2 100644 --- a/src/main/java/appeng/spatial/BiomeGenStorage.java +++ b/src/main/java/appeng/spatial/BiomeGenStorage.java @@ -18,28 +18,24 @@ package appeng.spatial; - import net.minecraft.world.biome.BiomeGenBase; +public class BiomeGenStorage extends BiomeGenBase { -public class BiomeGenStorage extends BiomeGenBase -{ - - public BiomeGenStorage( final int id ) - { - super( id ); - this.setBiomeName( "Storage Cell" ); + public BiomeGenStorage(final int id) { + super(id); + this.setBiomeName("Storage Cell"); - this.setDisableRain(); - this.temperature = -100; + this.setDisableRain(); + this.temperature = -100; - this.theBiomeDecorator.treesPerChunk = 0; - this.theBiomeDecorator.flowersPerChunk = 0; - this.theBiomeDecorator.grassPerChunk = 0; + this.theBiomeDecorator.treesPerChunk = 0; + this.theBiomeDecorator.flowersPerChunk = 0; + this.theBiomeDecorator.grassPerChunk = 0; - this.spawnableMonsterList.clear(); - this.spawnableCreatureList.clear(); - this.spawnableWaterCreatureList.clear(); - this.spawnableCaveCreatureList.clear(); - } + this.spawnableMonsterList.clear(); + this.spawnableCreatureList.clear(); + this.spawnableWaterCreatureList.clear(); + this.spawnableCaveCreatureList.clear(); + } } diff --git a/src/main/java/appeng/spatial/CachedPlane.java b/src/main/java/appeng/spatial/CachedPlane.java index becb198aad1..7e1d0803da6 100644 --- a/src/main/java/appeng/spatial/CachedPlane.java +++ b/src/main/java/appeng/spatial/CachedPlane.java @@ -18,7 +18,6 @@ package appeng.spatial; - import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; import appeng.api.movable.IMovableHandler; @@ -27,6 +26,10 @@ import appeng.core.AELog; import appeng.core.worlddata.WorldData; import appeng.util.Platform; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map.Entry; import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.ChunkPosition; @@ -36,408 +39,381 @@ import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import net.minecraftforge.common.util.ForgeDirection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map.Entry; - - -public class CachedPlane -{ - private final int x_size; - private final int z_size; - private final int cx_size; - private final int cz_size; - private final int x_offset; - private final int y_offset; - private final int z_offset; - private final int y_size; - private final Chunk[][] myChunks; - private final Column[][] myColumns; - private final LinkedList tiles = new LinkedList(); - private final LinkedList ticks = new LinkedList(); - private final World world; - private final IMovableRegistry reg = AEApi.instance().registries().movable(); - private final LinkedList updates = new LinkedList(); - private final IBlockDefinition matrixFrame = AEApi.instance().definitions().blocks().matrixFrame(); - private int verticalBits; - - public CachedPlane( final World w, final int minX, final int minY, final int minZ, final int maxX, final int maxY, final int maxZ ) - { - - this.world = w; - - this.x_size = maxX - minX + 1; - this.y_size = maxY - minY + 1; - this.z_size = maxZ - minZ + 1; - - this.x_offset = minX; - this.y_offset = minY; - this.z_offset = minZ; - - final int minCX = minX >> 4; - final int minCY = minY >> 4; - final int minCZ = minZ >> 4; - final int maxCX = maxX >> 4; - final int maxCY = maxY >> 4; - final int maxCZ = maxZ >> 4; - - this.cx_size = maxCX - minCX + 1; - final int cy_size = maxCY - minCY + 1; - this.cz_size = maxCZ - minCZ + 1; - - this.myChunks = new Chunk[this.cx_size][this.cz_size]; - this.myColumns = new Column[this.x_size][this.z_size]; - - this.verticalBits = 0; - for( int cy = 0; cy < cy_size; cy++ ) - { - this.verticalBits |= 1 << ( minCY + cy ); - } - - for( int x = 0; x < this.x_size; x++ ) - { - for( int z = 0; z < this.z_size; z++ ) - { - this.myColumns[x][z] = new Column( w.getChunkFromChunkCoords( ( minX + x ) >> 4, ( minZ + z ) >> 4 ), ( minX + x ) & 0xF, ( minZ + z ) & 0xF, minCY, cy_size ); - } - } - - final IMovableRegistry mr = AEApi.instance().registries().movable(); - - for( int cx = 0; cx < this.cx_size; cx++ ) - { - for( int cz = 0; cz < this.cz_size; cz++ ) - { - final LinkedList> rawTiles = new LinkedList>(); - final LinkedList deadTiles = new LinkedList(); - - final Chunk c = w.getChunkFromChunkCoords( minCX + cx, minCZ + cz ); - this.myChunks[cx][cz] = c; - - rawTiles.addAll( ( (HashMap) c.chunkTileEntityMap ).entrySet() ); - for( final Entry tx : rawTiles ) - { - final ChunkPosition cp = tx.getKey(); - final TileEntity te = tx.getValue(); - if( te.xCoord >= minX && te.xCoord <= maxX && te.yCoord >= minY && te.yCoord <= maxY && te.zCoord >= minZ && te.zCoord <= maxZ ) - { - if( mr.askToMove( te ) ) - { - this.tiles.add( te ); - deadTiles.add( cp ); - } - else - { - final Object[] details = this.myColumns[te.xCoord - minX][te.zCoord - minZ].getDetails( te.yCoord ); - final Block blk = (Block) details[0]; - - // don't skip air, just let the code replace it... - if( blk != null && blk.isAir( c.worldObj, te.xCoord, te.yCoord, te.zCoord ) && blk.isReplaceable( c.worldObj, te.xCoord, te.yCoord, te.zCoord ) ) - { - c.worldObj.setBlock( te.xCoord, te.yCoord, te.zCoord, Platform.AIR_BLOCK ); - c.worldObj.notifyBlocksOfNeighborChange( te.xCoord, te.yCoord, te.zCoord, Platform.AIR_BLOCK ); - } - else - { - this.myColumns[te.xCoord - minX][te.zCoord - minZ].setSkip( te.yCoord ); - } - } - } - } - - for( final ChunkPosition cp : deadTiles ) - { - c.chunkTileEntityMap.remove( cp ); - } - - final long k = this.getWorld().getTotalWorldTime(); - final List list = this.getWorld().getPendingBlockUpdates( c, false ); - if( list != null ) - { - for( final Object o : list ) - { - final NextTickListEntry entry = (NextTickListEntry) o; - if( entry.xCoord >= minX && entry.xCoord <= maxX && entry.yCoord >= minY && entry.yCoord <= maxY && entry.zCoord >= minZ && entry.zCoord <= maxZ ) - { - final NextTickListEntry newEntry = new NextTickListEntry( entry.xCoord, entry.yCoord, entry.zCoord, entry.func_151351_a() ); - newEntry.scheduledTime = entry.scheduledTime - k; - this.ticks.add( newEntry ); - } - } - } - } - } - - for( final TileEntity te : this.tiles ) - { - try - { - this.getWorld().loadedTileEntityList.remove( te ); - } - catch( final Exception e ) - { - AELog.debug( e ); - } - } - } - - private IMovableHandler getHandler( final TileEntity te ) - { - final IMovableRegistry mr = AEApi.instance().registries().movable(); - return mr.getHandler( te ); - } - - void swap( final CachedPlane dst ) - { - final IMovableRegistry mr = AEApi.instance().registries().movable(); - - if( dst.x_size == this.x_size && dst.y_size == this.y_size && dst.z_size == this.z_size ) - { - AELog.info( "Block Copy Scale: " + this.x_size + ", " + this.y_size + ", " + this.z_size ); - - long startTime = System.nanoTime(); - - for( int x = 0; x < this.x_size; x++ ) - { - for( int z = 0; z < this.z_size; z++ ) - { - final Column a = this.myColumns[x][z]; - final Column b = dst.myColumns[x][z]; - - for( int y = 0; y < this.y_size; y++ ) - { - final int src_y = y + this.y_offset; - final int dst_y = y + dst.y_offset; - - if( a.doNotSkip( src_y ) && b.doNotSkip( dst_y ) ) - { - final Object[] aD = a.getDetails( src_y ); - final Object[] bD = b.getDetails( dst_y ); - - a.setBlockIDWithMetadata( src_y, bD ); - b.setBlockIDWithMetadata( dst_y, aD ); - } - else - { - this.markForUpdate( x + this.x_offset, src_y, z + this.z_offset ); - dst.markForUpdate( x + dst.x_offset, dst_y, z + dst.z_offset ); - } - } - } - } - - long endTime = System.nanoTime(); - long duration = endTime - startTime; - AELog.info( "Block Copy Time: " + duration ); - - for( final TileEntity te : this.tiles ) - { - dst.addTile( te.xCoord - this.x_offset, te.yCoord - this.y_offset, te.zCoord - this.z_offset, te, this, mr ); - } - - for( final TileEntity te : dst.tiles ) - { - this.addTile( te.xCoord - dst.x_offset, te.yCoord - dst.y_offset, te.zCoord - dst.z_offset, te, dst, mr ); - } - - for( final NextTickListEntry entry : this.ticks ) - { - dst.addTick( entry.xCoord - this.x_offset, entry.yCoord - this.y_offset, entry.zCoord - this.z_offset, entry ); - } - - for( final NextTickListEntry entry : dst.ticks ) - { - this.addTick( entry.xCoord - dst.x_offset, entry.yCoord - dst.y_offset, entry.zCoord - dst.z_offset, entry ); - } - - startTime = System.nanoTime(); - this.updateChunks(); - dst.updateChunks(); - endTime = System.nanoTime(); - - duration = endTime - startTime; - AELog.info( "Update Time: " + duration ); - } - } - - private void markForUpdate( final int x, final int y, final int z ) - { - this.getUpdates().add( new WorldCoord( x, y, z ) ); - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - this.getUpdates().add( new WorldCoord( x + d.offsetX, y + d.offsetY, z + d.offsetZ ) ); - } - } - - private void addTick( final int x, final int y, final int z, final NextTickListEntry entry ) - { - this.getWorld().scheduleBlockUpdate( x + this.x_offset, y + this.y_offset, z + this.z_offset, entry.func_151351_a(), (int) entry.scheduledTime ); - } - - private void addTile( final int x, final int y, final int z, final TileEntity te, final CachedPlane alternateDestination, final IMovableRegistry mr ) - { - try - { - final Column c = this.myColumns[x][z]; - - if( c.doNotSkip( y + this.y_offset ) || alternateDestination == null ) - { - final IMovableHandler handler = this.getHandler( te ); - - try - { - handler.moveTile( te, this.getWorld(), x + this.x_offset, y + this.y_offset, z + this.z_offset ); - } - catch( final Throwable e ) - { - AELog.debug( e ); - - // attempt recovery... - te.setWorldObj( this.getWorld() ); - te.xCoord = x; - te.yCoord = y; - te.zCoord = z; - - c.c.func_150812_a( c.x, y + y, c.z, te ); - // c.c.setChunkTileEntity( c.x, y + y, c.z, te ); - - if( c.c.isChunkLoaded ) - { - this.getWorld().addTileEntity( te ); - this.getWorld().markBlockForUpdate( x, y, z ); - } - } - - mr.doneMoving( te ); - } - else - { - alternateDestination.addTile( x, y, z, te, null, mr ); - } - } - catch( final Throwable e ) - { - AELog.debug( e ); - } - } - - private void updateChunks() - { - - // update shit.. - for( int x = 0; x < this.cx_size; x++ ) - { - for( int z = 0; z < this.cz_size; z++ ) - { - final Chunk c = this.myChunks[x][z]; - c.resetRelightChecks(); - c.generateSkylightMap(); - c.isModified = true; - } - } - - // send shit... - for( int x = 0; x < this.cx_size; x++ ) - { - for( int z = 0; z < this.cz_size; z++ ) - { - - final Chunk c = this.myChunks[x][z]; - - for( int y = 1; y < 255; y += 32 ) - { - WorldData.instance().compassData().service().updateArea( this.getWorld(), c.xPosition << 4, y, c.zPosition << 4 ); - } - - Platform.sendChunk( c, this.verticalBits ); - } - } - } - - LinkedList getUpdates() - { - return this.updates; - } - - World getWorld() - { - return this.world; - } - - private class Column - { - - private final int x; - private final int z; - private final Chunk c; - private final Object[] ch = { 0, 0, 0 }; - private final ExtendedBlockStorage[] storage; - private List skipThese = null; - - public Column( final Chunk chunk, final int x, final int z, final int chunkY, final int chunkHeight ) - { - this.x = x; - this.z = z; - this.c = chunk; - this.storage = this.c.getBlockStorageArray(); - - // make sure storage exists before hand... - for( int ay = 0; ay < chunkHeight; ay++ ) - { - final int by = ( ay + chunkY ); - ExtendedBlockStorage extendedblockstorage = this.storage[by]; - if( extendedblockstorage == null ) - { - extendedblockstorage = this.storage[by] = new ExtendedBlockStorage( by << 4, !this.c.worldObj.provider.hasNoSky ); - } - } - } - - private void setBlockIDWithMetadata( final int y, final Object[] blk ) - { - for( final Block matrixFrameBlock : CachedPlane.this.matrixFrame.maybeBlock().asSet() ) - { - if( blk[0] == matrixFrameBlock ) - { - blk[0] = Platform.AIR_BLOCK; - } - } - - final ExtendedBlockStorage extendedBlockStorage = this.storage[y >> 4]; - extendedBlockStorage.func_150818_a( this.x, y & 15, this.z, (Block) blk[0] ); - // extendedBlockStorage.setExtBlockID( x, y & 15, z, blk[0] ); - extendedBlockStorage.setExtBlockMetadata( this.x, y & 15, this.z, (Integer) blk[1] ); - extendedBlockStorage.setExtBlocklightValue( this.x, y & 15, this.z, (Integer) blk[2] ); - } - - private Object[] getDetails( final int y ) - { - final ExtendedBlockStorage extendedblockstorage = this.storage[y >> 4]; - this.ch[0] = extendedblockstorage.getBlockByExtId( this.x, y & 15, this.z ); - this.ch[1] = extendedblockstorage.getExtBlockMetadata( this.x, y & 15, this.z ); - this.ch[2] = extendedblockstorage.getExtBlocklightValue( this.x, y & 15, this.z ); - return this.ch; - } - - private boolean doNotSkip( final int y ) - { - final ExtendedBlockStorage extendedblockstorage = this.storage[y >> 4]; - if( CachedPlane.this.reg.isBlacklisted( extendedblockstorage.getBlockByExtId( this.x, y & 15, this.z ) ) ) - { - return false; - } - - return this.skipThese == null || !this.skipThese.contains( y ); - } - - private void setSkip( final int yCoord ) - { - if( this.skipThese == null ) - { - this.skipThese = new LinkedList(); - } - this.skipThese.add( yCoord ); - } - } +public class CachedPlane { + private final int x_size; + private final int z_size; + private final int cx_size; + private final int cz_size; + private final int x_offset; + private final int y_offset; + private final int z_offset; + private final int y_size; + private final Chunk[][] myChunks; + private final Column[][] myColumns; + private final LinkedList tiles = new LinkedList(); + private final LinkedList ticks = new LinkedList(); + private final World world; + private final IMovableRegistry reg = AEApi.instance().registries().movable(); + private final LinkedList updates = new LinkedList(); + private final IBlockDefinition matrixFrame = + AEApi.instance().definitions().blocks().matrixFrame(); + private int verticalBits; + + public CachedPlane( + final World w, + final int minX, + final int minY, + final int minZ, + final int maxX, + final int maxY, + final int maxZ) { + + this.world = w; + + this.x_size = maxX - minX + 1; + this.y_size = maxY - minY + 1; + this.z_size = maxZ - minZ + 1; + + this.x_offset = minX; + this.y_offset = minY; + this.z_offset = minZ; + + final int minCX = minX >> 4; + final int minCY = minY >> 4; + final int minCZ = minZ >> 4; + final int maxCX = maxX >> 4; + final int maxCY = maxY >> 4; + final int maxCZ = maxZ >> 4; + + this.cx_size = maxCX - minCX + 1; + final int cy_size = maxCY - minCY + 1; + this.cz_size = maxCZ - minCZ + 1; + + this.myChunks = new Chunk[this.cx_size][this.cz_size]; + this.myColumns = new Column[this.x_size][this.z_size]; + + this.verticalBits = 0; + for (int cy = 0; cy < cy_size; cy++) { + this.verticalBits |= 1 << (minCY + cy); + } + + for (int x = 0; x < this.x_size; x++) { + for (int z = 0; z < this.z_size; z++) { + this.myColumns[x][z] = new Column( + w.getChunkFromChunkCoords((minX + x) >> 4, (minZ + z) >> 4), + (minX + x) & 0xF, + (minZ + z) & 0xF, + minCY, + cy_size); + } + } + + final IMovableRegistry mr = AEApi.instance().registries().movable(); + + for (int cx = 0; cx < this.cx_size; cx++) { + for (int cz = 0; cz < this.cz_size; cz++) { + final LinkedList> rawTiles = + new LinkedList>(); + final LinkedList deadTiles = new LinkedList(); + + final Chunk c = w.getChunkFromChunkCoords(minCX + cx, minCZ + cz); + this.myChunks[cx][cz] = c; + + rawTiles.addAll(((HashMap) c.chunkTileEntityMap).entrySet()); + for (final Entry tx : rawTiles) { + final ChunkPosition cp = tx.getKey(); + final TileEntity te = tx.getValue(); + if (te.xCoord >= minX + && te.xCoord <= maxX + && te.yCoord >= minY + && te.yCoord <= maxY + && te.zCoord >= minZ + && te.zCoord <= maxZ) { + if (mr.askToMove(te)) { + this.tiles.add(te); + deadTiles.add(cp); + } else { + final Object[] details = + this.myColumns[te.xCoord - minX][te.zCoord - minZ].getDetails(te.yCoord); + final Block blk = (Block) details[0]; + + // don't skip air, just let the code replace it... + if (blk != null + && blk.isAir(c.worldObj, te.xCoord, te.yCoord, te.zCoord) + && blk.isReplaceable(c.worldObj, te.xCoord, te.yCoord, te.zCoord)) { + c.worldObj.setBlock(te.xCoord, te.yCoord, te.zCoord, Platform.AIR_BLOCK); + c.worldObj.notifyBlocksOfNeighborChange( + te.xCoord, te.yCoord, te.zCoord, Platform.AIR_BLOCK); + } else { + this.myColumns[te.xCoord - minX][te.zCoord - minZ].setSkip(te.yCoord); + } + } + } + } + + for (final ChunkPosition cp : deadTiles) { + c.chunkTileEntityMap.remove(cp); + } + + final long k = this.getWorld().getTotalWorldTime(); + final List list = this.getWorld().getPendingBlockUpdates(c, false); + if (list != null) { + for (final Object o : list) { + final NextTickListEntry entry = (NextTickListEntry) o; + if (entry.xCoord >= minX + && entry.xCoord <= maxX + && entry.yCoord >= minY + && entry.yCoord <= maxY + && entry.zCoord >= minZ + && entry.zCoord <= maxZ) { + final NextTickListEntry newEntry = new NextTickListEntry( + entry.xCoord, entry.yCoord, entry.zCoord, entry.func_151351_a()); + newEntry.scheduledTime = entry.scheduledTime - k; + this.ticks.add(newEntry); + } + } + } + } + } + + for (final TileEntity te : this.tiles) { + try { + this.getWorld().loadedTileEntityList.remove(te); + } catch (final Exception e) { + AELog.debug(e); + } + } + } + + private IMovableHandler getHandler(final TileEntity te) { + final IMovableRegistry mr = AEApi.instance().registries().movable(); + return mr.getHandler(te); + } + + void swap(final CachedPlane dst) { + final IMovableRegistry mr = AEApi.instance().registries().movable(); + + if (dst.x_size == this.x_size && dst.y_size == this.y_size && dst.z_size == this.z_size) { + AELog.info("Block Copy Scale: " + this.x_size + ", " + this.y_size + ", " + this.z_size); + + long startTime = System.nanoTime(); + + for (int x = 0; x < this.x_size; x++) { + for (int z = 0; z < this.z_size; z++) { + final Column a = this.myColumns[x][z]; + final Column b = dst.myColumns[x][z]; + + for (int y = 0; y < this.y_size; y++) { + final int src_y = y + this.y_offset; + final int dst_y = y + dst.y_offset; + + if (a.doNotSkip(src_y) && b.doNotSkip(dst_y)) { + final Object[] aD = a.getDetails(src_y); + final Object[] bD = b.getDetails(dst_y); + + a.setBlockIDWithMetadata(src_y, bD); + b.setBlockIDWithMetadata(dst_y, aD); + } else { + this.markForUpdate(x + this.x_offset, src_y, z + this.z_offset); + dst.markForUpdate(x + dst.x_offset, dst_y, z + dst.z_offset); + } + } + } + } + + long endTime = System.nanoTime(); + long duration = endTime - startTime; + AELog.info("Block Copy Time: " + duration); + + for (final TileEntity te : this.tiles) { + dst.addTile( + te.xCoord - this.x_offset, te.yCoord - this.y_offset, te.zCoord - this.z_offset, te, this, mr); + } + + for (final TileEntity te : dst.tiles) { + this.addTile(te.xCoord - dst.x_offset, te.yCoord - dst.y_offset, te.zCoord - dst.z_offset, te, dst, mr); + } + + for (final NextTickListEntry entry : this.ticks) { + dst.addTick( + entry.xCoord - this.x_offset, + entry.yCoord - this.y_offset, + entry.zCoord - this.z_offset, + entry); + } + + for (final NextTickListEntry entry : dst.ticks) { + this.addTick( + entry.xCoord - dst.x_offset, entry.yCoord - dst.y_offset, entry.zCoord - dst.z_offset, entry); + } + + startTime = System.nanoTime(); + this.updateChunks(); + dst.updateChunks(); + endTime = System.nanoTime(); + + duration = endTime - startTime; + AELog.info("Update Time: " + duration); + } + } + + private void markForUpdate(final int x, final int y, final int z) { + this.getUpdates().add(new WorldCoord(x, y, z)); + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + this.getUpdates().add(new WorldCoord(x + d.offsetX, y + d.offsetY, z + d.offsetZ)); + } + } + + private void addTick(final int x, final int y, final int z, final NextTickListEntry entry) { + this.getWorld() + .scheduleBlockUpdate( + x + this.x_offset, y + this.y_offset, z + this.z_offset, entry.func_151351_a(), (int) + entry.scheduledTime); + } + + private void addTile( + final int x, + final int y, + final int z, + final TileEntity te, + final CachedPlane alternateDestination, + final IMovableRegistry mr) { + try { + final Column c = this.myColumns[x][z]; + + if (c.doNotSkip(y + this.y_offset) || alternateDestination == null) { + final IMovableHandler handler = this.getHandler(te); + + try { + handler.moveTile(te, this.getWorld(), x + this.x_offset, y + this.y_offset, z + this.z_offset); + } catch (final Throwable e) { + AELog.debug(e); + + // attempt recovery... + te.setWorldObj(this.getWorld()); + te.xCoord = x; + te.yCoord = y; + te.zCoord = z; + + c.c.func_150812_a(c.x, y + y, c.z, te); + // c.c.setChunkTileEntity( c.x, y + y, c.z, te ); + + if (c.c.isChunkLoaded) { + this.getWorld().addTileEntity(te); + this.getWorld().markBlockForUpdate(x, y, z); + } + } + + mr.doneMoving(te); + } else { + alternateDestination.addTile(x, y, z, te, null, mr); + } + } catch (final Throwable e) { + AELog.debug(e); + } + } + + private void updateChunks() { + + // update shit.. + for (int x = 0; x < this.cx_size; x++) { + for (int z = 0; z < this.cz_size; z++) { + final Chunk c = this.myChunks[x][z]; + c.resetRelightChecks(); + c.generateSkylightMap(); + c.isModified = true; + } + } + + // send shit... + for (int x = 0; x < this.cx_size; x++) { + for (int z = 0; z < this.cz_size; z++) { + + final Chunk c = this.myChunks[x][z]; + + for (int y = 1; y < 255; y += 32) { + WorldData.instance() + .compassData() + .service() + .updateArea(this.getWorld(), c.xPosition << 4, y, c.zPosition << 4); + } + + Platform.sendChunk(c, this.verticalBits); + } + } + } + + LinkedList getUpdates() { + return this.updates; + } + + World getWorld() { + return this.world; + } + + private class Column { + + private final int x; + private final int z; + private final Chunk c; + private final Object[] ch = {0, 0, 0}; + private final ExtendedBlockStorage[] storage; + private List skipThese = null; + + public Column(final Chunk chunk, final int x, final int z, final int chunkY, final int chunkHeight) { + this.x = x; + this.z = z; + this.c = chunk; + this.storage = this.c.getBlockStorageArray(); + + // make sure storage exists before hand... + for (int ay = 0; ay < chunkHeight; ay++) { + final int by = (ay + chunkY); + ExtendedBlockStorage extendedblockstorage = this.storage[by]; + if (extendedblockstorage == null) { + extendedblockstorage = + this.storage[by] = new ExtendedBlockStorage(by << 4, !this.c.worldObj.provider.hasNoSky); + } + } + } + + private void setBlockIDWithMetadata(final int y, final Object[] blk) { + for (final Block matrixFrameBlock : + CachedPlane.this.matrixFrame.maybeBlock().asSet()) { + if (blk[0] == matrixFrameBlock) { + blk[0] = Platform.AIR_BLOCK; + } + } + + final ExtendedBlockStorage extendedBlockStorage = this.storage[y >> 4]; + extendedBlockStorage.func_150818_a(this.x, y & 15, this.z, (Block) blk[0]); + // extendedBlockStorage.setExtBlockID( x, y & 15, z, blk[0] ); + extendedBlockStorage.setExtBlockMetadata(this.x, y & 15, this.z, (Integer) blk[1]); + extendedBlockStorage.setExtBlocklightValue(this.x, y & 15, this.z, (Integer) blk[2]); + } + + private Object[] getDetails(final int y) { + final ExtendedBlockStorage extendedblockstorage = this.storage[y >> 4]; + this.ch[0] = extendedblockstorage.getBlockByExtId(this.x, y & 15, this.z); + this.ch[1] = extendedblockstorage.getExtBlockMetadata(this.x, y & 15, this.z); + this.ch[2] = extendedblockstorage.getExtBlocklightValue(this.x, y & 15, this.z); + return this.ch; + } + + private boolean doNotSkip(final int y) { + final ExtendedBlockStorage extendedblockstorage = this.storage[y >> 4]; + if (CachedPlane.this.reg.isBlacklisted(extendedblockstorage.getBlockByExtId(this.x, y & 15, this.z))) { + return false; + } + + return this.skipThese == null || !this.skipThese.contains(y); + } + + private void setSkip(final int yCoord) { + if (this.skipThese == null) { + this.skipThese = new LinkedList(); + } + this.skipThese.add(yCoord); + } + } } diff --git a/src/main/java/appeng/spatial/DefaultSpatialHandler.java b/src/main/java/appeng/spatial/DefaultSpatialHandler.java index 3234dbae6dc..89e546bb948 100644 --- a/src/main/java/appeng/spatial/DefaultSpatialHandler.java +++ b/src/main/java/appeng/spatial/DefaultSpatialHandler.java @@ -18,45 +18,39 @@ package appeng.spatial; - import appeng.api.movable.IMovableHandler; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; - -public class DefaultSpatialHandler implements IMovableHandler -{ - - /** - * never called for the default. - * - * @param tile tile entity - * @return true - */ - @Override - public boolean canHandle( final Class myClass, final TileEntity tile ) - { - return true; - } - - @Override - public void moveTile( final TileEntity te, final World w, final int x, final int y, final int z ) - { - - te.setWorldObj( w ); - te.xCoord = x; - te.yCoord = y; - te.zCoord = z; - - final Chunk c = w.getChunkFromBlockCoords( x, z ); - c.func_150812_a( x & 0xF, y, z & 0xF, te ); - // c.setChunkBlockTileEntity( x & 0xF, y, z & 0xF, te ); - - if( c.isChunkLoaded ) - { - w.addTileEntity( te ); - w.markBlockForUpdate( x, y, z ); - } - } +public class DefaultSpatialHandler implements IMovableHandler { + + /** + * never called for the default. + * + * @param tile tile entity + * @return true + */ + @Override + public boolean canHandle(final Class myClass, final TileEntity tile) { + return true; + } + + @Override + public void moveTile(final TileEntity te, final World w, final int x, final int y, final int z) { + + te.setWorldObj(w); + te.xCoord = x; + te.yCoord = y; + te.zCoord = z; + + final Chunk c = w.getChunkFromBlockCoords(x, z); + c.func_150812_a(x & 0xF, y, z & 0xF, te); + // c.setChunkBlockTileEntity( x & 0xF, y, z & 0xF, te ); + + if (c.isChunkLoaded) { + w.addTileEntity(te); + w.markBlockForUpdate(x, y, z); + } + } } diff --git a/src/main/java/appeng/spatial/ISpatialVisitor.java b/src/main/java/appeng/spatial/ISpatialVisitor.java index 204bde08cff..31331de0b79 100644 --- a/src/main/java/appeng/spatial/ISpatialVisitor.java +++ b/src/main/java/appeng/spatial/ISpatialVisitor.java @@ -18,9 +18,7 @@ package appeng.spatial; +public interface ISpatialVisitor { -public interface ISpatialVisitor -{ - - void visit( int x, int y, int z ); + void visit(int x, int y, int z); } diff --git a/src/main/java/appeng/spatial/StorageChunkProvider.java b/src/main/java/appeng/spatial/StorageChunkProvider.java index 3d1da438b48..124ca30cca6 100644 --- a/src/main/java/appeng/spatial/StorageChunkProvider.java +++ b/src/main/java/appeng/spatial/StorageChunkProvider.java @@ -18,9 +18,10 @@ package appeng.spatial; - import appeng.api.AEApi; import appeng.core.AEConfig; +import java.util.ArrayList; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.entity.EnumCreatureType; import net.minecraft.world.World; @@ -28,73 +29,61 @@ import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.ChunkProviderGenerate; -import java.util.ArrayList; -import java.util.List; - - -public class StorageChunkProvider extends ChunkProviderGenerate -{ - private static final int SQUARE_CHUNK_SIZE = 256; - private static final Block[] BLOCKS; - - static - { - BLOCKS = new Block[255 * SQUARE_CHUNK_SIZE]; - - for( final Block matrixFrameBlock : AEApi.instance().definitions().blocks().matrixFrame().maybeBlock().asSet() ) - { - for( int x = 0; x < BLOCKS.length; x++ ) - { - BLOCKS[x] = matrixFrameBlock; - } - } - } - - private final World world; - - public StorageChunkProvider( final World world, final long i ) - { - super( world, i, false ); - this.world = world; - } - - @Override - public Chunk provideChunk( final int x, final int z ) - { - final Chunk chunk = new Chunk( this.world, BLOCKS, x, z ); - - final byte[] biomes = chunk.getBiomeArray(); - final AEConfig config = AEConfig.instance; - - for( int k = 0; k < biomes.length; ++k ) - { - biomes[k] = (byte) config.storageBiomeID; - } - - if( !chunk.isTerrainPopulated ) - { - chunk.isTerrainPopulated = true; - chunk.resetRelightChecks(); - } - - return chunk; - } - - @Override - public void populate( final IChunkProvider par1iChunkProvider, final int par2, final int par3 ) - { - - } - - @Override - public boolean unloadQueuedChunks() - { - return true; - } - - @Override - public List getPossibleCreatures( final EnumCreatureType a, final int b, final int c, final int d ) - { - return new ArrayList(); - } +public class StorageChunkProvider extends ChunkProviderGenerate { + private static final int SQUARE_CHUNK_SIZE = 256; + private static final Block[] BLOCKS; + + static { + BLOCKS = new Block[255 * SQUARE_CHUNK_SIZE]; + + for (final Block matrixFrameBlock : AEApi.instance() + .definitions() + .blocks() + .matrixFrame() + .maybeBlock() + .asSet()) { + for (int x = 0; x < BLOCKS.length; x++) { + BLOCKS[x] = matrixFrameBlock; + } + } + } + + private final World world; + + public StorageChunkProvider(final World world, final long i) { + super(world, i, false); + this.world = world; + } + + @Override + public Chunk provideChunk(final int x, final int z) { + final Chunk chunk = new Chunk(this.world, BLOCKS, x, z); + + final byte[] biomes = chunk.getBiomeArray(); + final AEConfig config = AEConfig.instance; + + for (int k = 0; k < biomes.length; ++k) { + biomes[k] = (byte) config.storageBiomeID; + } + + if (!chunk.isTerrainPopulated) { + chunk.isTerrainPopulated = true; + chunk.resetRelightChecks(); + } + + return chunk; + } + + @Override + public void populate(final IChunkProvider par1iChunkProvider, final int par2, final int par3) {} + + @Override + public boolean unloadQueuedChunks() { + return true; + } + + @Override + public List getPossibleCreatures(final EnumCreatureType a, final int b, final int c, final int d) { + return new ArrayList(); + } } diff --git a/src/main/java/appeng/spatial/StorageHelper.java b/src/main/java/appeng/spatial/StorageHelper.java index 3befb3aff20..ff7436a61d1 100644 --- a/src/main/java/appeng/spatial/StorageHelper.java +++ b/src/main/java/appeng/spatial/StorageHelper.java @@ -18,11 +18,11 @@ package appeng.spatial; - import appeng.api.AEApi; import appeng.api.util.WorldCoord; import appeng.core.stats.Achievements; import appeng.util.Platform; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityHanging; @@ -34,331 +34,326 @@ import net.minecraft.world.World; import net.minecraft.world.WorldServer; -import java.util.List; - - -public class StorageHelper -{ - - private static StorageHelper instance; - - public static StorageHelper getInstance() - { - if( instance == null ) - { - instance = new StorageHelper(); - } - return instance; - } - - /** - * Mostly from dimensional doors.. which mostly got it form X-Comp. - * - * @param entity to be teleported entity - * @param link destination - * @return teleported entity - */ - private Entity teleportEntity( Entity entity, final TelDestination link ) - { - final WorldServer oldWorld; - final WorldServer newWorld; - final EntityPlayerMP player; - - try - { - oldWorld = (WorldServer) entity.worldObj; - newWorld = (WorldServer) link.dim; - player = ( entity instanceof EntityPlayerMP ) ? (EntityPlayerMP) entity : null; - } - catch( final Throwable e ) - { - return entity; - } - - if( oldWorld == null ) - { - return entity; - } - if( newWorld == null ) - { - return entity; - } - - // Is something riding? Handle it first. - if( entity.riddenByEntity != null ) - { - return this.teleportEntity( entity.riddenByEntity, link ); - } - // Are we riding something? Dismount and tell the mount to go first. - Entity cart = entity.ridingEntity; - if( cart != null ) - { - entity.mountEntity( null ); - cart = this.teleportEntity( cart, link ); - // We keep track of both so we can remount them on the other side. - } - - // load the chunk! - WorldServer.class.cast( newWorld ).getChunkProvider().loadChunk( MathHelper.floor_double( link.x ) >> 4, MathHelper.floor_double( link.z ) >> 4 ); - - final boolean diffDestination = newWorld != oldWorld; - if( diffDestination ) - { - if( player != null ) - { - if( link.dim.provider instanceof StorageWorldProvider ) - { - Achievements.SpatialIOExplorer.addToPlayer( player ); - } - - player.mcServer.getConfigurationManager().transferPlayerToDimension( player, link.dim.provider.dimensionId, new METeleporter( newWorld, link ) ); - } - else - { - final int entX = entity.chunkCoordX; - final int entZ = entity.chunkCoordZ; - - if( ( entity.addedToChunk ) && ( oldWorld.getChunkProvider().chunkExists( entX, entZ ) ) ) - { - oldWorld.getChunkFromChunkCoords( entX, entZ ).removeEntity( entity ); - oldWorld.getChunkFromChunkCoords( entX, entZ ).isModified = true; - } - - final Entity newEntity = EntityList.createEntityByName( EntityList.getEntityString( entity ), newWorld ); - if( newEntity != null ) - { - entity.lastTickPosX = entity.prevPosX = entity.posX = link.x; - entity.lastTickPosY = entity.prevPosY = entity.posY = link.y; - entity.lastTickPosZ = entity.prevPosZ = entity.posZ = link.z; - - if( entity instanceof EntityHanging ) - { - final EntityHanging h = (EntityHanging) entity; - h.field_146063_b += link.xOff; - h.field_146064_c += link.yOff; - h.field_146062_d += link.zOff; - } - - newEntity.copyDataFrom( entity, true ); - newEntity.dimension = newWorld.provider.dimensionId; - newEntity.forceSpawn = true; - - entity.isDead = true; - entity = newEntity; - } - else - { - return null; - } - - // myChunk.addEntity( entity ); - // newWorld.loadedEntityList.add( entity ); - // newWorld.onEntityAdded( entity ); - newWorld.spawnEntityInWorld( entity ); - } - } - - entity.worldObj.updateEntityWithOptionalForce( entity, false ); - - if( cart != null ) - { - if( player != null ) - { - entity.worldObj.updateEntityWithOptionalForce( entity, true ); - } - - entity.mountEntity( cart ); - } - - return entity; - } - - private void transverseEdges( final int minX, final int minY, final int minZ, final int maxX, final int maxY, final int maxZ, final ISpatialVisitor visitor ) - { - for( int y = minY; y < maxY; y++ ) - { - for( int z = minZ; z < maxZ; z++ ) - { - visitor.visit( minX, y, z ); - visitor.visit( maxX, y, z ); - } - } - - for( int x = minX; x < maxX; x++ ) - { - for( int z = minZ; z < maxZ; z++ ) - { - visitor.visit( x, minY, z ); - visitor.visit( x, maxY, z ); - } - } - - for( int x = minX; x < maxX; x++ ) - { - for( int y = minY; y < maxY; y++ ) - { - visitor.visit( x, y, minZ ); - visitor.visit( x, y, maxZ ); - } - } - } - - public void swapRegions( final World src /** over world **/ - , final World dst /** storage cell **/ - , final int x, final int y, final int z, final int i, final int j, final int k, final int scaleX, final int scaleY, final int scaleZ ) - { - for( final Block matrixFrameBlock : AEApi.instance().definitions().blocks().matrixFrame().maybeBlock().asSet() ) - { - this.transverseEdges( i - 1, j - 1, k - 1, i + scaleX + 1, j + scaleY + 1, k + scaleZ + 1, new WrapInMatrixFrame( matrixFrameBlock, 0, dst ) ); - } - - final AxisAlignedBB srcBox = AxisAlignedBB.getBoundingBox( x, y, z, x + scaleX + 1, y + scaleY + 1, z + scaleZ + 1 ); - - final AxisAlignedBB dstBox = AxisAlignedBB.getBoundingBox( i, j, k, i + scaleX + 1, j + scaleY + 1, k + scaleZ + 1 ); - - final CachedPlane cDst = new CachedPlane( dst, i, j, k, i + scaleX, j + scaleY, k + scaleZ ); - final CachedPlane cSrc = new CachedPlane( src, x, y, z, x + scaleX, y + scaleY, z + scaleZ ); - - // do nearly all the work... swaps blocks, tiles, and block ticks - cSrc.swap( cDst ); - - final List srcE = src.getEntitiesWithinAABB( Entity.class, srcBox ); - final List dstE = dst.getEntitiesWithinAABB( Entity.class, dstBox ); - - for( final Entity e : dstE ) - { - this.teleportEntity( e, new TelDestination( src, srcBox, e.posX, e.posY, e.posZ, -i + x, -j + y, -k + z ) ); - } - - for( final Entity e : srcE ) - { - this.teleportEntity( e, new TelDestination( dst, dstBox, e.posX, e.posY, e.posZ, -x + i, -y + j, -z + k ) ); - } - - for( final WorldCoord wc : cDst.getUpdates() ) - { - cDst.getWorld().notifyBlockOfNeighborChange( wc.x, wc.y, wc.z, Platform.AIR_BLOCK ); - } - - for( final WorldCoord wc : cSrc.getUpdates() ) - { - cSrc.getWorld().notifyBlockOfNeighborChange( wc.x, wc.y, wc.z, Platform.AIR_BLOCK ); - } - - this.transverseEdges( x - 1, y - 1, z - 1, x + scaleX + 1, y + scaleY + 1, z + scaleZ + 1, new TriggerUpdates( src ) ); - this.transverseEdges( i - 1, j - 1, k - 1, i + scaleX + 1, j + scaleY + 1, k + scaleZ + 1, new TriggerUpdates( dst ) ); - - this.transverseEdges( x, y, z, x + scaleX, y + scaleY, z + scaleZ, new TriggerUpdates( src ) ); - this.transverseEdges( i, j, k, i + scaleX, j + scaleY, k + scaleZ, new TriggerUpdates( dst ) ); - - /* - * IChunkProvider cp = destination.getChunkProvider(); if ( cp instanceof ChunkProviderServer ) { - * ChunkProviderServer - * srv = (ChunkProviderServer) cp; srv.unloadAllChunks(); } - * cp.unloadQueuedChunks(); - */ - - } - - private static class TriggerUpdates implements ISpatialVisitor - { - - private final World dst; - - public TriggerUpdates( final World dst2 ) - { - this.dst = dst2; - } - - @Override - public void visit( final int x, final int y, final int z ) - { - final Block blk = this.dst.getBlock( x, y, z ); - blk.onNeighborBlockChange( this.dst, x, y, z, Platform.AIR_BLOCK ); - } - } - - - private static class WrapInMatrixFrame implements ISpatialVisitor - { - - private final World dst; - private final Block blkID; - private final int Meta; - - public WrapInMatrixFrame( final Block blockID, final int metaData, final World dst2 ) - { - this.dst = dst2; - this.blkID = blockID; - this.Meta = metaData; - } - - @Override - public void visit( final int x, final int y, final int z ) - { - this.dst.setBlock( x, y, z, this.blkID, this.Meta, 3 ); - } - } - - - private static class TelDestination - { - - private final World dim; - private final double x; - private final double y; - private final double z; - private final int xOff; - private final int yOff; - private final int zOff; - - TelDestination( final World dimension, final AxisAlignedBB srcBox, final double x, final double y, final double z, final int tileX, final int tileY, final int tileZ ) - { - this.dim = dimension; - this.x = Math.min( srcBox.maxX - 0.5, Math.max( srcBox.minX + 0.5, x + tileX ) ); - this.y = Math.min( srcBox.maxY - 0.5, Math.max( srcBox.minY + 0.5, y + tileY ) ); - this.z = Math.min( srcBox.maxZ - 0.5, Math.max( srcBox.minZ + 0.5, z + tileZ ) ); - this.xOff = tileX; - this.yOff = tileY; - this.zOff = tileZ; - } - } - - - private static class METeleporter extends Teleporter - { - - private final TelDestination destination; - - public METeleporter( final WorldServer par1WorldServer, final TelDestination d ) - { - super( par1WorldServer ); - this.destination = d; - } - - @Override - public void placeInPortal( final Entity par1Entity, final double par2, final double par4, final double par6, final float par8 ) - { - par1Entity.setLocationAndAngles( this.destination.x, this.destination.y, this.destination.z, par1Entity.rotationYaw, 0.0F ); - par1Entity.motionX = par1Entity.motionY = par1Entity.motionZ = 0.0D; - } - - @Override - public boolean placeInExistingPortal( final Entity par1Entity, final double par2, final double par4, final double par6, final float par8 ) - { - return false; - } - - @Override - public boolean makePortal( final Entity par1Entity ) - { - return false; - } - - @Override - public void removeStalePortalLocations( final long par1 ) - { - - } - } +public class StorageHelper { + + private static StorageHelper instance; + + public static StorageHelper getInstance() { + if (instance == null) { + instance = new StorageHelper(); + } + return instance; + } + + /** + * Mostly from dimensional doors.. which mostly got it form X-Comp. + * + * @param entity to be teleported entity + * @param link destination + * @return teleported entity + */ + private Entity teleportEntity(Entity entity, final TelDestination link) { + final WorldServer oldWorld; + final WorldServer newWorld; + final EntityPlayerMP player; + + try { + oldWorld = (WorldServer) entity.worldObj; + newWorld = (WorldServer) link.dim; + player = (entity instanceof EntityPlayerMP) ? (EntityPlayerMP) entity : null; + } catch (final Throwable e) { + return entity; + } + + if (oldWorld == null) { + return entity; + } + if (newWorld == null) { + return entity; + } + + // Is something riding? Handle it first. + if (entity.riddenByEntity != null) { + return this.teleportEntity(entity.riddenByEntity, link); + } + // Are we riding something? Dismount and tell the mount to go first. + Entity cart = entity.ridingEntity; + if (cart != null) { + entity.mountEntity(null); + cart = this.teleportEntity(cart, link); + // We keep track of both so we can remount them on the other side. + } + + // load the chunk! + WorldServer.class + .cast(newWorld) + .getChunkProvider() + .loadChunk(MathHelper.floor_double(link.x) >> 4, MathHelper.floor_double(link.z) >> 4); + + final boolean diffDestination = newWorld != oldWorld; + if (diffDestination) { + if (player != null) { + if (link.dim.provider instanceof StorageWorldProvider) { + Achievements.SpatialIOExplorer.addToPlayer(player); + } + + player.mcServer + .getConfigurationManager() + .transferPlayerToDimension( + player, link.dim.provider.dimensionId, new METeleporter(newWorld, link)); + } else { + final int entX = entity.chunkCoordX; + final int entZ = entity.chunkCoordZ; + + if ((entity.addedToChunk) && (oldWorld.getChunkProvider().chunkExists(entX, entZ))) { + oldWorld.getChunkFromChunkCoords(entX, entZ).removeEntity(entity); + oldWorld.getChunkFromChunkCoords(entX, entZ).isModified = true; + } + + final Entity newEntity = EntityList.createEntityByName(EntityList.getEntityString(entity), newWorld); + if (newEntity != null) { + entity.lastTickPosX = entity.prevPosX = entity.posX = link.x; + entity.lastTickPosY = entity.prevPosY = entity.posY = link.y; + entity.lastTickPosZ = entity.prevPosZ = entity.posZ = link.z; + + if (entity instanceof EntityHanging) { + final EntityHanging h = (EntityHanging) entity; + h.field_146063_b += link.xOff; + h.field_146064_c += link.yOff; + h.field_146062_d += link.zOff; + } + + newEntity.copyDataFrom(entity, true); + newEntity.dimension = newWorld.provider.dimensionId; + newEntity.forceSpawn = true; + + entity.isDead = true; + entity = newEntity; + } else { + return null; + } + + // myChunk.addEntity( entity ); + // newWorld.loadedEntityList.add( entity ); + // newWorld.onEntityAdded( entity ); + newWorld.spawnEntityInWorld(entity); + } + } + + entity.worldObj.updateEntityWithOptionalForce(entity, false); + + if (cart != null) { + if (player != null) { + entity.worldObj.updateEntityWithOptionalForce(entity, true); + } + + entity.mountEntity(cart); + } + + return entity; + } + + private void transverseEdges( + final int minX, + final int minY, + final int minZ, + final int maxX, + final int maxY, + final int maxZ, + final ISpatialVisitor visitor) { + for (int y = minY; y < maxY; y++) { + for (int z = minZ; z < maxZ; z++) { + visitor.visit(minX, y, z); + visitor.visit(maxX, y, z); + } + } + + for (int x = minX; x < maxX; x++) { + for (int z = minZ; z < maxZ; z++) { + visitor.visit(x, minY, z); + visitor.visit(x, maxY, z); + } + } + + for (int x = minX; x < maxX; x++) { + for (int y = minY; y < maxY; y++) { + visitor.visit(x, y, minZ); + visitor.visit(x, y, maxZ); + } + } + } + + public void swapRegions( + final World src + /** over world **/ + , + final World dst + /** storage cell **/ + , + final int x, + final int y, + final int z, + final int i, + final int j, + final int k, + final int scaleX, + final int scaleY, + final int scaleZ) { + for (final Block matrixFrameBlock : AEApi.instance() + .definitions() + .blocks() + .matrixFrame() + .maybeBlock() + .asSet()) { + this.transverseEdges( + i - 1, + j - 1, + k - 1, + i + scaleX + 1, + j + scaleY + 1, + k + scaleZ + 1, + new WrapInMatrixFrame(matrixFrameBlock, 0, dst)); + } + + final AxisAlignedBB srcBox = + AxisAlignedBB.getBoundingBox(x, y, z, x + scaleX + 1, y + scaleY + 1, z + scaleZ + 1); + + final AxisAlignedBB dstBox = + AxisAlignedBB.getBoundingBox(i, j, k, i + scaleX + 1, j + scaleY + 1, k + scaleZ + 1); + + final CachedPlane cDst = new CachedPlane(dst, i, j, k, i + scaleX, j + scaleY, k + scaleZ); + final CachedPlane cSrc = new CachedPlane(src, x, y, z, x + scaleX, y + scaleY, z + scaleZ); + + // do nearly all the work... swaps blocks, tiles, and block ticks + cSrc.swap(cDst); + + final List srcE = src.getEntitiesWithinAABB(Entity.class, srcBox); + final List dstE = dst.getEntitiesWithinAABB(Entity.class, dstBox); + + for (final Entity e : dstE) { + this.teleportEntity(e, new TelDestination(src, srcBox, e.posX, e.posY, e.posZ, -i + x, -j + y, -k + z)); + } + + for (final Entity e : srcE) { + this.teleportEntity(e, new TelDestination(dst, dstBox, e.posX, e.posY, e.posZ, -x + i, -y + j, -z + k)); + } + + for (final WorldCoord wc : cDst.getUpdates()) { + cDst.getWorld().notifyBlockOfNeighborChange(wc.x, wc.y, wc.z, Platform.AIR_BLOCK); + } + + for (final WorldCoord wc : cSrc.getUpdates()) { + cSrc.getWorld().notifyBlockOfNeighborChange(wc.x, wc.y, wc.z, Platform.AIR_BLOCK); + } + + this.transverseEdges( + x - 1, y - 1, z - 1, x + scaleX + 1, y + scaleY + 1, z + scaleZ + 1, new TriggerUpdates(src)); + this.transverseEdges( + i - 1, j - 1, k - 1, i + scaleX + 1, j + scaleY + 1, k + scaleZ + 1, new TriggerUpdates(dst)); + + this.transverseEdges(x, y, z, x + scaleX, y + scaleY, z + scaleZ, new TriggerUpdates(src)); + this.transverseEdges(i, j, k, i + scaleX, j + scaleY, k + scaleZ, new TriggerUpdates(dst)); + + /* + * IChunkProvider cp = destination.getChunkProvider(); if ( cp instanceof ChunkProviderServer ) { + * ChunkProviderServer + * srv = (ChunkProviderServer) cp; srv.unloadAllChunks(); } + * cp.unloadQueuedChunks(); + */ + + } + + private static class TriggerUpdates implements ISpatialVisitor { + + private final World dst; + + public TriggerUpdates(final World dst2) { + this.dst = dst2; + } + + @Override + public void visit(final int x, final int y, final int z) { + final Block blk = this.dst.getBlock(x, y, z); + blk.onNeighborBlockChange(this.dst, x, y, z, Platform.AIR_BLOCK); + } + } + + private static class WrapInMatrixFrame implements ISpatialVisitor { + + private final World dst; + private final Block blkID; + private final int Meta; + + public WrapInMatrixFrame(final Block blockID, final int metaData, final World dst2) { + this.dst = dst2; + this.blkID = blockID; + this.Meta = metaData; + } + + @Override + public void visit(final int x, final int y, final int z) { + this.dst.setBlock(x, y, z, this.blkID, this.Meta, 3); + } + } + + private static class TelDestination { + + private final World dim; + private final double x; + private final double y; + private final double z; + private final int xOff; + private final int yOff; + private final int zOff; + + TelDestination( + final World dimension, + final AxisAlignedBB srcBox, + final double x, + final double y, + final double z, + final int tileX, + final int tileY, + final int tileZ) { + this.dim = dimension; + this.x = Math.min(srcBox.maxX - 0.5, Math.max(srcBox.minX + 0.5, x + tileX)); + this.y = Math.min(srcBox.maxY - 0.5, Math.max(srcBox.minY + 0.5, y + tileY)); + this.z = Math.min(srcBox.maxZ - 0.5, Math.max(srcBox.minZ + 0.5, z + tileZ)); + this.xOff = tileX; + this.yOff = tileY; + this.zOff = tileZ; + } + } + + private static class METeleporter extends Teleporter { + + private final TelDestination destination; + + public METeleporter(final WorldServer par1WorldServer, final TelDestination d) { + super(par1WorldServer); + this.destination = d; + } + + @Override + public void placeInPortal( + final Entity par1Entity, final double par2, final double par4, final double par6, final float par8) { + par1Entity.setLocationAndAngles( + this.destination.x, this.destination.y, this.destination.z, par1Entity.rotationYaw, 0.0F); + par1Entity.motionX = par1Entity.motionY = par1Entity.motionZ = 0.0D; + } + + @Override + public boolean placeInExistingPortal( + final Entity par1Entity, final double par2, final double par4, final double par6, final float par8) { + return false; + } + + @Override + public boolean makePortal(final Entity par1Entity) { + return false; + } + + @Override + public void removeStalePortalLocations(final long par1) {} + } } diff --git a/src/main/java/appeng/spatial/StorageWorldProvider.java b/src/main/java/appeng/spatial/StorageWorldProvider.java index 3eee9324860..334b38f39c1 100644 --- a/src/main/java/appeng/spatial/StorageWorldProvider.java +++ b/src/main/java/appeng/spatial/StorageWorldProvider.java @@ -18,7 +18,6 @@ package appeng.spatial; - import appeng.client.render.SpatialSkyRender; import appeng.core.AppEng; import appeng.core.Registration; @@ -34,126 +33,105 @@ import net.minecraft.world.chunk.IChunkProvider; import net.minecraftforge.client.IRenderHandler; - -public class StorageWorldProvider extends WorldProvider -{ - - public StorageWorldProvider() - { - this.hasNoSky = true; - } - - @Override - protected void registerWorldChunkManager() - { - final AppEng ae2internal = AppEng.instance(); - final Registration ae2registration = ae2internal.getRegistration(); - final BiomeGenBase storageBiome = ae2registration.getStorageBiome(); - - super.worldChunkMgr = new WorldChunkManagerHell( storageBiome, 0.0F ); - } - - @Override - public IChunkProvider createChunkGenerator() - { - return new StorageChunkProvider( this.worldObj, 0 ); - } - - @Override - public float calculateCelestialAngle( final long par1, final float par3 ) - { - return 0; - } - - @Override - public boolean isSurfaceWorld() - { - return false; - } - - @Override - @SideOnly( Side.CLIENT ) - public float[] calcSunriseSunsetColors( final float celestialAngle, final float partialTicks ) - { - return null; - } - - @Override - public Vec3 getFogColor( final float par1, final float par2 ) - { - return Vec3.createVectorHelper( 0.07, 0.07, 0.07 ); - } - - @Override - public boolean canRespawnHere() - { - return false; - } - - @Override - @SideOnly( Side.CLIENT ) - public boolean isSkyColored() - { - return true; - } - - @Override - public boolean doesXZShowFog( final int par1, final int par2 ) - { - return false; - } - - @Override - public String getDimensionName() - { - return "Storage Cell"; - } - - @Override - public IRenderHandler getSkyRenderer() - { - return SpatialSkyRender.getInstance(); - } - - @Override - public boolean isDaytime() - { - return false; - } - - @Override - public Vec3 getSkyColor( final Entity cameraEntity, final float partialTicks ) - { - return Vec3.createVectorHelper( 0.07, 0.07, 0.07 ); - } - - @Override - public float getStarBrightness( final float par1 ) - { - return 0; - } - - @Override - public boolean canSnowAt( final int x, final int y, final int z, final boolean checkLight ) - { - return false; - } - - @Override - public ChunkCoordinates getSpawnPoint() - { - return new ChunkCoordinates( 0, 0, 0 ); - } - - @Override - public boolean isBlockHighHumidity( final int x, final int y, final int z ) - { - return false; - } - - @Override - public boolean canDoLightning( final Chunk chunk ) - { - return false; - } +public class StorageWorldProvider extends WorldProvider { + + public StorageWorldProvider() { + this.hasNoSky = true; + } + + @Override + protected void registerWorldChunkManager() { + final AppEng ae2internal = AppEng.instance(); + final Registration ae2registration = ae2internal.getRegistration(); + final BiomeGenBase storageBiome = ae2registration.getStorageBiome(); + + super.worldChunkMgr = new WorldChunkManagerHell(storageBiome, 0.0F); + } + + @Override + public IChunkProvider createChunkGenerator() { + return new StorageChunkProvider(this.worldObj, 0); + } + + @Override + public float calculateCelestialAngle(final long par1, final float par3) { + return 0; + } + + @Override + public boolean isSurfaceWorld() { + return false; + } + + @Override + @SideOnly(Side.CLIENT) + public float[] calcSunriseSunsetColors(final float celestialAngle, final float partialTicks) { + return null; + } + + @Override + public Vec3 getFogColor(final float par1, final float par2) { + return Vec3.createVectorHelper(0.07, 0.07, 0.07); + } + + @Override + public boolean canRespawnHere() { + return false; + } + + @Override + @SideOnly(Side.CLIENT) + public boolean isSkyColored() { + return true; + } + + @Override + public boolean doesXZShowFog(final int par1, final int par2) { + return false; + } + + @Override + public String getDimensionName() { + return "Storage Cell"; + } + + @Override + public IRenderHandler getSkyRenderer() { + return SpatialSkyRender.getInstance(); + } + + @Override + public boolean isDaytime() { + return false; + } + + @Override + public Vec3 getSkyColor(final Entity cameraEntity, final float partialTicks) { + return Vec3.createVectorHelper(0.07, 0.07, 0.07); + } + + @Override + public float getStarBrightness(final float par1) { + return 0; + } + + @Override + public boolean canSnowAt(final int x, final int y, final int z, final boolean checkLight) { + return false; + } + + @Override + public ChunkCoordinates getSpawnPoint() { + return new ChunkCoordinates(0, 0, 0); + } + + @Override + public boolean isBlockHighHumidity(final int x, final int y, final int z) { + return false; + } + + @Override + public boolean canDoLightning(final Chunk chunk) { + return false; + } } diff --git a/src/main/java/appeng/tile/AEBaseInvTile.java b/src/main/java/appeng/tile/AEBaseInvTile.java index f0b2da244c8..5dc903d99fb 100644 --- a/src/main/java/appeng/tile/AEBaseInvTile.java +++ b/src/main/java/appeng/tile/AEBaseInvTile.java @@ -18,11 +18,11 @@ package appeng.tile; - import appeng.block.AEBaseBlock; import appeng.tile.events.TileEventType; import appeng.tile.inventory.IAEAppEngInventory; import appeng.tile.inventory.InvOperation; +import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; @@ -31,148 +31,123 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nullable; - - -public abstract class AEBaseInvTile extends AEBaseTile implements ISidedInventory, IAEAppEngInventory -{ - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_AEBaseInvTile( final net.minecraft.nbt.NBTTagCompound data ) - { - final IInventory inv = this.getInternalInventory(); - final NBTTagCompound opt = data.getCompoundTag( "inv" ); - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - final NBTTagCompound item = opt.getCompoundTag( "item" + x ); - inv.setInventorySlotContents( x, ItemStack.loadItemStackFromNBT( item ) ); - } - } - - public abstract IInventory getInternalInventory(); - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_AEBaseInvTile( final net.minecraft.nbt.NBTTagCompound data ) - { - final IInventory inv = this.getInternalInventory(); - final NBTTagCompound opt = new NBTTagCompound(); - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - final NBTTagCompound item = new NBTTagCompound(); - final ItemStack is = this.getStackInSlot( x ); - if( is != null ) - { - is.writeToNBT( item ); - } - opt.setTag( "item" + x, item ); - } - data.setTag( "inv", opt ); - } - - @Override - public int getSizeInventory() - { - return this.getInternalInventory().getSizeInventory(); - } - - @Override - public ItemStack getStackInSlot( final int i ) - { - return this.getInternalInventory().getStackInSlot( i ); - } - - @Override - public ItemStack decrStackSize( final int i, final int j ) - { - return this.getInternalInventory().decrStackSize( i, j ); - } - - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - return null; - } - - @Override - public void setInventorySlotContents( final int i, @Nullable final ItemStack itemstack ) - { - this.getInternalInventory().setInventorySlotContents( i, itemstack ); - } - - /** - * Returns the name of the inventory - */ - @Override - public String getInventoryName() - { - return this.getCustomName(); - } - - /** - * Returns if the inventory is named - */ - @Override - public boolean hasCustomInventoryName() - { - return this.hasCustomName(); - } - - @Override - public int getInventoryStackLimit() - { - return 64; - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer p ) - { - final double squaredMCReach = 64.0D; - - return this.worldObj.getTileEntity( this.xCoord, this.yCoord, this.zCoord ) == this && p.getDistanceSq( this.xCoord + 0.5D, this.yCoord + 0.5D, this.zCoord + 0.5D ) <= squaredMCReach; - } - - @Override - public void openInventory() - { - } - - @Override - public void closeInventory() - { - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return true; - } - - @Override - public abstract void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ); - - @Override - public final int[] getAccessibleSlotsFromSide( final int side ) - { - final Block blk = this.worldObj.getBlock( this.xCoord, this.yCoord, this.zCoord ); - if( blk instanceof AEBaseBlock ) - { - final ForgeDirection mySide = ForgeDirection.getOrientation( side ); - return this.getAccessibleSlotsBySide( ( (AEBaseBlock) blk ).mapRotation( this, mySide ) ); - } - return this.getAccessibleSlotsBySide( ForgeDirection.getOrientation( side ) ); - } - - @Override - public boolean canInsertItem( final int slotIndex, final ItemStack insertingItem, final int side ) - { - return this.isItemValidForSlot( slotIndex, insertingItem ); - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - return true; - } - - public abstract int[] getAccessibleSlotsBySide( ForgeDirection whichSide ); +public abstract class AEBaseInvTile extends AEBaseTile implements ISidedInventory, IAEAppEngInventory { + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_AEBaseInvTile(final net.minecraft.nbt.NBTTagCompound data) { + final IInventory inv = this.getInternalInventory(); + final NBTTagCompound opt = data.getCompoundTag("inv"); + for (int x = 0; x < inv.getSizeInventory(); x++) { + final NBTTagCompound item = opt.getCompoundTag("item" + x); + inv.setInventorySlotContents(x, ItemStack.loadItemStackFromNBT(item)); + } + } + + public abstract IInventory getInternalInventory(); + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_AEBaseInvTile(final net.minecraft.nbt.NBTTagCompound data) { + final IInventory inv = this.getInternalInventory(); + final NBTTagCompound opt = new NBTTagCompound(); + for (int x = 0; x < inv.getSizeInventory(); x++) { + final NBTTagCompound item = new NBTTagCompound(); + final ItemStack is = this.getStackInSlot(x); + if (is != null) { + is.writeToNBT(item); + } + opt.setTag("item" + x, item); + } + data.setTag("inv", opt); + } + + @Override + public int getSizeInventory() { + return this.getInternalInventory().getSizeInventory(); + } + + @Override + public ItemStack getStackInSlot(final int i) { + return this.getInternalInventory().getStackInSlot(i); + } + + @Override + public ItemStack decrStackSize(final int i, final int j) { + return this.getInternalInventory().decrStackSize(i, j); + } + + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + return null; + } + + @Override + public void setInventorySlotContents(final int i, @Nullable final ItemStack itemstack) { + this.getInternalInventory().setInventorySlotContents(i, itemstack); + } + + /** + * Returns the name of the inventory + */ + @Override + public String getInventoryName() { + return this.getCustomName(); + } + + /** + * Returns if the inventory is named + */ + @Override + public boolean hasCustomInventoryName() { + return this.hasCustomName(); + } + + @Override + public int getInventoryStackLimit() { + return 64; + } + + @Override + public boolean isUseableByPlayer(final EntityPlayer p) { + final double squaredMCReach = 64.0D; + + return this.worldObj.getTileEntity(this.xCoord, this.yCoord, this.zCoord) == this + && p.getDistanceSq(this.xCoord + 0.5D, this.yCoord + 0.5D, this.zCoord + 0.5D) <= squaredMCReach; + } + + @Override + public void openInventory() {} + + @Override + public void closeInventory() {} + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return true; + } + + @Override + public abstract void onChangeInventory( + IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added); + + @Override + public final int[] getAccessibleSlotsFromSide(final int side) { + final Block blk = this.worldObj.getBlock(this.xCoord, this.yCoord, this.zCoord); + if (blk instanceof AEBaseBlock) { + final ForgeDirection mySide = ForgeDirection.getOrientation(side); + return this.getAccessibleSlotsBySide(((AEBaseBlock) blk).mapRotation(this, mySide)); + } + return this.getAccessibleSlotsBySide(ForgeDirection.getOrientation(side)); + } + + @Override + public boolean canInsertItem(final int slotIndex, final ItemStack insertingItem, final int side) { + return this.isItemValidForSlot(slotIndex, insertingItem); + } + + @Override + public boolean canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + return true; + } + + public abstract int[] getAccessibleSlotsBySide(ForgeDirection whichSide); } diff --git a/src/main/java/appeng/tile/AEBaseTile.java b/src/main/java/appeng/tile/AEBaseTile.java index 7eda68ef97f..15303d9ce26 100644 --- a/src/main/java/appeng/tile/AEBaseTile.java +++ b/src/main/java/appeng/tile/AEBaseTile.java @@ -18,7 +18,6 @@ package appeng.tile; - import appeng.api.implementations.tiles.ISegmentedInventory; import appeng.api.util.ICommonTile; import appeng.api.util.IConfigManager; @@ -35,6 +34,11 @@ import appeng.util.SettingsFrom; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import java.lang.ref.WeakReference; +import java.lang.reflect.Method; +import java.util.*; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -46,545 +50,441 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.lang.ref.WeakReference; -import java.lang.reflect.Method; -import java.util.*; - - -public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, ICustomNameObject -{ - - private static final ThreadLocal> DROP_NO_ITEMS = new ThreadLocal>(); - private static final Map, Map>> HANDLERS = new HashMap, Map>>(); - private static final Map, IStackSrc> ITEM_STACKS = new HashMap, IStackSrc>(); - private int renderFragment = 0; - @Nullable - private String customName; - private ForgeDirection forward = ForgeDirection.UNKNOWN; - private ForgeDirection up = ForgeDirection.UNKNOWN; - - public static void registerTileItem( final Class c, final IStackSrc wat ) - { - ITEM_STACKS.put( c, wat ); - } - - public boolean dropItems() - { - final WeakReference what = DROP_NO_ITEMS.get(); - return what == null || what.get() != this; - } - - public boolean notLoaded() - { - return !this.worldObj.blockExists( this.xCoord, this.yCoord, this.zCoord ); - } - - @Nonnull - public TileEntity getTile() - { - return this; - } - - @Nullable - protected ItemStack getItemFromTile( final Object obj ) - { - final IStackSrc src = ITEM_STACKS.get( obj.getClass() ); - if( src == null ) - { - return null; - } - return src.stack( 1 ); - } - - /** - * for dormant chunk cache. - */ - public void onChunkLoad() - { - if( this.isInvalid() ) - { - this.validate(); - } - } - - @Override - // NOTE: WAS FINAL, changed for Immibis - public final void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - - if( data.hasKey( "customName" ) ) - { - this.customName = data.getString( "customName" ); - } - else - { - this.customName = null; - } - - try - { - if( this.canBeRotated() ) - { - this.forward = ForgeDirection.valueOf( data.getString( "orientation_forward" ) ); - this.up = ForgeDirection.valueOf( data.getString( "orientation_up" ) ); - } - } - catch( final IllegalArgumentException ignored ) - { - } - - for( final AETileEventHandler h : this.getHandlerListFor( TileEventType.WORLD_NBT_READ ) ) - { - h.readFromNBT( this, data ); - } - } - - @Override - // NOTE: WAS FINAL, changed for Immibis - public final void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - - if( this.canBeRotated() ) - { - data.setString( "orientation_forward", this.forward.name() ); - data.setString( "orientation_up", this.up.name() ); - } - - if( this.customName != null ) - { - data.setString( "customName", this.customName ); - } - - for( final AETileEventHandler h : this.getHandlerListFor( TileEventType.WORLD_NBT_WRITE ) ) - { - h.writeToNBT( this, data ); - } - } - - @Override - public final void updateEntity() - { - for( final AETileEventHandler h : this.getHandlerListFor( TileEventType.TICK ) ) - { - h.tick( this ); - } - } - - @Override - public Packet getDescriptionPacket() - { - final NBTTagCompound data = new NBTTagCompound(); - - final ByteBuf stream = Unpooled.buffer(); - - try - { - this.writeToStream( stream ); - if( stream.readableBytes() == 0 ) - { - return null; - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - - stream.capacity( stream.readableBytes() ); - data.setByteArray( "X", stream.array() ); - return new S35PacketUpdateTileEntity( this.xCoord, this.yCoord, this.zCoord, 64, data ); - } - - @Override - public final boolean canUpdate() - { - return this.hasHandlerFor( TileEventType.TICK ); - } - - private boolean hasHandlerFor( final TileEventType type ) - { - final List list = this.getHandlerListFor( type ); - - return !list.isEmpty(); - } - - @Override - public void onDataPacket( final NetworkManager net, final S35PacketUpdateTileEntity pkt ) - { - // / pkt.actionType - if( pkt.func_148853_f() == 64 ) - { - final ByteBuf stream = Unpooled.copiedBuffer( pkt.func_148857_g().getByteArray( "X" ) ); - if( this.readFromStream( stream ) ) - { - this.markForUpdate(); - } - } - } - - @Override - public void onChunkUnload() - { - if( !this.isInvalid() ) - { - this.invalidate(); - } - } - - private final boolean readFromStream( final ByteBuf data ) - { - boolean output = false; - - try - { - - if( this.canBeRotated() ) - { - final ForgeDirection old_Forward = this.forward; - final ForgeDirection old_Up = this.up; - - final byte orientation = data.readByte(); - this.forward = ForgeDirection.getOrientation( orientation & 0x7 ); - this.up = ForgeDirection.getOrientation( orientation >> 3 ); - - output = this.forward != old_Forward || this.up != old_Up; - } - - this.renderFragment = 100; - for( final AETileEventHandler h : this.getHandlerListFor( TileEventType.NETWORK_READ ) ) - { - if( h.readFromStream( this, data ) ) - { - output = true; - } - } - - if( ( this.renderFragment & 1 ) == 1 ) - { - output = true; - } - this.renderFragment = 0; - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - - return output; - } - - public void markForUpdate() - { - if( this.renderFragment > 0 ) - { - this.renderFragment |= 1; - } - else - { - // TODO: Optimize Network Load - if( this.worldObj != null ) - { - AELog.blockUpdate( this.xCoord, this.yCoord, this.zCoord, this ); - this.worldObj.markBlockForUpdate( this.xCoord, this.yCoord, this.zCoord ); - this.worldObj.markTileEntityChunkModified( this.xCoord, this.yCoord, this.zCoord, this ); - } - } - } - - private final void writeToStream( final ByteBuf data ) - { - try - { - if( this.canBeRotated() ) - { - final byte orientation = (byte) ( ( this.up.ordinal() << 3 ) | this.forward.ordinal() ); - data.writeByte( orientation ); - } - - for( final AETileEventHandler h : this.getHandlerListFor( TileEventType.NETWORK_WRITE ) ) - { - h.writeToStream( this, data ); - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - } - - /** - * By default all blocks can have orientation, this handles saving, and loading, as well as synchronization. - * - * @return true if tile can be rotated - */ - @Override - public boolean canBeRotated() - { - return true; - } - - @Nonnull - private List getHandlerListFor( final TileEventType type ) - { - final Map> eventToHandlers = this.getEventToHandlers(); - final List handlers = this.getHandlers( eventToHandlers, type ); - - return handlers; - } - - @Nonnull - private Map> getEventToHandlers() - { - final Class clazz = this.getClass(); - final Map> storedHandlers = HANDLERS.get( clazz ); - - if( storedHandlers == null ) - { - final Map> newStoredHandlers = new EnumMap>( TileEventType.class ); - - HANDLERS.put( clazz, newStoredHandlers ); - - for( final Method method : clazz.getMethods() ) - { - final TileEvent event = method.getAnnotation( TileEvent.class ); - if( event != null ) - { - this.addHandler( newStoredHandlers, event.value(), method ); - } - } - - return newStoredHandlers; - } - else - { - return storedHandlers; - } - } - - @Nonnull - private List getHandlers( final Map> eventToHandlers, final TileEventType event ) - { - final List oldHandlers = eventToHandlers.get( event ); - - if( oldHandlers == null ) - { - final List newHandlers = new LinkedList(); - eventToHandlers.put( event, newHandlers ); - - return newHandlers; - } - else - { - return oldHandlers; - } - } - - private void addHandler( final Map> handlerSet, final TileEventType value, final Method m ) - { - List list = handlerSet.get( value ); - - if( list == null ) - { - list = new ArrayList(); - handlerSet.put( value, list ); - } - - list.add( new AETileEventHandler( m ) ); - } - - @Override - public ForgeDirection getForward() - { - return this.forward; - } - - @Override - public ForgeDirection getUp() - { - return this.up; - } - - @Override - public void setOrientation( final ForgeDirection inForward, final ForgeDirection inUp ) - { - this.forward = inForward; - this.up = inUp; - this.markForUpdate(); - Platform.notifyBlocksOfNeighbors( this.worldObj, this.xCoord, this.yCoord, this.zCoord ); - } - - public void onPlacement( final ItemStack stack, final EntityPlayer player, final int side ) - { - if( stack.hasTagCompound() ) - { - this.uploadSettings( SettingsFrom.DISMANTLE_ITEM, stack.getTagCompound() ); - } - } - - /** - * depending on the from, different settings will be accepted, don't call this with null - * - * @param from source of settings - * @param compound compound of source - */ - public void uploadSettings( final SettingsFrom from, final NBTTagCompound compound ) - { - if( compound != null && this instanceof IConfigurableObject ) - { - final IConfigManager cm = ( (IConfigurableObject) this ).getConfigManager(); - if( cm != null ) - { - cm.readFromNBT( compound ); - } - } - - if( this instanceof IPriorityHost ) - { - final IPriorityHost pHost = (IPriorityHost) this; - pHost.setPriority( compound.getInteger( "priority" ) ); - } - - if( this instanceof ISegmentedInventory ) - { - final IInventory inv = ( (ISegmentedInventory) this ).getInventoryByName( "config" ); - if( inv instanceof AppEngInternalAEInventory ) - { - final AppEngInternalAEInventory target = (AppEngInternalAEInventory) inv; - final AppEngInternalAEInventory tmp = new AppEngInternalAEInventory( null, target.getSizeInventory() ); - tmp.readFromNBT( compound, "config" ); - for( int x = 0; x < tmp.getSizeInventory(); x++ ) - { - target.setInventorySlotContents( x, tmp.getStackInSlot( x ) ); - } - } - } - } - - /** - * returns the contents of the tile entity, into the world, defaults to dropping everything in the inventory. - * - * @param w world - * @param x x pos of tile entity - * @param y y pos of tile entity - * @param z z pos of tile entity - * @param drops drops of tile entity - */ - @Override - public void getDrops( final World w, final int x, final int y, final int z, final List drops ) - { - if( this instanceof IInventory ) - { - final IInventory inv = (IInventory) this; - - for( int l = 0; l < inv.getSizeInventory(); l++ ) - { - final ItemStack is = inv.getStackInSlot( l ); - if( is != null ) - { - drops.add( is ); - } - } - } - } - - public void getNoDrops( final World w, final int x, final int y, final int z, final List drops ) - { - - } - - public void onReady() - { - - } - - /** - * null means nothing to store... - * - * @param from source of settings - * @return compound of source - */ - public NBTTagCompound downloadSettings( final SettingsFrom from ) - { - final NBTTagCompound output = new NBTTagCompound(); - - if( this.hasCustomName() ) - { - final NBTTagCompound dsp = new NBTTagCompound(); - dsp.setString( "Name", this.getCustomName() ); - output.setTag( "display", dsp ); - } - - if( this instanceof IConfigurableObject ) - { - final IConfigManager cm = ( (IConfigurableObject) this ).getConfigManager(); - if( cm != null ) - { - cm.writeToNBT( output ); - } - } - - if( this instanceof IPriorityHost ) - { - final IPriorityHost pHost = (IPriorityHost) this; - output.setInteger( "priority", pHost.getPriority() ); - } - - if( this instanceof ISegmentedInventory ) - { - final IInventory inv = ( (ISegmentedInventory) this ).getInventoryByName( "config" ); - if( inv instanceof AppEngInternalAEInventory ) - { - ( (AppEngInternalAEInventory) inv ).writeToNBT( output, "config" ); - } - } - - return output.hasNoTags() ? null : output; - } - - @Override - public String getCustomName() - { - return this.hasCustomName() ? this.customName : this.getClass().getSimpleName(); - } - - @Override - public boolean hasCustomName() - { - return this.customName != null && this.customName.length() > 0; - } - - @Override - public void setCustomName(String name) { - setName(name); - } - - public void securityBreak() - { - this.worldObj.func_147480_a( this.xCoord, this.yCoord, this.zCoord, true ); - this.disableDrops(); - } - - public void disableDrops() - { - DROP_NO_ITEMS.set( new WeakReference( this ) ); - } - - public void saveChanges() - { - super.markDirty(); - } - - public boolean requiresTESR() - { - return false; - } - - public void setName( final String name ) - { - this.customName = name; - } +public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, ICustomNameObject { + + private static final ThreadLocal> DROP_NO_ITEMS = + new ThreadLocal>(); + private static final Map, Map>> HANDLERS = + new HashMap, Map>>(); + private static final Map, IStackSrc> ITEM_STACKS = + new HashMap, IStackSrc>(); + private int renderFragment = 0; + + @Nullable + private String customName; + + private ForgeDirection forward = ForgeDirection.UNKNOWN; + private ForgeDirection up = ForgeDirection.UNKNOWN; + + public static void registerTileItem(final Class c, final IStackSrc wat) { + ITEM_STACKS.put(c, wat); + } + + public boolean dropItems() { + final WeakReference what = DROP_NO_ITEMS.get(); + return what == null || what.get() != this; + } + + public boolean notLoaded() { + return !this.worldObj.blockExists(this.xCoord, this.yCoord, this.zCoord); + } + + @Nonnull + public TileEntity getTile() { + return this; + } + + @Nullable + protected ItemStack getItemFromTile(final Object obj) { + final IStackSrc src = ITEM_STACKS.get(obj.getClass()); + if (src == null) { + return null; + } + return src.stack(1); + } + + /** + * for dormant chunk cache. + */ + public void onChunkLoad() { + if (this.isInvalid()) { + this.validate(); + } + } + + @Override + // NOTE: WAS FINAL, changed for Immibis + public final void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + + if (data.hasKey("customName")) { + this.customName = data.getString("customName"); + } else { + this.customName = null; + } + + try { + if (this.canBeRotated()) { + this.forward = ForgeDirection.valueOf(data.getString("orientation_forward")); + this.up = ForgeDirection.valueOf(data.getString("orientation_up")); + } + } catch (final IllegalArgumentException ignored) { + } + + for (final AETileEventHandler h : this.getHandlerListFor(TileEventType.WORLD_NBT_READ)) { + h.readFromNBT(this, data); + } + } + + @Override + // NOTE: WAS FINAL, changed for Immibis + public final void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + + if (this.canBeRotated()) { + data.setString("orientation_forward", this.forward.name()); + data.setString("orientation_up", this.up.name()); + } + + if (this.customName != null) { + data.setString("customName", this.customName); + } + + for (final AETileEventHandler h : this.getHandlerListFor(TileEventType.WORLD_NBT_WRITE)) { + h.writeToNBT(this, data); + } + } + + @Override + public final void updateEntity() { + for (final AETileEventHandler h : this.getHandlerListFor(TileEventType.TICK)) { + h.tick(this); + } + } + + @Override + public Packet getDescriptionPacket() { + final NBTTagCompound data = new NBTTagCompound(); + + final ByteBuf stream = Unpooled.buffer(); + + try { + this.writeToStream(stream); + if (stream.readableBytes() == 0) { + return null; + } + } catch (final Throwable t) { + AELog.debug(t); + } + + stream.capacity(stream.readableBytes()); + data.setByteArray("X", stream.array()); + return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, 64, data); + } + + @Override + public final boolean canUpdate() { + return this.hasHandlerFor(TileEventType.TICK); + } + + private boolean hasHandlerFor(final TileEventType type) { + final List list = this.getHandlerListFor(type); + + return !list.isEmpty(); + } + + @Override + public void onDataPacket(final NetworkManager net, final S35PacketUpdateTileEntity pkt) { + // / pkt.actionType + if (pkt.func_148853_f() == 64) { + final ByteBuf stream = Unpooled.copiedBuffer(pkt.func_148857_g().getByteArray("X")); + if (this.readFromStream(stream)) { + this.markForUpdate(); + } + } + } + + @Override + public void onChunkUnload() { + if (!this.isInvalid()) { + this.invalidate(); + } + } + + private final boolean readFromStream(final ByteBuf data) { + boolean output = false; + + try { + + if (this.canBeRotated()) { + final ForgeDirection old_Forward = this.forward; + final ForgeDirection old_Up = this.up; + + final byte orientation = data.readByte(); + this.forward = ForgeDirection.getOrientation(orientation & 0x7); + this.up = ForgeDirection.getOrientation(orientation >> 3); + + output = this.forward != old_Forward || this.up != old_Up; + } + + this.renderFragment = 100; + for (final AETileEventHandler h : this.getHandlerListFor(TileEventType.NETWORK_READ)) { + if (h.readFromStream(this, data)) { + output = true; + } + } + + if ((this.renderFragment & 1) == 1) { + output = true; + } + this.renderFragment = 0; + } catch (final Throwable t) { + AELog.debug(t); + } + + return output; + } + + public void markForUpdate() { + if (this.renderFragment > 0) { + this.renderFragment |= 1; + } else { + // TODO: Optimize Network Load + if (this.worldObj != null) { + AELog.blockUpdate(this.xCoord, this.yCoord, this.zCoord, this); + this.worldObj.markBlockForUpdate(this.xCoord, this.yCoord, this.zCoord); + this.worldObj.markTileEntityChunkModified(this.xCoord, this.yCoord, this.zCoord, this); + } + } + } + + private final void writeToStream(final ByteBuf data) { + try { + if (this.canBeRotated()) { + final byte orientation = (byte) ((this.up.ordinal() << 3) | this.forward.ordinal()); + data.writeByte(orientation); + } + + for (final AETileEventHandler h : this.getHandlerListFor(TileEventType.NETWORK_WRITE)) { + h.writeToStream(this, data); + } + } catch (final Throwable t) { + AELog.debug(t); + } + } + + /** + * By default all blocks can have orientation, this handles saving, and loading, as well as synchronization. + * + * @return true if tile can be rotated + */ + @Override + public boolean canBeRotated() { + return true; + } + + @Nonnull + private List getHandlerListFor(final TileEventType type) { + final Map> eventToHandlers = this.getEventToHandlers(); + final List handlers = this.getHandlers(eventToHandlers, type); + + return handlers; + } + + @Nonnull + private Map> getEventToHandlers() { + final Class clazz = this.getClass(); + final Map> storedHandlers = HANDLERS.get(clazz); + + if (storedHandlers == null) { + final Map> newStoredHandlers = + new EnumMap>(TileEventType.class); + + HANDLERS.put(clazz, newStoredHandlers); + + for (final Method method : clazz.getMethods()) { + final TileEvent event = method.getAnnotation(TileEvent.class); + if (event != null) { + this.addHandler(newStoredHandlers, event.value(), method); + } + } + + return newStoredHandlers; + } else { + return storedHandlers; + } + } + + @Nonnull + private List getHandlers( + final Map> eventToHandlers, final TileEventType event) { + final List oldHandlers = eventToHandlers.get(event); + + if (oldHandlers == null) { + final List newHandlers = new LinkedList(); + eventToHandlers.put(event, newHandlers); + + return newHandlers; + } else { + return oldHandlers; + } + } + + private void addHandler( + final Map> handlerSet, final TileEventType value, final Method m) { + List list = handlerSet.get(value); + + if (list == null) { + list = new ArrayList(); + handlerSet.put(value, list); + } + + list.add(new AETileEventHandler(m)); + } + + @Override + public ForgeDirection getForward() { + return this.forward; + } + + @Override + public ForgeDirection getUp() { + return this.up; + } + + @Override + public void setOrientation(final ForgeDirection inForward, final ForgeDirection inUp) { + this.forward = inForward; + this.up = inUp; + this.markForUpdate(); + Platform.notifyBlocksOfNeighbors(this.worldObj, this.xCoord, this.yCoord, this.zCoord); + } + + public void onPlacement(final ItemStack stack, final EntityPlayer player, final int side) { + if (stack.hasTagCompound()) { + this.uploadSettings(SettingsFrom.DISMANTLE_ITEM, stack.getTagCompound()); + } + } + + /** + * depending on the from, different settings will be accepted, don't call this with null + * + * @param from source of settings + * @param compound compound of source + */ + public void uploadSettings(final SettingsFrom from, final NBTTagCompound compound) { + if (compound != null && this instanceof IConfigurableObject) { + final IConfigManager cm = ((IConfigurableObject) this).getConfigManager(); + if (cm != null) { + cm.readFromNBT(compound); + } + } + + if (this instanceof IPriorityHost) { + final IPriorityHost pHost = (IPriorityHost) this; + pHost.setPriority(compound.getInteger("priority")); + } + + if (this instanceof ISegmentedInventory) { + final IInventory inv = ((ISegmentedInventory) this).getInventoryByName("config"); + if (inv instanceof AppEngInternalAEInventory) { + final AppEngInternalAEInventory target = (AppEngInternalAEInventory) inv; + final AppEngInternalAEInventory tmp = new AppEngInternalAEInventory(null, target.getSizeInventory()); + tmp.readFromNBT(compound, "config"); + for (int x = 0; x < tmp.getSizeInventory(); x++) { + target.setInventorySlotContents(x, tmp.getStackInSlot(x)); + } + } + } + } + + /** + * returns the contents of the tile entity, into the world, defaults to dropping everything in the inventory. + * + * @param w world + * @param x x pos of tile entity + * @param y y pos of tile entity + * @param z z pos of tile entity + * @param drops drops of tile entity + */ + @Override + public void getDrops(final World w, final int x, final int y, final int z, final List drops) { + if (this instanceof IInventory) { + final IInventory inv = (IInventory) this; + + for (int l = 0; l < inv.getSizeInventory(); l++) { + final ItemStack is = inv.getStackInSlot(l); + if (is != null) { + drops.add(is); + } + } + } + } + + public void getNoDrops(final World w, final int x, final int y, final int z, final List drops) {} + + public void onReady() {} + + /** + * null means nothing to store... + * + * @param from source of settings + * @return compound of source + */ + public NBTTagCompound downloadSettings(final SettingsFrom from) { + final NBTTagCompound output = new NBTTagCompound(); + + if (this.hasCustomName()) { + final NBTTagCompound dsp = new NBTTagCompound(); + dsp.setString("Name", this.getCustomName()); + output.setTag("display", dsp); + } + + if (this instanceof IConfigurableObject) { + final IConfigManager cm = ((IConfigurableObject) this).getConfigManager(); + if (cm != null) { + cm.writeToNBT(output); + } + } + + if (this instanceof IPriorityHost) { + final IPriorityHost pHost = (IPriorityHost) this; + output.setInteger("priority", pHost.getPriority()); + } + + if (this instanceof ISegmentedInventory) { + final IInventory inv = ((ISegmentedInventory) this).getInventoryByName("config"); + if (inv instanceof AppEngInternalAEInventory) { + ((AppEngInternalAEInventory) inv).writeToNBT(output, "config"); + } + } + + return output.hasNoTags() ? null : output; + } + + @Override + public String getCustomName() { + return this.hasCustomName() ? this.customName : this.getClass().getSimpleName(); + } + + @Override + public boolean hasCustomName() { + return this.customName != null && this.customName.length() > 0; + } + + @Override + public void setCustomName(String name) { + setName(name); + } + + public void securityBreak() { + this.worldObj.func_147480_a(this.xCoord, this.yCoord, this.zCoord, true); + this.disableDrops(); + } + + public void disableDrops() { + DROP_NO_ITEMS.set(new WeakReference(this)); + } + + public void saveChanges() { + super.markDirty(); + } + + public boolean requiresTESR() { + return false; + } + + public void setName(final String name) { + this.customName = name; + } } diff --git a/src/main/java/appeng/tile/TileEvent.java b/src/main/java/appeng/tile/TileEvent.java index 8a0024f1893..8d8c4bca9ef 100644 --- a/src/main/java/appeng/tile/TileEvent.java +++ b/src/main/java/appeng/tile/TileEvent.java @@ -18,16 +18,12 @@ package appeng.tile; - import appeng.tile.events.TileEventType; - import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +@Retention(RetentionPolicy.RUNTIME) +public @interface TileEvent { -@Retention( RetentionPolicy.RUNTIME ) -public @interface TileEvent -{ - - TileEventType value(); + TileEventType value(); } diff --git a/src/main/java/appeng/tile/crafting/TileCraftingMonitorTile.java b/src/main/java/appeng/tile/crafting/TileCraftingMonitorTile.java index 4657730cc88..baaf9a7d656 100644 --- a/src/main/java/appeng/tile/crafting/TileCraftingMonitorTile.java +++ b/src/main/java/appeng/tile/crafting/TileCraftingMonitorTile.java @@ -18,7 +18,6 @@ package appeng.tile.crafting; - import appeng.api.implementations.tiles.IColorableTile; import appeng.api.storage.data.IAEItemStack; import appeng.api.util.AEColor; @@ -28,154 +27,124 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; - - -public class TileCraftingMonitorTile extends TileCraftingTile implements IColorableTile -{ - - @SideOnly( Side.CLIENT ) - private Integer dspList; - - @SideOnly( Side.CLIENT ) - private boolean updateList; - - private IAEItemStack dspPlay; - private AEColor paintedColor = AEColor.Transparent; - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileCraftingMonitorTile( final ByteBuf data ) throws IOException - { - final AEColor oldPaintedColor = this.paintedColor; - this.paintedColor = AEColor.values()[data.readByte()]; - - final boolean hasItem = data.readBoolean(); - - if( hasItem ) - { - this.dspPlay = AEItemStack.loadItemStackFromPacket( data ); - } - else - { - this.dspPlay = null; - } - - this.setUpdateList( true ); - return oldPaintedColor != this.paintedColor; // tesr! - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileCraftingMonitorTile( final ByteBuf data ) throws IOException - { - data.writeByte( this.paintedColor.ordinal() ); - - if( this.dspPlay == null ) - { - data.writeBoolean( false ); - } - else - { - data.writeBoolean( true ); - this.dspPlay.writeToPacket( data ); - } - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileCraftingMonitorTile( final NBTTagCompound data ) - { - if( data.hasKey( "paintedColor" ) ) - { - this.paintedColor = AEColor.values()[data.getByte( "paintedColor" )]; - } - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileCraftingMonitorTile( final NBTTagCompound data ) - { - data.setByte( "paintedColor", (byte) this.paintedColor.ordinal() ); - } - - @Override - public boolean isAccelerator() - { - return false; - } - - @Override - public boolean isStatus() - { - return true; - } - - public void setJob( final IAEItemStack is ) - { - if( ( is == null ) != ( this.dspPlay == null ) ) - { - this.dspPlay = is == null ? null : is.copy(); - this.markForUpdate(); - } - else if( is != null && this.dspPlay != null ) - { - if( is.getStackSize() != this.dspPlay.getStackSize() ) - { - this.dspPlay = is.copy(); - this.markForUpdate(); - } - } - } - - public IAEItemStack getJobProgress() - { - return this.dspPlay;// AEItemStack.create( new ItemStack( Items.diamond, 64 ) ); - } - - @Override - public boolean requiresTESR() - { - return this.dspPlay != null; - } - - @Override - public AEColor getColor() - { - return this.paintedColor; - } - - @Override - public boolean recolourBlock( final ForgeDirection side, final AEColor newPaintedColor, final EntityPlayer who ) - { - if( this.paintedColor == newPaintedColor ) - { - return false; - } - - this.paintedColor = newPaintedColor; - this.markDirty(); - this.markForUpdate(); - return true; - } - - public Integer getDisplayList() - { - return this.dspList; - } - - public void setDisplayList( final Integer dspList ) - { - this.dspList = dspList; - } - - public boolean isUpdateList() - { - return this.updateList; - } - - public void setUpdateList( final boolean updateList ) - { - this.updateList = updateList; - } +public class TileCraftingMonitorTile extends TileCraftingTile implements IColorableTile { + + @SideOnly(Side.CLIENT) + private Integer dspList; + + @SideOnly(Side.CLIENT) + private boolean updateList; + + private IAEItemStack dspPlay; + private AEColor paintedColor = AEColor.Transparent; + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileCraftingMonitorTile(final ByteBuf data) throws IOException { + final AEColor oldPaintedColor = this.paintedColor; + this.paintedColor = AEColor.values()[data.readByte()]; + + final boolean hasItem = data.readBoolean(); + + if (hasItem) { + this.dspPlay = AEItemStack.loadItemStackFromPacket(data); + } else { + this.dspPlay = null; + } + + this.setUpdateList(true); + return oldPaintedColor != this.paintedColor; // tesr! + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileCraftingMonitorTile(final ByteBuf data) throws IOException { + data.writeByte(this.paintedColor.ordinal()); + + if (this.dspPlay == null) { + data.writeBoolean(false); + } else { + data.writeBoolean(true); + this.dspPlay.writeToPacket(data); + } + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileCraftingMonitorTile(final NBTTagCompound data) { + if (data.hasKey("paintedColor")) { + this.paintedColor = AEColor.values()[data.getByte("paintedColor")]; + } + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileCraftingMonitorTile(final NBTTagCompound data) { + data.setByte("paintedColor", (byte) this.paintedColor.ordinal()); + } + + @Override + public boolean isAccelerator() { + return false; + } + + @Override + public boolean isStatus() { + return true; + } + + public void setJob(final IAEItemStack is) { + if ((is == null) != (this.dspPlay == null)) { + this.dspPlay = is == null ? null : is.copy(); + this.markForUpdate(); + } else if (is != null && this.dspPlay != null) { + if (is.getStackSize() != this.dspPlay.getStackSize()) { + this.dspPlay = is.copy(); + this.markForUpdate(); + } + } + } + + public IAEItemStack getJobProgress() { + return this.dspPlay; // AEItemStack.create( new ItemStack( Items.diamond, 64 ) ); + } + + @Override + public boolean requiresTESR() { + return this.dspPlay != null; + } + + @Override + public AEColor getColor() { + return this.paintedColor; + } + + @Override + public boolean recolourBlock(final ForgeDirection side, final AEColor newPaintedColor, final EntityPlayer who) { + if (this.paintedColor == newPaintedColor) { + return false; + } + + this.paintedColor = newPaintedColor; + this.markDirty(); + this.markForUpdate(); + return true; + } + + public Integer getDisplayList() { + return this.dspList; + } + + public void setDisplayList(final Integer dspList) { + this.dspList = dspList; + } + + public boolean isUpdateList() { + return this.updateList; + } + + public void setUpdateList(final boolean updateList) { + this.updateList = updateList; + } } diff --git a/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java b/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java index b015d1368ad..eecebdf4001 100644 --- a/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java +++ b/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java @@ -18,78 +18,68 @@ package appeng.tile.crafting; - import appeng.api.AEApi; import appeng.api.definitions.IBlocks; import net.minecraft.item.ItemStack; +public class TileCraftingStorageTile extends TileCraftingTile { + private static final int KILO_SCALAR = 1024; -public class TileCraftingStorageTile extends TileCraftingTile -{ - private static final int KILO_SCALAR = 1024; - - @Override - protected ItemStack getItemFromTile( final Object obj ) - { - final IBlocks blocks = AEApi.instance().definitions().blocks(); - final int storage = ( (TileCraftingTile) obj ).getStorageBytes() / KILO_SCALAR; + @Override + protected ItemStack getItemFromTile(final Object obj) { + final IBlocks blocks = AEApi.instance().definitions().blocks(); + final int storage = ((TileCraftingTile) obj).getStorageBytes() / KILO_SCALAR; - switch( storage ) - { - case 4: - for( final ItemStack stack : blocks.craftingStorage4k().maybeStack( 1 ).asSet() ) - { - return stack; - } - break; - case 16: - for( final ItemStack stack : blocks.craftingStorage16k().maybeStack( 1 ).asSet() ) - { - return stack; - } - break; - case 64: - for( final ItemStack stack : blocks.craftingStorage64k().maybeStack( 1 ).asSet() ) - { - return stack; - } - break; - } + switch (storage) { + case 4: + for (final ItemStack stack : + blocks.craftingStorage4k().maybeStack(1).asSet()) { + return stack; + } + break; + case 16: + for (final ItemStack stack : + blocks.craftingStorage16k().maybeStack(1).asSet()) { + return stack; + } + break; + case 64: + for (final ItemStack stack : + blocks.craftingStorage64k().maybeStack(1).asSet()) { + return stack; + } + break; + } - return super.getItemFromTile( obj ); - } + return super.getItemFromTile(obj); + } - @Override - public boolean isAccelerator() - { - return false; - } + @Override + public boolean isAccelerator() { + return false; + } - @Override - public boolean isStorage() - { - return true; - } + @Override + public boolean isStorage() { + return true; + } - @Override - public int getStorageBytes() - { - if( this.worldObj == null || this.notLoaded() ) - { - return 0; - } + @Override + public int getStorageBytes() { + if (this.worldObj == null || this.notLoaded()) { + return 0; + } - switch( this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) & 3 ) - { - default: - case 0: - return 1024; - case 1: - return 4 * 1024; - case 2: - return 16 * 1024; - case 3: - return 64 * 1024; - } - } + switch (this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord) & 3) { + default: + case 0: + return 1024; + case 1: + return 4 * 1024; + case 2: + return 16 * 1024; + case 3: + return 64 * 1024; + } + } } diff --git a/src/main/java/appeng/tile/crafting/TileCraftingTile.java b/src/main/java/appeng/tile/crafting/TileCraftingTile.java index ad18b302080..c0d23164c65 100644 --- a/src/main/java/appeng/tile/crafting/TileCraftingTile.java +++ b/src/main/java/appeng/tile/crafting/TileCraftingTile.java @@ -18,7 +18,6 @@ package appeng.tile.crafting; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.implementations.IPowerChannelState; @@ -41,345 +40,287 @@ import appeng.tile.events.TileEventType; import appeng.tile.grid.AENetworkTile; import appeng.util.Platform; +import java.util.Arrays; +import java.util.Collections; +import java.util.EnumSet; +import java.util.Iterator; +import java.util.LinkedList; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Arrays; +public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IPowerChannelState { + private final CraftingCPUCalculator calc = new CraftingCPUCalculator(this); + + private ISimplifiedBundle lightCache; + + private NBTTagCompound previousState = null; + private boolean isCoreBlock = false; + private CraftingCPUCluster cluster; + private static final int ACCELERATOR_SCALE_FACTOR = 4; + + public TileCraftingTile() { + this.getProxy().setFlags(GridFlags.MULTIBLOCK, GridFlags.REQUIRE_CHANNEL); + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + } + @Override + protected AENetworkProxy createProxy() { + return new AENetworkProxyMultiblock(this, "proxy", this.getItemFromTile(this), true); + } + + @Override + protected ItemStack getItemFromTile(final Object obj) { + if (((TileCraftingTile) obj).isAccelerator()) { + for (final ItemStack accelerator : AEApi.instance() + .definitions() + .blocks() + .craftingAccelerator() + .maybeStack(1) + .asSet()) { + return accelerator; + } + } + + return super.getItemFromTile(obj); + } + + @Override + public boolean canBeRotated() { + return true; // return BlockCraftingUnit.checkType( worldObj.getBlockMetadata( xCoord, yCoord, zCoord ), + // BlockCraftingUnit.BASE_MONITOR ); + } -public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IPowerChannelState -{ - private final CraftingCPUCalculator calc = new CraftingCPUCalculator( this ); - - private ISimplifiedBundle lightCache; - - private NBTTagCompound previousState = null; - private boolean isCoreBlock = false; - private CraftingCPUCluster cluster; - private static final int ACCELERATOR_SCALE_FACTOR = 4; - - public TileCraftingTile() - { - this.getProxy().setFlags( GridFlags.MULTIBLOCK, GridFlags.REQUIRE_CHANNEL ); - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - } - - @Override - protected AENetworkProxy createProxy() - { - return new AENetworkProxyMultiblock( this, "proxy", this.getItemFromTile( this ), true ); - } - - @Override - protected ItemStack getItemFromTile( final Object obj ) - { - if( ( (TileCraftingTile) obj ).isAccelerator() ) - { - for( final ItemStack accelerator : AEApi.instance().definitions().blocks().craftingAccelerator().maybeStack( 1 ).asSet() ) - { - return accelerator; - } - } - - return super.getItemFromTile( obj ); - } - - @Override - public boolean canBeRotated() - { - return true;// return BlockCraftingUnit.checkType( worldObj.getBlockMetadata( xCoord, yCoord, zCoord ), - // BlockCraftingUnit.BASE_MONITOR ); - } - - @Override - public void setName( final String name ) - { - super.setName( name ); - if( this.cluster != null ) - { - this.cluster.updateName(); - } - } - - public boolean isAccelerator() - { - if( this.worldObj == null ) - { - return false; - } - return Arrays.asList( 1, 2, 3 ).contains(this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) & 3); - } - - public int acceleratorValue() - { - int meta = this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) & 3; - return (int) Math.pow( ACCELERATOR_SCALE_FACTOR, meta - 1 ); + @Override + public void setName(final String name) { + super.setName(name); + if (this.cluster != null) { + this.cluster.updateName(); + } } - @Override - public void onReady() - { - super.onReady(); - this.getProxy().setVisualRepresentation( this.getItemFromTile( this ) ); - this.updateMultiBlock(); - } - - public void updateMultiBlock() - { - this.calc.calculateMultiblock( this.worldObj, this.getLocation() ); - } - - public void updateStatus( final CraftingCPUCluster c ) - { - if( this.cluster != null && this.cluster != c ) - { - this.cluster.breakCluster(); - } - - this.cluster = c; - this.updateMeta( true ); - } - - public void updateMeta( final boolean updateFormed ) - { - if( this.worldObj == null || this.notLoaded() ) - { - return; - } - - final boolean formed = this.isFormed(); - boolean power = false; - - if( this.getProxy().isReady() ) - { - power = this.getProxy().isActive(); - } - - final int current = this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ); - final int newMeta = ( current & 3 ) | ( formed ? 8 : 0 ) | ( power ? 4 : 0 ); - - if( current != newMeta ) - { - this.worldObj.setBlockMetadataWithNotify( this.xCoord, this.yCoord, this.zCoord, newMeta, 2 ); - } - - if( updateFormed ) - { - if( formed ) - { - this.getProxy().setValidSides( EnumSet.allOf( ForgeDirection.class ) ); - } - else - { - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - } - } - } - - public boolean isFormed() - { - if( Platform.isClient() ) - { - return ( this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) & 8 ) == 8; - } - return this.cluster != null; - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileCraftingTile( final NBTTagCompound data ) - { - data.setBoolean( "core", this.isCoreBlock() ); - if( this.isCoreBlock() && this.cluster != null ) - { - this.cluster.writeToNBT( data ); - } - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileCraftingTile( final NBTTagCompound data ) - { - this.setCoreBlock( data.getBoolean( "core" ) ); - if( this.isCoreBlock() ) - { - if( this.cluster != null ) - { - this.cluster.readFromNBT( data ); - } - else - { - this.setPreviousState( (NBTTagCompound) data.copy() ); - } - } - } - - @Override - public void disconnect( final boolean update ) - { - if( this.cluster != null ) - { - this.cluster.destroy(); - if( update ) - { - this.updateMeta( true ); - } - } - } - - @Override - public IAECluster getCluster() - { - return this.cluster; - } - - @Override - public boolean isValid() - { - return true; - } - - @MENetworkEventSubscribe - public void onPowerStateChange( final MENetworkChannelsChanged ev ) - { - this.updateMeta( false ); - } - - @MENetworkEventSubscribe - public void onPowerStateChange( final MENetworkPowerStatusChange ev ) - { - this.updateMeta( false ); - } - - public boolean isStatus() - { - return false; - } - - public boolean isStorage() - { - return false; - } - - public int getStorageBytes() - { - return 0; - } - - public void breakCluster() - { - if( this.cluster != null ) - { - this.cluster.cancel(); - final IMEInventory inv = this.cluster.getInventory(); - - final LinkedList places = new LinkedList(); - - final Iterator i = this.cluster.getTiles(); - while( i.hasNext() ) - { - final IGridHost h = i.next(); - if( h == this ) - { - places.add( new WorldCoord( this ) ); - } - else - { - final TileEntity te = (TileEntity) h; - - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - final WorldCoord wc = new WorldCoord( te ); - wc.add( d, 1 ); - if( this.worldObj.isAirBlock( wc.x, wc.y, wc.z ) ) - { - places.add( wc ); - } - } - } - } - - Collections.shuffle( places ); - - if( places.isEmpty() ) - { - throw new IllegalStateException( this.cluster + " does not contain any kind of blocks, which were destroyed." ); - } - - for( IAEItemStack ais : inv.getAvailableItems( AEApi.instance().storage().createItemList() ) ) - { - ais = ais.copy(); - ais.setStackSize( ais.getItemStack().getMaxStackSize() ); - while( true ) - { - final IAEItemStack g = inv.extractItems( ais.copy(), Actionable.MODULATE, this.cluster.getActionSource() ); - if( g == null ) - { - break; - } - - final WorldCoord wc = places.poll(); - places.add( wc ); - - Platform.spawnDrops( this.worldObj, wc.x, wc.y, wc.z, Collections.singletonList( g.getItemStack() ) ); - } - } - - this.cluster.destroy(); - } - } - - @Override - public boolean isPowered() - { - if( Platform.isClient() ) - { - return ( this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) & 4 ) == 4; - } - return this.getProxy().isActive(); - } - - @Override - public boolean isActive() - { - if( Platform.isServer() ) - { - return this.getProxy().isActive(); - } - return this.isPowered() && this.isFormed(); - } - - public boolean isCoreBlock() - { - return this.isCoreBlock; - } - - public void setCoreBlock( final boolean isCoreBlock ) - { - this.isCoreBlock = isCoreBlock; - } - - public ISimplifiedBundle getLightCache() - { - return this.lightCache; - } - - public void setLightCache( final ISimplifiedBundle lightCache ) - { - this.lightCache = lightCache; - } - - public NBTTagCompound getPreviousState() - { - return this.previousState; - } - - public void setPreviousState( final NBTTagCompound previousState ) - { - this.previousState = previousState; - } + public boolean isAccelerator() { + if (this.worldObj == null) { + return false; + } + return Arrays.asList(1, 2, 3) + .contains(this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord) & 3); + } + + public int acceleratorValue() { + int meta = this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord) & 3; + return (int) Math.pow(ACCELERATOR_SCALE_FACTOR, meta - 1); + } + + @Override + public void onReady() { + super.onReady(); + this.getProxy().setVisualRepresentation(this.getItemFromTile(this)); + this.updateMultiBlock(); + } + + public void updateMultiBlock() { + this.calc.calculateMultiblock(this.worldObj, this.getLocation()); + } + + public void updateStatus(final CraftingCPUCluster c) { + if (this.cluster != null && this.cluster != c) { + this.cluster.breakCluster(); + } + + this.cluster = c; + this.updateMeta(true); + } + + public void updateMeta(final boolean updateFormed) { + if (this.worldObj == null || this.notLoaded()) { + return; + } + + final boolean formed = this.isFormed(); + boolean power = false; + + if (this.getProxy().isReady()) { + power = this.getProxy().isActive(); + } + + final int current = this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord); + final int newMeta = (current & 3) | (formed ? 8 : 0) | (power ? 4 : 0); + + if (current != newMeta) { + this.worldObj.setBlockMetadataWithNotify(this.xCoord, this.yCoord, this.zCoord, newMeta, 2); + } + + if (updateFormed) { + if (formed) { + this.getProxy().setValidSides(EnumSet.allOf(ForgeDirection.class)); + } else { + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + } + } + } + + public boolean isFormed() { + if (Platform.isClient()) { + return (this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord) & 8) == 8; + } + return this.cluster != null; + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileCraftingTile(final NBTTagCompound data) { + data.setBoolean("core", this.isCoreBlock()); + if (this.isCoreBlock() && this.cluster != null) { + this.cluster.writeToNBT(data); + } + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileCraftingTile(final NBTTagCompound data) { + this.setCoreBlock(data.getBoolean("core")); + if (this.isCoreBlock()) { + if (this.cluster != null) { + this.cluster.readFromNBT(data); + } else { + this.setPreviousState((NBTTagCompound) data.copy()); + } + } + } + + @Override + public void disconnect(final boolean update) { + if (this.cluster != null) { + this.cluster.destroy(); + if (update) { + this.updateMeta(true); + } + } + } + + @Override + public IAECluster getCluster() { + return this.cluster; + } + + @Override + public boolean isValid() { + return true; + } + + @MENetworkEventSubscribe + public void onPowerStateChange(final MENetworkChannelsChanged ev) { + this.updateMeta(false); + } + + @MENetworkEventSubscribe + public void onPowerStateChange(final MENetworkPowerStatusChange ev) { + this.updateMeta(false); + } + + public boolean isStatus() { + return false; + } + + public boolean isStorage() { + return false; + } + + public int getStorageBytes() { + return 0; + } + + public void breakCluster() { + if (this.cluster != null) { + this.cluster.cancel(); + final IMEInventory inv = this.cluster.getInventory(); + + final LinkedList places = new LinkedList(); + + final Iterator i = this.cluster.getTiles(); + while (i.hasNext()) { + final IGridHost h = i.next(); + if (h == this) { + places.add(new WorldCoord(this)); + } else { + final TileEntity te = (TileEntity) h; + + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + final WorldCoord wc = new WorldCoord(te); + wc.add(d, 1); + if (this.worldObj.isAirBlock(wc.x, wc.y, wc.z)) { + places.add(wc); + } + } + } + } + + Collections.shuffle(places); + + if (places.isEmpty()) { + throw new IllegalStateException( + this.cluster + " does not contain any kind of blocks, which were destroyed."); + } + + for (IAEItemStack ais : + inv.getAvailableItems(AEApi.instance().storage().createItemList())) { + ais = ais.copy(); + ais.setStackSize(ais.getItemStack().getMaxStackSize()); + while (true) { + final IAEItemStack g = + inv.extractItems(ais.copy(), Actionable.MODULATE, this.cluster.getActionSource()); + if (g == null) { + break; + } + + final WorldCoord wc = places.poll(); + places.add(wc); + + Platform.spawnDrops(this.worldObj, wc.x, wc.y, wc.z, Collections.singletonList(g.getItemStack())); + } + } + + this.cluster.destroy(); + } + } + + @Override + public boolean isPowered() { + if (Platform.isClient()) { + return (this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord) & 4) == 4; + } + return this.getProxy().isActive(); + } + + @Override + public boolean isActive() { + if (Platform.isServer()) { + return this.getProxy().isActive(); + } + return this.isPowered() && this.isFormed(); + } + + public boolean isCoreBlock() { + return this.isCoreBlock; + } + + public void setCoreBlock(final boolean isCoreBlock) { + this.isCoreBlock = isCoreBlock; + } + + public ISimplifiedBundle getLightCache() { + return this.lightCache; + } + + public void setLightCache(final ISimplifiedBundle lightCache) { + this.lightCache = lightCache; + } + + public NBTTagCompound getPreviousState() { + return this.previousState; + } + + public void setPreviousState(final NBTTagCompound previousState) { + this.previousState = previousState; + } } diff --git a/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java b/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java index 48e93e5f459..ef99b424b15 100644 --- a/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java +++ b/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java @@ -18,7 +18,6 @@ package appeng.tile.crafting; - import appeng.api.AEApi; import appeng.api.config.*; import appeng.api.definitions.ITileDefinition; @@ -57,6 +56,8 @@ import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint; import io.netty.buffer.ByteBuf; +import java.io.IOException; +import java.util.List; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; @@ -66,596 +67,506 @@ import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; -import java.util.List; - - public class TileMolecularAssembler extends AENetworkInvTile - implements IUpgradeableHost, IConfigManagerHost, IGridTickable, ICraftingMachine, IPowerChannelState -{ - private static final int[] SIDES = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - - private final InventoryCrafting craftingInv; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 9 + 2 ); - private final IConfigManager settings; - private final UpgradeInventory upgrades; - private ISimplifiedBundle lightCache; - private boolean isPowered = false; - private ForgeDirection pushDirection = ForgeDirection.UNKNOWN; - private ItemStack myPattern = null; - private ICraftingPatternDetails myPlan = null; - private double progress = 0; - private boolean isAwake = false; - private boolean forcePlan = false; - private boolean reboot = true; - - public TileMolecularAssembler() - { - final ITileDefinition assembler = AEApi.instance().definitions().blocks().molecularAssembler(); - - this.settings = new ConfigManager( this ); - this.settings.registerSetting( Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.inv.setMaxStackSize( 1 ); - this.getProxy().setIdlePowerUsage( 0.0 ); - this.upgrades = new DefinitionUpgradeInventory( assembler, this, this.getUpgradeSlots() ); - this.craftingInv = new InventoryCrafting( new ContainerNull(), 3, 3 ); - } - - private int getUpgradeSlots() - { - return 5; - } - - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table, final ForgeDirection where ) - { - if( this.myPattern == null ) - { - boolean isEmpty = true; - for( int x = 0; x < this.inv.getSizeInventory(); x++ ) - { - isEmpty = this.inv.getStackInSlot( x ) == null && isEmpty; - } - - if( isEmpty && patternDetails.isCraftable() ) - { - this.forcePlan = true; - this.myPlan = patternDetails; - this.pushDirection = where; - - for( int x = 0; x < table.getSizeInventory(); x++ ) - { - this.inv.setInventorySlotContents( x, table.getStackInSlot( x ) ); - } - - this.updateSleepiness(); - this.markDirty(); - return true; - } - } - return false; - } - - private void updateSleepiness() - { - final boolean wasEnabled = this.isAwake; - this.isAwake = this.myPlan != null && this.hasMats() || this.canPush(); - if( wasEnabled != this.isAwake ) - { - try - { - if( this.isAwake ) - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - else - { - this.getProxy().getTick().sleepDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - } - - private boolean canPush() - { - return this.inv.getStackInSlot( 9 ) != null; - } - - private boolean hasMats() - { - if( this.myPlan == null ) - { - return false; - } - - for( int x = 0; x < this.craftingInv.getSizeInventory(); x++ ) - { - this.craftingInv.setInventorySlotContents( x, this.inv.getStackInSlot( x ) ); - } - - return this.myPlan.getOutput( this.craftingInv, this.getWorldObj() ) != null; - } - - @Override - public boolean acceptsPlans() - { - return this.inv.getStackInSlot( 10 ) == null; - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.upgrades.getInstalledUpgrades( u ); - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileMolecularAssembler( final ByteBuf data ) - { - final boolean oldPower = this.isPowered; - this.isPowered = data.readBoolean(); - return this.isPowered != oldPower; - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileMolecularAssembler( final ByteBuf data ) - { - data.writeBoolean( this.isPowered ); - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileMolecularAssembler( final NBTTagCompound data ) - { - if( this.forcePlan && this.myPlan != null ) - { - final ItemStack pattern = this.myPlan.getPattern(); - if( pattern != null ) - { - final NBTTagCompound compound = new NBTTagCompound(); - pattern.writeToNBT( compound ); - data.setTag( "myPlan", compound ); - data.setInteger( "pushDirection", this.pushDirection.ordinal() ); - } - } - - this.upgrades.writeToNBT( data, "upgrades" ); - this.inv.writeToNBT( data, "inv" ); - this.settings.writeToNBT( data ); - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileMolecularAssembler( final NBTTagCompound data ) - { - if( data.hasKey( "myPlan" ) ) - { - final ItemStack myPat = ItemStack.loadItemStackFromNBT( data.getCompoundTag( "myPlan" ) ); - - if( myPat != null && myPat.getItem() instanceof ItemEncodedPattern ) - { - final World w = this.getWorldObj(); - final ItemEncodedPattern iep = (ItemEncodedPattern) myPat.getItem(); - final ICraftingPatternDetails ph = iep.getPatternForItem( myPat, w ); - if( ph != null && ph.isCraftable() ) - { - this.forcePlan = true; - this.myPlan = ph; - this.pushDirection = ForgeDirection.getOrientation( data.getInteger( "pushDirection" ) ); - } - } - } - - this.upgrades.readFromNBT( data, "upgrades" ); - this.inv.readFromNBT( data, "inv" ); - this.settings.readFromNBT( data ); - this.recalculatePlan(); - } - - private void recalculatePlan() - { - this.reboot = true; - - if( this.forcePlan ) - { - return; - } - - final ItemStack is = this.inv.getStackInSlot( 10 ); - - if( is != null && is.getItem() instanceof ItemEncodedPattern ) - { - if( !Platform.isSameItem( is, this.myPattern ) ) - { - final World w = this.getWorldObj(); - final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); - final ICraftingPatternDetails ph = iep.getPatternForItem( is, w ); - - if( ph != null && ph.isCraftable() ) - { - this.progress = 0; - this.myPattern = is; - this.myPlan = ph; - } - } - } - else - { - this.progress = 0; - this.forcePlan = false; - this.myPlan = null; - this.myPattern = null; - this.pushDirection = ForgeDirection.UNKNOWN; - } - - this.updateSleepiness(); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - @Override - public IConfigManager getConfigManager() - { - return this.settings; - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "upgrades" ) ) - { - return this.upgrades; - } - - if( name.equals( "mac" ) ) - { - return this.inv; - } - - return null; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - - @Override - public int getInventoryStackLimit() - { - return 1; - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - if( i >= 9 ) - { - return false; - } - - if( this.hasPattern() ) - { - return this.myPlan.isValidItemForSlot( i, itemstack, this.getWorldObj() ); - } - - return false; - } - - private boolean hasPattern() - { - return this.myPlan != null && this.inv.getStackInSlot( 10 ) != null; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( inv == this.inv ) - { - this.recalculatePlan(); - } - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - return slotIndex == 9; - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection whichSide ) - { - return SIDES; - } - - public int getCraftingProgress() - { - return (int) this.progress; - } - - @Override - public void getDrops( final World w, final int x, final int y, final int z, final List drops ) - { - super.getDrops( w, x, y, z, drops ); - - for( int h = 0; h < this.upgrades.getSizeInventory(); h++ ) - { - final ItemStack is = this.upgrades.getStackInSlot( h ); - if( is != null ) - { - drops.add( is ); - } - } - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - this.recalculatePlan(); - this.updateSleepiness(); - return new TickingRequest( 1, 1, !this.isAwake, false ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, int ticksSinceLastCall ) - { - if( this.inv.getStackInSlot( 9 ) != null ) - { - this.pushOut( this.inv.getStackInSlot( 9 ) ); - - // did it eject? - if( this.inv.getStackInSlot( 9 ) == null ) - { - this.markDirty(); - } - - this.ejectHeldItems(); - this.updateSleepiness(); - this.progress = 0; - return this.isAwake ? TickRateModulation.IDLE : TickRateModulation.SLEEP; - } - - if( this.myPlan == null ) - { - this.updateSleepiness(); - return TickRateModulation.SLEEP; - } - - if( this.reboot ) - { - ticksSinceLastCall = 1; - } - - if( !this.isAwake ) - { - return TickRateModulation.SLEEP; - } - - this.reboot = false; - int speed = 10; - switch( this.upgrades.getInstalledUpgrades( Upgrades.SPEED ) ) - { - case 0: - this.progress += this.userPower( ticksSinceLastCall, speed = 10, 1.0 ); - break; - case 1: - this.progress += this.userPower( ticksSinceLastCall, speed = 13, 1.3 ); - break; - case 2: - this.progress += this.userPower( ticksSinceLastCall, speed = 17, 1.7 ); - break; - case 3: - this.progress += this.userPower( ticksSinceLastCall, speed = 20, 2.0 ); - break; - case 4: - this.progress += this.userPower( ticksSinceLastCall, speed = 25, 2.5 ); - break; - case 5: - this.progress += this.userPower( ticksSinceLastCall, speed = 50, 5.0 ); - break; - } - - if( this.progress >= 100 ) - { - for( int x = 0; x < this.craftingInv.getSizeInventory(); x++ ) - { - this.craftingInv.setInventorySlotContents( x, this.inv.getStackInSlot( x ) ); - } - - this.progress = 0; - final ItemStack output = this.myPlan.getOutput( this.craftingInv, this.getWorldObj() ); - if( output != null ) - { - FMLCommonHandler.instance().firePlayerCraftingEvent( Platform.getPlayer( (WorldServer) this.getWorldObj() ), output, this.craftingInv ); - - this.pushOut( output.copy() ); - - for( int x = 0; x < this.craftingInv.getSizeInventory(); x++ ) - { - this.inv.setInventorySlotContents( x, Platform.getContainerItem( this.craftingInv.getStackInSlot( x ) ) ); - } - - if( this.inv.getStackInSlot( 10 ) == null ) - { - this.forcePlan = false; - this.myPlan = null; - this.pushDirection = ForgeDirection.UNKNOWN; - } - - this.ejectHeldItems(); - - try - { - final TargetPoint where = new TargetPoint( this.worldObj.provider.dimensionId, this.xCoord, this.yCoord, this.zCoord, 32 ); - final IAEItemStack item = AEItemStack.create( output ); - NetworkHandler.instance.sendToAllAround( new PacketAssemblerAnimation( this.xCoord, this.yCoord, this.zCoord, (byte) speed, item ), where ); - } - catch( final IOException e ) - { - // ;P - } - - this.markDirty(); - this.updateSleepiness(); - return this.isAwake ? TickRateModulation.IDLE : TickRateModulation.SLEEP; - } - } - - return TickRateModulation.FASTER; - } - - private void ejectHeldItems() - { - if( this.inv.getStackInSlot( 9 ) == null ) - { - for( int x = 0; x < 9; x++ ) - { - final ItemStack is = this.inv.getStackInSlot( x ); - if( is != null ) - { - if( this.myPlan == null || !this.myPlan.isValidItemForSlot( x, is, this.worldObj ) ) - { - this.inv.setInventorySlotContents( 9, is ); - this.inv.setInventorySlotContents( x, null ); - this.markDirty(); - return; - } - } - } - } - } - - private int userPower( final int ticksPassed, final int bonusValue, final double acceleratorTax ) - { - try - { - return (int) ( this.getProxy().getEnergy().extractAEPower( ticksPassed * bonusValue * acceleratorTax, Actionable.MODULATE, PowerMultiplier.CONFIG ) / acceleratorTax ); - } - catch( final GridAccessException e ) - { - return 0; - } - } - - private void pushOut( ItemStack output ) - { - if( this.pushDirection == ForgeDirection.UNKNOWN ) - { - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - output = this.pushTo( output, d ); - } - } - else - { - output = this.pushTo( output, this.pushDirection ); - } - - if( output == null && this.forcePlan ) - { - this.forcePlan = false; - this.recalculatePlan(); - } - - this.inv.setInventorySlotContents( 9, output ); - } - - private ItemStack pushTo( ItemStack output, final ForgeDirection d ) - { - if( output == null ) - { - return output; - } - - final TileEntity te = this.getWorldObj().getTileEntity( this.xCoord + d.offsetX, this.yCoord + d.offsetY, this.zCoord + d.offsetZ ); - - if( te == null ) - { - return output; - } - - final InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor( te, d.getOpposite() ); - - if( adaptor == null ) - { - return output; - } - - final int size = output.stackSize; - output = adaptor.addItems( output ); - final int newSize = output == null ? 0 : output.stackSize; - - if( size != newSize ) - { - this.markDirty(); - } - - return output; - } - - @MENetworkEventSubscribe - public void onPowerEvent( final MENetworkPowerStatusChange p ) - { - this.updatePowerState(); - } - - private void updatePowerState() - { - boolean newState = false; - - try - { - newState = this.getProxy().isActive() && this.getProxy().getEnergy().extractAEPower( 1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0.0001; - } - catch( final GridAccessException ignored ) - { - - } - - if( newState != this.isPowered ) - { - this.isPowered = newState; - this.markForUpdate(); - } - } - - @Override - public boolean isPowered() - { - return this.isPowered; - } - - @Override - public boolean isActive() - { - return this.isPowered; - } - - public ISimplifiedBundle getLightCache() - { - return this.lightCache; - } - - public void setLightCache( final ISimplifiedBundle lightCache ) - { - this.lightCache = lightCache; - } + implements IUpgradeableHost, IConfigManagerHost, IGridTickable, ICraftingMachine, IPowerChannelState { + private static final int[] SIDES = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + + private final InventoryCrafting craftingInv; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 9 + 2); + private final IConfigManager settings; + private final UpgradeInventory upgrades; + private ISimplifiedBundle lightCache; + private boolean isPowered = false; + private ForgeDirection pushDirection = ForgeDirection.UNKNOWN; + private ItemStack myPattern = null; + private ICraftingPatternDetails myPlan = null; + private double progress = 0; + private boolean isAwake = false; + private boolean forcePlan = false; + private boolean reboot = true; + + public TileMolecularAssembler() { + final ITileDefinition assembler = + AEApi.instance().definitions().blocks().molecularAssembler(); + + this.settings = new ConfigManager(this); + this.settings.registerSetting(Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.inv.setMaxStackSize(1); + this.getProxy().setIdlePowerUsage(0.0); + this.upgrades = new DefinitionUpgradeInventory(assembler, this, this.getUpgradeSlots()); + this.craftingInv = new InventoryCrafting(new ContainerNull(), 3, 3); + } + + private int getUpgradeSlots() { + return 5; + } + + @Override + public boolean pushPattern( + final ICraftingPatternDetails patternDetails, final InventoryCrafting table, final ForgeDirection where) { + if (this.myPattern == null) { + boolean isEmpty = true; + for (int x = 0; x < this.inv.getSizeInventory(); x++) { + isEmpty = this.inv.getStackInSlot(x) == null && isEmpty; + } + + if (isEmpty && patternDetails.isCraftable()) { + this.forcePlan = true; + this.myPlan = patternDetails; + this.pushDirection = where; + + for (int x = 0; x < table.getSizeInventory(); x++) { + this.inv.setInventorySlotContents(x, table.getStackInSlot(x)); + } + + this.updateSleepiness(); + this.markDirty(); + return true; + } + } + return false; + } + + private void updateSleepiness() { + final boolean wasEnabled = this.isAwake; + this.isAwake = this.myPlan != null && this.hasMats() || this.canPush(); + if (wasEnabled != this.isAwake) { + try { + if (this.isAwake) { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } else { + this.getProxy().getTick().sleepDevice(this.getProxy().getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } + } + + private boolean canPush() { + return this.inv.getStackInSlot(9) != null; + } + + private boolean hasMats() { + if (this.myPlan == null) { + return false; + } + + for (int x = 0; x < this.craftingInv.getSizeInventory(); x++) { + this.craftingInv.setInventorySlotContents(x, this.inv.getStackInSlot(x)); + } + + return this.myPlan.getOutput(this.craftingInv, this.getWorldObj()) != null; + } + + @Override + public boolean acceptsPlans() { + return this.inv.getStackInSlot(10) == null; + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.upgrades.getInstalledUpgrades(u); + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileMolecularAssembler(final ByteBuf data) { + final boolean oldPower = this.isPowered; + this.isPowered = data.readBoolean(); + return this.isPowered != oldPower; + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileMolecularAssembler(final ByteBuf data) { + data.writeBoolean(this.isPowered); + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileMolecularAssembler(final NBTTagCompound data) { + if (this.forcePlan && this.myPlan != null) { + final ItemStack pattern = this.myPlan.getPattern(); + if (pattern != null) { + final NBTTagCompound compound = new NBTTagCompound(); + pattern.writeToNBT(compound); + data.setTag("myPlan", compound); + data.setInteger("pushDirection", this.pushDirection.ordinal()); + } + } + + this.upgrades.writeToNBT(data, "upgrades"); + this.inv.writeToNBT(data, "inv"); + this.settings.writeToNBT(data); + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileMolecularAssembler(final NBTTagCompound data) { + if (data.hasKey("myPlan")) { + final ItemStack myPat = ItemStack.loadItemStackFromNBT(data.getCompoundTag("myPlan")); + + if (myPat != null && myPat.getItem() instanceof ItemEncodedPattern) { + final World w = this.getWorldObj(); + final ItemEncodedPattern iep = (ItemEncodedPattern) myPat.getItem(); + final ICraftingPatternDetails ph = iep.getPatternForItem(myPat, w); + if (ph != null && ph.isCraftable()) { + this.forcePlan = true; + this.myPlan = ph; + this.pushDirection = ForgeDirection.getOrientation(data.getInteger("pushDirection")); + } + } + } + + this.upgrades.readFromNBT(data, "upgrades"); + this.inv.readFromNBT(data, "inv"); + this.settings.readFromNBT(data); + this.recalculatePlan(); + } + + private void recalculatePlan() { + this.reboot = true; + + if (this.forcePlan) { + return; + } + + final ItemStack is = this.inv.getStackInSlot(10); + + if (is != null && is.getItem() instanceof ItemEncodedPattern) { + if (!Platform.isSameItem(is, this.myPattern)) { + final World w = this.getWorldObj(); + final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); + final ICraftingPatternDetails ph = iep.getPatternForItem(is, w); + + if (ph != null && ph.isCraftable()) { + this.progress = 0; + this.myPattern = is; + this.myPlan = ph; + } + } + } else { + this.progress = 0; + this.forcePlan = false; + this.myPlan = null; + this.myPattern = null; + this.pushDirection = ForgeDirection.UNKNOWN; + } + + this.updateSleepiness(); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + @Override + public IConfigManager getConfigManager() { + return this.settings; + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("upgrades")) { + return this.upgrades; + } + + if (name.equals("mac")) { + return this.inv; + } + + return null; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) {} + + @Override + public IInventory getInternalInventory() { + return this.inv; + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + if (i >= 9) { + return false; + } + + if (this.hasPattern()) { + return this.myPlan.isValidItemForSlot(i, itemstack, this.getWorldObj()); + } + + return false; + } + + private boolean hasPattern() { + return this.myPlan != null && this.inv.getStackInSlot(10) != null; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) { + if (inv == this.inv) { + this.recalculatePlan(); + } + } + + @Override + public boolean canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + return slotIndex == 9; + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection whichSide) { + return SIDES; + } + + public int getCraftingProgress() { + return (int) this.progress; + } + + @Override + public void getDrops(final World w, final int x, final int y, final int z, final List drops) { + super.getDrops(w, x, y, z, drops); + + for (int h = 0; h < this.upgrades.getSizeInventory(); h++) { + final ItemStack is = this.upgrades.getStackInSlot(h); + if (is != null) { + drops.add(is); + } + } + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + this.recalculatePlan(); + this.updateSleepiness(); + return new TickingRequest(1, 1, !this.isAwake, false); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, int ticksSinceLastCall) { + if (this.inv.getStackInSlot(9) != null) { + this.pushOut(this.inv.getStackInSlot(9)); + + // did it eject? + if (this.inv.getStackInSlot(9) == null) { + this.markDirty(); + } + + this.ejectHeldItems(); + this.updateSleepiness(); + this.progress = 0; + return this.isAwake ? TickRateModulation.IDLE : TickRateModulation.SLEEP; + } + + if (this.myPlan == null) { + this.updateSleepiness(); + return TickRateModulation.SLEEP; + } + + if (this.reboot) { + ticksSinceLastCall = 1; + } + + if (!this.isAwake) { + return TickRateModulation.SLEEP; + } + + this.reboot = false; + int speed = 10; + switch (this.upgrades.getInstalledUpgrades(Upgrades.SPEED)) { + case 0: + this.progress += this.userPower(ticksSinceLastCall, speed = 10, 1.0); + break; + case 1: + this.progress += this.userPower(ticksSinceLastCall, speed = 13, 1.3); + break; + case 2: + this.progress += this.userPower(ticksSinceLastCall, speed = 17, 1.7); + break; + case 3: + this.progress += this.userPower(ticksSinceLastCall, speed = 20, 2.0); + break; + case 4: + this.progress += this.userPower(ticksSinceLastCall, speed = 25, 2.5); + break; + case 5: + this.progress += this.userPower(ticksSinceLastCall, speed = 50, 5.0); + break; + } + + if (this.progress >= 100) { + for (int x = 0; x < this.craftingInv.getSizeInventory(); x++) { + this.craftingInv.setInventorySlotContents(x, this.inv.getStackInSlot(x)); + } + + this.progress = 0; + final ItemStack output = this.myPlan.getOutput(this.craftingInv, this.getWorldObj()); + if (output != null) { + FMLCommonHandler.instance() + .firePlayerCraftingEvent( + Platform.getPlayer((WorldServer) this.getWorldObj()), output, this.craftingInv); + + this.pushOut(output.copy()); + + for (int x = 0; x < this.craftingInv.getSizeInventory(); x++) { + this.inv.setInventorySlotContents(x, Platform.getContainerItem(this.craftingInv.getStackInSlot(x))); + } + + if (this.inv.getStackInSlot(10) == null) { + this.forcePlan = false; + this.myPlan = null; + this.pushDirection = ForgeDirection.UNKNOWN; + } + + this.ejectHeldItems(); + + try { + final TargetPoint where = new TargetPoint( + this.worldObj.provider.dimensionId, this.xCoord, this.yCoord, this.zCoord, 32); + final IAEItemStack item = AEItemStack.create(output); + NetworkHandler.instance.sendToAllAround( + new PacketAssemblerAnimation(this.xCoord, this.yCoord, this.zCoord, (byte) speed, item), + where); + } catch (final IOException e) { + // ;P + } + + this.markDirty(); + this.updateSleepiness(); + return this.isAwake ? TickRateModulation.IDLE : TickRateModulation.SLEEP; + } + } + + return TickRateModulation.FASTER; + } + + private void ejectHeldItems() { + if (this.inv.getStackInSlot(9) == null) { + for (int x = 0; x < 9; x++) { + final ItemStack is = this.inv.getStackInSlot(x); + if (is != null) { + if (this.myPlan == null || !this.myPlan.isValidItemForSlot(x, is, this.worldObj)) { + this.inv.setInventorySlotContents(9, is); + this.inv.setInventorySlotContents(x, null); + this.markDirty(); + return; + } + } + } + } + } + + private int userPower(final int ticksPassed, final int bonusValue, final double acceleratorTax) { + try { + return (int) (this.getProxy() + .getEnergy() + .extractAEPower( + ticksPassed * bonusValue * acceleratorTax, + Actionable.MODULATE, + PowerMultiplier.CONFIG) + / acceleratorTax); + } catch (final GridAccessException e) { + return 0; + } + } + + private void pushOut(ItemStack output) { + if (this.pushDirection == ForgeDirection.UNKNOWN) { + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + output = this.pushTo(output, d); + } + } else { + output = this.pushTo(output, this.pushDirection); + } + + if (output == null && this.forcePlan) { + this.forcePlan = false; + this.recalculatePlan(); + } + + this.inv.setInventorySlotContents(9, output); + } + + private ItemStack pushTo(ItemStack output, final ForgeDirection d) { + if (output == null) { + return output; + } + + final TileEntity te = this.getWorldObj() + .getTileEntity(this.xCoord + d.offsetX, this.yCoord + d.offsetY, this.zCoord + d.offsetZ); + + if (te == null) { + return output; + } + + final InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor(te, d.getOpposite()); + + if (adaptor == null) { + return output; + } + + final int size = output.stackSize; + output = adaptor.addItems(output); + final int newSize = output == null ? 0 : output.stackSize; + + if (size != newSize) { + this.markDirty(); + } + + return output; + } + + @MENetworkEventSubscribe + public void onPowerEvent(final MENetworkPowerStatusChange p) { + this.updatePowerState(); + } + + private void updatePowerState() { + boolean newState = false; + + try { + newState = this.getProxy().isActive() + && this.getProxy().getEnergy().extractAEPower(1, Actionable.SIMULATE, PowerMultiplier.CONFIG) + > 0.0001; + } catch (final GridAccessException ignored) { + + } + + if (newState != this.isPowered) { + this.isPowered = newState; + this.markForUpdate(); + } + } + + @Override + public boolean isPowered() { + return this.isPowered; + } + + @Override + public boolean isActive() { + return this.isPowered; + } + + public ISimplifiedBundle getLightCache() { + return this.lightCache; + } + + public void setLightCache(final ISimplifiedBundle lightCache) { + this.lightCache = lightCache; + } } diff --git a/src/main/java/appeng/tile/events/AETileEventHandler.java b/src/main/java/appeng/tile/events/AETileEventHandler.java index f4dccab157e..2bc8b54cfd6 100644 --- a/src/main/java/appeng/tile/events/AETileEventHandler.java +++ b/src/main/java/appeng/tile/events/AETileEventHandler.java @@ -18,137 +18,92 @@ package appeng.tile.events; - import appeng.tile.AEBaseTile; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; -import net.minecraft.nbt.NBTTagCompound; - import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import net.minecraft.nbt.NBTTagCompound; +public final class AETileEventHandler { -public final class AETileEventHandler -{ - - private final Method method; + private final Method method; - public AETileEventHandler( final Method method ) - { - this.method = method; - } + public AETileEventHandler(final Method method) { + this.method = method; + } - // TICK - public void tick( final AEBaseTile tile ) - { - try - { - this.method.invoke( tile ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( e ); - } - catch( final IllegalArgumentException e ) - { - throw new IllegalStateException( e ); - } - catch( final InvocationTargetException e ) - { - throw new IllegalStateException( e ); - } - } + // TICK + public void tick(final AEBaseTile tile) { + try { + this.method.invoke(tile); + } catch (final IllegalAccessException e) { + throw new IllegalStateException(e); + } catch (final IllegalArgumentException e) { + throw new IllegalStateException(e); + } catch (final InvocationTargetException e) { + throw new IllegalStateException(e); + } + } - // WORLD_NBT - public void writeToNBT( final AEBaseTile tile, final NBTTagCompound data ) - { - try - { - this.method.invoke( tile, data ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( e ); - } - catch( final IllegalArgumentException e ) - { - throw new IllegalStateException( e ); - } - catch( final InvocationTargetException e ) - { - throw new IllegalStateException( e ); - } - } + // WORLD_NBT + public void writeToNBT(final AEBaseTile tile, final NBTTagCompound data) { + try { + this.method.invoke(tile, data); + } catch (final IllegalAccessException e) { + throw new IllegalStateException(e); + } catch (final IllegalArgumentException e) { + throw new IllegalStateException(e); + } catch (final InvocationTargetException e) { + throw new IllegalStateException(e); + } + } - // WORLD NBT - public void readFromNBT( final AEBaseTile tile, final NBTTagCompound data ) - { - try - { - this.method.invoke( tile, data ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( e ); - } - catch( final IllegalArgumentException e ) - { - throw new IllegalStateException( e ); - } - catch( final InvocationTargetException e ) - { - throw new IllegalStateException( e ); - } - } + // WORLD NBT + public void readFromNBT(final AEBaseTile tile, final NBTTagCompound data) { + try { + this.method.invoke(tile, data); + } catch (final IllegalAccessException e) { + throw new IllegalStateException(e); + } catch (final IllegalArgumentException e) { + throw new IllegalStateException(e); + } catch (final InvocationTargetException e) { + throw new IllegalStateException(e); + } + } - // NETWORK - public void writeToStream( final AEBaseTile tile, final ByteBuf data ) - { - try - { - this.method.invoke( tile, data ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( e ); - } - catch( final IllegalArgumentException e ) - { - throw new IllegalStateException( e ); - } - catch( final InvocationTargetException e ) - { - throw new IllegalStateException( e ); - } - } + // NETWORK + public void writeToStream(final AEBaseTile tile, final ByteBuf data) { + try { + this.method.invoke(tile, data); + } catch (final IllegalAccessException e) { + throw new IllegalStateException(e); + } catch (final IllegalArgumentException e) { + throw new IllegalStateException(e); + } catch (final InvocationTargetException e) { + throw new IllegalStateException(e); + } + } - // NETWORK + // NETWORK - /** - * returning true from this method, will update the block's render - * - * @param data data of stream - * @return true of method could be invoked - */ - @SideOnly( Side.CLIENT ) - public boolean readFromStream( final AEBaseTile tile, final ByteBuf data ) - { - try - { - return (Boolean) this.method.invoke( tile, data ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( e ); - } - catch( final IllegalArgumentException e ) - { - throw new IllegalStateException( e ); - } - catch( final InvocationTargetException e ) - { - throw new IllegalStateException( e ); - } - } + /** + * returning true from this method, will update the block's render + * + * @param data data of stream + * @return true of method could be invoked + */ + @SideOnly(Side.CLIENT) + public boolean readFromStream(final AEBaseTile tile, final ByteBuf data) { + try { + return (Boolean) this.method.invoke(tile, data); + } catch (final IllegalAccessException e) { + throw new IllegalStateException(e); + } catch (final IllegalArgumentException e) { + throw new IllegalStateException(e); + } catch (final InvocationTargetException e) { + throw new IllegalStateException(e); + } + } } diff --git a/src/main/java/appeng/tile/events/TileEventType.java b/src/main/java/appeng/tile/events/TileEventType.java index 26cadd3dbd9..a7ee4b8fd0e 100644 --- a/src/main/java/appeng/tile/events/TileEventType.java +++ b/src/main/java/appeng/tile/events/TileEventType.java @@ -18,17 +18,16 @@ package appeng.tile.events; +public enum TileEventType { + TICK, -public enum TileEventType -{ - TICK, + WORLD_NBT_READ, + WORLD_NBT_WRITE, - WORLD_NBT_READ, WORLD_NBT_WRITE, + /** + * Methods annotated with this need to return a boolean + */ + NETWORK_READ, - /** - * Methods annotated with this need to return a boolean - */ - NETWORK_READ, - - NETWORK_WRITE + NETWORK_WRITE } diff --git a/src/main/java/appeng/tile/grid/AENetworkInvTile.java b/src/main/java/appeng/tile/grid/AENetworkInvTile.java index c24ffaa90b7..1bd0965508e 100644 --- a/src/main/java/appeng/tile/grid/AENetworkInvTile.java +++ b/src/main/java/appeng/tile/grid/AENetworkInvTile.java @@ -18,7 +18,6 @@ package appeng.tile.grid; - import appeng.api.networking.IGridNode; import appeng.api.networking.security.IActionHost; import appeng.me.helpers.AENetworkProxy; @@ -29,74 +28,59 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; - -public abstract class AENetworkInvTile extends AEBaseInvTile implements IActionHost, IGridProxyable -{ - - private final AENetworkProxy gridProxy = new AENetworkProxy( this, "proxy", this.getItemFromTile( this ), true ); - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_AENetwork( final NBTTagCompound data ) - { - this.getProxy().readFromNBT( data ); - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_AENetwork( final NBTTagCompound data ) - { - this.getProxy().writeToNBT( data ); - } - - @Override - public AENetworkProxy getProxy() - { - return this.gridProxy; - } - - @Override - public void gridChanged() - { - - } - - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - return this.getProxy().getNode(); - } - - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - this.getProxy().onChunkUnload(); - } - - @Override - public void onReady() - { - super.onReady(); - this.getProxy().onReady(); - } - - @Override - public void invalidate() - { - super.invalidate(); - this.getProxy().invalidate(); - } - - @Override - public void validate() - { - super.validate(); - this.getProxy().validate(); - } - - @Override - public IGridNode getActionableNode() - { - return this.getProxy().getNode(); - } - +public abstract class AENetworkInvTile extends AEBaseInvTile implements IActionHost, IGridProxyable { + + private final AENetworkProxy gridProxy = new AENetworkProxy(this, "proxy", this.getItemFromTile(this), true); + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_AENetwork(final NBTTagCompound data) { + this.getProxy().readFromNBT(data); + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_AENetwork(final NBTTagCompound data) { + this.getProxy().writeToNBT(data); + } + + @Override + public AENetworkProxy getProxy() { + return this.gridProxy; + } + + @Override + public void gridChanged() {} + + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + return this.getProxy().getNode(); + } + + @Override + public void onChunkUnload() { + super.onChunkUnload(); + this.getProxy().onChunkUnload(); + } + + @Override + public void onReady() { + super.onReady(); + this.getProxy().onReady(); + } + + @Override + public void invalidate() { + super.invalidate(); + this.getProxy().invalidate(); + } + + @Override + public void validate() { + super.validate(); + this.getProxy().validate(); + } + + @Override + public IGridNode getActionableNode() { + return this.getProxy().getNode(); + } } diff --git a/src/main/java/appeng/tile/grid/AENetworkPowerTile.java b/src/main/java/appeng/tile/grid/AENetworkPowerTile.java index f042362f117..70a2d02bc46 100644 --- a/src/main/java/appeng/tile/grid/AENetworkPowerTile.java +++ b/src/main/java/appeng/tile/grid/AENetworkPowerTile.java @@ -18,7 +18,6 @@ package appeng.tile.grid; - import appeng.api.networking.IGridNode; import appeng.api.networking.security.IActionHost; import appeng.api.util.AECableType; @@ -31,86 +30,69 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; - -public abstract class AENetworkPowerTile extends AEBasePoweredTile implements IActionHost, IGridProxyable -{ - - private final AENetworkProxy gridProxy = new AENetworkProxy( this, "proxy", this.getItemFromTile( this ), true ); - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_AENetwork( final NBTTagCompound data ) - { - this.getProxy().readFromNBT( data ); - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_AENetwork( final NBTTagCompound data ) - { - this.getProxy().writeToNBT( data ); - } - - @Override - public AENetworkProxy getProxy() - { - return this.gridProxy; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - @Override - public void gridChanged() - { - - } - - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - return this.getProxy().getNode(); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } - - @Override - public void validate() - { - super.validate(); - this.getProxy().validate(); - } - - @Override - public void invalidate() - { - super.invalidate(); - this.getProxy().invalidate(); - } - - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - this.getProxy().onChunkUnload(); - } - - @Override - public void onReady() - { - super.onReady(); - this.getProxy().onReady(); - } - - @Override - public IGridNode getActionableNode() - { - return this.getProxy().getNode(); - } - +public abstract class AENetworkPowerTile extends AEBasePoweredTile implements IActionHost, IGridProxyable { + + private final AENetworkProxy gridProxy = new AENetworkProxy(this, "proxy", this.getItemFromTile(this), true); + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_AENetwork(final NBTTagCompound data) { + this.getProxy().readFromNBT(data); + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_AENetwork(final NBTTagCompound data) { + this.getProxy().writeToNBT(data); + } + + @Override + public AENetworkProxy getProxy() { + return this.gridProxy; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + @Override + public void gridChanged() {} + + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + return this.getProxy().getNode(); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } + + @Override + public void validate() { + super.validate(); + this.getProxy().validate(); + } + + @Override + public void invalidate() { + super.invalidate(); + this.getProxy().invalidate(); + } + + @Override + public void onChunkUnload() { + super.onChunkUnload(); + this.getProxy().onChunkUnload(); + } + + @Override + public void onReady() { + super.onReady(); + this.getProxy().onReady(); + } + + @Override + public IGridNode getActionableNode() { + return this.getProxy().getNode(); + } } diff --git a/src/main/java/appeng/tile/grid/AENetworkTile.java b/src/main/java/appeng/tile/grid/AENetworkTile.java index 3f574300e45..fed49f69a6c 100644 --- a/src/main/java/appeng/tile/grid/AENetworkTile.java +++ b/src/main/java/appeng/tile/grid/AENetworkTile.java @@ -18,7 +18,6 @@ package appeng.tile.grid; - import appeng.api.networking.IGridNode; import appeng.api.networking.security.IActionHost; import appeng.api.util.AECableType; @@ -31,90 +30,73 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; - -public class AENetworkTile extends AEBaseTile implements IActionHost, IGridProxyable -{ - - private final AENetworkProxy gridProxy = this.createProxy(); - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_AENetwork( final NBTTagCompound data ) - { - this.getProxy().readFromNBT( data ); - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_AENetwork( final NBTTagCompound data ) - { - this.getProxy().writeToNBT( data ); - } - - protected AENetworkProxy createProxy() - { - return new AENetworkProxy( this, "proxy", this.getItemFromTile( this ), true ); - } - - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - return this.getProxy().getNode(); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } - - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - this.getProxy().onChunkUnload(); - } - - @Override - public void onReady() - { - super.onReady(); - this.getProxy().onReady(); - } - - @Override - public void invalidate() - { - super.invalidate(); - this.getProxy().invalidate(); - } - - @Override - public void validate() - { - super.validate(); - this.getProxy().validate(); - } - - @Override - public AENetworkProxy getProxy() - { - return this.gridProxy; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - @Override - public void gridChanged() - { - - } - - @Override - public IGridNode getActionableNode() - { - return this.getProxy().getNode(); - } +public class AENetworkTile extends AEBaseTile implements IActionHost, IGridProxyable { + + private final AENetworkProxy gridProxy = this.createProxy(); + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_AENetwork(final NBTTagCompound data) { + this.getProxy().readFromNBT(data); + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_AENetwork(final NBTTagCompound data) { + this.getProxy().writeToNBT(data); + } + + protected AENetworkProxy createProxy() { + return new AENetworkProxy(this, "proxy", this.getItemFromTile(this), true); + } + + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + return this.getProxy().getNode(); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } + + @Override + public void onChunkUnload() { + super.onChunkUnload(); + this.getProxy().onChunkUnload(); + } + + @Override + public void onReady() { + super.onReady(); + this.getProxy().onReady(); + } + + @Override + public void invalidate() { + super.invalidate(); + this.getProxy().invalidate(); + } + + @Override + public void validate() { + super.validate(); + this.getProxy().validate(); + } + + @Override + public AENetworkProxy getProxy() { + return this.gridProxy; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + @Override + public void gridChanged() {} + + @Override + public IGridNode getActionableNode() { + return this.getProxy().getNode(); + } } diff --git a/src/main/java/appeng/tile/grindstone/TileCrank.java b/src/main/java/appeng/tile/grindstone/TileCrank.java index ab5bb22e623..1e528efccb3 100644 --- a/src/main/java/appeng/tile/grindstone/TileCrank.java +++ b/src/main/java/appeng/tile/grindstone/TileCrank.java @@ -18,7 +18,6 @@ package appeng.tile.grindstone; - import appeng.api.implementations.tiles.ICrankable; import appeng.helpers.ICustomCollision; import appeng.tile.AEBaseTile; @@ -26,154 +25,144 @@ import appeng.tile.events.TileEventType; import appeng.util.Platform; import io.netty.buffer.ByteBuf; +import java.util.Collections; +import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.List; - - -public class TileCrank extends AEBaseTile implements ICustomCollision -{ - - private final int ticksPerRotation = 18; - - // sided values.. - private float visibleRotation = 0; - private int charge = 0; - - private int hits = 0; - private int rotation = 0; - - @TileEvent( TileEventType.TICK ) - public void Tick_TileCrank() - { - if( this.rotation > 0 ) - { - this.setVisibleRotation( this.getVisibleRotation() - 360 / ( this.ticksPerRotation ) ); - this.charge++; - if( this.charge >= this.ticksPerRotation ) - { - this.charge -= this.ticksPerRotation; - final ICrankable g = this.getGrinder(); - if( g != null ) - { - g.applyTurn(); - } - } - - this.rotation--; - } - } - - private ICrankable getGrinder() - { - if( Platform.isClient() ) - { - return null; - } - - final ForgeDirection grinder = this.getUp().getOpposite(); - final TileEntity te = this.worldObj.getTileEntity( this.xCoord + grinder.offsetX, this.yCoord + grinder.offsetY, this.zCoord + grinder.offsetZ ); - if( te instanceof ICrankable ) - { - return (ICrankable) te; - } - return null; - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileCrank( final ByteBuf data ) - { - this.rotation = data.readInt(); - return false; - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileCrank( final ByteBuf data ) - { - data.writeInt( this.rotation ); - } - - @Override - public void setOrientation( final ForgeDirection inForward, final ForgeDirection inUp ) - { - super.setOrientation( inForward, inUp ); - this.getBlockType().onNeighborBlockChange( this.worldObj, this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK ); - } - - @Override - public boolean requiresTESR() - { - return true; - } - - /** - * return true if this should count towards stats. - */ - public boolean power() - { - if( Platform.isClient() ) - { - return false; - } - - if( this.rotation < 3 ) - { - final ICrankable g = this.getGrinder(); - if( g != null ) - { - if( g.canTurn() ) - { - this.hits = 0; - this.rotation += this.ticksPerRotation; - this.markForUpdate(); - return true; - } - else - { - this.hits++; - if( this.hits > 10 ) - { - this.worldObj.func_147480_a( this.xCoord, this.yCoord, this.zCoord, false ); - // worldObj.destroyBlock( xCoord, yCoord, zCoord, false ); - } - } - } - } - - return false; - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - final double xOff = -0.15 * this.getUp().offsetX; - final double yOff = -0.15 * this.getUp().offsetY; - final double zOff = -0.15 * this.getUp().offsetZ; - return Collections.singletonList( AxisAlignedBB.getBoundingBox( xOff + 0.15, yOff + 0.15, zOff + 0.15, xOff + 0.85, yOff + 0.85, zOff + 0.85 ) ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - final double xOff = -0.15 * this.getUp().offsetX; - final double yOff = -0.15 * this.getUp().offsetY; - final double zOff = -0.15 * this.getUp().offsetZ; - out.add( AxisAlignedBB.getBoundingBox( xOff + 0.15, yOff + 0.15, zOff + 0.15,// ahh - xOff + 0.85, yOff + 0.85, zOff + 0.85 ) ); - } - - public float getVisibleRotation() - { - return this.visibleRotation; - } - - private void setVisibleRotation( final float visibleRotation ) - { - this.visibleRotation = visibleRotation; - } +public class TileCrank extends AEBaseTile implements ICustomCollision { + + private final int ticksPerRotation = 18; + + // sided values.. + private float visibleRotation = 0; + private int charge = 0; + + private int hits = 0; + private int rotation = 0; + + @TileEvent(TileEventType.TICK) + public void Tick_TileCrank() { + if (this.rotation > 0) { + this.setVisibleRotation(this.getVisibleRotation() - 360 / (this.ticksPerRotation)); + this.charge++; + if (this.charge >= this.ticksPerRotation) { + this.charge -= this.ticksPerRotation; + final ICrankable g = this.getGrinder(); + if (g != null) { + g.applyTurn(); + } + } + + this.rotation--; + } + } + + private ICrankable getGrinder() { + if (Platform.isClient()) { + return null; + } + + final ForgeDirection grinder = this.getUp().getOpposite(); + final TileEntity te = this.worldObj.getTileEntity( + this.xCoord + grinder.offsetX, this.yCoord + grinder.offsetY, this.zCoord + grinder.offsetZ); + if (te instanceof ICrankable) { + return (ICrankable) te; + } + return null; + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileCrank(final ByteBuf data) { + this.rotation = data.readInt(); + return false; + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileCrank(final ByteBuf data) { + data.writeInt(this.rotation); + } + + @Override + public void setOrientation(final ForgeDirection inForward, final ForgeDirection inUp) { + super.setOrientation(inForward, inUp); + this.getBlockType() + .onNeighborBlockChange(this.worldObj, this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK); + } + + @Override + public boolean requiresTESR() { + return true; + } + + /** + * return true if this should count towards stats. + */ + public boolean power() { + if (Platform.isClient()) { + return false; + } + + if (this.rotation < 3) { + final ICrankable g = this.getGrinder(); + if (g != null) { + if (g.canTurn()) { + this.hits = 0; + this.rotation += this.ticksPerRotation; + this.markForUpdate(); + return true; + } else { + this.hits++; + if (this.hits > 10) { + this.worldObj.func_147480_a(this.xCoord, this.yCoord, this.zCoord, false); + // worldObj.destroyBlock( xCoord, yCoord, zCoord, false ); + } + } + } + } + + return false; + } + + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual) { + final double xOff = -0.15 * this.getUp().offsetX; + final double yOff = -0.15 * this.getUp().offsetY; + final double zOff = -0.15 * this.getUp().offsetZ; + return Collections.singletonList(AxisAlignedBB.getBoundingBox( + xOff + 0.15, yOff + 0.15, zOff + 0.15, xOff + 0.85, yOff + 0.85, zOff + 0.85)); + } + + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e) { + final double xOff = -0.15 * this.getUp().offsetX; + final double yOff = -0.15 * this.getUp().offsetY; + final double zOff = -0.15 * this.getUp().offsetZ; + out.add(AxisAlignedBB.getBoundingBox( + xOff + 0.15, + yOff + 0.15, + zOff + 0.15, // ahh + xOff + 0.85, + yOff + 0.85, + zOff + 0.85)); + } + + public float getVisibleRotation() { + return this.visibleRotation; + } + + private void setVisibleRotation(final float visibleRotation) { + this.visibleRotation = visibleRotation; + } } diff --git a/src/main/java/appeng/tile/grindstone/TileGrinder.java b/src/main/java/appeng/tile/grindstone/TileGrinder.java index 33f2575347f..d93a2939384 100644 --- a/src/main/java/appeng/tile/grindstone/TileGrinder.java +++ b/src/main/java/appeng/tile/grindstone/TileGrinder.java @@ -18,7 +18,6 @@ package appeng.tile.grindstone; - import appeng.api.AEApi; import appeng.api.features.IGrinderEntry; import appeng.api.implementations.tiles.ICrankable; @@ -29,172 +28,150 @@ import appeng.util.InventoryAdaptor; import appeng.util.Platform; import appeng.util.inv.WrapperInventoryRange; +import java.util.ArrayList; +import java.util.List; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.List; - - -public class TileGrinder extends AEBaseInvTile implements ICrankable -{ - - private final int[] inputs = { 0, 1, 2 }; - private final int[] sides = { 0, 1, 2, 3, 4, 5 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 7 ); - private int points; - - @Override - public void setOrientation( final ForgeDirection inForward, final ForgeDirection inUp ) - { - super.setOrientation( inForward, inUp ); - this.getBlockType().onNeighborBlockChange( this.worldObj, this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK ); - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - - } - - @Override - public boolean canInsertItem( final int slotIndex, final ItemStack insertingItem, final int side ) - { - if( AEApi.instance().registries().grinder().getRecipeForInput( insertingItem ) == null ) - { - return false; - } - - return slotIndex >= 0 && slotIndex <= 2; - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - return slotIndex >= 3 && slotIndex <= 5; - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.sides; - } - - @Override - public boolean canTurn() - { - if( Platform.isClient() ) - { - return false; - } - - if( null == this.getStackInSlot( 6 ) ) // Add if there isn't one... - { - final IInventory src = new WrapperInventoryRange( this, this.inputs, true ); - for( int x = 0; x < src.getSizeInventory(); x++ ) - { - ItemStack item = src.getStackInSlot( x ); - if( item == null ) - { - continue; - } - - final IGrinderEntry r = AEApi.instance().registries().grinder().getRecipeForInput( item ); - if( r != null ) - { - if( item.stackSize >= r.getInput().stackSize ) - { - item.stackSize -= r.getInput().stackSize; - final ItemStack ais = item.copy(); - ais.stackSize = r.getInput().stackSize; - - if( item.stackSize <= 0 ) - { - item = null; - } - - src.setInventorySlotContents( x, item ); - this.setInventorySlotContents( 6, ais ); - return true; - } - } - } - return false; - } - return true; - } - - @Override - public void applyTurn() - { - if( Platform.isClient() ) - { - return; - } - - this.points++; - - final ItemStack processing = this.getStackInSlot( 6 ); - final IGrinderEntry r = AEApi.instance().registries().grinder().getRecipeForInput( processing ); - if( r != null ) - { - if( r.getEnergyCost() > this.points ) - { - return; - } - - this.points = 0; - final InventoryAdaptor sia = InventoryAdaptor.getAdaptor( new WrapperInventoryRange( this, 3, 3, true ), ForgeDirection.EAST ); - - this.addItem( sia, r.getOutput() ); - - float chance = ( Platform.getRandomInt() % 2000 ) / 2000.0f; - if( chance <= r.getOptionalChance() ) - { - this.addItem( sia, r.getOptionalOutput() ); - } - - chance = ( Platform.getRandomInt() % 2000 ) / 2000.0f; - if( chance <= r.getSecondOptionalChance() ) - { - this.addItem( sia, r.getSecondOptionalOutput() ); - } - - this.setInventorySlotContents( 6, null ); - } - } - - private void addItem( final InventoryAdaptor sia, final ItemStack output ) - { - if( output == null ) - { - return; - } - - final ItemStack notAdded = sia.addItems( output ); - if( notAdded != null ) - { - final WorldCoord wc = new WorldCoord( this.xCoord, this.yCoord, this.zCoord ); - - wc.add( this.getForward(), 1 ); - - final List out = new ArrayList(); - out.add( notAdded ); - - Platform.spawnDrops( this.worldObj, wc.x, wc.y, wc.z, out ); - } - } - - @Override - public boolean canCrankAttach( final ForgeDirection directionToCrank ) - { - return this.getUp() == directionToCrank; - } +public class TileGrinder extends AEBaseInvTile implements ICrankable { + + private final int[] inputs = {0, 1, 2}; + private final int[] sides = {0, 1, 2, 3, 4, 5}; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 7); + private int points; + + @Override + public void setOrientation(final ForgeDirection inForward, final ForgeDirection inUp) { + super.setOrientation(inForward, inUp); + this.getBlockType() + .onNeighborBlockChange(this.worldObj, this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK); + } + + @Override + public IInventory getInternalInventory() { + return this.inv; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) {} + + @Override + public boolean canInsertItem(final int slotIndex, final ItemStack insertingItem, final int side) { + if (AEApi.instance().registries().grinder().getRecipeForInput(insertingItem) == null) { + return false; + } + + return slotIndex >= 0 && slotIndex <= 2; + } + + @Override + public boolean canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + return slotIndex >= 3 && slotIndex <= 5; + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return this.sides; + } + + @Override + public boolean canTurn() { + if (Platform.isClient()) { + return false; + } + + if (null == this.getStackInSlot(6)) // Add if there isn't one... + { + final IInventory src = new WrapperInventoryRange(this, this.inputs, true); + for (int x = 0; x < src.getSizeInventory(); x++) { + ItemStack item = src.getStackInSlot(x); + if (item == null) { + continue; + } + + final IGrinderEntry r = AEApi.instance().registries().grinder().getRecipeForInput(item); + if (r != null) { + if (item.stackSize >= r.getInput().stackSize) { + item.stackSize -= r.getInput().stackSize; + final ItemStack ais = item.copy(); + ais.stackSize = r.getInput().stackSize; + + if (item.stackSize <= 0) { + item = null; + } + + src.setInventorySlotContents(x, item); + this.setInventorySlotContents(6, ais); + return true; + } + } + } + return false; + } + return true; + } + + @Override + public void applyTurn() { + if (Platform.isClient()) { + return; + } + + this.points++; + + final ItemStack processing = this.getStackInSlot(6); + final IGrinderEntry r = AEApi.instance().registries().grinder().getRecipeForInput(processing); + if (r != null) { + if (r.getEnergyCost() > this.points) { + return; + } + + this.points = 0; + final InventoryAdaptor sia = + InventoryAdaptor.getAdaptor(new WrapperInventoryRange(this, 3, 3, true), ForgeDirection.EAST); + + this.addItem(sia, r.getOutput()); + + float chance = (Platform.getRandomInt() % 2000) / 2000.0f; + if (chance <= r.getOptionalChance()) { + this.addItem(sia, r.getOptionalOutput()); + } + + chance = (Platform.getRandomInt() % 2000) / 2000.0f; + if (chance <= r.getSecondOptionalChance()) { + this.addItem(sia, r.getSecondOptionalOutput()); + } + + this.setInventorySlotContents(6, null); + } + } + + private void addItem(final InventoryAdaptor sia, final ItemStack output) { + if (output == null) { + return; + } + + final ItemStack notAdded = sia.addItems(output); + if (notAdded != null) { + final WorldCoord wc = new WorldCoord(this.xCoord, this.yCoord, this.zCoord); + + wc.add(this.getForward(), 1); + + final List out = new ArrayList(); + out.add(notAdded); + + Platform.spawnDrops(this.worldObj, wc.x, wc.y, wc.z, out); + } + } + + @Override + public boolean canCrankAttach(final ForgeDirection directionToCrank) { + return this.getUp() == directionToCrank; + } } diff --git a/src/main/java/appeng/tile/inventory/AppEngInternalAEInventory.java b/src/main/java/appeng/tile/inventory/AppEngInternalAEInventory.java index a76591dae11..0d42b14940c 100644 --- a/src/main/java/appeng/tile/inventory/AppEngInternalAEInventory.java +++ b/src/main/java/appeng/tile/inventory/AppEngInternalAEInventory.java @@ -18,7 +18,6 @@ package appeng.tile.inventory; - import appeng.api.AEApi; import appeng.api.storage.data.IAEItemStack; import appeng.core.AELog; @@ -26,253 +25,198 @@ import appeng.util.item.AEItemStack; import appeng.util.iterators.AEInvIterator; import appeng.util.iterators.InvIterator; +import java.util.Iterator; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.util.Iterator; - - -public class AppEngInternalAEInventory implements IInventory, Iterable -{ - - private final IAEAppEngInventory te; - private final IAEItemStack[] inv; - private final int size; - private int maxStack; - - public AppEngInternalAEInventory( final IAEAppEngInventory te, final int s ) - { - this.te = te; - this.size = s; - this.maxStack = 64; - this.inv = new IAEItemStack[s]; - } - - public boolean isEmpty() - { - for( int x = 0; x < this.size; x++ ) - { - if( this.getStackInSlot( x ) != null ) - { - return false; - } - } - return true; - } - - public void setMaxStackSize( final int s ) - { - this.maxStack = s; - } - - public IAEItemStack getAEStackInSlot( final int var1 ) - { - return this.inv[var1]; - } - - public void writeToNBT( final NBTTagCompound data, final String name ) - { - final NBTTagCompound c = new NBTTagCompound(); - this.writeToNBT( c ); - data.setTag( name, c ); - } - - private void writeToNBT( final NBTTagCompound target ) - { - for( int x = 0; x < this.size; x++ ) - { - try - { - final NBTTagCompound c = new NBTTagCompound(); - - if( this.inv[x] != null ) - { - this.inv[x].writeToNBT( c ); - } - - target.setTag( "#" + x, c ); - } - catch( final Exception ignored ) - { - } - } - } - - public void readFromNBT( final NBTTagCompound data, final String name ) - { - final NBTTagCompound c = data.getCompoundTag( name ); - if( c != null ) - { - this.readFromNBT( c ); - } - } - - private void readFromNBT( final NBTTagCompound target ) - { - for( int x = 0; x < this.size; x++ ) - { - try - { - final NBTTagCompound c = target.getCompoundTag( "#" + x ); - - if( c != null ) - { - this.inv[x] = AEItemStack.loadItemStackFromNBT( c ); - } - } - catch( final Exception e ) - { - AELog.debug( e ); - } - } - } - - @Override - public int getSizeInventory() - { - return this.size; - } - - @Override - public ItemStack getStackInSlot( final int var1 ) - { - if( this.inv[var1] == null ) - { - return null; - } - - return this.inv[var1].getItemStack(); - } - - @Override - public ItemStack decrStackSize( final int slot, final int qty ) - { - if( this.inv[slot] != null ) - { - final ItemStack split = this.getStackInSlot( slot ); - ItemStack ns = null; - - if( qty >= split.stackSize ) - { - ns = this.getStackInSlot( slot ); - this.inv[slot] = null; - } - else - { - ns = split.splitStack( qty ); - } - - if( this.te != null && Platform.isServer() ) - { - this.te.onChangeInventory( this, slot, InvOperation.decreaseStackSize, ns, null ); - } - - return ns; - } - - return null; - } - - @Override - public ItemStack getStackInSlotOnClosing( final int var1 ) - { - return null; - } - - @Override - public void setInventorySlotContents( final int slot, final ItemStack newItemStack ) - { - final ItemStack oldStack = this.getStackInSlot( slot ); - this.inv[slot] = AEApi.instance().storage().createItemStack( newItemStack ); - - if( this.te != null && Platform.isServer() ) - { - ItemStack removed = oldStack; - ItemStack added = newItemStack; - - if( oldStack != null && newItemStack != null && Platform.isSameItem( oldStack, newItemStack ) ) - { - if( oldStack.stackSize > newItemStack.stackSize ) - { - removed = removed.copy(); - removed.stackSize -= newItemStack.stackSize; - added = null; - } - else if( oldStack.stackSize < newItemStack.stackSize ) - { - added = added.copy(); - added.stackSize -= oldStack.stackSize; - removed = null; - } - else - { - removed = added = null; - } - } - - this.te.onChangeInventory( this, slot, InvOperation.setInventorySlotContents, removed, added ); - } - } - - @Override - public String getInventoryName() - { - return "appeng-internal"; - } - - @Override - public boolean hasCustomInventoryName() - { - return false; - } - - @Override - public int getInventoryStackLimit() - { - return this.maxStack > 64 ? 64 : this.maxStack; - } - - @Override - public void markDirty() - { - if( this.te != null && Platform.isServer() ) - { - this.te.onChangeInventory( this, -1, InvOperation.markDirty, null, null ); - } - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer var1 ) - { - return true; - } - - @Override - public void openInventory() - { - } - - @Override - public void closeInventory() - { - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return true; - } - - @Override - public Iterator iterator() - { - return new InvIterator( this ); - } - - public Iterator getNewAEIterator() - { - return new AEInvIterator( this ); - } +public class AppEngInternalAEInventory implements IInventory, Iterable { + + private final IAEAppEngInventory te; + private final IAEItemStack[] inv; + private final int size; + private int maxStack; + + public AppEngInternalAEInventory(final IAEAppEngInventory te, final int s) { + this.te = te; + this.size = s; + this.maxStack = 64; + this.inv = new IAEItemStack[s]; + } + + public boolean isEmpty() { + for (int x = 0; x < this.size; x++) { + if (this.getStackInSlot(x) != null) { + return false; + } + } + return true; + } + + public void setMaxStackSize(final int s) { + this.maxStack = s; + } + + public IAEItemStack getAEStackInSlot(final int var1) { + return this.inv[var1]; + } + + public void writeToNBT(final NBTTagCompound data, final String name) { + final NBTTagCompound c = new NBTTagCompound(); + this.writeToNBT(c); + data.setTag(name, c); + } + + private void writeToNBT(final NBTTagCompound target) { + for (int x = 0; x < this.size; x++) { + try { + final NBTTagCompound c = new NBTTagCompound(); + + if (this.inv[x] != null) { + this.inv[x].writeToNBT(c); + } + + target.setTag("#" + x, c); + } catch (final Exception ignored) { + } + } + } + + public void readFromNBT(final NBTTagCompound data, final String name) { + final NBTTagCompound c = data.getCompoundTag(name); + if (c != null) { + this.readFromNBT(c); + } + } + + private void readFromNBT(final NBTTagCompound target) { + for (int x = 0; x < this.size; x++) { + try { + final NBTTagCompound c = target.getCompoundTag("#" + x); + + if (c != null) { + this.inv[x] = AEItemStack.loadItemStackFromNBT(c); + } + } catch (final Exception e) { + AELog.debug(e); + } + } + } + + @Override + public int getSizeInventory() { + return this.size; + } + + @Override + public ItemStack getStackInSlot(final int var1) { + if (this.inv[var1] == null) { + return null; + } + + return this.inv[var1].getItemStack(); + } + + @Override + public ItemStack decrStackSize(final int slot, final int qty) { + if (this.inv[slot] != null) { + final ItemStack split = this.getStackInSlot(slot); + ItemStack ns = null; + + if (qty >= split.stackSize) { + ns = this.getStackInSlot(slot); + this.inv[slot] = null; + } else { + ns = split.splitStack(qty); + } + + if (this.te != null && Platform.isServer()) { + this.te.onChangeInventory(this, slot, InvOperation.decreaseStackSize, ns, null); + } + + return ns; + } + + return null; + } + + @Override + public ItemStack getStackInSlotOnClosing(final int var1) { + return null; + } + + @Override + public void setInventorySlotContents(final int slot, final ItemStack newItemStack) { + final ItemStack oldStack = this.getStackInSlot(slot); + this.inv[slot] = AEApi.instance().storage().createItemStack(newItemStack); + + if (this.te != null && Platform.isServer()) { + ItemStack removed = oldStack; + ItemStack added = newItemStack; + + if (oldStack != null && newItemStack != null && Platform.isSameItem(oldStack, newItemStack)) { + if (oldStack.stackSize > newItemStack.stackSize) { + removed = removed.copy(); + removed.stackSize -= newItemStack.stackSize; + added = null; + } else if (oldStack.stackSize < newItemStack.stackSize) { + added = added.copy(); + added.stackSize -= oldStack.stackSize; + removed = null; + } else { + removed = added = null; + } + } + + this.te.onChangeInventory(this, slot, InvOperation.setInventorySlotContents, removed, added); + } + } + + @Override + public String getInventoryName() { + return "appeng-internal"; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public int getInventoryStackLimit() { + return this.maxStack > 64 ? 64 : this.maxStack; + } + + @Override + public void markDirty() { + if (this.te != null && Platform.isServer()) { + this.te.onChangeInventory(this, -1, InvOperation.markDirty, null, null); + } + } + + @Override + public boolean isUseableByPlayer(final EntityPlayer var1) { + return true; + } + + @Override + public void openInventory() {} + + @Override + public void closeInventory() {} + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return true; + } + + @Override + public Iterator iterator() { + return new InvIterator(this); + } + + public Iterator getNewAEIterator() { + return new AEInvIterator(this); + } } diff --git a/src/main/java/appeng/tile/inventory/AppEngInternalInventory.java b/src/main/java/appeng/tile/inventory/AppEngInternalInventory.java index 1ac8c0eb3b5..c7c40ed2eb1 100644 --- a/src/main/java/appeng/tile/inventory/AppEngInternalInventory.java +++ b/src/main/java/appeng/tile/inventory/AppEngInternalInventory.java @@ -18,292 +18,230 @@ package appeng.tile.inventory; - import appeng.api.storage.IMEInventory; import appeng.core.AELog; import appeng.me.storage.MEIInventoryWrapper; import appeng.util.Platform; import appeng.util.iterators.InvIterator; +import java.util.Iterator; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.util.Iterator; - - -public class AppEngInternalInventory implements IInventory, Iterable -{ - - private final int size; - protected final ItemStack[] inv; - private boolean enableClientEvents = false; - private IAEAppEngInventory te; - private int maxStack; - - public AppEngInternalInventory( final IAEAppEngInventory inventory, final int size ) - { - this(inventory, size, 64); - } - - public AppEngInternalInventory( final IAEAppEngInventory inventory, final int size, final int maxstack ) - { - this.setTileEntity( inventory ); - this.size = size; - this.maxStack = maxstack; - this.inv = new ItemStack[size]; - } - - public IMEInventory getMEInventory() - { - return new MEIInventoryWrapper( this, null ); - } - - public boolean isEmpty() - { - for( int x = 0; x < this.size; x++ ) - { - if( this.getStackInSlot( x ) != null ) - { - return false; - } - } - return true; - } - - @Override - public int getSizeInventory() - { - return this.size; - } - - @Override - public ItemStack getStackInSlot( final int var1 ) - { - return this.inv[var1]; - } - - @Override - public ItemStack decrStackSize( final int slot, final int qty ) - { - if( this.inv[slot] != null ) - { - final ItemStack split = this.getStackInSlot( slot ); - ItemStack ns = null; - - if( qty >= split.stackSize ) - { - ns = this.inv[slot]; - this.inv[slot] = null; - } - else - { - ns = split.splitStack( qty ); - } - - if( this.getTileEntity() != null && this.eventsEnabled() ) - { - this.getTileEntity().onChangeInventory( this, slot, InvOperation.decreaseStackSize, ns, null ); - } - - this.markDirty(); - return ns; - } - - return null; - } - - protected boolean eventsEnabled() - { - return Platform.isServer() || this.isEnableClientEvents(); - } - - @Override - public ItemStack getStackInSlotOnClosing( final int var1 ) - { - return null; - } - - @Override - public void setInventorySlotContents( final int slot, final ItemStack newItemStack ) - { - final ItemStack oldStack = this.inv[slot]; - this.inv[slot] = newItemStack; - - if( this.getTileEntity() != null && this.eventsEnabled() ) - { - ItemStack removed = oldStack; - ItemStack added = newItemStack; - - if( oldStack != null && newItemStack != null && Platform.isSameItem( oldStack, newItemStack ) ) - { - if( oldStack.stackSize > newItemStack.stackSize ) - { - removed = removed.copy(); - removed.stackSize -= newItemStack.stackSize; - added = null; - } - else if( oldStack.stackSize < newItemStack.stackSize ) - { - added = added.copy(); - added.stackSize -= oldStack.stackSize; - removed = null; - } - else - { - removed = added = null; - } - } - - this.getTileEntity().onChangeInventory( this, slot, InvOperation.setInventorySlotContents, removed, added ); - } - - this.markDirty(); - } - - @Override - public String getInventoryName() - { - return "appeng-internal"; - } - - @Override - public boolean hasCustomInventoryName() - { - return false; - } - - @Override - public int getInventoryStackLimit() - { - return this.maxStack > 64 ? 64 : this.maxStack; - } - - @Override - public void markDirty() - { - if( this.getTileEntity() != null && this.eventsEnabled() ) - { - this.getTileEntity().onChangeInventory( this, -1, InvOperation.markDirty, null, null ); - } - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer var1 ) - { - return true; - } - - @Override - public void openInventory() - { - } - - @Override - public void closeInventory() - { - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return true; - } - - public void setMaxStackSize( final int s ) - { - this.maxStack = s; - } - - // for guis... - public void markDirty( final int slotIndex ) - { - if( this.getTileEntity() != null && this.eventsEnabled() ) - { - this.getTileEntity().onChangeInventory( this, slotIndex, InvOperation.markDirty, null, null ); - } - } - - public void writeToNBT( final NBTTagCompound data, final String name ) - { - final NBTTagCompound c = new NBTTagCompound(); - this.writeToNBT( c ); - data.setTag( name, c ); - } - - protected void writeToNBT( final NBTTagCompound target ) - { - for( int x = 0; x < this.size; x++ ) - { - try - { - final NBTTagCompound c = new NBTTagCompound(); - - if( this.inv[x] != null ) - { - this.inv[x].writeToNBT( c ); - } - - target.setTag( "#" + x, c ); - } - catch( final Exception ignored ) - { - } - } - } - - public void readFromNBT( final NBTTagCompound data, final String name ) - { - final NBTTagCompound c = data.getCompoundTag( name ); - if( c != null ) - { - this.readFromNBT( c ); - } - } - - public void readFromNBT( final NBTTagCompound target ) - { - for( int x = 0; x < this.size; x++ ) - { - try - { - final NBTTagCompound c = target.getCompoundTag( "#" + x ); - - if( c != null ) - { - this.inv[x] = ItemStack.loadItemStackFromNBT( c ); - } - } - catch( final Exception e ) - { - AELog.debug( e ); - } - } - } - - @Override - public Iterator iterator() - { - return new InvIterator( this ); - } - - private boolean isEnableClientEvents() - { - return this.enableClientEvents; - } - - public void setEnableClientEvents( final boolean enableClientEvents ) - { - this.enableClientEvents = enableClientEvents; - } - - private IAEAppEngInventory getTileEntity() - { - return this.te; - } - - public void setTileEntity( final IAEAppEngInventory te ) - { - this.te = te; - } +public class AppEngInternalInventory implements IInventory, Iterable { + + private final int size; + protected final ItemStack[] inv; + private boolean enableClientEvents = false; + private IAEAppEngInventory te; + private int maxStack; + + public AppEngInternalInventory(final IAEAppEngInventory inventory, final int size) { + this(inventory, size, 64); + } + + public AppEngInternalInventory(final IAEAppEngInventory inventory, final int size, final int maxstack) { + this.setTileEntity(inventory); + this.size = size; + this.maxStack = maxstack; + this.inv = new ItemStack[size]; + } + + public IMEInventory getMEInventory() { + return new MEIInventoryWrapper(this, null); + } + + public boolean isEmpty() { + for (int x = 0; x < this.size; x++) { + if (this.getStackInSlot(x) != null) { + return false; + } + } + return true; + } + + @Override + public int getSizeInventory() { + return this.size; + } + + @Override + public ItemStack getStackInSlot(final int var1) { + return this.inv[var1]; + } + + @Override + public ItemStack decrStackSize(final int slot, final int qty) { + if (this.inv[slot] != null) { + final ItemStack split = this.getStackInSlot(slot); + ItemStack ns = null; + + if (qty >= split.stackSize) { + ns = this.inv[slot]; + this.inv[slot] = null; + } else { + ns = split.splitStack(qty); + } + + if (this.getTileEntity() != null && this.eventsEnabled()) { + this.getTileEntity().onChangeInventory(this, slot, InvOperation.decreaseStackSize, ns, null); + } + + this.markDirty(); + return ns; + } + + return null; + } + + protected boolean eventsEnabled() { + return Platform.isServer() || this.isEnableClientEvents(); + } + + @Override + public ItemStack getStackInSlotOnClosing(final int var1) { + return null; + } + + @Override + public void setInventorySlotContents(final int slot, final ItemStack newItemStack) { + final ItemStack oldStack = this.inv[slot]; + this.inv[slot] = newItemStack; + + if (this.getTileEntity() != null && this.eventsEnabled()) { + ItemStack removed = oldStack; + ItemStack added = newItemStack; + + if (oldStack != null && newItemStack != null && Platform.isSameItem(oldStack, newItemStack)) { + if (oldStack.stackSize > newItemStack.stackSize) { + removed = removed.copy(); + removed.stackSize -= newItemStack.stackSize; + added = null; + } else if (oldStack.stackSize < newItemStack.stackSize) { + added = added.copy(); + added.stackSize -= oldStack.stackSize; + removed = null; + } else { + removed = added = null; + } + } + + this.getTileEntity().onChangeInventory(this, slot, InvOperation.setInventorySlotContents, removed, added); + } + + this.markDirty(); + } + + @Override + public String getInventoryName() { + return "appeng-internal"; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public int getInventoryStackLimit() { + return this.maxStack > 64 ? 64 : this.maxStack; + } + + @Override + public void markDirty() { + if (this.getTileEntity() != null && this.eventsEnabled()) { + this.getTileEntity().onChangeInventory(this, -1, InvOperation.markDirty, null, null); + } + } + + @Override + public boolean isUseableByPlayer(final EntityPlayer var1) { + return true; + } + + @Override + public void openInventory() {} + + @Override + public void closeInventory() {} + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return true; + } + + public void setMaxStackSize(final int s) { + this.maxStack = s; + } + + // for guis... + public void markDirty(final int slotIndex) { + if (this.getTileEntity() != null && this.eventsEnabled()) { + this.getTileEntity().onChangeInventory(this, slotIndex, InvOperation.markDirty, null, null); + } + } + + public void writeToNBT(final NBTTagCompound data, final String name) { + final NBTTagCompound c = new NBTTagCompound(); + this.writeToNBT(c); + data.setTag(name, c); + } + + protected void writeToNBT(final NBTTagCompound target) { + for (int x = 0; x < this.size; x++) { + try { + final NBTTagCompound c = new NBTTagCompound(); + + if (this.inv[x] != null) { + this.inv[x].writeToNBT(c); + } + + target.setTag("#" + x, c); + } catch (final Exception ignored) { + } + } + } + + public void readFromNBT(final NBTTagCompound data, final String name) { + final NBTTagCompound c = data.getCompoundTag(name); + if (c != null) { + this.readFromNBT(c); + } + } + + public void readFromNBT(final NBTTagCompound target) { + for (int x = 0; x < this.size; x++) { + try { + final NBTTagCompound c = target.getCompoundTag("#" + x); + + if (c != null) { + this.inv[x] = ItemStack.loadItemStackFromNBT(c); + } + } catch (final Exception e) { + AELog.debug(e); + } + } + } + + @Override + public Iterator iterator() { + return new InvIterator(this); + } + + private boolean isEnableClientEvents() { + return this.enableClientEvents; + } + + public void setEnableClientEvents(final boolean enableClientEvents) { + this.enableClientEvents = enableClientEvents; + } + + private IAEAppEngInventory getTileEntity() { + return this.te; + } + + public void setTileEntity(final IAEAppEngInventory te) { + this.te = te; + } } diff --git a/src/main/java/appeng/tile/inventory/AppEngNullInventory.java b/src/main/java/appeng/tile/inventory/AppEngNullInventory.java index 1cb62853a71..1c09f15751c 100644 --- a/src/main/java/appeng/tile/inventory/AppEngNullInventory.java +++ b/src/main/java/appeng/tile/inventory/AppEngNullInventory.java @@ -18,97 +18,71 @@ package appeng.tile.inventory; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +public class AppEngNullInventory implements IInventory { + + public AppEngNullInventory() {} + + public void writeToNBT(final NBTTagCompound target) {} + + @Override + public int getSizeInventory() { + return 0; + } + + @Override + public ItemStack getStackInSlot(final int var1) { + return null; + } + + @Override + public ItemStack decrStackSize(final int slot, final int qty) { + return null; + } + + @Override + public ItemStack getStackInSlotOnClosing(final int var1) { + return null; + } + + @Override + public void setInventorySlotContents(final int slot, final ItemStack newItemStack) {} + + @Override + public String getInventoryName() { + return "appeng-internal"; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public int getInventoryStackLimit() { + return 0; + } + + @Override + public void markDirty() {} + + @Override + public boolean isUseableByPlayer(final EntityPlayer var1) { + return false; + } + + @Override + public void openInventory() {} + + @Override + public void closeInventory() {} -public class AppEngNullInventory implements IInventory -{ - - public AppEngNullInventory() - { - } - - public void writeToNBT( final NBTTagCompound target ) - { - } - - @Override - public int getSizeInventory() - { - return 0; - } - - @Override - public ItemStack getStackInSlot( final int var1 ) - { - return null; - } - - @Override - public ItemStack decrStackSize( final int slot, final int qty ) - { - return null; - } - - @Override - public ItemStack getStackInSlotOnClosing( final int var1 ) - { - return null; - } - - @Override - public void setInventorySlotContents( final int slot, final ItemStack newItemStack ) - { - - } - - @Override - public String getInventoryName() - { - return "appeng-internal"; - } - - @Override - public boolean hasCustomInventoryName() - { - return false; - } - - @Override - public int getInventoryStackLimit() - { - return 0; - } - - @Override - public void markDirty() - { - - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer var1 ) - { - return false; - } - - @Override - public void openInventory() - { - } - - @Override - public void closeInventory() - { - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return false; - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return false; + } } diff --git a/src/main/java/appeng/tile/inventory/BiggerAppEngInventory.java b/src/main/java/appeng/tile/inventory/BiggerAppEngInventory.java index 099d2d85235..73759d31384 100644 --- a/src/main/java/appeng/tile/inventory/BiggerAppEngInventory.java +++ b/src/main/java/appeng/tile/inventory/BiggerAppEngInventory.java @@ -4,53 +4,38 @@ import appeng.util.Platform; import net.minecraft.nbt.NBTTagCompound; -public class BiggerAppEngInventory extends AppEngInternalInventory -{ +public class BiggerAppEngInventory extends AppEngInternalInventory { - public BiggerAppEngInventory( IAEAppEngInventory inventory, int size ) - { - super( inventory, size ); + public BiggerAppEngInventory(IAEAppEngInventory inventory, int size) { + super(inventory, size); } - protected void writeToNBT( final NBTTagCompound target ) - { - for( int x = 0; x < this.getSizeInventory(); x++ ) - { - try - { + protected void writeToNBT(final NBTTagCompound target) { + for (int x = 0; x < this.getSizeInventory(); x++) { + try { final NBTTagCompound c = new NBTTagCompound(); - if( this.inv[x] != null ) - { - Platform.writeItemStackToNBT( this.inv[x], c ); + if (this.inv[x] != null) { + Platform.writeItemStackToNBT(this.inv[x], c); } - target.setTag( "#" + x, c ); - } - catch( final Exception ignored ) - { + target.setTag("#" + x, c); + } catch (final Exception ignored) { } } } - public void readFromNBT( final NBTTagCompound target ) - { - for( int x = 0; x < this.getSizeInventory(); x++ ) - { - try - { - final NBTTagCompound c = target.getCompoundTag( "#" + x ); - - if( c != null ) - { - this.inv[x] = Platform.loadItemStackFromNBT( c ); + public void readFromNBT(final NBTTagCompound target) { + for (int x = 0; x < this.getSizeInventory(); x++) { + try { + final NBTTagCompound c = target.getCompoundTag("#" + x); + + if (c != null) { + this.inv[x] = Platform.loadItemStackFromNBT(c); } - } - catch( final Exception e ) - { - AELog.debug( e ); + } catch (final Exception e) { + AELog.debug(e); } } } - } diff --git a/src/main/java/appeng/tile/inventory/IAEAppEngInventory.java b/src/main/java/appeng/tile/inventory/IAEAppEngInventory.java index 2ca28a38620..bb2d021dab7 100644 --- a/src/main/java/appeng/tile/inventory/IAEAppEngInventory.java +++ b/src/main/java/appeng/tile/inventory/IAEAppEngInventory.java @@ -18,15 +18,12 @@ package appeng.tile.inventory; - import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public interface IAEAppEngInventory { -public interface IAEAppEngInventory -{ - - void saveChanges(); + void saveChanges(); - void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack ); + void onChangeInventory(IInventory inv, int slot, InvOperation mc, ItemStack removedStack, ItemStack newStack); } diff --git a/src/main/java/appeng/tile/inventory/InvOperation.java b/src/main/java/appeng/tile/inventory/InvOperation.java index aaa9a0165d2..da9cedbf4ef 100644 --- a/src/main/java/appeng/tile/inventory/InvOperation.java +++ b/src/main/java/appeng/tile/inventory/InvOperation.java @@ -18,9 +18,8 @@ package appeng.tile.inventory; - -public enum InvOperation -{ - decreaseStackSize, setInventorySlotContents, markDirty - +public enum InvOperation { + decreaseStackSize, + setInventorySlotContents, + markDirty } diff --git a/src/main/java/appeng/tile/misc/TileCellWorkbench.java b/src/main/java/appeng/tile/misc/TileCellWorkbench.java index ec2121c194f..e64c2c7206f 100644 --- a/src/main/java/appeng/tile/misc/TileCellWorkbench.java +++ b/src/main/java/appeng/tile/misc/TileCellWorkbench.java @@ -18,7 +18,6 @@ package appeng.tile.misc; - import appeng.api.config.CopyMode; import appeng.api.config.Settings; import appeng.api.config.Upgrades; @@ -36,255 +35,213 @@ import appeng.tile.inventory.InvOperation; import appeng.util.ConfigManager; import appeng.util.IConfigManagerHost; +import java.util.List; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -import java.util.List; - - -public class TileCellWorkbench extends AEBaseTile implements IUpgradeableHost, IAEAppEngInventory, IConfigManagerHost, IOreFilterable -{ - - private final AppEngInternalInventory cell = new AppEngInternalInventory( this, 1 ); - private final AppEngInternalAEInventory config = new AppEngInternalAEInventory( this, 63 ); - private final ConfigManager manager = new ConfigManager( this ); - - private IInventory cacheUpgrades = null; - private IInventory cacheConfig = null; - private boolean locked = false; - - public TileCellWorkbench() - { - this.manager.registerSetting( Settings.COPY_MODE, CopyMode.CLEAR_ON_REMOVE ); - this.cell.setEnableClientEvents( true ); - } - - public IInventory getCellUpgradeInventory() - { - if( this.cacheUpgrades == null ) - { - final ICellWorkbenchItem cell = this.getCell(); - if( cell == null ) - { - return null; - } - - final ItemStack is = this.cell.getStackInSlot( 0 ); - if( is == null ) - { - return null; - } - - final IInventory inv = cell.getUpgradesInventory( is ); - if( inv == null ) - { - return null; - } - - return this.cacheUpgrades = inv; - } - return this.cacheUpgrades; - } - - public ICellWorkbenchItem getCell() - { - if( this.cell.getStackInSlot( 0 ) == null ) - { - return null; - } - - if( this.cell.getStackInSlot( 0 ).getItem() instanceof ICellWorkbenchItem ) - { - return ( (ICellWorkbenchItem) this.cell.getStackInSlot( 0 ).getItem() ); - } - - return null; - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileCellWorkbench( final NBTTagCompound data ) - { - this.cell.writeToNBT( data, "cell" ); - this.config.writeToNBT( data, "config" ); - this.manager.writeToNBT( data ); - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileCellWorkbench( final NBTTagCompound data ) - { - this.cell.readFromNBT( data, "cell" ); - this.config.readFromNBT( data, "config" ); - this.manager.readFromNBT( data ); - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "config" ) ) - { - return this.config; - } - - if( name.equals( "cell" ) ) - { - return this.cell; - } - - return null; - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - final IInventory inv = getCellUpgradeInventory(); - if (inv != null) { - for (int x = 0; x < inv.getSizeInventory(); x++) { - final ItemStack is = inv.getStackInSlot(x); - if (is != null && is.getItem() instanceof IUpgradeModule) { - if (((IUpgradeModule) is.getItem()).getType(is) == u) - return 1; - } - } - } - return 0; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - if( inv == this.cell && !this.locked ) - { - this.locked = true; - - this.cacheUpgrades = null; - this.cacheConfig = null; - - final IInventory configInventory = this.getCellConfigInventory(); - if( configInventory != null ) - { - boolean cellHasConfig = false; - for( int x = 0; x < configInventory.getSizeInventory(); x++ ) - { - if( configInventory.getStackInSlot( x ) != null ) - { - cellHasConfig = true; - break; - } - } - - if( cellHasConfig ) - { - for( int x = 0; x < this.config.getSizeInventory(); x++ ) - { - this.config.setInventorySlotContents( x, configInventory.getStackInSlot( x ) ); - } - } - else - { - for( int x = 0; x < this.config.getSizeInventory(); x++ ) - { - configInventory.setInventorySlotContents( x, this.config.getStackInSlot( x ) ); - } - - configInventory.markDirty(); - } - } - else if( this.manager.getSetting( Settings.COPY_MODE ) == CopyMode.CLEAR_ON_REMOVE ) - { - for( int x = 0; x < this.config.getSizeInventory(); x++ ) - { - this.config.setInventorySlotContents( x, null ); - } - - this.markDirty(); - } - - this.locked = false; - } - else if( inv == this.config && !this.locked ) - { - final IInventory c = this.getCellConfigInventory(); - if( c != null ) - { - for( int x = 0; x < this.config.getSizeInventory(); x++ ) - { - c.setInventorySlotContents( x, this.config.getStackInSlot( x ) ); - } - - c.markDirty(); - } - } - else if (inv == cacheUpgrades) - { - if (getInstalledUpgrades(Upgrades.ORE_FILTER) == 0) - setFilter(""); - } - } - - private IInventory getCellConfigInventory() - { - if( this.cacheConfig == null ) - { - final ICellWorkbenchItem cell = this.getCell(); - if( cell == null ) - { - return null; - } - - final ItemStack is = this.cell.getStackInSlot( 0 ); - if( is == null ) - { - return null; - } - - final IInventory inv = cell.getConfigInventory( is ); - if( inv == null ) - { - return null; - } - - this.cacheConfig = inv; - } - return this.cacheConfig; - } - - @Override - public void getDrops( final World w, final int x, final int y, final int z, final List drops ) - { - super.getDrops( w, x, y, z, drops ); - - if( this.cell.getStackInSlot( 0 ) != null ) - { - drops.add( this.cell.getStackInSlot( 0 ) ); - } - } - - @Override - public IConfigManager getConfigManager() - { - return this.manager; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - // nothing here.. - } - - @Override - public String getFilter() { - ItemStack is = this.cell.getStackInSlot( 0 ); - if (is != null && is.getItem() instanceof ICellWorkbenchItem) - return ((ICellWorkbenchItem) is.getItem()).getOreFilter(is); - else return ""; - } - - @Override - public void setFilter(String filter) { - ItemStack is = this.cell.getStackInSlot( 0 ); - if (is != null && is.getItem() instanceof ICellWorkbenchItem) - ((ICellWorkbenchItem) is.getItem()).setOreFilter(is, filter); - } +public class TileCellWorkbench extends AEBaseTile + implements IUpgradeableHost, IAEAppEngInventory, IConfigManagerHost, IOreFilterable { + + private final AppEngInternalInventory cell = new AppEngInternalInventory(this, 1); + private final AppEngInternalAEInventory config = new AppEngInternalAEInventory(this, 63); + private final ConfigManager manager = new ConfigManager(this); + + private IInventory cacheUpgrades = null; + private IInventory cacheConfig = null; + private boolean locked = false; + + public TileCellWorkbench() { + this.manager.registerSetting(Settings.COPY_MODE, CopyMode.CLEAR_ON_REMOVE); + this.cell.setEnableClientEvents(true); + } + + public IInventory getCellUpgradeInventory() { + if (this.cacheUpgrades == null) { + final ICellWorkbenchItem cell = this.getCell(); + if (cell == null) { + return null; + } + + final ItemStack is = this.cell.getStackInSlot(0); + if (is == null) { + return null; + } + + final IInventory inv = cell.getUpgradesInventory(is); + if (inv == null) { + return null; + } + + return this.cacheUpgrades = inv; + } + return this.cacheUpgrades; + } + + public ICellWorkbenchItem getCell() { + if (this.cell.getStackInSlot(0) == null) { + return null; + } + + if (this.cell.getStackInSlot(0).getItem() instanceof ICellWorkbenchItem) { + return ((ICellWorkbenchItem) this.cell.getStackInSlot(0).getItem()); + } + + return null; + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileCellWorkbench(final NBTTagCompound data) { + this.cell.writeToNBT(data, "cell"); + this.config.writeToNBT(data, "config"); + this.manager.writeToNBT(data); + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileCellWorkbench(final NBTTagCompound data) { + this.cell.readFromNBT(data, "cell"); + this.config.readFromNBT(data, "config"); + this.manager.readFromNBT(data); + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("config")) { + return this.config; + } + + if (name.equals("cell")) { + return this.cell; + } + + return null; + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + final IInventory inv = getCellUpgradeInventory(); + if (inv != null) { + for (int x = 0; x < inv.getSizeInventory(); x++) { + final ItemStack is = inv.getStackInSlot(x); + if (is != null && is.getItem() instanceof IUpgradeModule) { + if (((IUpgradeModule) is.getItem()).getType(is) == u) return 1; + } + } + } + return 0; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) { + if (inv == this.cell && !this.locked) { + this.locked = true; + + this.cacheUpgrades = null; + this.cacheConfig = null; + + final IInventory configInventory = this.getCellConfigInventory(); + if (configInventory != null) { + boolean cellHasConfig = false; + for (int x = 0; x < configInventory.getSizeInventory(); x++) { + if (configInventory.getStackInSlot(x) != null) { + cellHasConfig = true; + break; + } + } + + if (cellHasConfig) { + for (int x = 0; x < this.config.getSizeInventory(); x++) { + this.config.setInventorySlotContents(x, configInventory.getStackInSlot(x)); + } + } else { + for (int x = 0; x < this.config.getSizeInventory(); x++) { + configInventory.setInventorySlotContents(x, this.config.getStackInSlot(x)); + } + + configInventory.markDirty(); + } + } else if (this.manager.getSetting(Settings.COPY_MODE) == CopyMode.CLEAR_ON_REMOVE) { + for (int x = 0; x < this.config.getSizeInventory(); x++) { + this.config.setInventorySlotContents(x, null); + } + + this.markDirty(); + } + + this.locked = false; + } else if (inv == this.config && !this.locked) { + final IInventory c = this.getCellConfigInventory(); + if (c != null) { + for (int x = 0; x < this.config.getSizeInventory(); x++) { + c.setInventorySlotContents(x, this.config.getStackInSlot(x)); + } + + c.markDirty(); + } + } else if (inv == cacheUpgrades) { + if (getInstalledUpgrades(Upgrades.ORE_FILTER) == 0) setFilter(""); + } + } + + private IInventory getCellConfigInventory() { + if (this.cacheConfig == null) { + final ICellWorkbenchItem cell = this.getCell(); + if (cell == null) { + return null; + } + + final ItemStack is = this.cell.getStackInSlot(0); + if (is == null) { + return null; + } + + final IInventory inv = cell.getConfigInventory(is); + if (inv == null) { + return null; + } + + this.cacheConfig = inv; + } + return this.cacheConfig; + } + + @Override + public void getDrops(final World w, final int x, final int y, final int z, final List drops) { + super.getDrops(w, x, y, z, drops); + + if (this.cell.getStackInSlot(0) != null) { + drops.add(this.cell.getStackInSlot(0)); + } + } + + @Override + public IConfigManager getConfigManager() { + return this.manager; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + // nothing here.. + } + + @Override + public String getFilter() { + ItemStack is = this.cell.getStackInSlot(0); + if (is != null && is.getItem() instanceof ICellWorkbenchItem) + return ((ICellWorkbenchItem) is.getItem()).getOreFilter(is); + else return ""; + } + + @Override + public void setFilter(String filter) { + ItemStack is = this.cell.getStackInSlot(0); + if (is != null && is.getItem() instanceof ICellWorkbenchItem) + ((ICellWorkbenchItem) is.getItem()).setOreFilter(is, filter); + } } diff --git a/src/main/java/appeng/tile/misc/TileCharger.java b/src/main/java/appeng/tile/misc/TileCharger.java index 69df7a9d512..cfb1cdd4504 100644 --- a/src/main/java/appeng/tile/misc/TileCharger.java +++ b/src/main/java/appeng/tile/misc/TileCharger.java @@ -18,7 +18,6 @@ package appeng.tile.misc; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -39,257 +38,243 @@ import appeng.util.Platform; import appeng.util.item.AEItemStack; import io.netty.buffer.ByteBuf; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraftforge.common.util.ForgeDirection; - import java.io.IOException; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.util.ForgeDirection; - -public class TileCharger extends AENetworkPowerTile implements ICrankable -{ - - private final int[] sides = { 0 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 1 ); - private int tickTickTimer = 0; - - private int lastUpdate = 0; - private boolean requiresUpdate = false; - - public TileCharger() - { - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - this.getProxy().setFlags(); - this.setInternalMaxPower( 1500 ); - this.getProxy().setIdlePowerUsage( 0 ); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileCharger( final ByteBuf data ) - { - try - { - final IAEItemStack item = AEItemStack.loadItemStackFromPacket( data ); - final ItemStack is = item.getItemStack(); - this.inv.setInventorySlotContents( 0, is ); - } - catch( final Throwable t ) - { - this.inv.setInventorySlotContents( 0, null ); - } - return false; // TESR doesn't need updates! - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileCharger( final ByteBuf data ) throws IOException - { - final AEItemStack is = AEItemStack.create( this.getStackInSlot( 0 ) ); - if( is != null ) - { - is.writeToPacket( data ); - } - } - - @TileEvent( TileEventType.TICK ) - public void Tick_TileCharger() - { - if( this.lastUpdate > 60 && this.requiresUpdate ) - { - this.requiresUpdate = false; - this.markForUpdate(); - this.lastUpdate = 0; - } - this.lastUpdate++; - - this.tickTickTimer++; - if( this.tickTickTimer < 20 ) - { - return; - } - this.tickTickTimer = 0; - - final ItemStack myItem = this.getStackInSlot( 0 ); - - // charge from the network! - if( this.getInternalCurrentPower() < getInternalMaxPower() ) - { - try - { - this.injectExternalPower( PowerUnits.AE, this.getProxy().getEnergy().extractAEPower( Math.min( 150.0, getInternalMaxPower() - this.getInternalCurrentPower() ), Actionable.MODULATE, PowerMultiplier.ONE ) ); - this.tickTickTimer = 20; // keep ticking... - } - catch( final GridAccessException e ) - { - // continue! - } - } - - if( myItem == null ) - { - return; - } - - final IMaterials materials = AEApi.instance().definitions().materials(); - - if( this.getInternalCurrentPower() > 149 && Platform.isChargeable( myItem ) ) - { - final IAEItemPowerStorage ps = (IAEItemPowerStorage) myItem.getItem(); - if( ps.getAEMaxPower( myItem ) > ps.getAECurrentPower( myItem ) ) - { - final double oldPower = this.getInternalCurrentPower(); - - final double adjustment = ps.injectAEPower( myItem, this.extractAEPower( 150.0, Actionable.MODULATE, PowerMultiplier.CONFIG ) ); - this.setInternalCurrentPower( this.getInternalCurrentPower() + adjustment ); - if( oldPower > this.getInternalCurrentPower() ) - { - this.requiresUpdate = true; - } - this.tickTickTimer = 20; // keep ticking... - } - } - else if( this.getInternalCurrentPower() == getInternalMaxPower() && materials.certusQuartzCrystal().isSameAs( myItem ) ) - { - if( Platform.getRandomFloat() > 0.8f ) // simulate wait - { - this.extractAEPower( this.getInternalMaxPower()/PowerMultiplier.CONFIG.multiplier, Actionable.MODULATE, PowerMultiplier.CONFIG );// 1500 - - for( final ItemStack charged : materials.certusQuartzCrystalCharged().maybeStack( myItem.stackSize ).asSet() ) - { - this.setInventorySlotContents( 0, charged ); - } - } - } - } - - @Override - public void setOrientation( final ForgeDirection inForward, final ForgeDirection inUp ) - { - super.setOrientation( inForward, inUp ); - this.getProxy().setValidSides( EnumSet.of( this.getUp(), this.getUp().getOpposite() ) ); - this.setPowerSides( EnumSet.of( this.getUp(), this.getUp().getOpposite() ) ); - } - - @Override - public boolean requiresTESR() - { - return true; - } - - @Override - public boolean canTurn() - { - return this.getInternalCurrentPower() < this.getInternalMaxPower(); - } - - @Override - public void applyTurn() - { - this.injectExternalPower( PowerUnits.AE, 150 ); - - final ItemStack myItem = this.getStackInSlot( 0 ); - if( this.getInternalCurrentPower() > 1499 ) - { - final IMaterials materials = AEApi.instance().definitions().materials(); - - if( materials.certusQuartzCrystal().isSameAs( myItem ) ) - { - this.extractAEPower( this.getInternalMaxPower(), Actionable.MODULATE, PowerMultiplier.CONFIG );// 1500 - - for( final ItemStack charged : materials.certusQuartzCrystalCharged().maybeStack( myItem.stackSize ).asSet() ) - { - this.setInventorySlotContents( 0, charged ); - } - } - } - } - - @Override - public boolean canCrankAttach( final ForgeDirection directionToCrank ) - { - return this.getUp() == directionToCrank || this.getUp().getOpposite() == directionToCrank; - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - - @Override - public int getInventoryStackLimit() - { - return 1; - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - final IItemDefinition cert = AEApi.instance().definitions().materials().certusQuartzCrystal(); - - return Platform.isChargeable( itemstack ) || cert.isSameAs( itemstack ); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - this.markForUpdate(); - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - if( Platform.isChargeable( extractedItem ) ) - { - final IAEItemPowerStorage ips = (IAEItemPowerStorage) extractedItem.getItem(); - if( ips.getAECurrentPower( extractedItem ) >= ips.getAEMaxPower( extractedItem ) ) - { - return true; - } - } - - return AEApi.instance().definitions().materials().certusQuartzCrystalCharged().isSameAs( extractedItem ); - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection whichSide ) - { - return this.sides; - } - - public void activate( final EntityPlayer player ) - { - if( !Platform.hasPermissions( new DimensionalCoord( this ), player ) ) - { - return; - } - - final ItemStack myItem = this.getStackInSlot( 0 ); - if( myItem == null ) - { - ItemStack held = player.inventory.getCurrentItem(); - - if( AEApi.instance().definitions().materials().certusQuartzCrystal().isSameAs( held ) || Platform.isChargeable( held ) ) - { - held = player.inventory.decrStackSize( player.inventory.currentItem, 1 ); - this.setInventorySlotContents( 0, held ); - } - } - else - { - final List drops = new ArrayList(); - drops.add( myItem ); - this.setInventorySlotContents( 0, null ); - Platform.spawnDrops( this.worldObj, this.xCoord + this.getForward().offsetX, this.yCoord + this.getForward().offsetY, this.zCoord + this.getForward().offsetZ, drops ); - } - } +public class TileCharger extends AENetworkPowerTile implements ICrankable { + + private final int[] sides = {0}; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 1); + private int tickTickTimer = 0; + + private int lastUpdate = 0; + private boolean requiresUpdate = false; + + public TileCharger() { + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + this.getProxy().setFlags(); + this.setInternalMaxPower(1500); + this.getProxy().setIdlePowerUsage(0); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileCharger(final ByteBuf data) { + try { + final IAEItemStack item = AEItemStack.loadItemStackFromPacket(data); + final ItemStack is = item.getItemStack(); + this.inv.setInventorySlotContents(0, is); + } catch (final Throwable t) { + this.inv.setInventorySlotContents(0, null); + } + return false; // TESR doesn't need updates! + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileCharger(final ByteBuf data) throws IOException { + final AEItemStack is = AEItemStack.create(this.getStackInSlot(0)); + if (is != null) { + is.writeToPacket(data); + } + } + + @TileEvent(TileEventType.TICK) + public void Tick_TileCharger() { + if (this.lastUpdate > 60 && this.requiresUpdate) { + this.requiresUpdate = false; + this.markForUpdate(); + this.lastUpdate = 0; + } + this.lastUpdate++; + + this.tickTickTimer++; + if (this.tickTickTimer < 20) { + return; + } + this.tickTickTimer = 0; + + final ItemStack myItem = this.getStackInSlot(0); + + // charge from the network! + if (this.getInternalCurrentPower() < getInternalMaxPower()) { + try { + this.injectExternalPower( + PowerUnits.AE, + this.getProxy() + .getEnergy() + .extractAEPower( + Math.min(150.0, getInternalMaxPower() - this.getInternalCurrentPower()), + Actionable.MODULATE, + PowerMultiplier.ONE)); + this.tickTickTimer = 20; // keep ticking... + } catch (final GridAccessException e) { + // continue! + } + } + + if (myItem == null) { + return; + } + + final IMaterials materials = AEApi.instance().definitions().materials(); + + if (this.getInternalCurrentPower() > 149 && Platform.isChargeable(myItem)) { + final IAEItemPowerStorage ps = (IAEItemPowerStorage) myItem.getItem(); + if (ps.getAEMaxPower(myItem) > ps.getAECurrentPower(myItem)) { + final double oldPower = this.getInternalCurrentPower(); + + final double adjustment = ps.injectAEPower( + myItem, this.extractAEPower(150.0, Actionable.MODULATE, PowerMultiplier.CONFIG)); + this.setInternalCurrentPower(this.getInternalCurrentPower() + adjustment); + if (oldPower > this.getInternalCurrentPower()) { + this.requiresUpdate = true; + } + this.tickTickTimer = 20; // keep ticking... + } + } else if (this.getInternalCurrentPower() == getInternalMaxPower() + && materials.certusQuartzCrystal().isSameAs(myItem)) { + if (Platform.getRandomFloat() > 0.8f) // simulate wait + { + this.extractAEPower( + this.getInternalMaxPower() / PowerMultiplier.CONFIG.multiplier, + Actionable.MODULATE, + PowerMultiplier.CONFIG); // 1500 + + for (final ItemStack charged : materials + .certusQuartzCrystalCharged() + .maybeStack(myItem.stackSize) + .asSet()) { + this.setInventorySlotContents(0, charged); + } + } + } + } + + @Override + public void setOrientation(final ForgeDirection inForward, final ForgeDirection inUp) { + super.setOrientation(inForward, inUp); + this.getProxy().setValidSides(EnumSet.of(this.getUp(), this.getUp().getOpposite())); + this.setPowerSides(EnumSet.of(this.getUp(), this.getUp().getOpposite())); + } + + @Override + public boolean requiresTESR() { + return true; + } + + @Override + public boolean canTurn() { + return this.getInternalCurrentPower() < this.getInternalMaxPower(); + } + + @Override + public void applyTurn() { + this.injectExternalPower(PowerUnits.AE, 150); + + final ItemStack myItem = this.getStackInSlot(0); + if (this.getInternalCurrentPower() > 1499) { + final IMaterials materials = AEApi.instance().definitions().materials(); + + if (materials.certusQuartzCrystal().isSameAs(myItem)) { + this.extractAEPower(this.getInternalMaxPower(), Actionable.MODULATE, PowerMultiplier.CONFIG); // 1500 + + for (final ItemStack charged : materials + .certusQuartzCrystalCharged() + .maybeStack(myItem.stackSize) + .asSet()) { + this.setInventorySlotContents(0, charged); + } + } + } + } + + @Override + public boolean canCrankAttach(final ForgeDirection directionToCrank) { + return this.getUp() == directionToCrank || this.getUp().getOpposite() == directionToCrank; + } + + @Override + public IInventory getInternalInventory() { + return this.inv; + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + final IItemDefinition cert = AEApi.instance().definitions().materials().certusQuartzCrystal(); + + return Platform.isChargeable(itemstack) || cert.isSameAs(itemstack); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) { + this.markForUpdate(); + } + + @Override + public boolean canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + if (Platform.isChargeable(extractedItem)) { + final IAEItemPowerStorage ips = (IAEItemPowerStorage) extractedItem.getItem(); + if (ips.getAECurrentPower(extractedItem) >= ips.getAEMaxPower(extractedItem)) { + return true; + } + } + + return AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystalCharged() + .isSameAs(extractedItem); + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection whichSide) { + return this.sides; + } + + public void activate(final EntityPlayer player) { + if (!Platform.hasPermissions(new DimensionalCoord(this), player)) { + return; + } + + final ItemStack myItem = this.getStackInSlot(0); + if (myItem == null) { + ItemStack held = player.inventory.getCurrentItem(); + + if (AEApi.instance().definitions().materials().certusQuartzCrystal().isSameAs(held) + || Platform.isChargeable(held)) { + held = player.inventory.decrStackSize(player.inventory.currentItem, 1); + this.setInventorySlotContents(0, held); + } + } else { + final List drops = new ArrayList(); + drops.add(myItem); + this.setInventorySlotContents(0, null); + Platform.spawnDrops( + this.worldObj, + this.xCoord + this.getForward().offsetX, + this.yCoord + this.getForward().offsetY, + this.zCoord + this.getForward().offsetZ, + drops); + } + } } diff --git a/src/main/java/appeng/tile/misc/TileCondenser.java b/src/main/java/appeng/tile/misc/TileCondenser.java index 5754e6c3fe0..6964fbd8751 100644 --- a/src/main/java/appeng/tile/misc/TileCondenser.java +++ b/src/main/java/appeng/tile/misc/TileCondenser.java @@ -18,7 +18,6 @@ package appeng.tile.misc; - import appeng.api.AEApi; import appeng.api.config.CondenserOutput; import appeng.api.config.Settings; @@ -43,248 +42,208 @@ import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; - -public class TileCondenser extends AEBaseInvTile implements IFluidHandler, IConfigManagerHost, IConfigurableObject -{ - - private static final FluidTankInfo[] EMPTY = { new FluidTankInfo( null, 10 ) }; - private final int[] sides = { 0, 1 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 3 ); - private final ConfigManager cm = new ConfigManager( this ); - - private double storedPower = 0; - - public TileCondenser() - { - this.cm.registerSetting( Settings.CONDENSER_OUTPUT, CondenserOutput.TRASH ); - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileCondenser( final NBTTagCompound data ) - { - this.cm.writeToNBT( data ); - data.setDouble( "storedPower", this.getStoredPower() ); - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileCondenser( final NBTTagCompound data ) - { - this.cm.readFromNBT( data ); - this.setStoredPower( data.getDouble( "storedPower" ) ); - } - - public double getStorage() - { - final ItemStack is = this.inv.getStackInSlot( 2 ); - if( is != null ) - { - if( is.getItem() instanceof IStorageComponent ) - { - final IStorageComponent sc = (IStorageComponent) is.getItem(); - if( sc.isStorageComponent( is ) ) - { - return sc.getBytes( is ) * 8; - } - } - } - return 0; - } - - public void addPower( final double rawPower ) - { - this.setStoredPower( this.getStoredPower() + rawPower ); - this.setStoredPower( Math.max( 0.0, Math.min( this.getStorage(), this.getStoredPower() ) ) ); - - final double requiredPower = this.getRequiredPower(); - final ItemStack output = this.getOutput(); - while( requiredPower <= this.getStoredPower() && output != null && requiredPower > 0 ) - { - if( this.canAddOutput( output ) ) - { - this.setStoredPower( this.getStoredPower() - requiredPower ); - this.addOutput( output ); - } - else - { - break; - } - } - } - - private boolean canAddOutput( final ItemStack output ) - { - final ItemStack outputStack = this.getStackInSlot( 1 ); - return outputStack == null || ( Platform.isSameItem( outputStack, output ) && outputStack.stackSize < outputStack.getMaxStackSize() ); - } - - /** - * make sure you validate with canAddOutput prior to this. - * - * @param output to be added output - */ - private void addOutput( final ItemStack output ) - { - final ItemStack outputStack = this.getStackInSlot( 1 ); - if( outputStack == null ) - { - this.setInventorySlotContents( 1, output.copy() ); - } - else - { - outputStack.stackSize++; - this.setInventorySlotContents( 1, outputStack ); - } - } - - private ItemStack getOutput() - { - final IMaterials materials = AEApi.instance().definitions().materials(); - - switch( (CondenserOutput) this.cm.getSetting( Settings.CONDENSER_OUTPUT ) ) - { - case MATTER_BALLS: - for( final ItemStack matterBallStack : materials.matterBall().maybeStack( 1 ).asSet() ) - { - return matterBallStack; - } - - case SINGULARITY: - for( final ItemStack singularityStack : materials.singularity().maybeStack( 1 ).asSet() ) - { - return singularityStack; - } - - case TRASH: - default: - } - return null; - } - - public double getRequiredPower() - { - return ( (CondenserOutput) this.cm.getSetting( Settings.CONDENSER_OUTPUT ) ).requiredPower; - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - if( i == 0 ) - { - if( itemstack != null ) - { - this.addPower( itemstack.stackSize ); - } - } - else - { - this.inv.setInventorySlotContents( 1, itemstack ); - } - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return i == 0; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( slot == 0 ) - { - final ItemStack is = inv.getStackInSlot( 0 ); - if( is != null ) - { - this.addPower( is.stackSize ); - inv.setInventorySlotContents( 0, null ); - } - } - } - - @Override - public boolean canInsertItem( final int slotIndex, final ItemStack insertingItem, final int side ) - { - return slotIndex == 0; - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - return slotIndex != 0; - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.sides; - } - - @Override - public int fill( final ForgeDirection from, final FluidStack resource, final boolean doFill ) - { - if( doFill ) - { - this.addPower( ( resource == null ? 0.0 : (double) resource.amount ) / 500.0 ); - } - - return resource == null ? 0 : resource.amount; - } - - @Override - public FluidStack drain( final ForgeDirection from, final FluidStack resource, final boolean doDrain ) - { - return null; - } - - @Override - public FluidStack drain( final ForgeDirection from, final int maxDrain, final boolean doDrain ) - { - return null; - } - - @Override - public boolean canFill( final ForgeDirection from, final Fluid fluid ) - { - return true; - } - - @Override - public boolean canDrain( final ForgeDirection from, final Fluid fluid ) - { - return false; - } - - @Override - public FluidTankInfo[] getTankInfo( final ForgeDirection from ) - { - return EMPTY; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - this.addPower( 0 ); - } - - @Override - public IConfigManager getConfigManager() - { - return this.cm; - } - - public double getStoredPower() - { - return this.storedPower; - } - - private void setStoredPower( final double storedPower ) - { - this.storedPower = storedPower; - } +public class TileCondenser extends AEBaseInvTile implements IFluidHandler, IConfigManagerHost, IConfigurableObject { + + private static final FluidTankInfo[] EMPTY = {new FluidTankInfo(null, 10)}; + private final int[] sides = {0, 1}; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 3); + private final ConfigManager cm = new ConfigManager(this); + + private double storedPower = 0; + + public TileCondenser() { + this.cm.registerSetting(Settings.CONDENSER_OUTPUT, CondenserOutput.TRASH); + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileCondenser(final NBTTagCompound data) { + this.cm.writeToNBT(data); + data.setDouble("storedPower", this.getStoredPower()); + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileCondenser(final NBTTagCompound data) { + this.cm.readFromNBT(data); + this.setStoredPower(data.getDouble("storedPower")); + } + + public double getStorage() { + final ItemStack is = this.inv.getStackInSlot(2); + if (is != null) { + if (is.getItem() instanceof IStorageComponent) { + final IStorageComponent sc = (IStorageComponent) is.getItem(); + if (sc.isStorageComponent(is)) { + return sc.getBytes(is) * 8; + } + } + } + return 0; + } + + public void addPower(final double rawPower) { + this.setStoredPower(this.getStoredPower() + rawPower); + this.setStoredPower(Math.max(0.0, Math.min(this.getStorage(), this.getStoredPower()))); + + final double requiredPower = this.getRequiredPower(); + final ItemStack output = this.getOutput(); + while (requiredPower <= this.getStoredPower() && output != null && requiredPower > 0) { + if (this.canAddOutput(output)) { + this.setStoredPower(this.getStoredPower() - requiredPower); + this.addOutput(output); + } else { + break; + } + } + } + + private boolean canAddOutput(final ItemStack output) { + final ItemStack outputStack = this.getStackInSlot(1); + return outputStack == null + || (Platform.isSameItem(outputStack, output) && outputStack.stackSize < outputStack.getMaxStackSize()); + } + + /** + * make sure you validate with canAddOutput prior to this. + * + * @param output to be added output + */ + private void addOutput(final ItemStack output) { + final ItemStack outputStack = this.getStackInSlot(1); + if (outputStack == null) { + this.setInventorySlotContents(1, output.copy()); + } else { + outputStack.stackSize++; + this.setInventorySlotContents(1, outputStack); + } + } + + private ItemStack getOutput() { + final IMaterials materials = AEApi.instance().definitions().materials(); + + switch ((CondenserOutput) this.cm.getSetting(Settings.CONDENSER_OUTPUT)) { + case MATTER_BALLS: + for (final ItemStack matterBallStack : + materials.matterBall().maybeStack(1).asSet()) { + return matterBallStack; + } + + case SINGULARITY: + for (final ItemStack singularityStack : + materials.singularity().maybeStack(1).asSet()) { + return singularityStack; + } + + case TRASH: + default: + } + return null; + } + + public double getRequiredPower() { + return ((CondenserOutput) this.cm.getSetting(Settings.CONDENSER_OUTPUT)).requiredPower; + } + + @Override + public IInventory getInternalInventory() { + return this.inv; + } + + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + if (i == 0) { + if (itemstack != null) { + this.addPower(itemstack.stackSize); + } + } else { + this.inv.setInventorySlotContents(1, itemstack); + } + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return i == 0; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) { + if (slot == 0) { + final ItemStack is = inv.getStackInSlot(0); + if (is != null) { + this.addPower(is.stackSize); + inv.setInventorySlotContents(0, null); + } + } + } + + @Override + public boolean canInsertItem(final int slotIndex, final ItemStack insertingItem, final int side) { + return slotIndex == 0; + } + + @Override + public boolean canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + return slotIndex != 0; + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return this.sides; + } + + @Override + public int fill(final ForgeDirection from, final FluidStack resource, final boolean doFill) { + if (doFill) { + this.addPower((resource == null ? 0.0 : (double) resource.amount) / 500.0); + } + + return resource == null ? 0 : resource.amount; + } + + @Override + public FluidStack drain(final ForgeDirection from, final FluidStack resource, final boolean doDrain) { + return null; + } + + @Override + public FluidStack drain(final ForgeDirection from, final int maxDrain, final boolean doDrain) { + return null; + } + + @Override + public boolean canFill(final ForgeDirection from, final Fluid fluid) { + return true; + } + + @Override + public boolean canDrain(final ForgeDirection from, final Fluid fluid) { + return false; + } + + @Override + public FluidTankInfo[] getTankInfo(final ForgeDirection from) { + return EMPTY; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + this.addPower(0); + } + + @Override + public IConfigManager getConfigManager() { + return this.cm; + } + + public double getStoredPower() { + return this.storedPower; + } + + private void setStoredPower(final double storedPower) { + this.storedPower = storedPower; + } } diff --git a/src/main/java/appeng/tile/misc/TileInscriber.java b/src/main/java/appeng/tile/misc/TileInscriber.java index 554ed8a5f2d..368a5ea9608 100644 --- a/src/main/java/appeng/tile/misc/TileInscriber.java +++ b/src/main/java/appeng/tile/misc/TileInscriber.java @@ -18,7 +18,6 @@ package appeng.tile.misc; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -55,523 +54,447 @@ import appeng.util.item.AEItemStack; import com.google.common.collect.Lists; import io.netty.buffer.ByteBuf; +import java.io.IOException; +import java.util.EnumSet; +import java.util.List; +import javax.annotation.Nullable; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nullable; -import java.io.IOException; -import java.util.EnumSet; -import java.util.List; - - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class TileInscriber extends AENetworkPowerTile implements IGridTickable, IUpgradeableHost, IConfigManagerHost -{ - - private final int maxProcessingTime = 100; - private final int[] top = { 0 }; - private final int[] bottom = { 1 }; - private final int[] sides = { 2, 3 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 4 ); - private final IConfigManager settings; - private final UpgradeInventory upgrades; - private int processingTime = 0; - // cycles from 0 - 16, at 8 it preforms the action, at 16 it re-enables the normal routine. - private boolean smash; - private int finalStep; - private long clientStart; - - @Reflected - public TileInscriber() - { - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - this.setInternalMaxPower( 1500 ); - this.getProxy().setIdlePowerUsage( 0 ); - this.settings = new ConfigManager( this ); - - final ITileDefinition inscriberDefinition = AEApi.instance().definitions().blocks().inscriber(); - this.upgrades = new DefinitionUpgradeInventory( inscriberDefinition, this, this.getUpgradeSlots() ); - } - - private int getUpgradeSlots() - { - return 3; - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileInscriber( final NBTTagCompound data ) - { - this.inv.writeToNBT( data, "inscriberInv" ); - this.upgrades.writeToNBT( data, "upgrades" ); - this.settings.writeToNBT( data ); - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileInscriber( final NBTTagCompound data ) - { - this.inv.readFromNBT( data, "inscriberInv" ); - this.upgrades.readFromNBT( data, "upgrades" ); - this.settings.readFromNBT( data ); - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileInscriber( final ByteBuf data ) throws IOException - { - final int slot = data.readByte(); - - final boolean oldSmash = this.isSmash(); - final boolean newSmash = ( slot & 64 ) == 64; - - if( oldSmash != newSmash && newSmash ) - { - this.setSmash( true ); - this.setClientStart( System.currentTimeMillis() ); - } - - for( int num = 0; num < this.inv.getSizeInventory(); num++ ) - { - if( ( slot & ( 1 << num ) ) > 0 ) - { - this.inv.setInventorySlotContents( num, AEItemStack.loadItemStackFromPacket( data ).getItemStack() ); - } - else - { - this.inv.setInventorySlotContents( num, null ); - } - } - - return false; - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileInscriber( final ByteBuf data ) throws IOException - { - int slot = this.isSmash() ? 64 : 0; - - for( int num = 0; num < this.inv.getSizeInventory(); num++ ) - { - if( this.inv.getStackInSlot( num ) != null ) - { - slot |= ( 1 << num ); - } - } - - data.writeByte( slot ); - for( int num = 0; num < this.inv.getSizeInventory(); num++ ) - { - if( ( slot & ( 1 << num ) ) > 0 ) - { - final AEItemStack st = AEItemStack.create( this.inv.getStackInSlot( num ) ); - st.writeToPacket( data ); - } - } - } - - @Override - public void setOrientation( final ForgeDirection inForward, final ForgeDirection inUp ) - { - super.setOrientation( inForward, inUp ); - this.getProxy().setValidSides( EnumSet.complementOf( EnumSet.of( this.getForward() ) ) ); - this.setPowerSides( EnumSet.complementOf( EnumSet.of( this.getForward() ) ) ); - } - - @Override - public void getDrops( final World w, final int x, final int y, final int z, final List drops ) - { - super.getDrops( w, x, y, z, drops ); - - for( int h = 0; h < this.upgrades.getSizeInventory(); h++ ) - { - final ItemStack is = this.upgrades.getStackInSlot( h ); - if( is != null ) - { - drops.add( is ); - } - } - } - - @Override - public boolean requiresTESR() - { - return true; - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - - @Override - public int getInventoryStackLimit() - { - return 1; - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - if( this.isSmash() ) - { - return false; - } - - if( i == 0 || i == 1 ) - { - if( AEApi.instance().definitions().materials().namePress().isSameAs( itemstack ) ) - { - return true; - } - - for( final ItemStack optionals : AEApi.instance().registries().inscriber().getOptionals() ) - { - if( Platform.isSameItemPrecise( optionals, itemstack ) ) - { - return true; - } - } - } - - return i == 2; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - try - { - if( mc != InvOperation.markDirty ) - { - if( slot != 3 ) - { - this.setProcessingTime( 0 ); - } - - if( !this.isSmash() ) - { - this.markForUpdate(); - } - - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - if( this.isSmash() ) - { - return false; - } - - return slotIndex == 0 || slotIndex == 1 || slotIndex == 3; - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection d ) - { - if( d == ForgeDirection.UP ) - { - return this.top; - } - - if( d == ForgeDirection.DOWN ) - { - return this.bottom; - } - - return this.sides; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.Inscriber.getMin(), TickRates.Inscriber.getMax(), !this.hasWork(), false ); - } - - private boolean hasWork() - { - if( this.getTask() != null ) - { - return true; - } - - this.setProcessingTime( 0 ); - return this.isSmash(); - } - - @Nullable - public IInscriberRecipe getTask() - { - final ItemStack plateA = this.getStackInSlot( 0 ); - final ItemStack plateB = this.getStackInSlot( 1 ); - ItemStack renamedItem = this.getStackInSlot( 2 ); - - if( plateA != null && plateA.stackSize > 1 ) - { - return null; - } - - if( plateB != null && plateB.stackSize > 1 ) - { - return null; - } - - if( renamedItem != null && renamedItem.stackSize > 1 ) - { - return null; - } - - final IComparableDefinition namePress = AEApi.instance().definitions().materials().namePress(); - final boolean isNameA = namePress.isSameAs( plateA ); - final boolean isNameB = namePress.isSameAs( plateB ); - - if( ( isNameA || isNameB ) && ( isNameA || plateA == null ) && ( isNameB || plateB == null ) ) - { - if( renamedItem != null ) - { - String name = ""; - - if( plateA != null ) - { - final NBTTagCompound tag = Platform.openNbtData( plateA ); - name += tag.getString( "InscribeName" ); - } - - if( plateB != null ) - { - final NBTTagCompound tag = Platform.openNbtData( plateB ); - if( name.length() > 0 ) - { - name += " "; - } - name += tag.getString( "InscribeName" ); - } - - final ItemStack startingItem = renamedItem.copy(); - renamedItem = renamedItem.copy(); - final NBTTagCompound tag = Platform.openNbtData( renamedItem ); - - final NBTTagCompound display = tag.getCompoundTag( "display" ); - tag.setTag( "display", display ); - - if( name.length() > 0 ) - { - display.setString( "Name", name ); - } - else - { - display.removeTag( "Name" ); - } - - final List inputs = Lists.newArrayList( startingItem ); - final InscriberProcessType type = InscriberProcessType.Inscribe; - - return new InscriberRecipe( inputs, renamedItem, plateA, plateB, type ); - } - } - - for( final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes() ) - { - - final boolean matchA = ( plateA == null && !recipe.getTopOptional().isPresent() ) || ( Platform.isSameItemPrecise( plateA, recipe.getTopOptional().orNull() ) ) && // and... - ( plateB == null && !recipe.getBottomOptional().isPresent() ) | ( Platform.isSameItemPrecise( plateB, recipe.getBottomOptional().orNull() ) ); - - final boolean matchB = ( plateB == null && !recipe.getTopOptional().isPresent() ) || ( Platform.isSameItemPrecise( plateB, recipe.getTopOptional().orNull() ) ) && // and... - ( plateA == null && !recipe.getBottomOptional().isPresent() ) | ( Platform.isSameItemPrecise( plateA, recipe.getBottomOptional().orNull() ) ); - - if( matchA || matchB ) - { - for( final ItemStack option : recipe.getInputs() ) - { - if( Platform.isSameItemPrecise( option, this.getStackInSlot( 2 ) ) ) - { - return recipe; - } - } - } - } - return null; - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( this.isSmash() ) - { - this.finalStep++; - if( this.finalStep == 8 ) - { - final IInscriberRecipe out = this.getTask(); - if( out != null ) - { - final ItemStack outputCopy = out.getOutput().copy(); - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( new WrapperInventoryRange( this.inv, 3, 1, true ), ForgeDirection.UNKNOWN ); - - if( ad.addItems( outputCopy ) == null ) - { - this.setProcessingTime( 0 ); - if( out.getProcessType() == InscriberProcessType.Press ) - { - this.setInventorySlotContents( 0, null ); - this.setInventorySlotContents( 1, null ); - } - this.setInventorySlotContents( 2, null ); - } - } - - this.markDirty(); - } - else if( this.finalStep == 16 ) - { - this.finalStep = 0; - this.setSmash( false ); - this.markForUpdate(); - } - } - else - { - try - { - final IEnergyGrid eg = this.getProxy().getEnergy(); - IEnergySource src = this; - - // Base 1, increase by 1 for each card - final int speedFactor = 1 + this.upgrades.getInstalledUpgrades( Upgrades.SPEED ); - final int powerConsumption = 10 * speedFactor; - final double powerThreshold = powerConsumption - 0.01; - double powerReq = this.extractAEPower( powerConsumption, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - - if( powerReq <= powerThreshold ) - { - src = eg; - powerReq = eg.extractAEPower( powerConsumption, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - } - - if( powerReq > powerThreshold ) - { - src.extractAEPower( powerConsumption, Actionable.MODULATE, PowerMultiplier.CONFIG ); - - if( this.getProcessingTime() == 0 ) - { - this.setProcessingTime( this.getProcessingTime() + speedFactor ); - } - else - { - this.setProcessingTime( this.getProcessingTime() + ticksSinceLastCall * speedFactor ); - } - } - } - catch( final GridAccessException e ) - { - // :P - } - - if( this.getProcessingTime() > this.getMaxProcessingTime() ) - { - this.setProcessingTime( this.getMaxProcessingTime() ); - final IInscriberRecipe out = this.getTask(); - if( out != null ) - { - final ItemStack outputCopy = out.getOutput().copy(); - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( new WrapperInventoryRange( this.inv, 3, 1, true ), ForgeDirection.UNKNOWN ); - if( ad.simulateAdd( outputCopy ) == null ) - { - this.setSmash( true ); - this.finalStep = 0; - this.markForUpdate(); - } - } - } - } - - return this.hasWork() ? TickRateModulation.URGENT : TickRateModulation.SLEEP; - } - - @Override - public IConfigManager getConfigManager() - { - return this.settings; - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "inv" ) ) - { - return this.inv; - } - - if( name.equals( "upgrades" ) ) - { - return this.upgrades; - } - - return null; - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.upgrades.getInstalledUpgrades( u ); - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - } - - public long getClientStart() - { - return this.clientStart; - } - - private void setClientStart( final long clientStart ) - { - this.clientStart = clientStart; - } - - public boolean isSmash() - { - return this.smash; - } - - public void setSmash( final boolean smash ) - { - this.smash = smash; - } - - public int getMaxProcessingTime() - { - return this.maxProcessingTime; - } - - public int getProcessingTime() - { - return this.processingTime; - } - - private void setProcessingTime( final int processingTime ) - { - this.processingTime = processingTime; - } +public class TileInscriber extends AENetworkPowerTile implements IGridTickable, IUpgradeableHost, IConfigManagerHost { + + private final int maxProcessingTime = 100; + private final int[] top = {0}; + private final int[] bottom = {1}; + private final int[] sides = {2, 3}; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 4); + private final IConfigManager settings; + private final UpgradeInventory upgrades; + private int processingTime = 0; + // cycles from 0 - 16, at 8 it preforms the action, at 16 it re-enables the normal routine. + private boolean smash; + private int finalStep; + private long clientStart; + + @Reflected + public TileInscriber() { + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + this.setInternalMaxPower(1500); + this.getProxy().setIdlePowerUsage(0); + this.settings = new ConfigManager(this); + + final ITileDefinition inscriberDefinition = + AEApi.instance().definitions().blocks().inscriber(); + this.upgrades = new DefinitionUpgradeInventory(inscriberDefinition, this, this.getUpgradeSlots()); + } + + private int getUpgradeSlots() { + return 3; + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileInscriber(final NBTTagCompound data) { + this.inv.writeToNBT(data, "inscriberInv"); + this.upgrades.writeToNBT(data, "upgrades"); + this.settings.writeToNBT(data); + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileInscriber(final NBTTagCompound data) { + this.inv.readFromNBT(data, "inscriberInv"); + this.upgrades.readFromNBT(data, "upgrades"); + this.settings.readFromNBT(data); + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileInscriber(final ByteBuf data) throws IOException { + final int slot = data.readByte(); + + final boolean oldSmash = this.isSmash(); + final boolean newSmash = (slot & 64) == 64; + + if (oldSmash != newSmash && newSmash) { + this.setSmash(true); + this.setClientStart(System.currentTimeMillis()); + } + + for (int num = 0; num < this.inv.getSizeInventory(); num++) { + if ((slot & (1 << num)) > 0) { + this.inv.setInventorySlotContents( + num, AEItemStack.loadItemStackFromPacket(data).getItemStack()); + } else { + this.inv.setInventorySlotContents(num, null); + } + } + + return false; + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileInscriber(final ByteBuf data) throws IOException { + int slot = this.isSmash() ? 64 : 0; + + for (int num = 0; num < this.inv.getSizeInventory(); num++) { + if (this.inv.getStackInSlot(num) != null) { + slot |= (1 << num); + } + } + + data.writeByte(slot); + for (int num = 0; num < this.inv.getSizeInventory(); num++) { + if ((slot & (1 << num)) > 0) { + final AEItemStack st = AEItemStack.create(this.inv.getStackInSlot(num)); + st.writeToPacket(data); + } + } + } + + @Override + public void setOrientation(final ForgeDirection inForward, final ForgeDirection inUp) { + super.setOrientation(inForward, inUp); + this.getProxy().setValidSides(EnumSet.complementOf(EnumSet.of(this.getForward()))); + this.setPowerSides(EnumSet.complementOf(EnumSet.of(this.getForward()))); + } + + @Override + public void getDrops(final World w, final int x, final int y, final int z, final List drops) { + super.getDrops(w, x, y, z, drops); + + for (int h = 0; h < this.upgrades.getSizeInventory(); h++) { + final ItemStack is = this.upgrades.getStackInSlot(h); + if (is != null) { + drops.add(is); + } + } + } + + @Override + public boolean requiresTESR() { + return true; + } + + @Override + public IInventory getInternalInventory() { + return this.inv; + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + if (this.isSmash()) { + return false; + } + + if (i == 0 || i == 1) { + if (AEApi.instance().definitions().materials().namePress().isSameAs(itemstack)) { + return true; + } + + for (final ItemStack optionals : + AEApi.instance().registries().inscriber().getOptionals()) { + if (Platform.isSameItemPrecise(optionals, itemstack)) { + return true; + } + } + } + + return i == 2; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) { + try { + if (mc != InvOperation.markDirty) { + if (slot != 3) { + this.setProcessingTime(0); + } + + if (!this.isSmash()) { + this.markForUpdate(); + } + + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } + + @Override + public boolean canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + if (this.isSmash()) { + return false; + } + + return slotIndex == 0 || slotIndex == 1 || slotIndex == 3; + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection d) { + if (d == ForgeDirection.UP) { + return this.top; + } + + if (d == ForgeDirection.DOWN) { + return this.bottom; + } + + return this.sides; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.Inscriber.getMin(), TickRates.Inscriber.getMax(), !this.hasWork(), false); + } + + private boolean hasWork() { + if (this.getTask() != null) { + return true; + } + + this.setProcessingTime(0); + return this.isSmash(); + } + + @Nullable + public IInscriberRecipe getTask() { + final ItemStack plateA = this.getStackInSlot(0); + final ItemStack plateB = this.getStackInSlot(1); + ItemStack renamedItem = this.getStackInSlot(2); + + if (plateA != null && plateA.stackSize > 1) { + return null; + } + + if (plateB != null && plateB.stackSize > 1) { + return null; + } + + if (renamedItem != null && renamedItem.stackSize > 1) { + return null; + } + + final IComparableDefinition namePress = + AEApi.instance().definitions().materials().namePress(); + final boolean isNameA = namePress.isSameAs(plateA); + final boolean isNameB = namePress.isSameAs(plateB); + + if ((isNameA || isNameB) && (isNameA || plateA == null) && (isNameB || plateB == null)) { + if (renamedItem != null) { + String name = ""; + + if (plateA != null) { + final NBTTagCompound tag = Platform.openNbtData(plateA); + name += tag.getString("InscribeName"); + } + + if (plateB != null) { + final NBTTagCompound tag = Platform.openNbtData(plateB); + if (name.length() > 0) { + name += " "; + } + name += tag.getString("InscribeName"); + } + + final ItemStack startingItem = renamedItem.copy(); + renamedItem = renamedItem.copy(); + final NBTTagCompound tag = Platform.openNbtData(renamedItem); + + final NBTTagCompound display = tag.getCompoundTag("display"); + tag.setTag("display", display); + + if (name.length() > 0) { + display.setString("Name", name); + } else { + display.removeTag("Name"); + } + + final List inputs = Lists.newArrayList(startingItem); + final InscriberProcessType type = InscriberProcessType.Inscribe; + + return new InscriberRecipe(inputs, renamedItem, plateA, plateB, type); + } + } + + for (final IInscriberRecipe recipe : + AEApi.instance().registries().inscriber().getRecipes()) { + + final boolean matchA = (plateA == null && !recipe.getTopOptional().isPresent()) + || (Platform.isSameItemPrecise( + plateA, recipe.getTopOptional().orNull())) + && // and... + (plateB == null && !recipe.getBottomOptional().isPresent()) + | (Platform.isSameItemPrecise( + plateB, recipe.getBottomOptional().orNull())); + + final boolean matchB = (plateB == null && !recipe.getTopOptional().isPresent()) + || (Platform.isSameItemPrecise( + plateB, recipe.getTopOptional().orNull())) + && // and... + (plateA == null && !recipe.getBottomOptional().isPresent()) + | (Platform.isSameItemPrecise( + plateA, recipe.getBottomOptional().orNull())); + + if (matchA || matchB) { + for (final ItemStack option : recipe.getInputs()) { + if (Platform.isSameItemPrecise(option, this.getStackInSlot(2))) { + return recipe; + } + } + } + } + return null; + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (this.isSmash()) { + this.finalStep++; + if (this.finalStep == 8) { + final IInscriberRecipe out = this.getTask(); + if (out != null) { + final ItemStack outputCopy = out.getOutput().copy(); + final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( + new WrapperInventoryRange(this.inv, 3, 1, true), ForgeDirection.UNKNOWN); + + if (ad.addItems(outputCopy) == null) { + this.setProcessingTime(0); + if (out.getProcessType() == InscriberProcessType.Press) { + this.setInventorySlotContents(0, null); + this.setInventorySlotContents(1, null); + } + this.setInventorySlotContents(2, null); + } + } + + this.markDirty(); + } else if (this.finalStep == 16) { + this.finalStep = 0; + this.setSmash(false); + this.markForUpdate(); + } + } else { + try { + final IEnergyGrid eg = this.getProxy().getEnergy(); + IEnergySource src = this; + + // Base 1, increase by 1 for each card + final int speedFactor = 1 + this.upgrades.getInstalledUpgrades(Upgrades.SPEED); + final int powerConsumption = 10 * speedFactor; + final double powerThreshold = powerConsumption - 0.01; + double powerReq = this.extractAEPower(powerConsumption, Actionable.SIMULATE, PowerMultiplier.CONFIG); + + if (powerReq <= powerThreshold) { + src = eg; + powerReq = eg.extractAEPower(powerConsumption, Actionable.SIMULATE, PowerMultiplier.CONFIG); + } + + if (powerReq > powerThreshold) { + src.extractAEPower(powerConsumption, Actionable.MODULATE, PowerMultiplier.CONFIG); + + if (this.getProcessingTime() == 0) { + this.setProcessingTime(this.getProcessingTime() + speedFactor); + } else { + this.setProcessingTime(this.getProcessingTime() + ticksSinceLastCall * speedFactor); + } + } + } catch (final GridAccessException e) { + // :P + } + + if (this.getProcessingTime() > this.getMaxProcessingTime()) { + this.setProcessingTime(this.getMaxProcessingTime()); + final IInscriberRecipe out = this.getTask(); + if (out != null) { + final ItemStack outputCopy = out.getOutput().copy(); + final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( + new WrapperInventoryRange(this.inv, 3, 1, true), ForgeDirection.UNKNOWN); + if (ad.simulateAdd(outputCopy) == null) { + this.setSmash(true); + this.finalStep = 0; + this.markForUpdate(); + } + } + } + } + + return this.hasWork() ? TickRateModulation.URGENT : TickRateModulation.SLEEP; + } + + @Override + public IConfigManager getConfigManager() { + return this.settings; + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("inv")) { + return this.inv; + } + + if (name.equals("upgrades")) { + return this.upgrades; + } + + return null; + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.upgrades.getInstalledUpgrades(u); + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) {} + + public long getClientStart() { + return this.clientStart; + } + + private void setClientStart(final long clientStart) { + this.clientStart = clientStart; + } + + public boolean isSmash() { + return this.smash; + } + + public void setSmash(final boolean smash) { + this.smash = smash; + } + + public int getMaxProcessingTime() { + return this.maxProcessingTime; + } + + public int getProcessingTime() { + return this.processingTime; + } + + private void setProcessingTime(final int processingTime) { + this.processingTime = processingTime; + } } diff --git a/src/main/java/appeng/tile/misc/TileInterface.java b/src/main/java/appeng/tile/misc/TileInterface.java index 3543110c27b..9a11ea7c6c8 100644 --- a/src/main/java/appeng/tile/misc/TileInterface.java +++ b/src/main/java/appeng/tile/misc/TileInterface.java @@ -18,7 +18,6 @@ package appeng.tile.misc; - import appeng.api.config.Actionable; import appeng.api.config.Upgrades; import appeng.api.implementations.IPowerChannelState; @@ -53,6 +52,8 @@ import appeng.util.inv.IInventoryDestination; import com.google.common.collect.ImmutableSet; import io.netty.buffer.ByteBuf; +import java.util.EnumSet; +import java.util.List; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; @@ -61,330 +62,275 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.List; - - public class TileInterface extends AENetworkInvTile - implements IGridTickable, ITileStorageMonitorable, IStorageMonitorable, IInventoryDestination, IInterfaceHost, IPriorityHost, IPowerChannelState -{ - - private final DualityInterface duality = new DualityInterface( this.getProxy(), this ); - private ForgeDirection pointAt = ForgeDirection.UNKNOWN; - - private static final int POWERED_FLAG = 1; - private static final int CHANNEL_FLAG = 2; - private static final int BOOTING_FLAG = 4; - private int clientFlags = 0; // sent as byte. - - - @MENetworkEventSubscribe - public void stateChange( final MENetworkChannelsChanged c ) - { - this.duality.notifyNeighbors(); - markForUpdate(); - } - - @MENetworkEventSubscribe - public void stateChange( final MENetworkPowerStatusChange c ) - { - this.duality.notifyNeighbors(); - markForUpdate(); - } - - public void setSide( final ForgeDirection axis ) - { - if( Platform.isClient() ) - { - return; - } - - if( this.pointAt == axis.getOpposite() ) - { - this.pointAt = axis; - } - else if( this.pointAt == axis || this.pointAt == axis.getOpposite() ) - { - this.pointAt = ForgeDirection.UNKNOWN; - } - else if( this.pointAt == ForgeDirection.UNKNOWN ) - { - this.pointAt = axis.getOpposite(); - } - else - { - this.pointAt = Platform.rotateAround( this.pointAt, axis ); - } - - if( ForgeDirection.UNKNOWN == this.pointAt ) - { - this.setOrientation( this.pointAt, this.pointAt ); - } - else - { - this.setOrientation( this.pointAt.offsetY != 0 ? ForgeDirection.SOUTH : ForgeDirection.UP, this.pointAt.getOpposite() ); - } - - this.getProxy().setValidSides( EnumSet.complementOf( EnumSet.of( this.pointAt ) ) ); - this.markForUpdate(); - this.markDirty(); - } - - @Override - public void markDirty() - { - this.duality.markDirty(); - } - - @Override - public void getDrops( final World w, final int x, final int y, final int z, final List drops ) - { - this.duality.addDrops( drops ); - } - - @Override - public void gridChanged() - { - this.duality.gridChanged(); - } - - @Override - public void onReady() - { - this.getProxy().setValidSides( EnumSet.complementOf( EnumSet.of( this.pointAt ) ) ); - super.onReady(); - this.duality.initialize(); - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileInterface( final NBTTagCompound data ) - { - data.setInteger( "pointAt", this.pointAt.ordinal() ); - this.duality.writeToNBT( data ); - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileInterface( final NBTTagCompound data ) - { - final int val = data.getInteger( "pointAt" ); - - if( val >= 0 && val < ForgeDirection.values().length ) - { - this.pointAt = ForgeDirection.values()[val]; - } - else - { - this.pointAt = ForgeDirection.UNKNOWN; - } - - this.duality.readFromNBT( data ); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return this.duality.getCableConnectionType( dir ); - } - - @Override - public DimensionalCoord getLocation() - { - return this.duality.getLocation(); - } - - @Override - public boolean canInsert( final ItemStack stack ) - { - return this.duality.canInsert( stack ); - } - - @Override - public IMEMonitor getItemInventory() - { - return this.duality.getItemInventory(); - } - - @Override - public IMEMonitor getFluidInventory() - { - return this.duality.getFluidInventory(); - } - - @Override - public IInventory getInventoryByName( final String name ) - { - return this.duality.getInventoryByName( name ); - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return this.duality.getTickingRequest( node ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.duality.tickingRequest( node, ticksSinceLastCall ); - } - - @Override - public IInventory getInternalInventory() - { - return this.duality.getInternalInventory(); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - this.duality.onChangeInventory( inv, slot, mc, removed, added ); - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.duality.getAccessibleSlotsFromSide( side.ordinal() ); - } - - @Override - public DualityInterface getInterfaceDuality() - { - return this.duality; - } - - @Override - public EnumSet getTargets() - { - if( this.pointAt == null || this.pointAt == ForgeDirection.UNKNOWN ) - { - return EnumSet.complementOf( EnumSet.of( ForgeDirection.UNKNOWN ) ); - } - return EnumSet.of( this.pointAt ); - } - - @Override - public TileEntity getTileEntity() - { - return this; - } - - @Override - public IStorageMonitorable getMonitorable( final ForgeDirection side, final BaseActionSource src ) - { - return this.duality.getMonitorable( side, src, this ); - } - - @Override - public IConfigManager getConfigManager() - { - return this.duality.getConfigManager(); - } - - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table ) - { - return this.duality.pushPattern( patternDetails, table ); - } - - @Override - public boolean isBusy() - { - return this.duality.isBusy(); - } - - @Override - public void provideCrafting( final ICraftingProviderHelper craftingTracker ) - { - this.duality.provideCrafting( craftingTracker ); - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.duality.getInstalledUpgrades( u ); - } - - @Override - public ImmutableSet getRequestedJobs() - { - return this.duality.getRequestedJobs(); - } - - @Override - public IAEItemStack injectCraftedItems( final ICraftingLink link, final IAEItemStack items, final Actionable mode ) - { - return this.duality.injectCraftedItems( link, items, mode ); - } - - @Override - public void jobStateChange( final ICraftingLink link ) - { - this.duality.jobStateChange( link ); - } - - @Override - public int getPriority() - { - return this.duality.getPriority(); - } - - @Override - public void setPriority( final int newValue ) - { - this.duality.setPriority( newValue ); - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileInterface( final ByteBuf data ) - { - int newState = data.readByte(); - if (newState != clientFlags) - { - clientFlags = newState; - this.markForUpdate(); - return true; - } - return false; - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileInterface( final ByteBuf data ) - { - clientFlags = 0; - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - clientFlags |= POWERED_FLAG; - - if( this.getProxy().getNode().meetsChannelRequirements() ) - clientFlags |= CHANNEL_FLAG; - - if( this.getProxy().getPath().isNetworkBooting() ) - clientFlags |= BOOTING_FLAG; - } - catch( final GridAccessException e ) - { - // meh - } - - data.writeByte( clientFlags ); - } - - @Override - public boolean isPowered() - { - return ( clientFlags & POWERED_FLAG ) == POWERED_FLAG; - } - - @Override - public boolean isActive() - { - return ( clientFlags & CHANNEL_FLAG ) == CHANNEL_FLAG; - } - - @Override - public boolean isBooting() - { - return ( clientFlags & BOOTING_FLAG ) == BOOTING_FLAG; - } + implements IGridTickable, + ITileStorageMonitorable, + IStorageMonitorable, + IInventoryDestination, + IInterfaceHost, + IPriorityHost, + IPowerChannelState { + + private final DualityInterface duality = new DualityInterface(this.getProxy(), this); + private ForgeDirection pointAt = ForgeDirection.UNKNOWN; + + private static final int POWERED_FLAG = 1; + private static final int CHANNEL_FLAG = 2; + private static final int BOOTING_FLAG = 4; + private int clientFlags = 0; // sent as byte. + + @MENetworkEventSubscribe + public void stateChange(final MENetworkChannelsChanged c) { + this.duality.notifyNeighbors(); + markForUpdate(); + } + + @MENetworkEventSubscribe + public void stateChange(final MENetworkPowerStatusChange c) { + this.duality.notifyNeighbors(); + markForUpdate(); + } + + public void setSide(final ForgeDirection axis) { + if (Platform.isClient()) { + return; + } + + if (this.pointAt == axis.getOpposite()) { + this.pointAt = axis; + } else if (this.pointAt == axis || this.pointAt == axis.getOpposite()) { + this.pointAt = ForgeDirection.UNKNOWN; + } else if (this.pointAt == ForgeDirection.UNKNOWN) { + this.pointAt = axis.getOpposite(); + } else { + this.pointAt = Platform.rotateAround(this.pointAt, axis); + } + + if (ForgeDirection.UNKNOWN == this.pointAt) { + this.setOrientation(this.pointAt, this.pointAt); + } else { + this.setOrientation( + this.pointAt.offsetY != 0 ? ForgeDirection.SOUTH : ForgeDirection.UP, this.pointAt.getOpposite()); + } + + this.getProxy().setValidSides(EnumSet.complementOf(EnumSet.of(this.pointAt))); + this.markForUpdate(); + this.markDirty(); + } + + @Override + public void markDirty() { + this.duality.markDirty(); + } + + @Override + public void getDrops(final World w, final int x, final int y, final int z, final List drops) { + this.duality.addDrops(drops); + } + + @Override + public void gridChanged() { + this.duality.gridChanged(); + } + + @Override + public void onReady() { + this.getProxy().setValidSides(EnumSet.complementOf(EnumSet.of(this.pointAt))); + super.onReady(); + this.duality.initialize(); + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileInterface(final NBTTagCompound data) { + data.setInteger("pointAt", this.pointAt.ordinal()); + this.duality.writeToNBT(data); + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileInterface(final NBTTagCompound data) { + final int val = data.getInteger("pointAt"); + + if (val >= 0 && val < ForgeDirection.values().length) { + this.pointAt = ForgeDirection.values()[val]; + } else { + this.pointAt = ForgeDirection.UNKNOWN; + } + + this.duality.readFromNBT(data); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return this.duality.getCableConnectionType(dir); + } + + @Override + public DimensionalCoord getLocation() { + return this.duality.getLocation(); + } + + @Override + public boolean canInsert(final ItemStack stack) { + return this.duality.canInsert(stack); + } + + @Override + public IMEMonitor getItemInventory() { + return this.duality.getItemInventory(); + } + + @Override + public IMEMonitor getFluidInventory() { + return this.duality.getFluidInventory(); + } + + @Override + public IInventory getInventoryByName(final String name) { + return this.duality.getInventoryByName(name); + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return this.duality.getTickingRequest(node); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.duality.tickingRequest(node, ticksSinceLastCall); + } + + @Override + public IInventory getInternalInventory() { + return this.duality.getInternalInventory(); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) { + this.duality.onChangeInventory(inv, slot, mc, removed, added); + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return this.duality.getAccessibleSlotsFromSide(side.ordinal()); + } + + @Override + public DualityInterface getInterfaceDuality() { + return this.duality; + } + + @Override + public EnumSet getTargets() { + if (this.pointAt == null || this.pointAt == ForgeDirection.UNKNOWN) { + return EnumSet.complementOf(EnumSet.of(ForgeDirection.UNKNOWN)); + } + return EnumSet.of(this.pointAt); + } + + @Override + public TileEntity getTileEntity() { + return this; + } + + @Override + public IStorageMonitorable getMonitorable(final ForgeDirection side, final BaseActionSource src) { + return this.duality.getMonitorable(side, src, this); + } + + @Override + public IConfigManager getConfigManager() { + return this.duality.getConfigManager(); + } + + @Override + public boolean pushPattern(final ICraftingPatternDetails patternDetails, final InventoryCrafting table) { + return this.duality.pushPattern(patternDetails, table); + } + + @Override + public boolean isBusy() { + return this.duality.isBusy(); + } + + @Override + public void provideCrafting(final ICraftingProviderHelper craftingTracker) { + this.duality.provideCrafting(craftingTracker); + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.duality.getInstalledUpgrades(u); + } + + @Override + public ImmutableSet getRequestedJobs() { + return this.duality.getRequestedJobs(); + } + + @Override + public IAEItemStack injectCraftedItems(final ICraftingLink link, final IAEItemStack items, final Actionable mode) { + return this.duality.injectCraftedItems(link, items, mode); + } + + @Override + public void jobStateChange(final ICraftingLink link) { + this.duality.jobStateChange(link); + } + + @Override + public int getPriority() { + return this.duality.getPriority(); + } + + @Override + public void setPriority(final int newValue) { + this.duality.setPriority(newValue); + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileInterface(final ByteBuf data) { + int newState = data.readByte(); + if (newState != clientFlags) { + clientFlags = newState; + this.markForUpdate(); + return true; + } + return false; + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileInterface(final ByteBuf data) { + clientFlags = 0; + try { + if (this.getProxy().getEnergy().isNetworkPowered()) clientFlags |= POWERED_FLAG; + + if (this.getProxy().getNode().meetsChannelRequirements()) clientFlags |= CHANNEL_FLAG; + + if (this.getProxy().getPath().isNetworkBooting()) clientFlags |= BOOTING_FLAG; + } catch (final GridAccessException e) { + // meh + } + + data.writeByte(clientFlags); + } + + @Override + public boolean isPowered() { + return (clientFlags & POWERED_FLAG) == POWERED_FLAG; + } + + @Override + public boolean isActive() { + return (clientFlags & CHANNEL_FLAG) == CHANNEL_FLAG; + } + + @Override + public boolean isBooting() { + return (clientFlags & BOOTING_FLAG) == BOOTING_FLAG; + } } diff --git a/src/main/java/appeng/tile/misc/TileLightDetector.java b/src/main/java/appeng/tile/misc/TileLightDetector.java index 1f6764ff043..405fd2dd85d 100644 --- a/src/main/java/appeng/tile/misc/TileLightDetector.java +++ b/src/main/java/appeng/tile/misc/TileLightDetector.java @@ -18,49 +18,40 @@ package appeng.tile.misc; - import appeng.tile.AEBaseTile; import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; import appeng.util.Platform; - -public class TileLightDetector extends AEBaseTile -{ - - private int lastCheck = 30; - private int lastLight = 0; - - public boolean isReady() - { - return this.lastLight > 0; - } - - @TileEvent( TileEventType.TICK ) - public void Tick_TileLightDetector() - { - this.lastCheck++; - if( this.lastCheck > 30 ) - { - this.lastCheck = 0; - this.updateLight(); - } - } - - public void updateLight() - { - final int val = this.worldObj.getBlockLightValue( this.xCoord, this.yCoord, this.zCoord ); - - if( this.lastLight != val ) - { - this.lastLight = val; - Platform.notifyBlocksOfNeighbors( this.worldObj, this.xCoord, this.yCoord, this.zCoord ); - } - } - - @Override - public boolean canBeRotated() - { - return false; - } +public class TileLightDetector extends AEBaseTile { + + private int lastCheck = 30; + private int lastLight = 0; + + public boolean isReady() { + return this.lastLight > 0; + } + + @TileEvent(TileEventType.TICK) + public void Tick_TileLightDetector() { + this.lastCheck++; + if (this.lastCheck > 30) { + this.lastCheck = 0; + this.updateLight(); + } + } + + public void updateLight() { + final int val = this.worldObj.getBlockLightValue(this.xCoord, this.yCoord, this.zCoord); + + if (this.lastLight != val) { + this.lastLight = val; + Platform.notifyBlocksOfNeighbors(this.worldObj, this.xCoord, this.yCoord, this.zCoord); + } + } + + @Override + public boolean canBeRotated() { + return false; + } } diff --git a/src/main/java/appeng/tile/misc/TilePaint.java b/src/main/java/appeng/tile/misc/TilePaint.java index e6fe87e8cb0..510d2bd8de0 100644 --- a/src/main/java/appeng/tile/misc/TilePaint.java +++ b/src/main/java/appeng/tile/misc/TilePaint.java @@ -18,7 +18,6 @@ package appeng.tile.misc; - import appeng.api.util.AEColor; import appeng.helpers.Splotch; import appeng.items.misc.ItemPaintBall; @@ -28,6 +27,10 @@ import com.google.common.collect.ImmutableList; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; @@ -36,231 +39,196 @@ import net.minecraft.world.EnumSkyBlock; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - - -public class TilePaint extends AEBaseTile -{ - - private static final int LIGHT_PER_DOT = 12; - - private int isLit = 0; - private List dots = null; - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TilePaint( final NBTTagCompound data ) - { - final ByteBuf myDat = Unpooled.buffer(); - this.writeBuffer( myDat ); - if( myDat.hasArray() ) - { - data.setByteArray( "dots", myDat.array() ); - } - } - - private void writeBuffer( final ByteBuf out ) - { - if( this.dots == null ) - { - out.writeByte( 0 ); - return; - } - - out.writeByte( this.dots.size() ); - - for( final Splotch s : this.dots ) - { - s.writeToStream( out ); - } - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TilePaint( final NBTTagCompound data ) - { - if( data.hasKey( "dots" ) ) - { - this.readBuffer( Unpooled.copiedBuffer( data.getByteArray( "dots" ) ) ); - } - } - - private void readBuffer( final ByteBuf in ) - { - final byte howMany = in.readByte(); - - if( howMany == 0 ) - { - this.isLit = 0; - this.dots = null; - return; - } - - this.dots = new ArrayList( howMany ); - for( int x = 0; x < howMany; x++ ) - { - this.dots.add( new Splotch( in ) ); - } - - this.isLit = 0; - for( final Splotch s : this.dots ) - { - if( s.isLumen() ) - { - this.isLit += LIGHT_PER_DOT; - } - } - - this.maxLit(); - } - - private void maxLit() - { - if( this.isLit > 14 ) - { - this.isLit = 14; - } - - if( this.worldObj != null ) - { - this.worldObj.updateLightByType( EnumSkyBlock.Block, this.xCoord, this.yCoord, this.zCoord ); - } - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TilePaint( final ByteBuf data ) - { - this.writeBuffer( data ); - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TilePaint( final ByteBuf data ) - { - this.readBuffer( data ); - return true; - } - - public void onNeighborBlockChange() - { - if( this.dots == null ) - { - return; - } - - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - if( !this.isSideValid( side ) ) - { - this.removeSide( side ); - } - } - - this.updateData(); - } - - public boolean isSideValid( final ForgeDirection side ) - { - final Block blk = this.worldObj.getBlock( this.xCoord + side.offsetX, this.yCoord + side.offsetY, this.zCoord + side.offsetZ ); - return blk.isSideSolid( this.worldObj, this.xCoord + side.offsetX, this.yCoord + side.offsetY, this.zCoord + side.offsetZ, side.getOpposite() ); - } - - private void removeSide( final ForgeDirection side ) - { - final Iterator i = this.dots.iterator(); - while( i.hasNext() ) - { - final Splotch s = i.next(); - if( s.getSide() == side ) - { - i.remove(); - } - } - - this.markForUpdate(); - this.markDirty(); - } - - private void updateData() - { - this.isLit = 0; - for( final Splotch s : this.dots ) - { - if( s.isLumen() ) - { - this.isLit += LIGHT_PER_DOT; - } - } - - this.maxLit(); - - if( this.dots.isEmpty() ) - { - this.dots = null; - } - - if( this.dots == null ) - { - this.worldObj.setBlock( this.xCoord, this.yCoord, this.zCoord, Blocks.air ); - } - } - - public void cleanSide( final ForgeDirection side ) - { - if( this.dots == null ) - { - return; - } - - this.removeSide( side ); - - this.updateData(); - } - - public int getLightLevel() - { - return this.isLit; - } - - public void addBlot( final ItemStack type, final ForgeDirection side, final Vec3 hitVec ) - { - final Block blk = this.worldObj.getBlock( this.xCoord + side.offsetX, this.yCoord + side.offsetY, this.zCoord + side.offsetZ ); - if( blk.isSideSolid( this.worldObj, this.xCoord + side.offsetX, this.yCoord + side.offsetY, this.zCoord + side.offsetZ, side.getOpposite() ) ) - { - final ItemPaintBall ipb = (ItemPaintBall) type.getItem(); - - final AEColor col = ipb.getColor( type ); - final boolean lit = ipb.isLumen( type ); - - if( this.dots == null ) - { - this.dots = new ArrayList(); - } - - if( this.dots.size() > 20 ) - { - this.dots.remove( 0 ); - } - - this.dots.add( new Splotch( col, lit, side, hitVec ) ); - if( lit ) - { - this.isLit += LIGHT_PER_DOT; - } - - this.maxLit(); - this.markForUpdate(); - this.markDirty(); - } - } - - public Collection getDots() - { - if( this.dots == null ) - { - return ImmutableList.of(); - } - - return this.dots; - } +public class TilePaint extends AEBaseTile { + + private static final int LIGHT_PER_DOT = 12; + + private int isLit = 0; + private List dots = null; + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TilePaint(final NBTTagCompound data) { + final ByteBuf myDat = Unpooled.buffer(); + this.writeBuffer(myDat); + if (myDat.hasArray()) { + data.setByteArray("dots", myDat.array()); + } + } + + private void writeBuffer(final ByteBuf out) { + if (this.dots == null) { + out.writeByte(0); + return; + } + + out.writeByte(this.dots.size()); + + for (final Splotch s : this.dots) { + s.writeToStream(out); + } + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TilePaint(final NBTTagCompound data) { + if (data.hasKey("dots")) { + this.readBuffer(Unpooled.copiedBuffer(data.getByteArray("dots"))); + } + } + + private void readBuffer(final ByteBuf in) { + final byte howMany = in.readByte(); + + if (howMany == 0) { + this.isLit = 0; + this.dots = null; + return; + } + + this.dots = new ArrayList(howMany); + for (int x = 0; x < howMany; x++) { + this.dots.add(new Splotch(in)); + } + + this.isLit = 0; + for (final Splotch s : this.dots) { + if (s.isLumen()) { + this.isLit += LIGHT_PER_DOT; + } + } + + this.maxLit(); + } + + private void maxLit() { + if (this.isLit > 14) { + this.isLit = 14; + } + + if (this.worldObj != null) { + this.worldObj.updateLightByType(EnumSkyBlock.Block, this.xCoord, this.yCoord, this.zCoord); + } + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TilePaint(final ByteBuf data) { + this.writeBuffer(data); + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TilePaint(final ByteBuf data) { + this.readBuffer(data); + return true; + } + + public void onNeighborBlockChange() { + if (this.dots == null) { + return; + } + + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + if (!this.isSideValid(side)) { + this.removeSide(side); + } + } + + this.updateData(); + } + + public boolean isSideValid(final ForgeDirection side) { + final Block blk = this.worldObj.getBlock( + this.xCoord + side.offsetX, this.yCoord + side.offsetY, this.zCoord + side.offsetZ); + return blk.isSideSolid( + this.worldObj, + this.xCoord + side.offsetX, + this.yCoord + side.offsetY, + this.zCoord + side.offsetZ, + side.getOpposite()); + } + + private void removeSide(final ForgeDirection side) { + final Iterator i = this.dots.iterator(); + while (i.hasNext()) { + final Splotch s = i.next(); + if (s.getSide() == side) { + i.remove(); + } + } + + this.markForUpdate(); + this.markDirty(); + } + + private void updateData() { + this.isLit = 0; + for (final Splotch s : this.dots) { + if (s.isLumen()) { + this.isLit += LIGHT_PER_DOT; + } + } + + this.maxLit(); + + if (this.dots.isEmpty()) { + this.dots = null; + } + + if (this.dots == null) { + this.worldObj.setBlock(this.xCoord, this.yCoord, this.zCoord, Blocks.air); + } + } + + public void cleanSide(final ForgeDirection side) { + if (this.dots == null) { + return; + } + + this.removeSide(side); + + this.updateData(); + } + + public int getLightLevel() { + return this.isLit; + } + + public void addBlot(final ItemStack type, final ForgeDirection side, final Vec3 hitVec) { + final Block blk = this.worldObj.getBlock( + this.xCoord + side.offsetX, this.yCoord + side.offsetY, this.zCoord + side.offsetZ); + if (blk.isSideSolid( + this.worldObj, + this.xCoord + side.offsetX, + this.yCoord + side.offsetY, + this.zCoord + side.offsetZ, + side.getOpposite())) { + final ItemPaintBall ipb = (ItemPaintBall) type.getItem(); + + final AEColor col = ipb.getColor(type); + final boolean lit = ipb.isLumen(type); + + if (this.dots == null) { + this.dots = new ArrayList(); + } + + if (this.dots.size() > 20) { + this.dots.remove(0); + } + + this.dots.add(new Splotch(col, lit, side, hitVec)); + if (lit) { + this.isLit += LIGHT_PER_DOT; + } + + this.maxLit(); + this.markForUpdate(); + this.markDirty(); + } + } + + public Collection getDots() { + if (this.dots == null) { + return ImmutableList.of(); + } + + return this.dots; + } } diff --git a/src/main/java/appeng/tile/misc/TileQuartzGrowthAccelerator.java b/src/main/java/appeng/tile/misc/TileQuartzGrowthAccelerator.java index 9ba0726f0d1..0aef8bdef9c 100644 --- a/src/main/java/appeng/tile/misc/TileQuartzGrowthAccelerator.java +++ b/src/main/java/appeng/tile/misc/TileQuartzGrowthAccelerator.java @@ -18,7 +18,6 @@ package appeng.tile.misc; - import appeng.api.implementations.IPowerChannelState; import appeng.api.implementations.tiles.ICrystalGrowthAccelerator; import appeng.api.networking.events.MENetworkEventSubscribe; @@ -30,89 +29,71 @@ import appeng.tile.grid.AENetworkTile; import appeng.util.Platform; import io.netty.buffer.ByteBuf; -import net.minecraftforge.common.util.ForgeDirection; - import java.util.EnumSet; +import net.minecraftforge.common.util.ForgeDirection; - -public class TileQuartzGrowthAccelerator extends AENetworkTile implements IPowerChannelState, ICrystalGrowthAccelerator -{ - - private boolean hasPower = false; - - public TileQuartzGrowthAccelerator() - { - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - this.getProxy().setFlags(); - this.getProxy().setIdlePowerUsage( 8 ); - } - - @MENetworkEventSubscribe - public void onPower( final MENetworkPowerStatusChange ch ) - { - this.markForUpdate(); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileQuartzGrowthAccelerator( final ByteBuf data ) - { - final boolean hadPower = this.isPowered(); - this.setPowered( data.readBoolean() ); - return this.isPowered() != hadPower; - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileQuartzGrowthAccelerator( final ByteBuf data ) - { - try - { - data.writeBoolean( this.getProxy().getEnergy().isNetworkPowered() ); - } - catch( final GridAccessException e ) - { - data.writeBoolean( false ); - } - } - - @Override - public void setOrientation( final ForgeDirection inForward, final ForgeDirection inUp ) - { - super.setOrientation( inForward, inUp ); - this.getProxy().setValidSides( EnumSet.of( this.getUp(), this.getUp().getOpposite() ) ); - } - - @Override - public boolean isPowered() - { - if( Platform.isServer() ) - { - try - { - return this.getProxy().getEnergy().isNetworkPowered(); - } - catch( final GridAccessException e ) - { - return false; - } - } - - return this.hasPower; - } - - @Override - public boolean isActive() - { - return this.isPowered(); - } - - private void setPowered( final boolean hasPower ) - { - this.hasPower = hasPower; - } +public class TileQuartzGrowthAccelerator extends AENetworkTile + implements IPowerChannelState, ICrystalGrowthAccelerator { + + private boolean hasPower = false; + + public TileQuartzGrowthAccelerator() { + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + this.getProxy().setFlags(); + this.getProxy().setIdlePowerUsage(8); + } + + @MENetworkEventSubscribe + public void onPower(final MENetworkPowerStatusChange ch) { + this.markForUpdate(); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileQuartzGrowthAccelerator(final ByteBuf data) { + final boolean hadPower = this.isPowered(); + this.setPowered(data.readBoolean()); + return this.isPowered() != hadPower; + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileQuartzGrowthAccelerator(final ByteBuf data) { + try { + data.writeBoolean(this.getProxy().getEnergy().isNetworkPowered()); + } catch (final GridAccessException e) { + data.writeBoolean(false); + } + } + + @Override + public void setOrientation(final ForgeDirection inForward, final ForgeDirection inUp) { + super.setOrientation(inForward, inUp); + this.getProxy().setValidSides(EnumSet.of(this.getUp(), this.getUp().getOpposite())); + } + + @Override + public boolean isPowered() { + if (Platform.isServer()) { + try { + return this.getProxy().getEnergy().isNetworkPowered(); + } catch (final GridAccessException e) { + return false; + } + } + + return this.hasPower; + } + + @Override + public boolean isActive() { + return this.isPowered(); + } + + private void setPowered(final boolean hasPower) { + this.hasPower = hasPower; + } } diff --git a/src/main/java/appeng/tile/misc/TileSecurity.java b/src/main/java/appeng/tile/misc/TileSecurity.java index 7c38f210d96..8dbd78eb6f9 100644 --- a/src/main/java/appeng/tile/misc/TileSecurity.java +++ b/src/main/java/appeng/tile/misc/TileSecurity.java @@ -18,7 +18,6 @@ package appeng.tile.misc; - import appeng.api.AEApi; import appeng.api.config.*; import appeng.api.events.LocatableEventAnnounce; @@ -57,6 +56,9 @@ import appeng.util.Platform; import appeng.util.item.AEItemStack; import io.netty.buffer.ByteBuf; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; @@ -67,295 +69,253 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.List; - - -public class TileSecurity extends AENetworkTile implements ITerminalHost, IAEAppEngInventory, ILocatable, IConfigManagerHost, ISecurityProvider, IColorableTile -{ - - private static int difference = 0; - private final AppEngInternalInventory configSlot = new AppEngInternalInventory( this, 1 ); - private final IConfigManager cm = new ConfigManager( this ); - private final SecurityInventory inventory = new SecurityInventory( this ); - private final MEMonitorHandler securityMonitor = new MEMonitorHandler( this.inventory ); - private long securityKey; - private AEColor paintedColor = AEColor.Transparent; - private boolean isActive = false; - - public TileSecurity() - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.getProxy().setIdlePowerUsage( 2.0 ); - difference++; - - this.securityKey = System.currentTimeMillis() * 10 + difference; - if( difference > 10 ) - { - difference = 0; - } - - this.cm.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - this.cm.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - this.cm.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - - } - - @Override - public void getDrops( final World w, final int x, final int y, final int z, final List drops ) - { - if( !this.getConfigSlot().isEmpty() ) - { - drops.add( this.getConfigSlot().getStackInSlot( 0 ) ); - } - - for( final IAEItemStack ais : this.inventory.getStoredItems() ) - { - drops.add( ais.getItemStack() ); - } - } - - IMEInventoryHandler getSecurityInventory() - { - return this.inventory; - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileSecurity( final ByteBuf data ) - { - final boolean wasActive = this.isActive; - this.isActive = data.readBoolean(); - - final AEColor oldPaintedColor = this.paintedColor; - this.paintedColor = AEColor.values()[data.readByte()]; - - return oldPaintedColor != this.paintedColor || wasActive != this.isActive; - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileSecurity( final ByteBuf data ) - { - data.writeBoolean( this.getProxy().isActive() ); - data.writeByte( this.paintedColor.ordinal() ); - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileSecurity( final NBTTagCompound data ) - { - this.cm.writeToNBT( data ); - data.setByte( "paintedColor", (byte) this.paintedColor.ordinal() ); - - data.setLong( "securityKey", this.securityKey ); - this.getConfigSlot().writeToNBT( data, "config" ); - - final NBTTagCompound storedItems = new NBTTagCompound(); - - int offset = 0; - for( final IAEItemStack ais : this.inventory.getStoredItems() ) - { - final NBTTagCompound it = new NBTTagCompound(); - ais.getItemStack().writeToNBT( it ); - storedItems.setTag( String.valueOf( offset ), it ); - offset++; - } - - data.setTag( "storedItems", storedItems ); - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileSecurity( final NBTTagCompound data ) - { - this.cm.readFromNBT( data ); - if( data.hasKey( "paintedColor" ) ) - { - this.paintedColor = AEColor.values()[data.getByte( "paintedColor" )]; - } - - this.securityKey = data.getLong( "securityKey" ); - this.getConfigSlot().readFromNBT( data, "config" ); - - final NBTTagCompound storedItems = data.getCompoundTag( "storedItems" ); - for( final Object key : storedItems.func_150296_c() ) - { - final NBTBase obj = storedItems.getTag( (String) key ); - if( obj instanceof NBTTagCompound ) - { - this.inventory.getStoredItems().add( AEItemStack.create( ItemStack.loadItemStackFromNBT( (NBTTagCompound) obj ) ) ); - } - } - } - - public void inventoryChanged() - { - try - { - this.saveChanges(); - this.getProxy().getGrid().postEvent( new MENetworkSecurityChange() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - @MENetworkEventSubscribe - public void bootUpdate( final MENetworkChannelsChanged changed ) - { - this.markForUpdate(); - } - - @MENetworkEventSubscribe - public void powerUpdate( final MENetworkPowerStatusChange changed ) - { - this.markForUpdate(); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } - - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); - this.isActive = false; - } - - @Override - public void onReady() - { - super.onReady(); - if( Platform.isServer() ) - { - this.isActive = true; - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Register ) ); - } - } - - @Override - public void invalidate() - { - super.invalidate(); - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); - this.isActive = false; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - public boolean isActive() - { - return this.isActive; - } - - @Override - public IMEMonitor getItemInventory() - { - return this.securityMonitor; - } - - @Override - public IMEMonitor getFluidInventory() - { - return null; - } - - @Override - public long getLocatableSerial() - { - return this.securityKey; - } - - public boolean isPowered() - { - return this.getProxy().isActive(); - } - - @Override - public IConfigManager getConfigManager() - { - return this.cm; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - - } - - @Override - public long getSecurityKey() - { - return this.securityKey; - } - - @Override - public void readPermissions( final HashMap> playerPerms ) - { - final IPlayerRegistry pr = AEApi.instance().registries().players(); - - // read permissions - for( final IAEItemStack ais : this.inventory.getStoredItems() ) - { - final ItemStack is = ais.getItemStack(); - final Item i = is.getItem(); - if( i instanceof IBiometricCard ) - { - final IBiometricCard bc = (IBiometricCard) i; - bc.registerPermissions( new PlayerSecurityWrapper( playerPerms ), pr, is ); - } - } - - // make sure thea admin is Boss. - playerPerms.put( this.getProxy().getNode().getPlayerID(), EnumSet.allOf( SecurityPermissions.class ) ); - } - - @Override - public boolean isSecurityEnabled() - { - return this.isActive && this.getProxy().isActive(); - } - - @Override - public int getOwner() - { - return this.getProxy().getNode().getPlayerID(); - } - - @Override - public AEColor getColor() - { - return this.paintedColor; - } - - @Override - public boolean recolourBlock( final ForgeDirection side, final AEColor newPaintedColor, final EntityPlayer who ) - { - if( this.paintedColor == newPaintedColor ) - { - return false; - } - - this.paintedColor = newPaintedColor; - this.markDirty(); - this.markForUpdate(); - return true; - } - - public AppEngInternalInventory getConfigSlot() - { - return this.configSlot; - } +public class TileSecurity extends AENetworkTile + implements ITerminalHost, + IAEAppEngInventory, + ILocatable, + IConfigManagerHost, + ISecurityProvider, + IColorableTile { + + private static int difference = 0; + private final AppEngInternalInventory configSlot = new AppEngInternalInventory(this, 1); + private final IConfigManager cm = new ConfigManager(this); + private final SecurityInventory inventory = new SecurityInventory(this); + private final MEMonitorHandler securityMonitor = new MEMonitorHandler(this.inventory); + private long securityKey; + private AEColor paintedColor = AEColor.Transparent; + private boolean isActive = false; + + public TileSecurity() { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.getProxy().setIdlePowerUsage(2.0); + difference++; + + this.securityKey = System.currentTimeMillis() * 10 + difference; + if (difference > 10) { + difference = 0; + } + + this.cm.registerSetting(Settings.SORT_BY, SortOrder.NAME); + this.cm.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + this.cm.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) {} + + @Override + public void getDrops(final World w, final int x, final int y, final int z, final List drops) { + if (!this.getConfigSlot().isEmpty()) { + drops.add(this.getConfigSlot().getStackInSlot(0)); + } + + for (final IAEItemStack ais : this.inventory.getStoredItems()) { + drops.add(ais.getItemStack()); + } + } + + IMEInventoryHandler getSecurityInventory() { + return this.inventory; + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileSecurity(final ByteBuf data) { + final boolean wasActive = this.isActive; + this.isActive = data.readBoolean(); + + final AEColor oldPaintedColor = this.paintedColor; + this.paintedColor = AEColor.values()[data.readByte()]; + + return oldPaintedColor != this.paintedColor || wasActive != this.isActive; + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileSecurity(final ByteBuf data) { + data.writeBoolean(this.getProxy().isActive()); + data.writeByte(this.paintedColor.ordinal()); + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileSecurity(final NBTTagCompound data) { + this.cm.writeToNBT(data); + data.setByte("paintedColor", (byte) this.paintedColor.ordinal()); + + data.setLong("securityKey", this.securityKey); + this.getConfigSlot().writeToNBT(data, "config"); + + final NBTTagCompound storedItems = new NBTTagCompound(); + + int offset = 0; + for (final IAEItemStack ais : this.inventory.getStoredItems()) { + final NBTTagCompound it = new NBTTagCompound(); + ais.getItemStack().writeToNBT(it); + storedItems.setTag(String.valueOf(offset), it); + offset++; + } + + data.setTag("storedItems", storedItems); + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileSecurity(final NBTTagCompound data) { + this.cm.readFromNBT(data); + if (data.hasKey("paintedColor")) { + this.paintedColor = AEColor.values()[data.getByte("paintedColor")]; + } + + this.securityKey = data.getLong("securityKey"); + this.getConfigSlot().readFromNBT(data, "config"); + + final NBTTagCompound storedItems = data.getCompoundTag("storedItems"); + for (final Object key : storedItems.func_150296_c()) { + final NBTBase obj = storedItems.getTag((String) key); + if (obj instanceof NBTTagCompound) { + this.inventory.getStoredItems().add(AEItemStack.create(ItemStack.loadItemStackFromNBT((NBTTagCompound) + obj))); + } + } + } + + public void inventoryChanged() { + try { + this.saveChanges(); + this.getProxy().getGrid().postEvent(new MENetworkSecurityChange()); + } catch (final GridAccessException e) { + // :P + } + } + + @MENetworkEventSubscribe + public void bootUpdate(final MENetworkChannelsChanged changed) { + this.markForUpdate(); + } + + @MENetworkEventSubscribe + public void powerUpdate(final MENetworkPowerStatusChange changed) { + this.markForUpdate(); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } + + @Override + public void onChunkUnload() { + super.onChunkUnload(); + MinecraftForge.EVENT_BUS.post(new LocatableEventAnnounce(this, LocatableEvent.Unregister)); + this.isActive = false; + } + + @Override + public void onReady() { + super.onReady(); + if (Platform.isServer()) { + this.isActive = true; + MinecraftForge.EVENT_BUS.post(new LocatableEventAnnounce(this, LocatableEvent.Register)); + } + } + + @Override + public void invalidate() { + super.invalidate(); + MinecraftForge.EVENT_BUS.post(new LocatableEventAnnounce(this, LocatableEvent.Unregister)); + this.isActive = false; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + public boolean isActive() { + return this.isActive; + } + + @Override + public IMEMonitor getItemInventory() { + return this.securityMonitor; + } + + @Override + public IMEMonitor getFluidInventory() { + return null; + } + + @Override + public long getLocatableSerial() { + return this.securityKey; + } + + public boolean isPowered() { + return this.getProxy().isActive(); + } + + @Override + public IConfigManager getConfigManager() { + return this.cm; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) {} + + @Override + public long getSecurityKey() { + return this.securityKey; + } + + @Override + public void readPermissions(final HashMap> playerPerms) { + final IPlayerRegistry pr = AEApi.instance().registries().players(); + + // read permissions + for (final IAEItemStack ais : this.inventory.getStoredItems()) { + final ItemStack is = ais.getItemStack(); + final Item i = is.getItem(); + if (i instanceof IBiometricCard) { + final IBiometricCard bc = (IBiometricCard) i; + bc.registerPermissions(new PlayerSecurityWrapper(playerPerms), pr, is); + } + } + + // make sure thea admin is Boss. + playerPerms.put(this.getProxy().getNode().getPlayerID(), EnumSet.allOf(SecurityPermissions.class)); + } + + @Override + public boolean isSecurityEnabled() { + return this.isActive && this.getProxy().isActive(); + } + + @Override + public int getOwner() { + return this.getProxy().getNode().getPlayerID(); + } + + @Override + public AEColor getColor() { + return this.paintedColor; + } + + @Override + public boolean recolourBlock(final ForgeDirection side, final AEColor newPaintedColor, final EntityPlayer who) { + if (this.paintedColor == newPaintedColor) { + return false; + } + + this.paintedColor = newPaintedColor; + this.markDirty(); + this.markForUpdate(); + return true; + } + + public AppEngInternalInventory getConfigSlot() { + return this.configSlot; + } } diff --git a/src/main/java/appeng/tile/misc/TileSkyCompass.java b/src/main/java/appeng/tile/misc/TileSkyCompass.java index 7937029b10e..15e07aab386 100644 --- a/src/main/java/appeng/tile/misc/TileSkyCompass.java +++ b/src/main/java/appeng/tile/misc/TileSkyCompass.java @@ -18,16 +18,12 @@ package appeng.tile.misc; - import appeng.tile.AEBaseTile; +public class TileSkyCompass extends AEBaseTile { -public class TileSkyCompass extends AEBaseTile -{ - - @Override - public boolean requiresTESR() - { - return true; - } + @Override + public boolean requiresTESR() { + return true; + } } diff --git a/src/main/java/appeng/tile/misc/TileVibrationChamber.java b/src/main/java/appeng/tile/misc/TileVibrationChamber.java index 60ff2e3b388..a6ec3696cc1 100644 --- a/src/main/java/appeng/tile/misc/TileVibrationChamber.java +++ b/src/main/java/appeng/tile/misc/TileVibrationChamber.java @@ -18,7 +18,6 @@ package appeng.tile.misc; - import appeng.api.config.Actionable; import appeng.api.networking.IGridNode; import appeng.api.networking.energy.IEnergyGrid; @@ -44,283 +43,239 @@ import net.minecraft.tileentity.TileEntityFurnace; import net.minecraftforge.common.util.ForgeDirection; - -public class TileVibrationChamber extends AENetworkInvTile implements IGridTickable -{ - private static final int FUEL_SLOT_INDEX = 0; - private static final double POWER_PER_TICK = 5; - private static final int[] ACCESSIBLE_SLOTS = { FUEL_SLOT_INDEX }; - private static final int MAX_BURN_SPEED = 200; - private static final double DILATION_SCALING = 100.0; - private static final int MIN_BURN_SPEED = 20; - private final IInventory inv = new AppEngInternalInventory( this, 1 ); - - private int burnSpeed = 100; - private double burnTime = 0; - private double maxBurnTime = 0; - - // client side.. - public boolean isOn; - - public TileVibrationChamber() - { - this.getProxy().setIdlePowerUsage( 0 ); - this.getProxy().setFlags(); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } - - @Reflected - @TileEvent( TileEventType.NETWORK_READ ) - public boolean hasUpdate( final ByteBuf data ) - { - final boolean wasOn = this.isOn; - - this.isOn = data.readBoolean(); - - return wasOn != this.isOn; // TESR doesn't need updates! - } - - @Reflected - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToNetwork( final ByteBuf data ) - { - data.writeBoolean( this.getBurnTime() > 0 ); - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileVibrationChamber( final NBTTagCompound data ) - { - data.setDouble( "burnTime", this.getBurnTime() ); - data.setDouble( "maxBurnTime", this.getMaxBurnTime() ); - data.setInteger( "burnSpeed", this.getBurnSpeed() ); - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileVibrationChamber( final NBTTagCompound data ) - { - this.setBurnTime( data.getDouble( "burnTime" ) ); - this.setMaxBurnTime( data.getDouble( "maxBurnTime" ) ); - this.setBurnSpeed( data.getInteger( "burnSpeed" ) ); - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return TileEntityFurnace.getItemBurnTime( itemstack ) > 0; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( this.getBurnTime() <= 0 ) - { - if( this.canEatFuel() ) - { - try - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // wake up! - } - } - } - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - return extractedItem.getItem() == Items.bucket; - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return ACCESSIBLE_SLOTS; - } - - private boolean canEatFuel() - { - final ItemStack is = this.getStackInSlot( FUEL_SLOT_INDEX ); - if( is != null ) - { - final int newBurnTime = TileEntityFurnace.getItemBurnTime( is ); - if( newBurnTime > 0 && is.stackSize > 0 ) - { - return true; - } - } - return false; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - if( this.getBurnTime() <= 0 ) - { - this.eatFuel(); - } - - return new TickingRequest( TickRates.VibrationChamber.getMin(), TickRates.VibrationChamber.getMax(), this.getBurnTime() <= 0, false ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( this.getBurnTime() <= 0 ) - { - this.eatFuel(); - - if( this.getBurnTime() > 0 ) - { - return TickRateModulation.URGENT; - } - - this.setBurnSpeed( 100 ); - return TickRateModulation.SLEEP; - } - - this.setBurnSpeed( Math.max( MIN_BURN_SPEED, Math.min( this.getBurnSpeed(), MAX_BURN_SPEED ) ) ); - final double dilation = this.getBurnSpeed() / DILATION_SCALING; - - double timePassed = ticksSinceLastCall * dilation; - this.setBurnTime( this.getBurnTime() - timePassed ); - if( this.getBurnTime() < 0 ) - { - timePassed += this.getBurnTime(); - this.setBurnTime( 0 ); - } - - try - { - final IEnergyGrid grid = this.getProxy().getEnergy(); - final double newPower = timePassed * POWER_PER_TICK; - final double overFlow = grid.injectPower( newPower, Actionable.SIMULATE ); - - // burn the over flow. - grid.injectPower( Math.max( 0.0, newPower - overFlow ), Actionable.MODULATE ); - - if( overFlow > 0 ) - { - this.setBurnSpeed( this.getBurnSpeed() - ticksSinceLastCall ); - } - else - { - this.setBurnSpeed( this.getBurnSpeed() + ticksSinceLastCall ); - } - - this.setBurnSpeed( Math.max( MIN_BURN_SPEED, Math.min( this.getBurnSpeed(), MAX_BURN_SPEED ) ) ); - return overFlow > 0 ? TickRateModulation.SLOWER : TickRateModulation.FASTER; - } - catch( final GridAccessException e ) - { - this.setBurnSpeed( this.getBurnSpeed() - ticksSinceLastCall ); - this.setBurnSpeed( Math.max( MIN_BURN_SPEED, Math.min( this.getBurnSpeed(), MAX_BURN_SPEED ) ) ); - return TickRateModulation.SLOWER; - } - } - - private void eatFuel() - { - final ItemStack is = this.getStackInSlot( FUEL_SLOT_INDEX ); - if( is != null ) - { - final int newBurnTime = TileEntityFurnace.getItemBurnTime( is ); - if( newBurnTime > 0 && is.stackSize > 0 ) - { - this.setBurnTime( this.getBurnTime() + newBurnTime ); - this.setMaxBurnTime( this.getBurnTime() ); - is.stackSize--; - if( is.stackSize <= 0 ) - { - ItemStack container = null; - - if( is.getItem() != null && is.getItem().hasContainerItem( is ) ) - { - container = is.getItem().getContainerItem( is ); - } - - this.setInventorySlotContents( 0, container ); - } - else - { - this.setInventorySlotContents( 0, is ); - } - - this.markDirty(); - } - } - - if( this.getBurnTime() > 0 ) - { - try - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // gah! - } - } - - // state change - if( ( !this.isOn && this.getBurnTime() > 0 ) || ( this.isOn && this.getBurnTime() <= 0 ) ) - { - this.isOn = this.getBurnTime() > 0; - this.markForUpdate(); - - if( this.hasWorldObj() ) - { - Platform.notifyBlocksOfNeighbors( this.worldObj, this.xCoord, this.yCoord, this.zCoord ); - } - } - } - - public int getBurnSpeed() - { - return this.burnSpeed; - } - - private void setBurnSpeed( final int burnSpeed ) - { - this.burnSpeed = burnSpeed; - } - - public double getMaxBurnTime() - { - return this.maxBurnTime; - } - - private void setMaxBurnTime( final double maxBurnTime ) - { - this.maxBurnTime = maxBurnTime; - } - - public double getBurnTime() - { - return this.burnTime; - } - - private void setBurnTime( final double burnTime ) - { - this.burnTime = burnTime; - } +public class TileVibrationChamber extends AENetworkInvTile implements IGridTickable { + private static final int FUEL_SLOT_INDEX = 0; + private static final double POWER_PER_TICK = 5; + private static final int[] ACCESSIBLE_SLOTS = {FUEL_SLOT_INDEX}; + private static final int MAX_BURN_SPEED = 200; + private static final double DILATION_SCALING = 100.0; + private static final int MIN_BURN_SPEED = 20; + private final IInventory inv = new AppEngInternalInventory(this, 1); + + private int burnSpeed = 100; + private double burnTime = 0; + private double maxBurnTime = 0; + + // client side.. + public boolean isOn; + + public TileVibrationChamber() { + this.getProxy().setIdlePowerUsage(0); + this.getProxy().setFlags(); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } + + @Reflected + @TileEvent(TileEventType.NETWORK_READ) + public boolean hasUpdate(final ByteBuf data) { + final boolean wasOn = this.isOn; + + this.isOn = data.readBoolean(); + + return wasOn != this.isOn; // TESR doesn't need updates! + } + + @Reflected + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToNetwork(final ByteBuf data) { + data.writeBoolean(this.getBurnTime() > 0); + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileVibrationChamber(final NBTTagCompound data) { + data.setDouble("burnTime", this.getBurnTime()); + data.setDouble("maxBurnTime", this.getMaxBurnTime()); + data.setInteger("burnSpeed", this.getBurnSpeed()); + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileVibrationChamber(final NBTTagCompound data) { + this.setBurnTime(data.getDouble("burnTime")); + this.setMaxBurnTime(data.getDouble("maxBurnTime")); + this.setBurnSpeed(data.getInteger("burnSpeed")); + } + + @Override + public IInventory getInternalInventory() { + return this.inv; + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return TileEntityFurnace.getItemBurnTime(itemstack) > 0; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) { + if (this.getBurnTime() <= 0) { + if (this.canEatFuel()) { + try { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // wake up! + } + } + } + } + + @Override + public boolean canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + return extractedItem.getItem() == Items.bucket; + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return ACCESSIBLE_SLOTS; + } + + private boolean canEatFuel() { + final ItemStack is = this.getStackInSlot(FUEL_SLOT_INDEX); + if (is != null) { + final int newBurnTime = TileEntityFurnace.getItemBurnTime(is); + if (newBurnTime > 0 && is.stackSize > 0) { + return true; + } + } + return false; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + if (this.getBurnTime() <= 0) { + this.eatFuel(); + } + + return new TickingRequest( + TickRates.VibrationChamber.getMin(), + TickRates.VibrationChamber.getMax(), + this.getBurnTime() <= 0, + false); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (this.getBurnTime() <= 0) { + this.eatFuel(); + + if (this.getBurnTime() > 0) { + return TickRateModulation.URGENT; + } + + this.setBurnSpeed(100); + return TickRateModulation.SLEEP; + } + + this.setBurnSpeed(Math.max(MIN_BURN_SPEED, Math.min(this.getBurnSpeed(), MAX_BURN_SPEED))); + final double dilation = this.getBurnSpeed() / DILATION_SCALING; + + double timePassed = ticksSinceLastCall * dilation; + this.setBurnTime(this.getBurnTime() - timePassed); + if (this.getBurnTime() < 0) { + timePassed += this.getBurnTime(); + this.setBurnTime(0); + } + + try { + final IEnergyGrid grid = this.getProxy().getEnergy(); + final double newPower = timePassed * POWER_PER_TICK; + final double overFlow = grid.injectPower(newPower, Actionable.SIMULATE); + + // burn the over flow. + grid.injectPower(Math.max(0.0, newPower - overFlow), Actionable.MODULATE); + + if (overFlow > 0) { + this.setBurnSpeed(this.getBurnSpeed() - ticksSinceLastCall); + } else { + this.setBurnSpeed(this.getBurnSpeed() + ticksSinceLastCall); + } + + this.setBurnSpeed(Math.max(MIN_BURN_SPEED, Math.min(this.getBurnSpeed(), MAX_BURN_SPEED))); + return overFlow > 0 ? TickRateModulation.SLOWER : TickRateModulation.FASTER; + } catch (final GridAccessException e) { + this.setBurnSpeed(this.getBurnSpeed() - ticksSinceLastCall); + this.setBurnSpeed(Math.max(MIN_BURN_SPEED, Math.min(this.getBurnSpeed(), MAX_BURN_SPEED))); + return TickRateModulation.SLOWER; + } + } + + private void eatFuel() { + final ItemStack is = this.getStackInSlot(FUEL_SLOT_INDEX); + if (is != null) { + final int newBurnTime = TileEntityFurnace.getItemBurnTime(is); + if (newBurnTime > 0 && is.stackSize > 0) { + this.setBurnTime(this.getBurnTime() + newBurnTime); + this.setMaxBurnTime(this.getBurnTime()); + is.stackSize--; + if (is.stackSize <= 0) { + ItemStack container = null; + + if (is.getItem() != null && is.getItem().hasContainerItem(is)) { + container = is.getItem().getContainerItem(is); + } + + this.setInventorySlotContents(0, container); + } else { + this.setInventorySlotContents(0, is); + } + + this.markDirty(); + } + } + + if (this.getBurnTime() > 0) { + try { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // gah! + } + } + + // state change + if ((!this.isOn && this.getBurnTime() > 0) || (this.isOn && this.getBurnTime() <= 0)) { + this.isOn = this.getBurnTime() > 0; + this.markForUpdate(); + + if (this.hasWorldObj()) { + Platform.notifyBlocksOfNeighbors(this.worldObj, this.xCoord, this.yCoord, this.zCoord); + } + } + } + + public int getBurnSpeed() { + return this.burnSpeed; + } + + private void setBurnSpeed(final int burnSpeed) { + this.burnSpeed = burnSpeed; + } + + public double getMaxBurnTime() { + return this.maxBurnTime; + } + + private void setMaxBurnTime(final double maxBurnTime) { + this.maxBurnTime = maxBurnTime; + } + + public double getBurnTime() { + return this.burnTime; + } + + private void setBurnTime(final double burnTime) { + this.burnTime = burnTime; + } } diff --git a/src/main/java/appeng/tile/networking/TileCableBus.java b/src/main/java/appeng/tile/networking/TileCableBus.java index 26a9905149d..320c1344247 100644 --- a/src/main/java/appeng/tile/networking/TileCableBus.java +++ b/src/main/java/appeng/tile/networking/TileCableBus.java @@ -18,7 +18,6 @@ package appeng.tile.networking; - import appeng.api.networking.IGridNode; import appeng.api.parts.IFacadeContainer; import appeng.api.parts.IPart; @@ -40,6 +39,9 @@ import appeng.tile.events.TileEventType; import appeng.util.Platform; import io.netty.buffer.ByteBuf; +import java.io.IOException; +import java.util.List; +import java.util.Set; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -49,340 +51,288 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; -import java.util.List; -import java.util.Set; - - -public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomCollision -{ - - private CableBusContainer cb = new CableBusContainer( this ); - - /** - * Immibis MB Support - */ - private boolean ImmibisMicroblocks_TransformableTileEntityMarker = true; - private int oldLV = -1; // on re-calculate light when it changes - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileCableBus( final NBTTagCompound data ) - { - this.getCableBus().readFromNBT( data ); - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileCableBus( final NBTTagCompound data ) - { - this.getCableBus().writeToNBT( data ); - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileCableBus( final ByteBuf data ) throws IOException - { - final boolean ret = this.getCableBus().readFromStream( data ); - - final int newLV = this.getCableBus().getLightValue(); - if( newLV != this.oldLV ) - { - this.oldLV = newLV; - this.worldObj.func_147451_t( this.xCoord, this.yCoord, this.zCoord ); - // worldObj.updateAllLightTypes( xCoord, yCoord, zCoord ); - } - - this.updateTileSetting(); - return ret; - } - - protected void updateTileSetting() - { - if( this.getCableBus().isRequiresDynamicRender() ) - { - try - { - final TileCableBus tcb = (TileCableBus) BlockCableBus.getTesrTile().newInstance(); - tcb.copyFrom( this ); - this.getWorldObj().setTileEntity( this.xCoord, this.yCoord, this.zCoord, tcb ); - } - catch( final Throwable ignored ) - { - - } - } - } - - protected void copyFrom( final TileCableBus oldTile ) - { - final CableBusContainer tmpCB = this.getCableBus(); - this.setCableBus( oldTile.getCableBus() ); - this.oldLV = oldTile.oldLV; - oldTile.setCableBus( tmpCB ); - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileCableBus( final ByteBuf data ) throws IOException - { - this.getCableBus().writeToStream( data ); - } - - @Override - public double getMaxRenderDistanceSquared() - { - return 900.0; - } - - @Override - public void invalidate() - { - super.invalidate(); - this.getCableBus().removeFromWorld(); - } - - @Override - public void validate() - { - super.validate(); - TickHandler.INSTANCE.addInit( this ); - } - - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - return this.getCableBus().getGridNode( dir ); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection side ) - { - return this.getCableBus().getCableConnectionType( side ); - } - - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - this.getCableBus().removeFromWorld(); - } - - @Override - public void markForUpdate() - { - if( this.worldObj == null ) - { - return; - } - - final int newLV = this.getCableBus().getLightValue(); - if( newLV != this.oldLV ) - { - this.oldLV = newLV; - this.worldObj.func_147451_t( this.xCoord, this.yCoord, this.zCoord ); - // worldObj.updateAllLightTypes( xCoord, yCoord, zCoord ); - } - - super.markForUpdate(); - } - - @Override - public boolean canBeRotated() - { - return false; - } - - @Override - public void getDrops( final World w, final int x, final int y, final int z, final List drops ) - { - this.getCableBus().getDrops( drops ); - } - - @Override - public void getNoDrops( final World w, final int x, final int y, final int z, final List drops ) - { - this.getCableBus().getNoDrops( drops ); - } - - @Override - public void onReady() - { - super.onReady(); - if( this.getCableBus().isEmpty() ) - { - if( this.worldObj.getTileEntity( this.xCoord, this.yCoord, this.zCoord ) == this ) - { - this.worldObj.func_147480_a( this.xCoord, this.yCoord, this.zCoord, true ); - } - } - else - { - this.getCableBus().addToWorld(); - } - } - - @Override - public boolean requiresTESR() - { - return this.getCableBus().isRequiresDynamicRender(); - } - - @Override - public IFacadeContainer getFacadeContainer() - { - return this.getCableBus().getFacadeContainer(); - } - - @Override - public boolean canAddPart( final ItemStack is, final ForgeDirection side ) - { - return this.getCableBus().canAddPart( is, side ); - } - - @Override - public ForgeDirection addPart( final ItemStack is, final ForgeDirection side, final EntityPlayer player ) - { - return this.getCableBus().addPart( is, side, player ); - } - - @Override - public IPart getPart( final ForgeDirection side ) - { - return this.getCableBus().getPart( side ); - } - - @Override - public void removePart( final ForgeDirection side, final boolean suppressUpdate ) - { - this.getCableBus().removePart( side, suppressUpdate ); - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - @Override - public AEColor getColor() - { - return this.getCableBus().getColor(); - } - - @Override - public void clearContainer() - { - this.setCableBus( new CableBusContainer( this ) ); - } - - @Override - public boolean isBlocked( final ForgeDirection side ) - { - return !this.ImmibisMicroblocks_isSideOpen( side.ordinal() ); - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean visual ) - { - return this.getCableBus().getSelectedBoundingBoxesFromPool( false, true, e, visual ); - } - - @Override - public SelectedPart selectPart( final Vec3 pos ) - { - return this.getCableBus().selectPart( pos ); - } - - @Override - public void markForSave() - { - super.markDirty(); - } - - @Override - public void partChanged() - { - this.notifyNeighbors(); - } - - @Override - public boolean hasRedstone( final ForgeDirection side ) - { - return this.getCableBus().hasRedstone( side ); - } - - @Override - public boolean isEmpty() - { - return this.getCableBus().isEmpty(); - } - - @Override - public Set getLayerFlags() - { - return this.getCableBus().getLayerFlags(); - } - - @Override - public void cleanup() - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.ImmibisMicroblocks ) ) - { - final IImmibisMicroblocks imb = (IImmibisMicroblocks) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.ImmibisMicroblocks ); - if( imb != null && imb.leaveParts( this ) ) - { - return; - } - } - - this.getWorldObj().setBlock( this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - for( final AxisAlignedBB bx : this.getSelectedBoundingBoxesFromPool( w, x, y, z, e, false ) ) - { - out.add( AxisAlignedBB.getBoundingBox( bx.minX, bx.minY, bx.minZ, bx.maxX, bx.maxY, bx.maxZ ) ); - } - } - - @Override - public void notifyNeighbors() - { - if( this.worldObj != null && this.worldObj.blockExists( this.xCoord, this.yCoord, this.zCoord ) && !CableBusContainer.isLoading() ) - { - Platform.notifyBlocksOfNeighbors( this.worldObj, this.xCoord, this.yCoord, this.zCoord ); - } - } - - @Override - public boolean isInWorld() - { - return this.getCableBus().isInWorld(); - } - - private boolean ImmibisMicroblocks_isSideOpen( final int side ) - { - return true; - } - - public void ImmibisMicroblocks_onMicroblocksChanged() - { - this.getCableBus().updateConnections(); - } - - @Override - public boolean recolourBlock( final ForgeDirection side, final AEColor colour, final EntityPlayer who ) - { - return this.getCableBus().recolourBlock( side, colour, who ); - } - - public CableBusContainer getCableBus() - { - return this.cb; - } - - private void setCableBus( final CableBusContainer cb ) - { - this.cb = cb; - } - +public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomCollision { + + private CableBusContainer cb = new CableBusContainer(this); + + /** + * Immibis MB Support + */ + private boolean ImmibisMicroblocks_TransformableTileEntityMarker = true; + + private int oldLV = -1; // on re-calculate light when it changes + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileCableBus(final NBTTagCompound data) { + this.getCableBus().readFromNBT(data); + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileCableBus(final NBTTagCompound data) { + this.getCableBus().writeToNBT(data); + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileCableBus(final ByteBuf data) throws IOException { + final boolean ret = this.getCableBus().readFromStream(data); + + final int newLV = this.getCableBus().getLightValue(); + if (newLV != this.oldLV) { + this.oldLV = newLV; + this.worldObj.func_147451_t(this.xCoord, this.yCoord, this.zCoord); + // worldObj.updateAllLightTypes( xCoord, yCoord, zCoord ); + } + + this.updateTileSetting(); + return ret; + } + + protected void updateTileSetting() { + if (this.getCableBus().isRequiresDynamicRender()) { + try { + final TileCableBus tcb = + (TileCableBus) BlockCableBus.getTesrTile().newInstance(); + tcb.copyFrom(this); + this.getWorldObj().setTileEntity(this.xCoord, this.yCoord, this.zCoord, tcb); + } catch (final Throwable ignored) { + + } + } + } + + protected void copyFrom(final TileCableBus oldTile) { + final CableBusContainer tmpCB = this.getCableBus(); + this.setCableBus(oldTile.getCableBus()); + this.oldLV = oldTile.oldLV; + oldTile.setCableBus(tmpCB); + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileCableBus(final ByteBuf data) throws IOException { + this.getCableBus().writeToStream(data); + } + + @Override + public double getMaxRenderDistanceSquared() { + return 900.0; + } + + @Override + public void invalidate() { + super.invalidate(); + this.getCableBus().removeFromWorld(); + } + + @Override + public void validate() { + super.validate(); + TickHandler.INSTANCE.addInit(this); + } + + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + return this.getCableBus().getGridNode(dir); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection side) { + return this.getCableBus().getCableConnectionType(side); + } + + @Override + public void onChunkUnload() { + super.onChunkUnload(); + this.getCableBus().removeFromWorld(); + } + + @Override + public void markForUpdate() { + if (this.worldObj == null) { + return; + } + + final int newLV = this.getCableBus().getLightValue(); + if (newLV != this.oldLV) { + this.oldLV = newLV; + this.worldObj.func_147451_t(this.xCoord, this.yCoord, this.zCoord); + // worldObj.updateAllLightTypes( xCoord, yCoord, zCoord ); + } + + super.markForUpdate(); + } + + @Override + public boolean canBeRotated() { + return false; + } + + @Override + public void getDrops(final World w, final int x, final int y, final int z, final List drops) { + this.getCableBus().getDrops(drops); + } + + @Override + public void getNoDrops(final World w, final int x, final int y, final int z, final List drops) { + this.getCableBus().getNoDrops(drops); + } + + @Override + public void onReady() { + super.onReady(); + if (this.getCableBus().isEmpty()) { + if (this.worldObj.getTileEntity(this.xCoord, this.yCoord, this.zCoord) == this) { + this.worldObj.func_147480_a(this.xCoord, this.yCoord, this.zCoord, true); + } + } else { + this.getCableBus().addToWorld(); + } + } + + @Override + public boolean requiresTESR() { + return this.getCableBus().isRequiresDynamicRender(); + } + + @Override + public IFacadeContainer getFacadeContainer() { + return this.getCableBus().getFacadeContainer(); + } + + @Override + public boolean canAddPart(final ItemStack is, final ForgeDirection side) { + return this.getCableBus().canAddPart(is, side); + } + + @Override + public ForgeDirection addPart(final ItemStack is, final ForgeDirection side, final EntityPlayer player) { + return this.getCableBus().addPart(is, side, player); + } + + @Override + public IPart getPart(final ForgeDirection side) { + return this.getCableBus().getPart(side); + } + + @Override + public void removePart(final ForgeDirection side, final boolean suppressUpdate) { + this.getCableBus().removePart(side, suppressUpdate); + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + @Override + public AEColor getColor() { + return this.getCableBus().getColor(); + } + + @Override + public void clearContainer() { + this.setCableBus(new CableBusContainer(this)); + } + + @Override + public boolean isBlocked(final ForgeDirection side) { + return !this.ImmibisMicroblocks_isSideOpen(side.ordinal()); + } + + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, final int x, final int y, final int z, final Entity e, final boolean visual) { + return this.getCableBus().getSelectedBoundingBoxesFromPool(false, true, e, visual); + } + + @Override + public SelectedPart selectPart(final Vec3 pos) { + return this.getCableBus().selectPart(pos); + } + + @Override + public void markForSave() { + super.markDirty(); + } + + @Override + public void partChanged() { + this.notifyNeighbors(); + } + + @Override + public boolean hasRedstone(final ForgeDirection side) { + return this.getCableBus().hasRedstone(side); + } + + @Override + public boolean isEmpty() { + return this.getCableBus().isEmpty(); + } + + @Override + public Set getLayerFlags() { + return this.getCableBus().getLayerFlags(); + } + + @Override + public void cleanup() { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.ImmibisMicroblocks)) { + final IImmibisMicroblocks imb = + (IImmibisMicroblocks) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.ImmibisMicroblocks); + if (imb != null && imb.leaveParts(this)) { + return; + } + } + + this.getWorldObj().setBlock(this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK); + } + + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e) { + for (final AxisAlignedBB bx : this.getSelectedBoundingBoxesFromPool(w, x, y, z, e, false)) { + out.add(AxisAlignedBB.getBoundingBox(bx.minX, bx.minY, bx.minZ, bx.maxX, bx.maxY, bx.maxZ)); + } + } + + @Override + public void notifyNeighbors() { + if (this.worldObj != null + && this.worldObj.blockExists(this.xCoord, this.yCoord, this.zCoord) + && !CableBusContainer.isLoading()) { + Platform.notifyBlocksOfNeighbors(this.worldObj, this.xCoord, this.yCoord, this.zCoord); + } + } + + @Override + public boolean isInWorld() { + return this.getCableBus().isInWorld(); + } + + private boolean ImmibisMicroblocks_isSideOpen(final int side) { + return true; + } + + public void ImmibisMicroblocks_onMicroblocksChanged() { + this.getCableBus().updateConnections(); + } + + @Override + public boolean recolourBlock(final ForgeDirection side, final AEColor colour, final EntityPlayer who) { + return this.getCableBus().recolourBlock(side, colour, who); + } + + public CableBusContainer getCableBus() { + return this.cb; + } + + private void setCableBus(final CableBusContainer cb) { + this.cb = cb; + } } diff --git a/src/main/java/appeng/tile/networking/TileCableBusTESR.java b/src/main/java/appeng/tile/networking/TileCableBusTESR.java index 4e3711f869a..8ebd71361e6 100644 --- a/src/main/java/appeng/tile/networking/TileCableBusTESR.java +++ b/src/main/java/appeng/tile/networking/TileCableBusTESR.java @@ -18,28 +18,21 @@ package appeng.tile.networking; - import appeng.block.networking.BlockCableBus; +public class TileCableBusTESR extends TileCableBus { -public class TileCableBusTESR extends TileCableBus -{ - - @Override - protected void updateTileSetting() - { - if( !this.getCableBus().isRequiresDynamicRender() ) - { - try - { - final TileCableBus tcb = (TileCableBus) BlockCableBus.getNoTesrTile().newInstance(); - tcb.copyFrom( this ); - this.getWorldObj().setTileEntity( this.xCoord, this.yCoord, this.zCoord, tcb ); - } - catch( final Throwable ignored ) - { + @Override + protected void updateTileSetting() { + if (!this.getCableBus().isRequiresDynamicRender()) { + try { + final TileCableBus tcb = + (TileCableBus) BlockCableBus.getNoTesrTile().newInstance(); + tcb.copyFrom(this); + this.getWorldObj().setTileEntity(this.xCoord, this.yCoord, this.zCoord, tcb); + } catch (final Throwable ignored) { - } - } - } + } + } + } } diff --git a/src/main/java/appeng/tile/networking/TileController.java b/src/main/java/appeng/tile/networking/TileController.java index fc3ef3bcb15..99a1039e189 100644 --- a/src/main/java/appeng/tile/networking/TileController.java +++ b/src/main/java/appeng/tile/networking/TileController.java @@ -18,7 +18,6 @@ package appeng.tile.networking; - import appeng.api.config.Actionable; import appeng.api.networking.GridFlags; import appeng.api.networking.events.MENetworkControllerChange; @@ -32,190 +31,160 @@ import appeng.tile.grid.AENetworkPowerTile; import appeng.tile.inventory.AppEngInternalInventory; import appeng.tile.inventory.InvOperation; +import java.util.EnumSet; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class TileController extends AENetworkPowerTile -{ - private static final IInventory NULL_INVENTORY = new AppEngInternalInventory( null, 0 ); - private static final int[] ACCESSIBLE_SLOTS_BY_SIDE = {}; - - private boolean isValid = false; - - public TileController() - { - this.setInternalMaxPower( 8000 ); - this.setInternalPublicPowerStorage( true ); - this.getProxy().setIdlePowerUsage( 3 ); - this.getProxy().setFlags( GridFlags.CANNOT_CARRY, GridFlags.DENSE_CAPACITY ); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.DENSE; - } - - @Override - public void onReady() - { - this.onNeighborChange( true ); - super.onReady(); - } - - public void onNeighborChange( final boolean force ) - { - final boolean xx = this.checkController( this.xCoord - 1, this.yCoord, this.zCoord ) && this.checkController( this.xCoord + 1, this.yCoord, this.zCoord ); - final boolean yy = this.checkController( this.xCoord, this.yCoord - 1, this.zCoord ) && this.checkController( this.xCoord, this.yCoord + 1, this.zCoord ); - final boolean zz = this.checkController( this.xCoord, this.yCoord, this.zCoord - 1 ) && this.checkController( this.xCoord, this.yCoord, this.zCoord + 1 ); - - // int meta = world.getBlockMetadata( xCoord, yCoord, zCoord ); - // boolean hasPower = meta > 0; - // boolean isConflict = meta == 2; - - final boolean oldValid = this.isValid; - - this.isValid = ( xx && !yy && !zz ) || ( !xx && yy && !zz ) || ( !xx && !yy && zz ) || ( ( xx ? 1 : 0 ) + ( yy ? 1 : 0 ) + ( zz ? 1 : 0 ) <= 1 ); - - if( oldValid != this.isValid || force ) - { - if( this.isValid ) - { - this.getProxy().setValidSides( EnumSet.allOf( ForgeDirection.class ) ); - } - else - { - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - } - - this.updateMeta(); - } - - } - - private void updateMeta() - { - if( !this.getProxy().isReady() ) - { - return; - } - - int meta = 0; - - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - meta = 1; - - if( this.getProxy().getPath().getControllerState() == ControllerState.CONTROLLER_CONFLICT ) - { - meta = 2; - } - } - } - catch( final GridAccessException e ) - { - meta = 0; - } - - if( this.checkController( this.xCoord, this.yCoord, this.zCoord ) && this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) != meta ) - { - this.worldObj.setBlockMetadataWithNotify( this.xCoord, this.yCoord, this.zCoord, meta, 2 ); - } - } - - @Override - protected double getFunnelPowerDemand( final double maxReceived ) - { - try - { - return this.getProxy().getEnergy().getEnergyDemand( 8000 ); - } - catch( final GridAccessException e ) - { - // no grid? use local... - return super.getFunnelPowerDemand( maxReceived ); - } - } - - @Override - protected double funnelPowerIntoStorage( final double power, final Actionable mode ) - { - try - { - final double ret = this.getProxy().getEnergy().injectPower( power, mode ); - if( mode == Actionable.SIMULATE ) - { - return ret; - } - return 0; - } - catch( final GridAccessException e ) - { - // no grid? use local... - return super.funnelPowerIntoStorage( power, mode ); - } - } - - @Override - protected void PowerEvent( final PowerEventType x ) - { - try - { - this.getProxy().getGrid().postEvent( new MENetworkPowerStorage( this, x ) ); - } - catch( final GridAccessException e ) - { - // not ready! - } - } - - @MENetworkEventSubscribe - public void onControllerChange( final MENetworkControllerChange status ) - { - this.updateMeta(); - } - - @MENetworkEventSubscribe - public void onPowerChange( final MENetworkPowerStatusChange status ) - { - this.updateMeta(); - } - - @Override - public IInventory getInternalInventory() - { - return NULL_INVENTORY; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return ACCESSIBLE_SLOTS_BY_SIDE; - } - - /** - * Check for a controller at this coordinates as well as is it loaded. - * - * @return true if there is a loaded controller - */ - private boolean checkController( final int x, final int y, final int z ) - { - if( this.worldObj.getChunkProvider().chunkExists( this.xCoord >> 4, this.zCoord >> 4 ) ) - { - return this.worldObj.getTileEntity( x, y, z ) instanceof TileController; - } - return false; - } +public class TileController extends AENetworkPowerTile { + private static final IInventory NULL_INVENTORY = new AppEngInternalInventory(null, 0); + private static final int[] ACCESSIBLE_SLOTS_BY_SIDE = {}; + + private boolean isValid = false; + + public TileController() { + this.setInternalMaxPower(8000); + this.setInternalPublicPowerStorage(true); + this.getProxy().setIdlePowerUsage(3); + this.getProxy().setFlags(GridFlags.CANNOT_CARRY, GridFlags.DENSE_CAPACITY); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.DENSE; + } + + @Override + public void onReady() { + this.onNeighborChange(true); + super.onReady(); + } + + public void onNeighborChange(final boolean force) { + final boolean xx = this.checkController(this.xCoord - 1, this.yCoord, this.zCoord) + && this.checkController(this.xCoord + 1, this.yCoord, this.zCoord); + final boolean yy = this.checkController(this.xCoord, this.yCoord - 1, this.zCoord) + && this.checkController(this.xCoord, this.yCoord + 1, this.zCoord); + final boolean zz = this.checkController(this.xCoord, this.yCoord, this.zCoord - 1) + && this.checkController(this.xCoord, this.yCoord, this.zCoord + 1); + + // int meta = world.getBlockMetadata( xCoord, yCoord, zCoord ); + // boolean hasPower = meta > 0; + // boolean isConflict = meta == 2; + + final boolean oldValid = this.isValid; + + this.isValid = (xx && !yy && !zz) + || (!xx && yy && !zz) + || (!xx && !yy && zz) + || ((xx ? 1 : 0) + (yy ? 1 : 0) + (zz ? 1 : 0) <= 1); + + if (oldValid != this.isValid || force) { + if (this.isValid) { + this.getProxy().setValidSides(EnumSet.allOf(ForgeDirection.class)); + } else { + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + } + + this.updateMeta(); + } + } + + private void updateMeta() { + if (!this.getProxy().isReady()) { + return; + } + + int meta = 0; + + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + meta = 1; + + if (this.getProxy().getPath().getControllerState() == ControllerState.CONTROLLER_CONFLICT) { + meta = 2; + } + } + } catch (final GridAccessException e) { + meta = 0; + } + + if (this.checkController(this.xCoord, this.yCoord, this.zCoord) + && this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord) != meta) { + this.worldObj.setBlockMetadataWithNotify(this.xCoord, this.yCoord, this.zCoord, meta, 2); + } + } + + @Override + protected double getFunnelPowerDemand(final double maxReceived) { + try { + return this.getProxy().getEnergy().getEnergyDemand(8000); + } catch (final GridAccessException e) { + // no grid? use local... + return super.getFunnelPowerDemand(maxReceived); + } + } + + @Override + protected double funnelPowerIntoStorage(final double power, final Actionable mode) { + try { + final double ret = this.getProxy().getEnergy().injectPower(power, mode); + if (mode == Actionable.SIMULATE) { + return ret; + } + return 0; + } catch (final GridAccessException e) { + // no grid? use local... + return super.funnelPowerIntoStorage(power, mode); + } + } + + @Override + protected void PowerEvent(final PowerEventType x) { + try { + this.getProxy().getGrid().postEvent(new MENetworkPowerStorage(this, x)); + } catch (final GridAccessException e) { + // not ready! + } + } + + @MENetworkEventSubscribe + public void onControllerChange(final MENetworkControllerChange status) { + this.updateMeta(); + } + + @MENetworkEventSubscribe + public void onPowerChange(final MENetworkPowerStatusChange status) { + this.updateMeta(); + } + + @Override + public IInventory getInternalInventory() { + return NULL_INVENTORY; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) {} + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return ACCESSIBLE_SLOTS_BY_SIDE; + } + + /** + * Check for a controller at this coordinates as well as is it loaded. + * + * @return true if there is a loaded controller + */ + private boolean checkController(final int x, final int y, final int z) { + if (this.worldObj.getChunkProvider().chunkExists(this.xCoord >> 4, this.zCoord >> 4)) { + return this.worldObj.getTileEntity(x, y, z) instanceof TileController; + } + return false; + } } diff --git a/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java b/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java index b11f9c06621..b4efa9b21d0 100644 --- a/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java +++ b/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java @@ -18,7 +18,6 @@ package appeng.tile.networking; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -27,54 +26,44 @@ import appeng.tile.grid.AENetworkTile; import net.minecraftforge.common.util.ForgeDirection; +public class TileCreativeEnergyCell extends AENetworkTile implements IAEPowerStorage { -public class TileCreativeEnergyCell extends AENetworkTile implements IAEPowerStorage -{ - - public TileCreativeEnergyCell() - { - this.getProxy().setIdlePowerUsage( 0 ); - } + public TileCreativeEnergyCell() { + this.getProxy().setIdlePowerUsage(0); + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } - @Override - public double injectAEPower( final double amt, final Actionable mode ) - { - return 0; - } + @Override + public double injectAEPower(final double amt, final Actionable mode) { + return 0; + } - @Override - public double getAEMaxPower() - { - return Long.MAX_VALUE / 10000; - } + @Override + public double getAEMaxPower() { + return Long.MAX_VALUE / 10000; + } - @Override - public double getAECurrentPower() - { - return Long.MAX_VALUE / 10000; - } + @Override + public double getAECurrentPower() { + return Long.MAX_VALUE / 10000; + } - @Override - public boolean isAEPublicPowerStorage() - { - return true; - } + @Override + public boolean isAEPublicPowerStorage() { + return true; + } - @Override - public AccessRestriction getPowerFlow() - { - return AccessRestriction.READ_WRITE; - } + @Override + public AccessRestriction getPowerFlow() { + return AccessRestriction.READ_WRITE; + } - @Override - public double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier pm ) - { - return amt; - } + @Override + public double extractAEPower(final double amt, final Actionable mode, final PowerMultiplier pm) { + return amt; + } } diff --git a/src/main/java/appeng/tile/networking/TileDenseEnergyCell.java b/src/main/java/appeng/tile/networking/TileDenseEnergyCell.java index 7c2a8deef00..284c17b2265 100644 --- a/src/main/java/appeng/tile/networking/TileDenseEnergyCell.java +++ b/src/main/java/appeng/tile/networking/TileDenseEnergyCell.java @@ -18,12 +18,9 @@ package appeng.tile.networking; +public class TileDenseEnergyCell extends TileEnergyCell { -public class TileDenseEnergyCell extends TileEnergyCell -{ - - public TileDenseEnergyCell() - { - this.setInternalMaxPower( 200000 * 8 ); - } + public TileDenseEnergyCell() { + this.setInternalMaxPower(200000 * 8); + } } diff --git a/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java b/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java index df25f95ea62..569e09ce34c 100644 --- a/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java +++ b/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java @@ -18,10 +18,8 @@ package appeng.tile.networking; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; -import appeng.api.config.PowerMultiplier; import appeng.api.networking.energy.IEnergyGrid; import appeng.api.networking.events.MENetworkPowerStorage; import appeng.api.util.AECableType; @@ -34,108 +32,92 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; - -public class TileEnergyAcceptor extends AENetworkPowerTile -{ - - private static final AppEngInternalInventory INTERNAL_INVENTORY = new AppEngInternalInventory( null, 0 ); - private final int[] sides = {}; - - public TileEnergyAcceptor() - { - this.getProxy().setIdlePowerUsage( 0.0 ); - this.setInternalMaxPower( 8000 ); - this.setInternalPublicPowerStorage(true); - this.setInternalPowerFlow(AccessRestriction.READ_WRITE); - } - - @Override - public void readFromNBT_AENetwork( final NBTTagCompound data ) - { - this.setInternalCurrentPower( data.getDouble( "internalCurrentPower" ) ); - /** - * Does nothing here since the NBT tag in the parent is not needed anymore - */ - } - - @Override - public void writeToNBT_AENetwork( final NBTTagCompound data ) - { - data.setDouble( "internalCurrentPower", this.getInternalCurrentPower() ); - /** - * Does nothing here since the NBT tag in the parent is not needed anymore - */ - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } - - @Override - protected double getFunnelPowerDemand( final double maxRequired ) - { - try - { - final IEnergyGrid grid = this.getProxy().getEnergy(); - return grid.getEnergyDemand( maxRequired ); - } - catch( final GridAccessException e ) - { - return this.getInternalMaxPower(); - } - } - - @Override - protected double funnelPowerIntoStorage( final double power, final Actionable mode ) - { - try - { - final IEnergyGrid grid = this.getProxy().getEnergy(); - final double leftOver = grid.injectPower( power, mode ); - if( mode == Actionable.SIMULATE ) - { - return leftOver; - } - return 0.0; - } - catch( final GridAccessException e ) - { - return super.funnelPowerIntoStorage( power, mode ); - } - } - @Override - protected double extractAEPower( double amt, final Actionable mode ) - { - double res = super.extractAEPower(amt, mode); - try - { - if (getInternalCurrentPower() < getInternalMaxPower()) - this.getProxy().getGrid().postEvent(new MENetworkPowerStorage(this, MENetworkPowerStorage.PowerEventType.REQUEST_POWER)); - } - catch( final GridAccessException ignored ) - { - - } - return res; - } - - @Override - public IInventory getInternalInventory() - { - return INTERNAL_INVENTORY; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.sides; - } +public class TileEnergyAcceptor extends AENetworkPowerTile { + + private static final AppEngInternalInventory INTERNAL_INVENTORY = new AppEngInternalInventory(null, 0); + private final int[] sides = {}; + + public TileEnergyAcceptor() { + this.getProxy().setIdlePowerUsage(0.0); + this.setInternalMaxPower(8000); + this.setInternalPublicPowerStorage(true); + this.setInternalPowerFlow(AccessRestriction.READ_WRITE); + } + + @Override + public void readFromNBT_AENetwork(final NBTTagCompound data) { + this.setInternalCurrentPower(data.getDouble("internalCurrentPower")); + /** + * Does nothing here since the NBT tag in the parent is not needed anymore + */ + } + + @Override + public void writeToNBT_AENetwork(final NBTTagCompound data) { + data.setDouble("internalCurrentPower", this.getInternalCurrentPower()); + /** + * Does nothing here since the NBT tag in the parent is not needed anymore + */ + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } + + @Override + protected double getFunnelPowerDemand(final double maxRequired) { + try { + final IEnergyGrid grid = this.getProxy().getEnergy(); + return grid.getEnergyDemand(maxRequired); + } catch (final GridAccessException e) { + return this.getInternalMaxPower(); + } + } + + @Override + protected double funnelPowerIntoStorage(final double power, final Actionable mode) { + try { + final IEnergyGrid grid = this.getProxy().getEnergy(); + final double leftOver = grid.injectPower(power, mode); + if (mode == Actionable.SIMULATE) { + return leftOver; + } + return 0.0; + } catch (final GridAccessException e) { + return super.funnelPowerIntoStorage(power, mode); + } + } + + @Override + protected double extractAEPower(double amt, final Actionable mode) { + double res = super.extractAEPower(amt, mode); + try { + if (getInternalCurrentPower() < getInternalMaxPower()) + this.getProxy() + .getGrid() + .postEvent(new MENetworkPowerStorage(this, MENetworkPowerStorage.PowerEventType.REQUEST_POWER)); + } catch (final GridAccessException ignored) { + + } + return res; + } + + @Override + public IInventory getInternalInventory() { + return INTERNAL_INVENTORY; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) {} + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return this.sides; + } } diff --git a/src/main/java/appeng/tile/networking/TileEnergyCell.java b/src/main/java/appeng/tile/networking/TileEnergyCell.java index 8e9fca0f5e7..65ccd8f1dfa 100644 --- a/src/main/java/appeng/tile/networking/TileEnergyCell.java +++ b/src/main/java/appeng/tile/networking/TileEnergyCell.java @@ -18,7 +18,6 @@ package appeng.tile.networking; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -34,212 +33,177 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; - -public class TileEnergyCell extends AENetworkTile implements IAEPowerStorage -{ - - private double internalCurrentPower = 0.0; - private double internalMaxPower = 200000.0; - - private byte currentMeta = -1; - - public TileEnergyCell() - { - this.getProxy().setIdlePowerUsage( 0 ); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } - - @Override - public void onReady() - { - super.onReady(); - this.currentMeta = (byte) this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ); - this.changePowerLevel(); - } - - private void changePowerLevel() - { - if( this.notLoaded() ) - { - return; - } - - byte boundMetadata = (byte) ( 8.0 * ( this.internalCurrentPower / this.getInternalMaxPower() ) ); - - if( boundMetadata > 7 ) - { - boundMetadata = 7; - } - if( boundMetadata < 0 ) - { - boundMetadata = 0; - } - - if( this.currentMeta != boundMetadata ) - { - this.currentMeta = boundMetadata; - this.worldObj.setBlockMetadataWithNotify( this.xCoord, this.yCoord, this.zCoord, this.currentMeta, 2 ); - } - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileEnergyCell( final NBTTagCompound data ) - { - if( !this.worldObj.isRemote ) - { - data.setDouble( "internalCurrentPower", this.internalCurrentPower ); - } - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileEnergyCell( final NBTTagCompound data ) - { - this.internalCurrentPower = data.getDouble( "internalCurrentPower" ); - } - - @Override - public boolean canBeRotated() - { - return false; - } - - @Override - public void uploadSettings( final SettingsFrom from, final NBTTagCompound compound ) - { - if( from == SettingsFrom.DISMANTLE_ITEM ) - { - this.internalCurrentPower = compound.getDouble( "internalCurrentPower" ); - } - } - - @Override - public NBTTagCompound downloadSettings( final SettingsFrom from ) - { - if( from == SettingsFrom.DISMANTLE_ITEM ) - { - final NBTTagCompound tag = new NBTTagCompound(); - tag.setDouble( "internalCurrentPower", this.internalCurrentPower ); - tag.setDouble( "internalMaxPower", this.getInternalMaxPower() ); // used for tool tip. - return tag; - } - return null; - } - - @Override - public final double injectAEPower( double amt, final Actionable mode ) - { - if( mode == Actionable.SIMULATE ) - { - final double fakeBattery = this.internalCurrentPower + amt; - if( fakeBattery > this.getInternalMaxPower() ) - { - return fakeBattery - this.getInternalMaxPower(); - } - - return 0; - } - - if( this.internalCurrentPower < 0.01 && amt > 0.01 ) - { - this.getProxy().getNode().getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.PROVIDE_POWER ) ); - } - - this.internalCurrentPower += amt; - if( this.internalCurrentPower > this.getInternalMaxPower() ) - { - amt = this.internalCurrentPower - this.getInternalMaxPower(); - this.internalCurrentPower = this.getInternalMaxPower(); - - this.changePowerLevel(); - return amt; - } - - this.changePowerLevel(); - return 0; - } - - @Override - public double getAEMaxPower() - { - return this.getInternalMaxPower(); - } - - @Override - public double getAECurrentPower() - { - return this.internalCurrentPower; - } - - @Override - public boolean isAEPublicPowerStorage() - { - return true; - } - - @Override - public AccessRestriction getPowerFlow() - { - return AccessRestriction.READ_WRITE; - } - - @Override - public final double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier pm ) - { - return pm.divide( this.extractAEPower( pm.multiply( amt ), mode ) ); - } - - private double extractAEPower( double amt, final Actionable mode ) - { - if( mode == Actionable.SIMULATE ) - { - if( this.internalCurrentPower > amt ) - { - return amt; - } - return this.internalCurrentPower; - } - - final boolean wasFull = this.internalCurrentPower >= this.getInternalMaxPower() - 0.001; - - if( wasFull && amt > 0.001 ) - { - try - { - this.getProxy().getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.REQUEST_POWER ) ); - } - catch( final GridAccessException ignored ) - { - - } - } - - if( this.internalCurrentPower > amt ) - { - this.internalCurrentPower -= amt; - - this.changePowerLevel(); - return amt; - } - - amt = this.internalCurrentPower; - this.internalCurrentPower = 0; - - this.changePowerLevel(); - return amt; - } - - private double getInternalMaxPower() - { - return this.internalMaxPower * PowerMultiplier.CONFIG.multiplier; - } - - void setInternalMaxPower( final double internalMaxPower ) - { - this.internalMaxPower = internalMaxPower; - } +public class TileEnergyCell extends AENetworkTile implements IAEPowerStorage { + + private double internalCurrentPower = 0.0; + private double internalMaxPower = 200000.0; + + private byte currentMeta = -1; + + public TileEnergyCell() { + this.getProxy().setIdlePowerUsage(0); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } + + @Override + public void onReady() { + super.onReady(); + this.currentMeta = (byte) this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord); + this.changePowerLevel(); + } + + private void changePowerLevel() { + if (this.notLoaded()) { + return; + } + + byte boundMetadata = (byte) (8.0 * (this.internalCurrentPower / this.getInternalMaxPower())); + + if (boundMetadata > 7) { + boundMetadata = 7; + } + if (boundMetadata < 0) { + boundMetadata = 0; + } + + if (this.currentMeta != boundMetadata) { + this.currentMeta = boundMetadata; + this.worldObj.setBlockMetadataWithNotify(this.xCoord, this.yCoord, this.zCoord, this.currentMeta, 2); + } + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileEnergyCell(final NBTTagCompound data) { + if (!this.worldObj.isRemote) { + data.setDouble("internalCurrentPower", this.internalCurrentPower); + } + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileEnergyCell(final NBTTagCompound data) { + this.internalCurrentPower = data.getDouble("internalCurrentPower"); + } + + @Override + public boolean canBeRotated() { + return false; + } + + @Override + public void uploadSettings(final SettingsFrom from, final NBTTagCompound compound) { + if (from == SettingsFrom.DISMANTLE_ITEM) { + this.internalCurrentPower = compound.getDouble("internalCurrentPower"); + } + } + + @Override + public NBTTagCompound downloadSettings(final SettingsFrom from) { + if (from == SettingsFrom.DISMANTLE_ITEM) { + final NBTTagCompound tag = new NBTTagCompound(); + tag.setDouble("internalCurrentPower", this.internalCurrentPower); + tag.setDouble("internalMaxPower", this.getInternalMaxPower()); // used for tool tip. + return tag; + } + return null; + } + + @Override + public final double injectAEPower(double amt, final Actionable mode) { + if (mode == Actionable.SIMULATE) { + final double fakeBattery = this.internalCurrentPower + amt; + if (fakeBattery > this.getInternalMaxPower()) { + return fakeBattery - this.getInternalMaxPower(); + } + + return 0; + } + + if (this.internalCurrentPower < 0.01 && amt > 0.01) { + this.getProxy() + .getNode() + .getGrid() + .postEvent(new MENetworkPowerStorage(this, PowerEventType.PROVIDE_POWER)); + } + + this.internalCurrentPower += amt; + if (this.internalCurrentPower > this.getInternalMaxPower()) { + amt = this.internalCurrentPower - this.getInternalMaxPower(); + this.internalCurrentPower = this.getInternalMaxPower(); + + this.changePowerLevel(); + return amt; + } + + this.changePowerLevel(); + return 0; + } + + @Override + public double getAEMaxPower() { + return this.getInternalMaxPower(); + } + + @Override + public double getAECurrentPower() { + return this.internalCurrentPower; + } + + @Override + public boolean isAEPublicPowerStorage() { + return true; + } + + @Override + public AccessRestriction getPowerFlow() { + return AccessRestriction.READ_WRITE; + } + + @Override + public final double extractAEPower(final double amt, final Actionable mode, final PowerMultiplier pm) { + return pm.divide(this.extractAEPower(pm.multiply(amt), mode)); + } + + private double extractAEPower(double amt, final Actionable mode) { + if (mode == Actionable.SIMULATE) { + if (this.internalCurrentPower > amt) { + return amt; + } + return this.internalCurrentPower; + } + + final boolean wasFull = this.internalCurrentPower >= this.getInternalMaxPower() - 0.001; + + if (wasFull && amt > 0.001) { + try { + this.getProxy().getGrid().postEvent(new MENetworkPowerStorage(this, PowerEventType.REQUEST_POWER)); + } catch (final GridAccessException ignored) { + + } + } + + if (this.internalCurrentPower > amt) { + this.internalCurrentPower -= amt; + + this.changePowerLevel(); + return amt; + } + + amt = this.internalCurrentPower; + this.internalCurrentPower = 0; + + this.changePowerLevel(); + return amt; + } + + private double getInternalMaxPower() { + return this.internalMaxPower * PowerMultiplier.CONFIG.multiplier; + } + + void setInternalMaxPower(final double internalMaxPower) { + this.internalMaxPower = internalMaxPower; + } } diff --git a/src/main/java/appeng/tile/networking/TileWireless.java b/src/main/java/appeng/tile/networking/TileWireless.java index cbdb63ba59e..26f822f4519 100644 --- a/src/main/java/appeng/tile/networking/TileWireless.java +++ b/src/main/java/appeng/tile/networking/TileWireless.java @@ -18,7 +18,6 @@ package appeng.tile.networking; - import appeng.api.AEApi; import appeng.api.implementations.IPowerChannelState; import appeng.api.implementations.tiles.IWirelessAccessPoint; @@ -38,186 +37,157 @@ import appeng.tile.inventory.InvOperation; import appeng.util.Platform; import io.netty.buffer.ByteBuf; +import java.util.EnumSet; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class TileWireless extends AENetworkInvTile implements IWirelessAccessPoint, IPowerChannelState -{ - - public static final int POWERED_FLAG = 1; - public static final int CHANNEL_FLAG = 2; - - private final int[] sides = { 0 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 1 ); - - private int clientFlags = 0; - - public TileWireless() - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - } - - @Override - public void setOrientation( final ForgeDirection inForward, final ForgeDirection inUp ) - { - super.setOrientation( inForward, inUp ); - this.getProxy().setValidSides( EnumSet.of( this.getForward().getOpposite() ) ); - } - - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged c ) - { - this.markForUpdate(); - } - - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.markForUpdate(); - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileWireless( final ByteBuf data ) - { - final int old = this.getClientFlags(); - this.setClientFlags( data.readByte() ); - - return old != this.getClientFlags(); - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileWireless( final ByteBuf data ) - { - this.setClientFlags( 0 ); - - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - this.setClientFlags( this.getClientFlags() | POWERED_FLAG ); - } - - if( this.getProxy().getNode().meetsChannelRequirements() ) - { - this.setClientFlags( this.getClientFlags() | CHANNEL_FLAG ); - } - } - catch( final GridAccessException e ) - { - // meh - } - - data.writeByte( (byte) this.getClientFlags() ); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return AEApi.instance().definitions().materials().wirelessBooster().isSameAs( itemstack ); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - // :P - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.sides; - } - - @Override - public void onReady() - { - this.updatePower(); - super.onReady(); - } - - private void updatePower() - { - this.getProxy().setIdlePowerUsage( AEConfig.instance.wireless_getPowerDrain( this.getBoosters() ) ); - } - - private int getBoosters() - { - final ItemStack boosters = this.inv.getStackInSlot( 0 ); - return boosters == null ? 0 : boosters.stackSize; - } - - @Override - public void markDirty() - { - this.updatePower(); - } - - @Override - public double getRange() - { - return AEConfig.instance.wireless_getMaxRange( this.getBoosters() ); - } - - @Override - public boolean isActive() - { - if( Platform.isClient() ) - { - return this.isPowered() && ( CHANNEL_FLAG == ( this.getClientFlags() & CHANNEL_FLAG ) ); - } - - return this.getProxy().isActive(); - } - - @Override - public IGrid getGrid() - { - try - { - return this.getProxy().getGrid(); - } - catch( final GridAccessException e ) - { - return null; - } - } - - @Override - public boolean isPowered() - { - return POWERED_FLAG == ( this.getClientFlags() & POWERED_FLAG ); - } - - public int getClientFlags() - { - return this.clientFlags; - } - - private void setClientFlags( final int clientFlags ) - { - this.clientFlags = clientFlags; - } +public class TileWireless extends AENetworkInvTile implements IWirelessAccessPoint, IPowerChannelState { + + public static final int POWERED_FLAG = 1; + public static final int CHANNEL_FLAG = 2; + + private final int[] sides = {0}; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 1); + + private int clientFlags = 0; + + public TileWireless() { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + } + + @Override + public void setOrientation(final ForgeDirection inForward, final ForgeDirection inUp) { + super.setOrientation(inForward, inUp); + this.getProxy().setValidSides(EnumSet.of(this.getForward().getOpposite())); + } + + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged c) { + this.markForUpdate(); + } + + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.markForUpdate(); + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileWireless(final ByteBuf data) { + final int old = this.getClientFlags(); + this.setClientFlags(data.readByte()); + + return old != this.getClientFlags(); + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileWireless(final ByteBuf data) { + this.setClientFlags(0); + + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + this.setClientFlags(this.getClientFlags() | POWERED_FLAG); + } + + if (this.getProxy().getNode().meetsChannelRequirements()) { + this.setClientFlags(this.getClientFlags() | CHANNEL_FLAG); + } + } catch (final GridAccessException e) { + // meh + } + + data.writeByte((byte) this.getClientFlags()); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + @Override + public IInventory getInternalInventory() { + return this.inv; + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return AEApi.instance().definitions().materials().wirelessBooster().isSameAs(itemstack); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) { + // :P + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return this.sides; + } + + @Override + public void onReady() { + this.updatePower(); + super.onReady(); + } + + private void updatePower() { + this.getProxy().setIdlePowerUsage(AEConfig.instance.wireless_getPowerDrain(this.getBoosters())); + } + + private int getBoosters() { + final ItemStack boosters = this.inv.getStackInSlot(0); + return boosters == null ? 0 : boosters.stackSize; + } + + @Override + public void markDirty() { + this.updatePower(); + } + + @Override + public double getRange() { + return AEConfig.instance.wireless_getMaxRange(this.getBoosters()); + } + + @Override + public boolean isActive() { + if (Platform.isClient()) { + return this.isPowered() && (CHANNEL_FLAG == (this.getClientFlags() & CHANNEL_FLAG)); + } + + return this.getProxy().isActive(); + } + + @Override + public IGrid getGrid() { + try { + return this.getProxy().getGrid(); + } catch (final GridAccessException e) { + return null; + } + } + + @Override + public boolean isPowered() { + return POWERED_FLAG == (this.getClientFlags() & POWERED_FLAG); + } + + public int getClientFlags() { + return this.clientFlags; + } + + private void setClientFlags(final int clientFlags) { + this.clientFlags = clientFlags; + } } diff --git a/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java b/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java index c386baf9c52..872d893374e 100644 --- a/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java +++ b/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java @@ -18,8 +18,4 @@ package appeng.tile.powersink; - -public abstract class AEBasePoweredTile extends RedstoneFlux -{ - -} +public abstract class AEBasePoweredTile extends RedstoneFlux {} diff --git a/src/main/java/appeng/tile/powersink/AERootPoweredTile.java b/src/main/java/appeng/tile/powersink/AERootPoweredTile.java index e19706820d9..e19eb21b502 100644 --- a/src/main/java/appeng/tile/powersink/AERootPoweredTile.java +++ b/src/main/java/appeng/tile/powersink/AERootPoweredTile.java @@ -18,7 +18,6 @@ package appeng.tile.powersink; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -28,205 +27,170 @@ import appeng.tile.AEBaseInvTile; import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; +import java.util.EnumSet; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public abstract class AERootPoweredTile extends AEBaseInvTile implements IAEPowerStorage -{ - - // values that determine general function, are set by inheriting classes if - // needed. These should generally remain static. - private double internalMaxPower = 10000; - private boolean internalPublicPowerStorage = false; - private AccessRestriction internalPowerFlow = AccessRestriction.READ_WRITE; - // the current power buffer. - private double internalCurrentPower = 0; - private EnumSet internalPowerSides = EnumSet.allOf( ForgeDirection.class ); - - protected EnumSet getPowerSides() - { - return this.internalPowerSides.clone(); - } - - protected void setPowerSides( final EnumSet sides ) - { - this.internalPowerSides = sides; - // trigger re-calc! - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_AERootPoweredTile( final NBTTagCompound data ) - { - data.setDouble( "internalCurrentPower", this.getInternalCurrentPower() ); - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_AERootPoweredTile( final NBTTagCompound data ) - { - this.setInternalCurrentPower( data.getDouble( "internalCurrentPower" ) ); - } - - protected final double getExternalPowerDemand( final PowerUnits externalUnit, final double maxPowerRequired ) - { - return PowerUnits.AE.convertTo( externalUnit, Math.max( 0.0, this.getFunnelPowerDemand( externalUnit.convertTo( PowerUnits.AE, maxPowerRequired ) ) ) ); - } - - protected double getFunnelPowerDemand( final double maxRequired ) - { - return this.getInternalMaxPower() - this.getInternalCurrentPower(); - } - - public final double injectExternalPower( final PowerUnits input, final double amt ) - { - return PowerUnits.AE.convertTo( input, this.funnelPowerIntoStorage( input.convertTo( PowerUnits.AE, amt ), Actionable.MODULATE ) ); - } - - protected double funnelPowerIntoStorage( final double power, final Actionable mode ) - { - return this.injectAEPower( power, mode ); - } - - @Override - public final double injectAEPower( double amt, final Actionable mode ) - { - if( amt < 0.000001 ) - { - return 0; - } - - if( mode == Actionable.SIMULATE ) - { - final double fakeBattery = this.getInternalCurrentPower() + amt; - - if( fakeBattery > this.getInternalMaxPower() ) - { - return fakeBattery - this.getInternalMaxPower(); - } - - return 0; - } - else - { - if( this.getInternalCurrentPower() < 0.01 && amt > 0.01 ) - { - this.PowerEvent( PowerEventType.PROVIDE_POWER ); - } - - this.setInternalCurrentPower( this.getInternalCurrentPower() + amt ); - if( this.getInternalCurrentPower() > this.getInternalMaxPower() ) - { - amt = this.getInternalCurrentPower() - this.getInternalMaxPower(); - this.setInternalCurrentPower( this.getInternalMaxPower() ); - return amt; - } - - return 0; - } - } - - protected void PowerEvent( final PowerEventType x ) - { - // nothing. - } - - @Override - public final double getAEMaxPower() - { - return this.getInternalMaxPower(); - } - - @Override - public final double getAECurrentPower() - { - return this.getInternalCurrentPower(); - } - - @Override - public final boolean isAEPublicPowerStorage() - { - return this.isInternalPublicPowerStorage(); - } - - @Override - public final AccessRestriction getPowerFlow() - { - return this.getInternalPowerFlow(); - } - - @Override - public final double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier multiplier ) - { - return multiplier.divide( this.extractAEPower( multiplier.multiply( amt ), mode ) ); - } - - protected double extractAEPower( double amt, final Actionable mode ) - { - if( mode == Actionable.SIMULATE ) - { - if( this.getInternalCurrentPower() > amt ) - { - return amt; - } - return this.getInternalCurrentPower(); - } - - final boolean wasFull = this.getInternalCurrentPower() >= this.getInternalMaxPower() - 0.001; - if( wasFull && amt > 0.001 ) - { - this.PowerEvent( PowerEventType.REQUEST_POWER ); - } - - if( this.getInternalCurrentPower() > amt ) - { - this.setInternalCurrentPower( this.getInternalCurrentPower() - amt ); - return amt; - } - - amt = this.getInternalCurrentPower(); - this.setInternalCurrentPower( 0 ); - return amt; - } - - public double getInternalCurrentPower() - { - return this.internalCurrentPower; - } - - public void setInternalCurrentPower( final double internalCurrentPower ) - { - this.internalCurrentPower = internalCurrentPower; - } - - public double getInternalMaxPower() - { - return this.internalMaxPower * PowerMultiplier.CONFIG.multiplier; - } - - public void setInternalMaxPower( final double internalMaxPower ) - { - this.internalMaxPower = internalMaxPower; - } - - private boolean isInternalPublicPowerStorage() - { - return this.internalPublicPowerStorage; - } - - public void setInternalPublicPowerStorage( final boolean internalPublicPowerStorage ) - { - this.internalPublicPowerStorage = internalPublicPowerStorage; - } - - private AccessRestriction getInternalPowerFlow() - { - return this.internalPowerFlow; - } - - public void setInternalPowerFlow( final AccessRestriction internalPowerFlow ) - { - this.internalPowerFlow = internalPowerFlow; - } +public abstract class AERootPoweredTile extends AEBaseInvTile implements IAEPowerStorage { + + // values that determine general function, are set by inheriting classes if + // needed. These should generally remain static. + private double internalMaxPower = 10000; + private boolean internalPublicPowerStorage = false; + private AccessRestriction internalPowerFlow = AccessRestriction.READ_WRITE; + // the current power buffer. + private double internalCurrentPower = 0; + private EnumSet internalPowerSides = EnumSet.allOf(ForgeDirection.class); + + protected EnumSet getPowerSides() { + return this.internalPowerSides.clone(); + } + + protected void setPowerSides(final EnumSet sides) { + this.internalPowerSides = sides; + // trigger re-calc! + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_AERootPoweredTile(final NBTTagCompound data) { + data.setDouble("internalCurrentPower", this.getInternalCurrentPower()); + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_AERootPoweredTile(final NBTTagCompound data) { + this.setInternalCurrentPower(data.getDouble("internalCurrentPower")); + } + + protected final double getExternalPowerDemand(final PowerUnits externalUnit, final double maxPowerRequired) { + return PowerUnits.AE.convertTo( + externalUnit, + Math.max(0.0, this.getFunnelPowerDemand(externalUnit.convertTo(PowerUnits.AE, maxPowerRequired)))); + } + + protected double getFunnelPowerDemand(final double maxRequired) { + return this.getInternalMaxPower() - this.getInternalCurrentPower(); + } + + public final double injectExternalPower(final PowerUnits input, final double amt) { + return PowerUnits.AE.convertTo( + input, this.funnelPowerIntoStorage(input.convertTo(PowerUnits.AE, amt), Actionable.MODULATE)); + } + + protected double funnelPowerIntoStorage(final double power, final Actionable mode) { + return this.injectAEPower(power, mode); + } + + @Override + public final double injectAEPower(double amt, final Actionable mode) { + if (amt < 0.000001) { + return 0; + } + + if (mode == Actionable.SIMULATE) { + final double fakeBattery = this.getInternalCurrentPower() + amt; + + if (fakeBattery > this.getInternalMaxPower()) { + return fakeBattery - this.getInternalMaxPower(); + } + + return 0; + } else { + if (this.getInternalCurrentPower() < 0.01 && amt > 0.01) { + this.PowerEvent(PowerEventType.PROVIDE_POWER); + } + + this.setInternalCurrentPower(this.getInternalCurrentPower() + amt); + if (this.getInternalCurrentPower() > this.getInternalMaxPower()) { + amt = this.getInternalCurrentPower() - this.getInternalMaxPower(); + this.setInternalCurrentPower(this.getInternalMaxPower()); + return amt; + } + + return 0; + } + } + + protected void PowerEvent(final PowerEventType x) { + // nothing. + } + + @Override + public final double getAEMaxPower() { + return this.getInternalMaxPower(); + } + + @Override + public final double getAECurrentPower() { + return this.getInternalCurrentPower(); + } + + @Override + public final boolean isAEPublicPowerStorage() { + return this.isInternalPublicPowerStorage(); + } + + @Override + public final AccessRestriction getPowerFlow() { + return this.getInternalPowerFlow(); + } + + @Override + public final double extractAEPower(final double amt, final Actionable mode, final PowerMultiplier multiplier) { + return multiplier.divide(this.extractAEPower(multiplier.multiply(amt), mode)); + } + + protected double extractAEPower(double amt, final Actionable mode) { + if (mode == Actionable.SIMULATE) { + if (this.getInternalCurrentPower() > amt) { + return amt; + } + return this.getInternalCurrentPower(); + } + + final boolean wasFull = this.getInternalCurrentPower() >= this.getInternalMaxPower() - 0.001; + if (wasFull && amt > 0.001) { + this.PowerEvent(PowerEventType.REQUEST_POWER); + } + + if (this.getInternalCurrentPower() > amt) { + this.setInternalCurrentPower(this.getInternalCurrentPower() - amt); + return amt; + } + + amt = this.getInternalCurrentPower(); + this.setInternalCurrentPower(0); + return amt; + } + + public double getInternalCurrentPower() { + return this.internalCurrentPower; + } + + public void setInternalCurrentPower(final double internalCurrentPower) { + this.internalCurrentPower = internalCurrentPower; + } + + public double getInternalMaxPower() { + return this.internalMaxPower * PowerMultiplier.CONFIG.multiplier; + } + + public void setInternalMaxPower(final double internalMaxPower) { + this.internalMaxPower = internalMaxPower; + } + + private boolean isInternalPublicPowerStorage() { + return this.internalPublicPowerStorage; + } + + public void setInternalPublicPowerStorage(final boolean internalPublicPowerStorage) { + this.internalPublicPowerStorage = internalPublicPowerStorage; + } + + private AccessRestriction getInternalPowerFlow() { + return this.internalPowerFlow; + } + + public void setInternalPowerFlow(final AccessRestriction internalPowerFlow) { + this.internalPowerFlow = internalPowerFlow; + } } diff --git a/src/main/java/appeng/tile/powersink/GTPowerSink.java b/src/main/java/appeng/tile/powersink/GTPowerSink.java index 4afe90ccf78..b5ec9f9ee31 100644 --- a/src/main/java/appeng/tile/powersink/GTPowerSink.java +++ b/src/main/java/appeng/tile/powersink/GTPowerSink.java @@ -15,7 +15,7 @@ import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.fluids.IFluidHandler; -@Integration.Interface(iname = IntegrationType.GT, iface = "gregtech.api.interfaces.tileentity.IEnergyConnected" ) +@Integration.Interface(iname = IntegrationType.GT, iface = "gregtech.api.interfaces.tileentity.IEnergyConnected") public abstract class GTPowerSink extends AERootPoweredTile implements IEnergyConnected { @Override public long injectEnergyUnits(byte side, long voltage, long amperage) { @@ -23,15 +23,12 @@ public long injectEnergyUnits(byte side, long voltage, long amperage) { double overflow = this.funnelPowerIntoStorage(e, Actionable.SIMULATE); // Energy grid may keep some "extra energy" that it is happy to get rid of // so overflow may actually be greater than input - if (overflow >= e) - return 0; - long used = amperage - (int)Math.ceil(PowerUnits.AE.convertTo(PowerUnits.EU, overflow) / voltage); + if (overflow >= e) return 0; + long used = amperage - (int) Math.ceil(PowerUnits.AE.convertTo(PowerUnits.EU, overflow) / voltage); if (used > 0) { e = PowerUnits.EU.convertTo(PowerUnits.AE, voltage * used); PowerUnits.AE.convertTo(PowerUnits.EU, this.funnelPowerIntoStorage(e, Actionable.MODULATE)); - } - else if (used < 0) - used = 0; + } else if (used < 0) used = 0; return used; } @@ -67,7 +64,7 @@ public int getXCoord() { @Override public short getYCoord() { - return (short)yCoord; + return (short) yCoord; } @Override @@ -325,9 +322,7 @@ public boolean isDead() { } @Override - public void sendBlockEvent(byte b, byte b1) { - - } + public void sendBlockEvent(byte b, byte b1) {} @Override public long getTimer() { @@ -335,9 +330,7 @@ public long getTimer() { } @Override - public void setLightValue(byte b) { - - } + public void setLightValue(byte b) {} @Override public boolean isInvalidTileEntity() { diff --git a/src/main/java/appeng/tile/powersink/IC2.java b/src/main/java/appeng/tile/powersink/IC2.java index f304810e95b..57b226e2c4f 100644 --- a/src/main/java/appeng/tile/powersink/IC2.java +++ b/src/main/java/appeng/tile/powersink/IC2.java @@ -18,7 +18,6 @@ package appeng.tile.powersink; - import appeng.api.config.PowerUnits; import appeng.integration.IntegrationRegistry; import appeng.integration.IntegrationType; @@ -26,98 +25,81 @@ import appeng.transformer.annotations.Integration.Interface; import appeng.util.Platform; import ic2.api.energy.tile.IEnergySink; +import java.util.EnumSet; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -@Interface( iname = IntegrationType.IC2, iface = "ic2.api.energy.tile.IEnergySink" ) -public abstract class IC2 extends GTPowerSink implements IEnergySink -{ - - private boolean isInIC2 = false; - - @Override - public final boolean acceptsEnergyFrom( final TileEntity emitter, final ForgeDirection direction ) - { - return this.getPowerSides().contains( direction ); - } - - @Override - public final double getDemandedEnergy() - { - return this.getExternalPowerDemand( PowerUnits.EU, Double.MAX_VALUE ); - } - - @Override - public final int getSinkTier() - { - return Integer.MAX_VALUE; - } - - @Override - public final double injectEnergy( final ForgeDirection directionFrom, final double amount, final double voltage ) - { - // just store the excess in the current block, if I return the waste, - // IC2 will just disintegrate it - Oct 20th 2013 - final double overflow = PowerUnits.EU.convertTo( PowerUnits.AE, this.injectExternalPower( PowerUnits.EU, amount ) ); - this.setInternalCurrentPower( this.getInternalCurrentPower() + overflow ); - return 0; // see above comment. - } - - @Override - public void invalidate() - { - super.invalidate(); - this.removeFromENet(); - } - - private void removeFromENet() - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.IC2 ) ) - { - final IIC2 ic2Integration = (IIC2) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.IC2 ); - if( this.isInIC2 && Platform.isServer() && ic2Integration != null ) - { - ic2Integration.removeFromEnergyNet( this ); - this.isInIC2 = false; - } - } - } - - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - this.removeFromENet(); - } - - @Override - public void onReady() - { - super.onReady(); - this.addToENet(); - } - - private void addToENet() - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.IC2 ) ) - { - final IIC2 ic2Integration = (IIC2) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.IC2 ); - if( !this.isInIC2 && Platform.isServer() && ic2Integration != null ) - { - ic2Integration.addToEnergyNet( this ); - this.isInIC2 = true; - } - } - } - - @Override - protected void setPowerSides( final EnumSet sides ) - { - super.setPowerSides( sides ); - this.removeFromENet(); - this.addToENet(); - } +@Interface(iname = IntegrationType.IC2, iface = "ic2.api.energy.tile.IEnergySink") +public abstract class IC2 extends GTPowerSink implements IEnergySink { + + private boolean isInIC2 = false; + + @Override + public final boolean acceptsEnergyFrom(final TileEntity emitter, final ForgeDirection direction) { + return this.getPowerSides().contains(direction); + } + + @Override + public final double getDemandedEnergy() { + return this.getExternalPowerDemand(PowerUnits.EU, Double.MAX_VALUE); + } + + @Override + public final int getSinkTier() { + return Integer.MAX_VALUE; + } + + @Override + public final double injectEnergy(final ForgeDirection directionFrom, final double amount, final double voltage) { + // just store the excess in the current block, if I return the waste, + // IC2 will just disintegrate it - Oct 20th 2013 + final double overflow = PowerUnits.EU.convertTo(PowerUnits.AE, this.injectExternalPower(PowerUnits.EU, amount)); + this.setInternalCurrentPower(this.getInternalCurrentPower() + overflow); + return 0; // see above comment. + } + + @Override + public void invalidate() { + super.invalidate(); + this.removeFromENet(); + } + + private void removeFromENet() { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.IC2)) { + final IIC2 ic2Integration = (IIC2) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.IC2); + if (this.isInIC2 && Platform.isServer() && ic2Integration != null) { + ic2Integration.removeFromEnergyNet(this); + this.isInIC2 = false; + } + } + } + + @Override + public void onChunkUnload() { + super.onChunkUnload(); + this.removeFromENet(); + } + + @Override + public void onReady() { + super.onReady(); + this.addToENet(); + } + + private void addToENet() { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.IC2)) { + final IIC2 ic2Integration = (IIC2) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.IC2); + if (!this.isInIC2 && Platform.isServer() && ic2Integration != null) { + ic2Integration.addToEnergyNet(this); + this.isInIC2 = true; + } + } + } + + @Override + protected void setPowerSides(final EnumSet sides) { + super.setPowerSides(sides); + this.removeFromENet(); + this.addToENet(); + } } diff --git a/src/main/java/appeng/tile/powersink/MekJoules.java b/src/main/java/appeng/tile/powersink/MekJoules.java index 21d53f82c1b..11f58ebef33 100644 --- a/src/main/java/appeng/tile/powersink/MekJoules.java +++ b/src/main/java/appeng/tile/powersink/MekJoules.java @@ -1,4 +1,4 @@ -///* +/// * // * This file is part of Applied Energistics 2. // * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. // * @@ -16,19 +16,19 @@ // * along with Applied Energistics 2. If not, see . // */ // -//package appeng.tile.powersink; +// package appeng.tile.powersink; // // -//import appeng.api.config.PowerUnits; -//import appeng.integration.IntegrationType; -//import appeng.transformer.annotations.Integration.Interface; -//import mekanism.api.energy.IStrictEnergyAcceptor; -//import net.minecraftforge.common.util.ForgeDirection; +// import appeng.api.config.PowerUnits; +// import appeng.integration.IntegrationType; +// import appeng.transformer.annotations.Integration.Interface; +// import mekanism.api.energy.IStrictEnergyAcceptor; +// import net.minecraftforge.common.util.ForgeDirection; // // -//@Interface( iname = IntegrationType.Mekanism, iface = "mekanism.api.energy.IStrictEnergyAcceptor" ) -//public abstract class MekJoules extends RedstoneFlux implements IStrictEnergyAcceptor -//{ +// @Interface( iname = IntegrationType.Mekanism, iface = "mekanism.api.energy.IStrictEnergyAcceptor" ) +// public abstract class MekJoules extends RedstoneFlux implements IStrictEnergyAcceptor +// { // // @Override // public double getEnergy() @@ -67,4 +67,4 @@ // { // return this.getPowerSides().contains( side ); // } -//} +// } diff --git a/src/main/java/appeng/tile/powersink/RedstoneFlux.java b/src/main/java/appeng/tile/powersink/RedstoneFlux.java index 9578da1ed08..83319d3adb2 100644 --- a/src/main/java/appeng/tile/powersink/RedstoneFlux.java +++ b/src/main/java/appeng/tile/powersink/RedstoneFlux.java @@ -18,46 +18,38 @@ package appeng.tile.powersink; - import appeng.api.config.PowerUnits; import appeng.integration.IntegrationType; import appeng.transformer.annotations.Integration.Interface; import cofh.api.energy.IEnergyReceiver; import net.minecraftforge.common.util.ForgeDirection; - -@Interface( iname = IntegrationType.RF, iface = "cofh.api.energy.IEnergyReceiver" ) -public abstract class RedstoneFlux extends IC2 implements IEnergyReceiver -{ - @Override - public final int receiveEnergy( final ForgeDirection from, final int maxReceive, final boolean simulate ) - { - final int networkRFDemand = (int) Math.floor( this.getExternalPowerDemand( PowerUnits.RF, maxReceive ) ); - final int usedRF = Math.min( maxReceive, networkRFDemand ); - - if( !simulate ) - { - this.injectExternalPower( PowerUnits.RF, usedRF ); - } - - return usedRF; - } - - @Override - public final int getEnergyStored( final ForgeDirection from ) - { - return (int) Math.floor( PowerUnits.AE.convertTo( PowerUnits.RF, this.getAECurrentPower() ) ); - } - - @Override - public final int getMaxEnergyStored( final ForgeDirection from ) - { - return (int) Math.floor( PowerUnits.AE.convertTo( PowerUnits.RF, this.getAEMaxPower() ) ); - } - - @Override - public final boolean canConnectEnergy( final ForgeDirection from ) - { - return this.getPowerSides().contains( from ); - } +@Interface(iname = IntegrationType.RF, iface = "cofh.api.energy.IEnergyReceiver") +public abstract class RedstoneFlux extends IC2 implements IEnergyReceiver { + @Override + public final int receiveEnergy(final ForgeDirection from, final int maxReceive, final boolean simulate) { + final int networkRFDemand = (int) Math.floor(this.getExternalPowerDemand(PowerUnits.RF, maxReceive)); + final int usedRF = Math.min(maxReceive, networkRFDemand); + + if (!simulate) { + this.injectExternalPower(PowerUnits.RF, usedRF); + } + + return usedRF; + } + + @Override + public final int getEnergyStored(final ForgeDirection from) { + return (int) Math.floor(PowerUnits.AE.convertTo(PowerUnits.RF, this.getAECurrentPower())); + } + + @Override + public final int getMaxEnergyStored(final ForgeDirection from) { + return (int) Math.floor(PowerUnits.AE.convertTo(PowerUnits.RF, this.getAEMaxPower())); + } + + @Override + public final boolean canConnectEnergy(final ForgeDirection from) { + return this.getPowerSides().contains(from); + } } diff --git a/src/main/java/appeng/tile/powersink/RotaryCraft.java b/src/main/java/appeng/tile/powersink/RotaryCraft.java index c3cb829818c..3223afc04fe 100644 --- a/src/main/java/appeng/tile/powersink/RotaryCraft.java +++ b/src/main/java/appeng/tile/powersink/RotaryCraft.java @@ -1,4 +1,4 @@ -///* +/// * // * This file is part of Applied Energistics 2. // * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. // * @@ -16,27 +16,29 @@ // * along with Applied Energistics 2. If not, see . // */ // -//package appeng.tile.powersink; +// package appeng.tile.powersink; // // -//import Reika.RotaryCraft.API.Interfaces.Transducerable; -//import Reika.RotaryCraft.API.Power.AdvancedShaftPowerReceiver; -//import appeng.api.config.PowerUnits; -//import appeng.integration.IntegrationType; -//import appeng.tile.TileEvent; -//import appeng.tile.events.TileEventType; -//import appeng.transformer.annotations.Integration.Interface; -//import appeng.transformer.annotations.Integration.InterfaceList; -//import appeng.transformer.annotations.Integration.Method; -//import net.minecraft.world.World; -//import net.minecraftforge.common.util.ForgeDirection; +// import Reika.RotaryCraft.API.Interfaces.Transducerable; +// import Reika.RotaryCraft.API.Power.AdvancedShaftPowerReceiver; +// import appeng.api.config.PowerUnits; +// import appeng.integration.IntegrationType; +// import appeng.tile.TileEvent; +// import appeng.tile.events.TileEventType; +// import appeng.transformer.annotations.Integration.Interface; +// import appeng.transformer.annotations.Integration.InterfaceList; +// import appeng.transformer.annotations.Integration.Method; +// import net.minecraft.world.World; +// import net.minecraftforge.common.util.ForgeDirection; // -//import java.util.ArrayList; +// import java.util.ArrayList; // // -//@InterfaceList( value = { @Interface( iname = IntegrationType.RotaryCraft, iface = "Reika.RotaryCraft.API.Power.AdvancedShaftPowerReceiver" ), @Interface( iname = IntegrationType.RotaryCraft, iface = "Reika.RotaryCraft.API.Interfaces.Transducerable" ) } ) -//public abstract class RotaryCraft extends IC2 implements AdvancedShaftPowerReceiver, Transducerable -//{ +// @InterfaceList( value = { @Interface( iname = IntegrationType.RotaryCraft, iface = +// "Reika.RotaryCraft.API.Power.AdvancedShaftPowerReceiver" ), @Interface( iname = IntegrationType.RotaryCraft, iface = +// "Reika.RotaryCraft.API.Interfaces.Transducerable" ) } ) +// public abstract class RotaryCraft extends IC2 implements AdvancedShaftPowerReceiver, Transducerable +// { // // private int omega = 0; // private int torque = 0; @@ -156,7 +158,8 @@ // } // // @Override -// public final ArrayList getMessages( final World world, final int x, final int y, final int z, final int side ) +// public final ArrayList getMessages( final World world, final int x, final int y, final int z, final int side +// ) // { // final String out; // if( this.power >= 1000000000 ) @@ -180,4 +183,4 @@ // messages.add( out ); // return messages; // } -//} +// } diff --git a/src/main/java/appeng/tile/powersink/UniversalElectricity.java b/src/main/java/appeng/tile/powersink/UniversalElectricity.java index 86f02773583..bdbe879f225 100644 --- a/src/main/java/appeng/tile/powersink/UniversalElectricity.java +++ b/src/main/java/appeng/tile/powersink/UniversalElectricity.java @@ -18,7 +18,6 @@ package appeng.tile.powersink; - /* * import net.minecraftforge.common.util.ForgeDirection; * import universalelectricity.core.block.IElectrical; @@ -71,4 +70,4 @@ * return 0; * } * } - */ \ No newline at end of file + */ diff --git a/src/main/java/appeng/tile/qnb/TileQuantumBridge.java b/src/main/java/appeng/tile/qnb/TileQuantumBridge.java index e06dbf6d160..c3c97867532 100644 --- a/src/main/java/appeng/tile/qnb/TileQuantumBridge.java +++ b/src/main/java/appeng/tile/qnb/TileQuantumBridge.java @@ -18,7 +18,6 @@ package appeng.tile.qnb; - import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; import appeng.api.networking.GridFlags; @@ -41,6 +40,7 @@ import appeng.util.Platform; import com.google.common.base.Optional; import io.netty.buffer.ByteBuf; +import java.util.EnumSet; import net.minecraft.block.Block; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -48,311 +48,266 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - -public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock -{ - private final byte corner = 16; - private final int[] sidesRing = {}; - private final int[] sidesLink = { 0 }; - private final AppEngInternalInventory internalInventory = new AppEngInternalInventory( this, 1 ); - private final byte hasSingularity = 32; - private final byte powered = 64; - - private final QuantumCalculator calc = new QuantumCalculator( this ); - private byte constructed = -1; - private QuantumCluster cluster; - private boolean updateStatus = false; - - public TileQuantumBridge() - { - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - if (AEConfig.instance.quantumBridgeBackboneTransfer) - this.getProxy().setFlags( GridFlags.DENSE_CAPACITY, GridFlags.ULTRA_DENSE_CAPACITY ); - else - this.getProxy().setFlags( GridFlags.DENSE_CAPACITY); - this.getProxy().setIdlePowerUsage( 22 ); - this.internalInventory.setMaxStackSize( 1 ); - } - - @TileEvent( TileEventType.TICK ) - public void onTickEvent() - { - if( this.updateStatus ) - { - if (AEConfig.instance.debugPathFinding) - { - AELog.debug("Pathfinding: QNB at (%d %d %d) is reforming", xCoord, yCoord, zCoord); - } - this.updateStatus = false; - if( this.cluster != null ) - { - this.cluster.updateStatus( true ); - } - this.markForUpdate(); - } - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void onNetworkWriteEvent( final ByteBuf data ) - { - int out = this.constructed; - - if( this.getStackInSlot( 0 ) != null && this.constructed != -1 ) - { - out |= this.hasSingularity; - } - - if( this.getProxy().isActive() && this.constructed != -1 ) - { - out |= this.powered; - } - - data.writeByte( (byte) out ); - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean onNetworkReadEvent( final ByteBuf data ) - { - final int oldValue = this.constructed; - this.constructed = data.readByte(); - return this.constructed != oldValue; - } - - @Override - public IInventory getInternalInventory() - { - return this.internalInventory; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( this.cluster != null ) - { - this.cluster.updateStatus( true ); - } - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - if( this.isCenter() ) - { - return this.sidesLink; - } - return this.sidesRing; - } - - private boolean isCenter() - { - for( final Block link : AEApi.instance().definitions().blocks().quantumLink().maybeBlock().asSet() ) - { - return this.getBlockType() == link; - } - - return false; - } - - @MENetworkEventSubscribe - public void onPowerStatusChange( final MENetworkPowerStatusChange c ) - { - this.updateStatus = true; - } - - @Override - public void onChunkUnload() - { - this.disconnect( false ); - super.onChunkUnload(); - } - - @Override - public void onReady() - { - super.onReady(); - - final IBlockDefinition quantumRing = AEApi.instance().definitions().blocks().quantumRing(); - final Optional maybeLinkBlock = quantumRing.maybeBlock(); - final Optional maybeLinkStack = quantumRing.maybeStack( 1 ); - - final boolean isPresent = maybeLinkBlock.isPresent() && maybeLinkStack.isPresent(); - - if( isPresent && this.getBlockType() == maybeLinkBlock.get() ) - { - final ItemStack linkStack = maybeLinkStack.get(); - - this.getProxy().setVisualRepresentation( linkStack ); - } - } - - @Override - public void invalidate() - { - this.disconnect( false ); - super.invalidate(); - } - - @Override - public void disconnect( final boolean affectWorld ) - { - if( this.cluster != null ) - { - if (AEConfig.instance.debugPathFinding) - { - AELog.debug("Pathfinding: QNB at (%d %d %d) is disconnecting, affectWorld = %b", xCoord, yCoord, zCoord, affectWorld); - } - if( !affectWorld ) - { - this.cluster.setUpdateStatus( false ); - } - - this.cluster.destroy(); - } - - this.cluster = null; - - if( affectWorld ) - { - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - } - } - - @Override - public IAECluster getCluster() - { - return this.cluster; - } - - @Override - public boolean isValid() - { - return !this.isInvalid(); - } - - public void updateStatus( final QuantumCluster c, final byte flags, final boolean affectWorld ) - { - if (AEConfig.instance.debugPathFinding) - { - AELog.debug("Pathfinding: QNB at (%d %d %d) is updating, affectWorld = %b, flags = %d", xCoord, yCoord, zCoord, affectWorld, (int)flags); - } - this.cluster = c; - - if( affectWorld ) - { - if( this.constructed != flags ) - { - this.constructed = flags; - this.markForUpdate(); - } - - if( this.isCorner() || this.isCenter() ) - { - this.getProxy().setValidSides( this.getConnections() ); - } - else - { - this.getProxy().setValidSides( EnumSet.allOf( ForgeDirection.class ) ); - } - } - } - - public boolean isCorner() - { - return ( this.constructed & this.getCorner() ) == this.getCorner() && this.constructed != -1; - } - - public EnumSet getConnections() - { - final EnumSet set = EnumSet.noneOf( ForgeDirection.class ); - - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - final TileEntity te = this.worldObj.getTileEntity( this.xCoord + d.offsetX, this.yCoord + d.offsetY, this.zCoord + d.offsetZ ); - if( te instanceof TileQuantumBridge ) - { - set.add( d ); - } - } - - return set; - } - - public long getQEFrequency() - { - final ItemStack is = this.internalInventory.getStackInSlot( 0 ); - if( is != null ) - { - final NBTTagCompound c = is.getTagCompound(); - if( c != null ) - { - return c.getLong( "freq" ); - } - } - return 0; - } - - public boolean isPowered() - { - if( Platform.isClient() ) - { - return ( this.constructed & this.powered ) == this.powered && this.constructed != -1; - } - - try - { - return this.getProxy().getEnergy().isNetworkPowered(); - } - catch( final GridAccessException e ) - { - // :P - } - - return false; - } - - public boolean isFormed() - { - return this.constructed != -1; - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.DENSE; - } - - public void neighborUpdate() - { - this.calc.calculateMultiblock( this.worldObj, this.getLocation() ); - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - public boolean hasQES() - { - if( this.constructed == -1 ) - { - return false; - } - return ( this.constructed & this.hasSingularity ) == this.hasSingularity; - } - - public void breakCluster() - { - if( this.cluster != null ) - { - this.cluster.destroy(); - } - } - - public byte getCorner() - { - return this.corner; - } +public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock { + private final byte corner = 16; + private final int[] sidesRing = {}; + private final int[] sidesLink = {0}; + private final AppEngInternalInventory internalInventory = new AppEngInternalInventory(this, 1); + private final byte hasSingularity = 32; + private final byte powered = 64; + + private final QuantumCalculator calc = new QuantumCalculator(this); + private byte constructed = -1; + private QuantumCluster cluster; + private boolean updateStatus = false; + + public TileQuantumBridge() { + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + if (AEConfig.instance.quantumBridgeBackboneTransfer) + this.getProxy().setFlags(GridFlags.DENSE_CAPACITY, GridFlags.ULTRA_DENSE_CAPACITY); + else this.getProxy().setFlags(GridFlags.DENSE_CAPACITY); + this.getProxy().setIdlePowerUsage(22); + this.internalInventory.setMaxStackSize(1); + } + + @TileEvent(TileEventType.TICK) + public void onTickEvent() { + if (this.updateStatus) { + if (AEConfig.instance.debugPathFinding) { + AELog.debug("Pathfinding: QNB at (%d %d %d) is reforming", xCoord, yCoord, zCoord); + } + this.updateStatus = false; + if (this.cluster != null) { + this.cluster.updateStatus(true); + } + this.markForUpdate(); + } + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void onNetworkWriteEvent(final ByteBuf data) { + int out = this.constructed; + + if (this.getStackInSlot(0) != null && this.constructed != -1) { + out |= this.hasSingularity; + } + + if (this.getProxy().isActive() && this.constructed != -1) { + out |= this.powered; + } + + data.writeByte((byte) out); + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean onNetworkReadEvent(final ByteBuf data) { + final int oldValue = this.constructed; + this.constructed = data.readByte(); + return this.constructed != oldValue; + } + + @Override + public IInventory getInternalInventory() { + return this.internalInventory; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) { + if (this.cluster != null) { + this.cluster.updateStatus(true); + } + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + if (this.isCenter()) { + return this.sidesLink; + } + return this.sidesRing; + } + + private boolean isCenter() { + for (final Block link : AEApi.instance() + .definitions() + .blocks() + .quantumLink() + .maybeBlock() + .asSet()) { + return this.getBlockType() == link; + } + + return false; + } + + @MENetworkEventSubscribe + public void onPowerStatusChange(final MENetworkPowerStatusChange c) { + this.updateStatus = true; + } + + @Override + public void onChunkUnload() { + this.disconnect(false); + super.onChunkUnload(); + } + + @Override + public void onReady() { + super.onReady(); + + final IBlockDefinition quantumRing = + AEApi.instance().definitions().blocks().quantumRing(); + final Optional maybeLinkBlock = quantumRing.maybeBlock(); + final Optional maybeLinkStack = quantumRing.maybeStack(1); + + final boolean isPresent = maybeLinkBlock.isPresent() && maybeLinkStack.isPresent(); + + if (isPresent && this.getBlockType() == maybeLinkBlock.get()) { + final ItemStack linkStack = maybeLinkStack.get(); + + this.getProxy().setVisualRepresentation(linkStack); + } + } + + @Override + public void invalidate() { + this.disconnect(false); + super.invalidate(); + } + + @Override + public void disconnect(final boolean affectWorld) { + if (this.cluster != null) { + if (AEConfig.instance.debugPathFinding) { + AELog.debug( + "Pathfinding: QNB at (%d %d %d) is disconnecting, affectWorld = %b", + xCoord, yCoord, zCoord, affectWorld); + } + if (!affectWorld) { + this.cluster.setUpdateStatus(false); + } + + this.cluster.destroy(); + } + + this.cluster = null; + + if (affectWorld) { + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + } + } + + @Override + public IAECluster getCluster() { + return this.cluster; + } + + @Override + public boolean isValid() { + return !this.isInvalid(); + } + + public void updateStatus(final QuantumCluster c, final byte flags, final boolean affectWorld) { + if (AEConfig.instance.debugPathFinding) { + AELog.debug( + "Pathfinding: QNB at (%d %d %d) is updating, affectWorld = %b, flags = %d", + xCoord, yCoord, zCoord, affectWorld, (int) flags); + } + this.cluster = c; + + if (affectWorld) { + if (this.constructed != flags) { + this.constructed = flags; + this.markForUpdate(); + } + + if (this.isCorner() || this.isCenter()) { + this.getProxy().setValidSides(this.getConnections()); + } else { + this.getProxy().setValidSides(EnumSet.allOf(ForgeDirection.class)); + } + } + } + + public boolean isCorner() { + return (this.constructed & this.getCorner()) == this.getCorner() && this.constructed != -1; + } + + public EnumSet getConnections() { + final EnumSet set = EnumSet.noneOf(ForgeDirection.class); + + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + final TileEntity te = this.worldObj.getTileEntity( + this.xCoord + d.offsetX, this.yCoord + d.offsetY, this.zCoord + d.offsetZ); + if (te instanceof TileQuantumBridge) { + set.add(d); + } + } + + return set; + } + + public long getQEFrequency() { + final ItemStack is = this.internalInventory.getStackInSlot(0); + if (is != null) { + final NBTTagCompound c = is.getTagCompound(); + if (c != null) { + return c.getLong("freq"); + } + } + return 0; + } + + public boolean isPowered() { + if (Platform.isClient()) { + return (this.constructed & this.powered) == this.powered && this.constructed != -1; + } + + try { + return this.getProxy().getEnergy().isNetworkPowered(); + } catch (final GridAccessException e) { + // :P + } + + return false; + } + + public boolean isFormed() { + return this.constructed != -1; + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.DENSE; + } + + public void neighborUpdate() { + this.calc.calculateMultiblock(this.worldObj, this.getLocation()); + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + public boolean hasQES() { + if (this.constructed == -1) { + return false; + } + return (this.constructed & this.hasSingularity) == this.hasSingularity; + } + + public void breakCluster() { + if (this.cluster != null) { + this.cluster.destroy(); + } + } + + public byte getCorner() { + return this.corner; + } } diff --git a/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java b/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java index 2881cb623bc..8a1fbd1a3e4 100644 --- a/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java +++ b/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java @@ -18,7 +18,6 @@ package appeng.tile.spatial; - import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; import appeng.api.config.YesNo; @@ -47,160 +46,136 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; - -public class TileSpatialIOPort extends AENetworkInvTile implements IWorldCallable -{ - - private final int[] sides = { 0, 1 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 2 ); - private YesNo lastRedstoneState = YesNo.UNDECIDED; - - public TileSpatialIOPort() - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileSpatialIOPort( final NBTTagCompound data ) - { - data.setInteger( "lastRedstoneState", this.lastRedstoneState.ordinal() ); - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileSpatialIOPort( final NBTTagCompound data ) - { - if( data.hasKey( "lastRedstoneState" ) ) - { - this.lastRedstoneState = YesNo.values()[data.getInteger( "lastRedstoneState" )]; - } - } - - public boolean getRedstoneState() - { - if( this.lastRedstoneState == YesNo.UNDECIDED ) - { - this.updateRedstoneState(); - } - - return this.lastRedstoneState == YesNo.YES; - } - - public void updateRedstoneState() - { - final YesNo currentState = this.worldObj.isBlockIndirectlyGettingPowered( this.xCoord, this.yCoord, this.zCoord ) ? YesNo.YES : YesNo.NO; - if( this.lastRedstoneState != currentState ) - { - this.lastRedstoneState = currentState; - if( this.lastRedstoneState == YesNo.YES ) - { - this.triggerTransition(); - } - } - } - - private void triggerTransition() - { - if( Platform.isServer() ) - { - final ItemStack cell = this.getStackInSlot( 0 ); - if( this.isSpatialCell( cell ) ) - { - TickHandler.INSTANCE.addCallable( null, this );// this needs to be cross world synced. - } - } - } - - private boolean isSpatialCell( final ItemStack cell ) - { - if( cell != null && cell.getItem() instanceof ISpatialStorageCell ) - { - final ISpatialStorageCell sc = (ISpatialStorageCell) cell.getItem(); - return sc != null && sc.isSpatialStorage( cell ); - } - return false; - } - - @Override - public Void call( final World world ) throws Exception - { - final ItemStack cell = this.getStackInSlot( 0 ); - if( this.isSpatialCell( cell ) && this.getStackInSlot( 1 ) == null ) - { - final IGrid gi = this.getProxy().getGrid(); - final IEnergyGrid energy = this.getProxy().getEnergy(); - - final ISpatialStorageCell sc = (ISpatialStorageCell) cell.getItem(); - - final SpatialPylonCache spc = gi.getCache( ISpatialCache.class ); - if( spc.hasRegion() && spc.isValidRegion() ) - { - final double req = spc.requiredPower(); - final double pr = energy.extractAEPower( req, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - if( Math.abs( pr - req ) < req * 0.001 ) - { - final MENetworkEvent res = gi.postEvent( new MENetworkSpatialEvent( this, req ) ); - if( !res.isCanceled() ) - { - final TransitionResult tr = sc.doSpatialTransition( cell, this.worldObj, spc.getMin(), spc.getMax(), true ); - if( tr.success ) - { - energy.extractAEPower( req, Actionable.MODULATE, PowerMultiplier.CONFIG ); - this.setInventorySlotContents( 0, null ); - this.setInventorySlotContents( 1, cell ); - } - } - } - } - } - - return null; - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return ( i == 0 && this.isSpatialCell( itemstack ) ); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - - } - - @Override - public boolean canInsertItem( final int slotIndex, final ItemStack insertingItem, final int side ) - { - return this.isItemValidForSlot( slotIndex, insertingItem ); - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - return slotIndex == 1; - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.sides; - } +public class TileSpatialIOPort extends AENetworkInvTile implements IWorldCallable { + + private final int[] sides = {0, 1}; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 2); + private YesNo lastRedstoneState = YesNo.UNDECIDED; + + public TileSpatialIOPort() { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileSpatialIOPort(final NBTTagCompound data) { + data.setInteger("lastRedstoneState", this.lastRedstoneState.ordinal()); + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileSpatialIOPort(final NBTTagCompound data) { + if (data.hasKey("lastRedstoneState")) { + this.lastRedstoneState = YesNo.values()[data.getInteger("lastRedstoneState")]; + } + } + + public boolean getRedstoneState() { + if (this.lastRedstoneState == YesNo.UNDECIDED) { + this.updateRedstoneState(); + } + + return this.lastRedstoneState == YesNo.YES; + } + + public void updateRedstoneState() { + final YesNo currentState = this.worldObj.isBlockIndirectlyGettingPowered(this.xCoord, this.yCoord, this.zCoord) + ? YesNo.YES + : YesNo.NO; + if (this.lastRedstoneState != currentState) { + this.lastRedstoneState = currentState; + if (this.lastRedstoneState == YesNo.YES) { + this.triggerTransition(); + } + } + } + + private void triggerTransition() { + if (Platform.isServer()) { + final ItemStack cell = this.getStackInSlot(0); + if (this.isSpatialCell(cell)) { + TickHandler.INSTANCE.addCallable(null, this); // this needs to be cross world synced. + } + } + } + + private boolean isSpatialCell(final ItemStack cell) { + if (cell != null && cell.getItem() instanceof ISpatialStorageCell) { + final ISpatialStorageCell sc = (ISpatialStorageCell) cell.getItem(); + return sc != null && sc.isSpatialStorage(cell); + } + return false; + } + + @Override + public Void call(final World world) throws Exception { + final ItemStack cell = this.getStackInSlot(0); + if (this.isSpatialCell(cell) && this.getStackInSlot(1) == null) { + final IGrid gi = this.getProxy().getGrid(); + final IEnergyGrid energy = this.getProxy().getEnergy(); + + final ISpatialStorageCell sc = (ISpatialStorageCell) cell.getItem(); + + final SpatialPylonCache spc = gi.getCache(ISpatialCache.class); + if (spc.hasRegion() && spc.isValidRegion()) { + final double req = spc.requiredPower(); + final double pr = energy.extractAEPower(req, Actionable.SIMULATE, PowerMultiplier.CONFIG); + if (Math.abs(pr - req) < req * 0.001) { + final MENetworkEvent res = gi.postEvent(new MENetworkSpatialEvent(this, req)); + if (!res.isCanceled()) { + final TransitionResult tr = + sc.doSpatialTransition(cell, this.worldObj, spc.getMin(), spc.getMax(), true); + if (tr.success) { + energy.extractAEPower(req, Actionable.MODULATE, PowerMultiplier.CONFIG); + this.setInventorySlotContents(0, null); + this.setInventorySlotContents(1, cell); + } + } + } + } + } + + return null; + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + @Override + public IInventory getInternalInventory() { + return this.inv; + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return (i == 0 && this.isSpatialCell(itemstack)); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) {} + + @Override + public boolean canInsertItem(final int slotIndex, final ItemStack insertingItem, final int side) { + return this.isItemValidForSlot(slotIndex, insertingItem); + } + + @Override + public boolean canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + return slotIndex == 1; + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return this.sides; + } } diff --git a/src/main/java/appeng/tile/spatial/TileSpatialPylon.java b/src/main/java/appeng/tile/spatial/TileSpatialPylon.java index 452dd58c90c..932bd35d6c0 100644 --- a/src/main/java/appeng/tile/spatial/TileSpatialPylon.java +++ b/src/main/java/appeng/tile/spatial/TileSpatialPylon.java @@ -18,7 +18,6 @@ package appeng.tile.spatial; - import appeng.api.networking.GridFlags; import appeng.api.networking.events.MENetworkChannelsChanged; import appeng.api.networking.events.MENetworkEventSubscribe; @@ -33,216 +32,179 @@ import appeng.tile.events.TileEventType; import appeng.tile.grid.AENetworkTile; import io.netty.buffer.ByteBuf; -import net.minecraftforge.common.util.ForgeDirection; - import java.util.EnumSet; +import net.minecraftforge.common.util.ForgeDirection; - -public class TileSpatialPylon extends AENetworkTile implements IAEMultiBlock -{ - - public static final int DISPLAY_END_MIN = 0x01; - public static final int DISPLAY_END_MAX = 0x02; - public static final int DISPLAY_MIDDLE = 0x01 + 0x02; - public static final int DISPLAY_X = 0x04; - public static final int DISPLAY_Y = 0x08; - public static final int DISPLAY_Z = 0x04 + 0x08; - public static final int MB_STATUS = 0x01 + 0x02 + 0x04 + 0x08; - - public static final int DISPLAY_ENABLED = 0x10; - public static final int DISPLAY_POWERED_ENABLED = 0x20; - public static final int NET_STATUS = 0x10 + 0x20; - - private final SpatialPylonCalculator calc = new SpatialPylonCalculator( this ); - private int displayBits = 0; - private SpatialPylonCluster cluster; - private boolean didHaveLight = false; - - public TileSpatialPylon() - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL, GridFlags.MULTIBLOCK ); - this.getProxy().setIdlePowerUsage( 0.5 ); - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - } - - @Override - protected AENetworkProxy createProxy() - { - return new AENetworkProxyMultiblock( this, "proxy", this.getItemFromTile( this ), true ); - } - - @Override - public void onChunkUnload() - { - this.disconnect( false ); - super.onChunkUnload(); - } - - @Override - public void onReady() - { - super.onReady(); - this.onNeighborBlockChange(); - } - - @Override - public void invalidate() - { - this.disconnect( false ); - super.invalidate(); - } - - public void onNeighborBlockChange() - { - this.calc.calculateMultiblock( this.worldObj, this.getLocation() ); - } - - @Override - public void disconnect( final boolean b ) - { - if( this.cluster != null ) - { - this.cluster.destroy(); - this.updateStatus( null ); - } - } - - @Override - public SpatialPylonCluster getCluster() - { - return this.cluster; - } - - @Override - public boolean isValid() - { - return true; - } - - public void updateStatus( final SpatialPylonCluster c ) - { - this.cluster = c; - this.getProxy().setValidSides( c == null ? EnumSet.noneOf( ForgeDirection.class ) : EnumSet.allOf( ForgeDirection.class ) ); - this.recalculateDisplay(); - } - - public void recalculateDisplay() - { - final int oldBits = this.displayBits; - - this.displayBits = 0; - - if( this.cluster != null ) - { - if( this.cluster.getMin().equals( this.getLocation() ) ) - { - this.displayBits = DISPLAY_END_MIN; - } - else if( this.cluster.getMax().equals( this.getLocation() ) ) - { - this.displayBits = DISPLAY_END_MAX; - } - else - { - this.displayBits = DISPLAY_MIDDLE; - } - - switch( this.cluster.getCurrentAxis() ) - { - case X: - this.displayBits |= DISPLAY_X; - break; - case Y: - this.displayBits |= DISPLAY_Y; - break; - case Z: - this.displayBits |= DISPLAY_Z; - break; - default: - this.displayBits = 0; - break; - } - - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - this.displayBits |= DISPLAY_POWERED_ENABLED; - } - - if( this.cluster.isValid() && this.getProxy().isActive() ) - { - this.displayBits |= DISPLAY_ENABLED; - } - } - catch( final GridAccessException e ) - { - // nothing? - } - } - - if( oldBits != this.displayBits ) - { - this.markForUpdate(); - } - } - - @Override - public void markForUpdate() - { - super.markForUpdate(); - final boolean hasLight = this.getLightValue() > 0; - if( hasLight != this.didHaveLight ) - { - this.didHaveLight = hasLight; - this.worldObj.func_147451_t( this.xCoord, this.yCoord, this.zCoord ); - // worldObj.updateAllLightTypes( xCoord, yCoord, zCoord ); - } - } - - @Override - public boolean canBeRotated() - { - return false; - } - - public int getLightValue() - { - if( ( this.displayBits & DISPLAY_POWERED_ENABLED ) == DISPLAY_POWERED_ENABLED ) - { - return 8; - } - return 0; - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileSpatialPylon( final ByteBuf data ) - { - final int old = this.displayBits; - this.displayBits = data.readByte(); - return old != this.displayBits; - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileSpatialPylon( final ByteBuf data ) - { - data.writeByte( this.displayBits ); - } - - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.recalculateDisplay(); - } - - @MENetworkEventSubscribe - public void activeRender( final MENetworkChannelsChanged c ) - { - this.recalculateDisplay(); - } - - public int getDisplayBits() - { - return this.displayBits; - } +public class TileSpatialPylon extends AENetworkTile implements IAEMultiBlock { + + public static final int DISPLAY_END_MIN = 0x01; + public static final int DISPLAY_END_MAX = 0x02; + public static final int DISPLAY_MIDDLE = 0x01 + 0x02; + public static final int DISPLAY_X = 0x04; + public static final int DISPLAY_Y = 0x08; + public static final int DISPLAY_Z = 0x04 + 0x08; + public static final int MB_STATUS = 0x01 + 0x02 + 0x04 + 0x08; + + public static final int DISPLAY_ENABLED = 0x10; + public static final int DISPLAY_POWERED_ENABLED = 0x20; + public static final int NET_STATUS = 0x10 + 0x20; + + private final SpatialPylonCalculator calc = new SpatialPylonCalculator(this); + private int displayBits = 0; + private SpatialPylonCluster cluster; + private boolean didHaveLight = false; + + public TileSpatialPylon() { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL, GridFlags.MULTIBLOCK); + this.getProxy().setIdlePowerUsage(0.5); + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + } + + @Override + protected AENetworkProxy createProxy() { + return new AENetworkProxyMultiblock(this, "proxy", this.getItemFromTile(this), true); + } + + @Override + public void onChunkUnload() { + this.disconnect(false); + super.onChunkUnload(); + } + + @Override + public void onReady() { + super.onReady(); + this.onNeighborBlockChange(); + } + + @Override + public void invalidate() { + this.disconnect(false); + super.invalidate(); + } + + public void onNeighborBlockChange() { + this.calc.calculateMultiblock(this.worldObj, this.getLocation()); + } + + @Override + public void disconnect(final boolean b) { + if (this.cluster != null) { + this.cluster.destroy(); + this.updateStatus(null); + } + } + + @Override + public SpatialPylonCluster getCluster() { + return this.cluster; + } + + @Override + public boolean isValid() { + return true; + } + + public void updateStatus(final SpatialPylonCluster c) { + this.cluster = c; + this.getProxy() + .setValidSides(c == null ? EnumSet.noneOf(ForgeDirection.class) : EnumSet.allOf(ForgeDirection.class)); + this.recalculateDisplay(); + } + + public void recalculateDisplay() { + final int oldBits = this.displayBits; + + this.displayBits = 0; + + if (this.cluster != null) { + if (this.cluster.getMin().equals(this.getLocation())) { + this.displayBits = DISPLAY_END_MIN; + } else if (this.cluster.getMax().equals(this.getLocation())) { + this.displayBits = DISPLAY_END_MAX; + } else { + this.displayBits = DISPLAY_MIDDLE; + } + + switch (this.cluster.getCurrentAxis()) { + case X: + this.displayBits |= DISPLAY_X; + break; + case Y: + this.displayBits |= DISPLAY_Y; + break; + case Z: + this.displayBits |= DISPLAY_Z; + break; + default: + this.displayBits = 0; + break; + } + + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + this.displayBits |= DISPLAY_POWERED_ENABLED; + } + + if (this.cluster.isValid() && this.getProxy().isActive()) { + this.displayBits |= DISPLAY_ENABLED; + } + } catch (final GridAccessException e) { + // nothing? + } + } + + if (oldBits != this.displayBits) { + this.markForUpdate(); + } + } + + @Override + public void markForUpdate() { + super.markForUpdate(); + final boolean hasLight = this.getLightValue() > 0; + if (hasLight != this.didHaveLight) { + this.didHaveLight = hasLight; + this.worldObj.func_147451_t(this.xCoord, this.yCoord, this.zCoord); + // worldObj.updateAllLightTypes( xCoord, yCoord, zCoord ); + } + } + + @Override + public boolean canBeRotated() { + return false; + } + + public int getLightValue() { + if ((this.displayBits & DISPLAY_POWERED_ENABLED) == DISPLAY_POWERED_ENABLED) { + return 8; + } + return 0; + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileSpatialPylon(final ByteBuf data) { + final int old = this.displayBits; + this.displayBits = data.readByte(); + return old != this.displayBits; + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileSpatialPylon(final ByteBuf data) { + data.writeByte(this.displayBits); + } + + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.recalculateDisplay(); + } + + @MENetworkEventSubscribe + public void activeRender(final MENetworkChannelsChanged c) { + this.recalculateDisplay(); + } + + public int getDisplayBits() { + return this.displayBits; + } } diff --git a/src/main/java/appeng/tile/storage/TileChest.java b/src/main/java/appeng/tile/storage/TileChest.java index f27a20c6328..1edfef5f63c 100644 --- a/src/main/java/appeng/tile/storage/TileChest.java +++ b/src/main/java/appeng/tile/storage/TileChest.java @@ -18,7 +18,6 @@ package appeng.tile.storage; - import appeng.api.AEApi; import appeng.api.config.*; import appeng.api.implementations.tiles.IColorableTile; @@ -51,6 +50,9 @@ import appeng.util.Platform; import appeng.util.item.AEFluidStack; import io.netty.buffer.ByteBuf; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; @@ -62,907 +64,724 @@ import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - - -public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHandler, ITerminalHost, IPriorityHost, IConfigManagerHost, IColorableTile -{ - - private static final ChestNoHandler NO_HANDLER = new ChestNoHandler(); - private static final int[] SIDES = { 0 }; - private static final int[] FRONT = { 1 }; - private static final int[] NO_SLOTS = {}; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 2 ); - private final BaseActionSource mySrc = new MachineSource( this ); - private final IConfigManager config = new ConfigManager( this ); - private ItemStack storageType; - private long lastStateChange = 0; - private int priority = 0; - private int state = 0; - private boolean wasActive = false; - private AEColor paintedColor = AEColor.Transparent; - private boolean isCached = false; - private ICellHandler cellHandler; - private MEMonitorHandler itemCell; - private MEMonitorHandler fluidCell; - - public TileChest() - { - this.setInternalMaxPower( PowerMultiplier.CONFIG.multiply( 40 ) ); - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.config.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - this.config.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - this.config.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); - - this.setInternalPublicPowerStorage( true ); - this.setInternalPowerFlow( AccessRestriction.WRITE ); - } - - @Override - protected void PowerEvent( final PowerEventType x ) - { - if( x == PowerEventType.REQUEST_POWER ) - { - try - { - this.getProxy().getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.REQUEST_POWER ) ); - } - catch( final GridAccessException e ) - { - // :( - } - } - else - { - this.recalculateDisplay(); - } - } - - private void recalculateDisplay() - { - final int oldState = this.state; - - for( int x = 0; x < this.getCellCount(); x++ ) - { - this.state |= ( this.getCellStatus( x ) << ( 3 * x ) ); - } - - if( this.isPowered() ) - { - this.state |= 0x40; - } - else - { - this.state &= ~0x40; - } - - final boolean currentActive = this.getProxy().isActive(); - if( this.wasActive != currentActive ) - { - this.wasActive = currentActive; - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - if( oldState != this.state ) - { - this.markForUpdate(); - } - } - - @Override - public int getCellCount() - { - return 1; - } - - private IMEInventoryHandler getHandler( final StorageChannel channel ) throws ChestNoHandler - { - if( !this.isCached ) - { - this.itemCell = null; - this.fluidCell = null; - - final ItemStack is = this.inv.getStackInSlot( 1 ); - if( is != null ) - { - this.isCached = true; - this.cellHandler = AEApi.instance().registries().cell().getHandler( is ); - if( this.cellHandler != null ) - { - double power = 1.0; - - final IMEInventoryHandler itemCell = this.cellHandler.getCellInventory( is, this, StorageChannel.ITEMS ); - final IMEInventoryHandler fluidCell = this.cellHandler.getCellInventory( is, this, StorageChannel.FLUIDS ); - - if( itemCell != null ) - { - power += this.cellHandler.cellIdleDrain( is, itemCell ); - } - else if( fluidCell != null ) - { - power += this.cellHandler.cellIdleDrain( is, fluidCell ); - } - - this.getProxy().setIdlePowerUsage( power ); - - this.itemCell = this.wrap( itemCell ); - this.fluidCell = this.wrap( fluidCell ); - } - } - } - - switch( channel ) - { - case FLUIDS: - if( this.fluidCell == null ) - { - throw NO_HANDLER; - } - return this.fluidCell; - case ITEMS: - if( this.itemCell == null ) - { - throw NO_HANDLER; - } - return this.itemCell; - default: - } - - return null; - } - - private MEMonitorHandler wrap( final IMEInventoryHandler h ) - { - if( h == null ) - { - return null; - } - - final MEInventoryHandler ih = new MEInventoryHandler( h, h.getChannel() ); - ih.setPriority( this.priority ); - - final MEMonitorHandler g = new ChestMonitorHandler( ih ); - g.addListener( new ChestNetNotifier( h.getChannel() ), g ); - - return g; - } - - @Override - public int getCellStatus( final int slot ) - { - if( Platform.isClient() ) - { - return ( this.state >> ( slot * 3 ) ) & 3; - } - - final ItemStack cell = this.inv.getStackInSlot( 1 ); - final ICellHandler ch = AEApi.instance().registries().cell().getHandler( cell ); - - if( ch != null ) - { - try - { - final IMEInventoryHandler handler = this.getHandler( StorageChannel.ITEMS ); - if( handler instanceof ChestMonitorHandler ) - { - return ch.getStatusForCell( cell, ( (ChestMonitorHandler) handler ).getInternalHandler() ); - } - } - catch( final ChestNoHandler ignored ) - { - } - - try - { - final IMEInventoryHandler handler = this.getHandler( StorageChannel.FLUIDS ); - if( handler instanceof ChestMonitorHandler ) - { - return ch.getStatusForCell( cell, ( (ChestMonitorHandler) handler ).getInternalHandler() ); - } - } - catch( final ChestNoHandler ignored ) - { - } - } - - return 0; - } - - @Override - public boolean isPowered() - { - if( Platform.isClient() ) - { - return ( this.state & 0x40 ) == 0x40; - } - - boolean gridPowered = this.getAECurrentPower() > 64; - - if( !gridPowered ) - { - try - { - gridPowered = this.getProxy().getEnergy().isNetworkPowered(); - } - catch( final GridAccessException ignored ) - { - } - } - - return super.getAECurrentPower() > 1 || gridPowered; - } - - @Override - public boolean isCellBlinking( final int slot ) - { - final long now = this.worldObj.getTotalWorldTime(); - if( now - this.lastStateChange > 8 ) - { - return false; - } - - return ( ( this.state >> ( slot * 3 + 2 ) ) & 0x01 ) == 0x01; - } - - @Override - protected double extractAEPower( final double amt, final Actionable mode ) - { - double stash = 0.0; - - try - { - final IEnergyGrid eg = this.getProxy().getEnergy(); - stash = eg.extractAEPower( amt, mode, PowerMultiplier.ONE ); - if( stash >= amt ) - { - return stash; - } - } - catch( final GridAccessException e ) - { - // no grid :( - } - - // local battery! - return super.extractAEPower( amt - stash, mode ) + stash; - } - - @TileEvent( TileEventType.TICK ) - public void Tick_TileChest() - { - if( this.worldObj.isRemote ) - { - return; - } - - final double idleUsage = this.getProxy().getIdlePowerUsage(); - - try - { - if( !this.getProxy().getEnergy().isNetworkPowered() ) - { - final double powerUsed = this.extractAEPower( idleUsage, Actionable.MODULATE, PowerMultiplier.CONFIG ); // drain - if( powerUsed + 0.1 >= idleUsage != ( this.state & 0x40 ) > 0 ) - { - this.recalculateDisplay(); - } - } - } - catch( final GridAccessException e ) - { - final double powerUsed = this.extractAEPower( this.getProxy().getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG ); // drain - if( powerUsed + 0.1 >= idleUsage != ( this.state & 0x40 ) > 0 ) - { - this.recalculateDisplay(); - } - } - - if( this.inv.getStackInSlot( 0 ) != null ) - { - this.tryToStoreContents(); - } - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileChest( final ByteBuf data ) - { - if( this.worldObj.getTotalWorldTime() - this.lastStateChange > 8 ) - { - this.state = 0; - } - else - { - this.state &= 0x24924924; // just keep the blinks... - } - - for( int x = 0; x < this.getCellCount(); x++ ) - { - this.state |= ( this.getCellStatus( x ) << ( 3 * x ) ); - } - - if( this.isPowered() ) - { - this.state |= 0x40; - } - else - { - this.state &= ~0x40; - } - - data.writeByte( this.state ); - data.writeByte( this.paintedColor.ordinal() ); - - final ItemStack is = this.inv.getStackInSlot( 1 ); - - if( is == null ) - { - data.writeInt( 0 ); - } - else - { - data.writeInt( ( is.getItemDamage() << Platform.DEF_OFFSET ) | Item.getIdFromItem( is.getItem() ) ); - } - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileChest( final ByteBuf data ) - { - final int oldState = this.state; - final ItemStack oldType = this.storageType; - - this.state = data.readByte(); - final AEColor oldPaintedColor = this.paintedColor; - this.paintedColor = AEColor.values()[data.readByte()]; - - final int item = data.readInt(); - - if( item == 0 ) - { - this.storageType = null; - } - else - { - this.storageType = new ItemStack( Item.getItemById( item & 0xffff ), 1, item >> Platform.DEF_OFFSET ); - } - - this.lastStateChange = this.worldObj.getTotalWorldTime(); - - return oldPaintedColor != this.paintedColor || ( this.state & 0xDB6DB6DB ) != ( oldState & 0xDB6DB6DB ) || !Platform.isSameItemPrecise( oldType, this.storageType ); - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileChest( final NBTTagCompound data ) - { - this.config.readFromNBT( data ); - this.priority = data.getInteger( "priority" ); - if( data.hasKey( "paintedColor" ) ) - { - this.paintedColor = AEColor.values()[data.getByte( "paintedColor" )]; - } - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileChest( final NBTTagCompound data ) - { - this.config.writeToNBT( data ); - data.setInteger( "priority", this.priority ); - data.setByte( "paintedColor", (byte) this.paintedColor.ordinal() ); - } - - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.recalculateDisplay(); - } - - @MENetworkEventSubscribe - public void channelRender( final MENetworkChannelsChanged c ) - { - this.recalculateDisplay(); - } - - @Override - public IMEMonitor getItemInventory() - { - return this.itemCell; - } - - @Override - public IMEMonitor getFluidInventory() - { - return this.fluidCell; - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - this.inv.setInventorySlotContents( i, itemstack ); - this.tryToStoreContents(); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( slot == 1 ) - { - this.itemCell = null; - this.fluidCell = null; - this.isCached = false; // recalculate the storage cell. - - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - - final IStorageGrid gs = this.getProxy().getStorage(); - Platform.postChanges( gs, removed, added, this.mySrc ); - } - catch( final GridAccessException ignored ) - { - - } - - // update the neighbors - if( this.worldObj != null ) - { - Platform.notifyBlocksOfNeighbors( this.worldObj, this.xCoord, this.yCoord, this.zCoord ); - this.markForUpdate(); - } - } - } - - @Override - public boolean canInsertItem( final int slotIndex, final ItemStack insertingItem, final int side ) - { - if( slotIndex == 1 ) - { - if( AEApi.instance().registries().cell().getCellInventory( insertingItem, this, StorageChannel.ITEMS ) != null ) - { - return true; - } - if( AEApi.instance().registries().cell().getCellInventory( insertingItem, this, StorageChannel.FLUIDS ) != null ) - { - return true; - } - } - else - { - try - { - final IMEInventory cell = this.getHandler( StorageChannel.ITEMS ); - final IAEItemStack returns = cell.injectItems( AEApi.instance().storage().createItemStack( this.inv.getStackInSlot( 0 ) ), Actionable.SIMULATE, this.mySrc ); - return returns == null || returns.getStackSize() != insertingItem.stackSize; - } - catch( final ChestNoHandler ignored ) - { - } - } - return false; - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - return slotIndex == 1; - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - if( ForgeDirection.SOUTH == side ) - { - return FRONT; - } - - if( this.isPowered() ) - { - try - { - if( this.getHandler( StorageChannel.ITEMS ) != null ) - { - return SIDES; - } - } - catch( final ChestNoHandler e ) - { - // nope! - } - } - return NO_SLOTS; - } - - private void tryToStoreContents() - { - try - { - if( this.getStackInSlot( 0 ) != null ) - { - final IMEInventory cell = this.getHandler( StorageChannel.ITEMS ); - - final IAEItemStack returns = Platform.poweredInsert( this, cell, AEApi.instance().storage().createItemStack( this.inv.getStackInSlot( 0 ) ), this.mySrc ); - - if( returns == null ) - { - this.inv.setInventorySlotContents( 0, null ); - } - else - { - this.inv.setInventorySlotContents( 0, returns.getItemStack() ); - } - } - } - catch( final ChestNoHandler ignored ) - { - } - } - - @Override - public List getCellArray( final StorageChannel channel ) - { - if( this.getProxy().isActive() ) - { - try - { - return Collections.singletonList( this.getHandler( channel ) ); - } - catch( final ChestNoHandler e ) - { - // :P - } - } - return new ArrayList(); - } - - @Override - public int getPriority() - { - return this.priority; - } - - @Override - public void setPriority( final int newValue ) - { - this.priority = newValue; - - this.itemCell = null; - this.fluidCell = null; - this.isCached = false; // recalculate the storage cell. - - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - @Override - public void blinkCell( final int slot ) - { - final long now = this.worldObj.getTotalWorldTime(); - if( now - this.lastStateChange > 8 ) - { - this.state = 0; - } - this.lastStateChange = now; - - this.state |= 1 << ( slot * 3 + 2 ); - - this.recalculateDisplay(); - } - - @Override - public int fill( final ForgeDirection from, final FluidStack resource, final boolean doFill ) - { - final double req = resource.amount / 500.0; - final double available = this.extractAEPower( req, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - if( available >= req - 0.01 ) - { - try - { - final IMEInventoryHandler h = this.getHandler( StorageChannel.FLUIDS ); - - this.extractAEPower( req, Actionable.MODULATE, PowerMultiplier.CONFIG ); - final IAEStack results = h.injectItems( AEFluidStack.create( resource ), doFill ? Actionable.MODULATE : Actionable.SIMULATE, this.mySrc ); - - if( results == null ) - { - return resource.amount; - } - - return resource.amount - (int) results.getStackSize(); - } - catch( final ChestNoHandler ignored ) - { - } - } - return 0; - } - - @Override - public FluidStack drain( final ForgeDirection from, final FluidStack resource, final boolean doDrain ) - { - return null; - } - - @Override - public FluidStack drain( final ForgeDirection from, final int maxDrain, final boolean doDrain ) - { - return null; - } - - @Override - public boolean canFill( final ForgeDirection from, final Fluid fluid ) - { - try - { - final IMEInventoryHandler h = this.getHandler( StorageChannel.FLUIDS ); - return h.canAccept( AEFluidStack.create( new FluidStack( fluid, 1 ) ) ); - } - catch( final ChestNoHandler ignored ) - { - } - return false; - } - - @Override - public boolean canDrain( final ForgeDirection from, final Fluid fluid ) - { - return false; - } - - @Override - public FluidTankInfo[] getTankInfo( final ForgeDirection from ) - { - try - { - final IMEInventoryHandler h = this.getHandler( StorageChannel.FLUIDS ); - if( h.getChannel() == StorageChannel.FLUIDS ) - { - return new FluidTankInfo[] { new FluidTankInfo( null, 1 ) }; // eh? - } - } - catch( final ChestNoHandler ignored ) - { - } - - return null; - } - - @Override - public IStorageMonitorable getMonitorable( final ForgeDirection side, final BaseActionSource src ) - { - if( Platform.canAccess( this.getProxy(), src ) && side != this.getForward() ) - { - return this; - } - return null; - } - - public ItemStack getStorageType() - { - if( this.isPowered() ) - { - return this.storageType; - } - return null; - } - - @Override - public IConfigManager getConfigManager() - { - return this.config; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - - } - - public boolean openGui( final EntityPlayer p, final ICellHandler ch, final ItemStack cell, final int side ) - { - try - { - final IMEInventoryHandler invHandler = this.getHandler( StorageChannel.ITEMS ); - if( ch != null && invHandler != null ) - { - ch.openChestGui( p, this, ch, invHandler, cell, StorageChannel.ITEMS ); - return true; - } - } - catch( final ChestNoHandler e ) - { - // :P - } - - try - { - final IMEInventoryHandler invHandler = this.getHandler( StorageChannel.FLUIDS ); - if( ch != null && invHandler != null ) - { - ch.openChestGui( p, this, ch, invHandler, cell, StorageChannel.FLUIDS ); - return true; - } - } - catch( final ChestNoHandler e ) - { - // :P - } - - return false; - } - - @Override - public AEColor getColor() - { - return this.paintedColor; - } - - @Override - public boolean recolourBlock( final ForgeDirection side, final AEColor newPaintedColor, final EntityPlayer who ) - { - if( this.paintedColor == newPaintedColor ) - { - return false; - } - - this.paintedColor = newPaintedColor; - this.markDirty(); - this.markForUpdate(); - return true; - } - - @Override - public void saveChanges( final IMEInventory cellInventory ) - { - this.worldObj.markTileEntityChunkModified( this.xCoord, this.yCoord, this.zCoord, this ); - } - - private static class ChestNoHandler extends Exception - { - private static final long serialVersionUID = 7995805326136526631L; - } - - - private class ChestNetNotifier> implements IMEMonitorHandlerReceiver - { - - private final StorageChannel chan; - - public ChestNetNotifier( final StorageChannel chan ) - { - this.chan = chan; - } - - @Override - public boolean isValid( final Object verificationToken ) - { - if( this.chan == StorageChannel.ITEMS ) - { - return verificationToken == TileChest.this.itemCell; - } - if( this.chan == StorageChannel.FLUIDS ) - { - return verificationToken == TileChest.this.fluidCell; - } - return false; - } - - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final BaseActionSource source ) - { - if( source == TileChest.this.mySrc || ( source instanceof PlayerSource && ( (PlayerSource) source ).via == TileChest.this ) ) - { - try - { - if( TileChest.this.getProxy().isActive() ) - { - TileChest.this.getProxy().getStorage().postAlterationOfStoredItems( this.chan, change, TileChest.this.mySrc ); - } - } - catch( final GridAccessException e ) - { - // :( - } - } - - TileChest.this.blinkCell( 0 ); - } - - @Override - public void onListUpdate() - { - // not used here - } - } - - - private class ChestMonitorHandler extends MEMonitorHandler - { - - public ChestMonitorHandler( final IMEInventoryHandler t ) - { - super( t ); - } - - private IMEInventoryHandler getInternalHandler() - { - final IMEInventoryHandler h = this.getHandler(); - if( h instanceof MEInventoryHandler ) - { - return (IMEInventoryHandler) ( (MEInventoryHandler) h ).getInternal(); - } - return this.getHandler(); - } - - @Override - public T injectItems( final T input, final Actionable mode, final BaseActionSource src ) - { - if( src.isPlayer() && !this.securityCheck( ( (PlayerSource) src ).player, SecurityPermissions.INJECT ) ) - { - return input; - } - return super.injectItems( input, mode, src ); - } - - private boolean securityCheck( final EntityPlayer player, final SecurityPermissions requiredPermission ) - { - if( TileChest.this.getTile() instanceof IActionHost && requiredPermission != null ) - { - final IGridNode gn = ( (IActionHost) TileChest.this.getTile() ).getActionableNode(); - if( gn != null ) - { - final IGrid g = gn.getGrid(); - if( g != null ) - { - final boolean requirePower = false; - if( requirePower ) - { - final IEnergyGrid eg = g.getCache( IEnergyGrid.class ); - if( !eg.isNetworkPowered() ) - { - return false; - } - } - - final ISecurityGrid sg = g.getCache( ISecurityGrid.class ); - if( sg.hasPermission( player, requiredPermission ) ) - { - return true; - } - } - } - - return false; - } - return true; - } - - @Override - public T extractItems( final T request, final Actionable mode, final BaseActionSource src ) - { - if( src.isPlayer() && !this.securityCheck( ( (PlayerSource) src ).player, SecurityPermissions.EXTRACT ) ) - { - return null; - } - return super.extractItems( request, mode, src ); - } - } +public class TileChest extends AENetworkPowerTile + implements IMEChest, IFluidHandler, ITerminalHost, IPriorityHost, IConfigManagerHost, IColorableTile { + + private static final ChestNoHandler NO_HANDLER = new ChestNoHandler(); + private static final int[] SIDES = {0}; + private static final int[] FRONT = {1}; + private static final int[] NO_SLOTS = {}; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 2); + private final BaseActionSource mySrc = new MachineSource(this); + private final IConfigManager config = new ConfigManager(this); + private ItemStack storageType; + private long lastStateChange = 0; + private int priority = 0; + private int state = 0; + private boolean wasActive = false; + private AEColor paintedColor = AEColor.Transparent; + private boolean isCached = false; + private ICellHandler cellHandler; + private MEMonitorHandler itemCell; + private MEMonitorHandler fluidCell; + + public TileChest() { + this.setInternalMaxPower(PowerMultiplier.CONFIG.multiply(40)); + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.config.registerSetting(Settings.SORT_BY, SortOrder.NAME); + this.config.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + this.config.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); + + this.setInternalPublicPowerStorage(true); + this.setInternalPowerFlow(AccessRestriction.WRITE); + } + + @Override + protected void PowerEvent(final PowerEventType x) { + if (x == PowerEventType.REQUEST_POWER) { + try { + this.getProxy().getGrid().postEvent(new MENetworkPowerStorage(this, PowerEventType.REQUEST_POWER)); + } catch (final GridAccessException e) { + // :( + } + } else { + this.recalculateDisplay(); + } + } + + private void recalculateDisplay() { + final int oldState = this.state; + + for (int x = 0; x < this.getCellCount(); x++) { + this.state |= (this.getCellStatus(x) << (3 * x)); + } + + if (this.isPowered()) { + this.state |= 0x40; + } else { + this.state &= ~0x40; + } + + final boolean currentActive = this.getProxy().isActive(); + if (this.wasActive != currentActive) { + this.wasActive = currentActive; + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } + + if (oldState != this.state) { + this.markForUpdate(); + } + } + + @Override + public int getCellCount() { + return 1; + } + + private IMEInventoryHandler getHandler(final StorageChannel channel) throws ChestNoHandler { + if (!this.isCached) { + this.itemCell = null; + this.fluidCell = null; + + final ItemStack is = this.inv.getStackInSlot(1); + if (is != null) { + this.isCached = true; + this.cellHandler = AEApi.instance().registries().cell().getHandler(is); + if (this.cellHandler != null) { + double power = 1.0; + + final IMEInventoryHandler itemCell = + this.cellHandler.getCellInventory(is, this, StorageChannel.ITEMS); + final IMEInventoryHandler fluidCell = + this.cellHandler.getCellInventory(is, this, StorageChannel.FLUIDS); + + if (itemCell != null) { + power += this.cellHandler.cellIdleDrain(is, itemCell); + } else if (fluidCell != null) { + power += this.cellHandler.cellIdleDrain(is, fluidCell); + } + + this.getProxy().setIdlePowerUsage(power); + + this.itemCell = this.wrap(itemCell); + this.fluidCell = this.wrap(fluidCell); + } + } + } + + switch (channel) { + case FLUIDS: + if (this.fluidCell == null) { + throw NO_HANDLER; + } + return this.fluidCell; + case ITEMS: + if (this.itemCell == null) { + throw NO_HANDLER; + } + return this.itemCell; + default: + } + + return null; + } + + private MEMonitorHandler wrap(final IMEInventoryHandler h) { + if (h == null) { + return null; + } + + final MEInventoryHandler ih = new MEInventoryHandler(h, h.getChannel()); + ih.setPriority(this.priority); + + final MEMonitorHandler g = new ChestMonitorHandler(ih); + g.addListener(new ChestNetNotifier(h.getChannel()), g); + + return g; + } + + @Override + public int getCellStatus(final int slot) { + if (Platform.isClient()) { + return (this.state >> (slot * 3)) & 3; + } + + final ItemStack cell = this.inv.getStackInSlot(1); + final ICellHandler ch = AEApi.instance().registries().cell().getHandler(cell); + + if (ch != null) { + try { + final IMEInventoryHandler handler = this.getHandler(StorageChannel.ITEMS); + if (handler instanceof ChestMonitorHandler) { + return ch.getStatusForCell(cell, ((ChestMonitorHandler) handler).getInternalHandler()); + } + } catch (final ChestNoHandler ignored) { + } + + try { + final IMEInventoryHandler handler = this.getHandler(StorageChannel.FLUIDS); + if (handler instanceof ChestMonitorHandler) { + return ch.getStatusForCell(cell, ((ChestMonitorHandler) handler).getInternalHandler()); + } + } catch (final ChestNoHandler ignored) { + } + } + + return 0; + } + + @Override + public boolean isPowered() { + if (Platform.isClient()) { + return (this.state & 0x40) == 0x40; + } + + boolean gridPowered = this.getAECurrentPower() > 64; + + if (!gridPowered) { + try { + gridPowered = this.getProxy().getEnergy().isNetworkPowered(); + } catch (final GridAccessException ignored) { + } + } + + return super.getAECurrentPower() > 1 || gridPowered; + } + + @Override + public boolean isCellBlinking(final int slot) { + final long now = this.worldObj.getTotalWorldTime(); + if (now - this.lastStateChange > 8) { + return false; + } + + return ((this.state >> (slot * 3 + 2)) & 0x01) == 0x01; + } + + @Override + protected double extractAEPower(final double amt, final Actionable mode) { + double stash = 0.0; + + try { + final IEnergyGrid eg = this.getProxy().getEnergy(); + stash = eg.extractAEPower(amt, mode, PowerMultiplier.ONE); + if (stash >= amt) { + return stash; + } + } catch (final GridAccessException e) { + // no grid :( + } + + // local battery! + return super.extractAEPower(amt - stash, mode) + stash; + } + + @TileEvent(TileEventType.TICK) + public void Tick_TileChest() { + if (this.worldObj.isRemote) { + return; + } + + final double idleUsage = this.getProxy().getIdlePowerUsage(); + + try { + if (!this.getProxy().getEnergy().isNetworkPowered()) { + final double powerUsed = + this.extractAEPower(idleUsage, Actionable.MODULATE, PowerMultiplier.CONFIG); // drain + if (powerUsed + 0.1 >= idleUsage != (this.state & 0x40) > 0) { + this.recalculateDisplay(); + } + } + } catch (final GridAccessException e) { + final double powerUsed = this.extractAEPower( + this.getProxy().getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG); // drain + if (powerUsed + 0.1 >= idleUsage != (this.state & 0x40) > 0) { + this.recalculateDisplay(); + } + } + + if (this.inv.getStackInSlot(0) != null) { + this.tryToStoreContents(); + } + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileChest(final ByteBuf data) { + if (this.worldObj.getTotalWorldTime() - this.lastStateChange > 8) { + this.state = 0; + } else { + this.state &= 0x24924924; // just keep the blinks... + } + + for (int x = 0; x < this.getCellCount(); x++) { + this.state |= (this.getCellStatus(x) << (3 * x)); + } + + if (this.isPowered()) { + this.state |= 0x40; + } else { + this.state &= ~0x40; + } + + data.writeByte(this.state); + data.writeByte(this.paintedColor.ordinal()); + + final ItemStack is = this.inv.getStackInSlot(1); + + if (is == null) { + data.writeInt(0); + } else { + data.writeInt((is.getItemDamage() << Platform.DEF_OFFSET) | Item.getIdFromItem(is.getItem())); + } + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileChest(final ByteBuf data) { + final int oldState = this.state; + final ItemStack oldType = this.storageType; + + this.state = data.readByte(); + final AEColor oldPaintedColor = this.paintedColor; + this.paintedColor = AEColor.values()[data.readByte()]; + + final int item = data.readInt(); + + if (item == 0) { + this.storageType = null; + } else { + this.storageType = new ItemStack(Item.getItemById(item & 0xffff), 1, item >> Platform.DEF_OFFSET); + } + + this.lastStateChange = this.worldObj.getTotalWorldTime(); + + return oldPaintedColor != this.paintedColor + || (this.state & 0xDB6DB6DB) != (oldState & 0xDB6DB6DB) + || !Platform.isSameItemPrecise(oldType, this.storageType); + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileChest(final NBTTagCompound data) { + this.config.readFromNBT(data); + this.priority = data.getInteger("priority"); + if (data.hasKey("paintedColor")) { + this.paintedColor = AEColor.values()[data.getByte("paintedColor")]; + } + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileChest(final NBTTagCompound data) { + this.config.writeToNBT(data); + data.setInteger("priority", this.priority); + data.setByte("paintedColor", (byte) this.paintedColor.ordinal()); + } + + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.recalculateDisplay(); + } + + @MENetworkEventSubscribe + public void channelRender(final MENetworkChannelsChanged c) { + this.recalculateDisplay(); + } + + @Override + public IMEMonitor getItemInventory() { + return this.itemCell; + } + + @Override + public IMEMonitor getFluidInventory() { + return this.fluidCell; + } + + @Override + public IInventory getInternalInventory() { + return this.inv; + } + + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + this.inv.setInventorySlotContents(i, itemstack); + this.tryToStoreContents(); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) { + if (slot == 1) { + this.itemCell = null; + this.fluidCell = null; + this.isCached = false; // recalculate the storage cell. + + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + + final IStorageGrid gs = this.getProxy().getStorage(); + Platform.postChanges(gs, removed, added, this.mySrc); + } catch (final GridAccessException ignored) { + + } + + // update the neighbors + if (this.worldObj != null) { + Platform.notifyBlocksOfNeighbors(this.worldObj, this.xCoord, this.yCoord, this.zCoord); + this.markForUpdate(); + } + } + } + + @Override + public boolean canInsertItem(final int slotIndex, final ItemStack insertingItem, final int side) { + if (slotIndex == 1) { + if (AEApi.instance().registries().cell().getCellInventory(insertingItem, this, StorageChannel.ITEMS) + != null) { + return true; + } + if (AEApi.instance().registries().cell().getCellInventory(insertingItem, this, StorageChannel.FLUIDS) + != null) { + return true; + } + } else { + try { + final IMEInventory cell = this.getHandler(StorageChannel.ITEMS); + final IAEItemStack returns = cell.injectItems( + AEApi.instance().storage().createItemStack(this.inv.getStackInSlot(0)), + Actionable.SIMULATE, + this.mySrc); + return returns == null || returns.getStackSize() != insertingItem.stackSize; + } catch (final ChestNoHandler ignored) { + } + } + return false; + } + + @Override + public boolean canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + return slotIndex == 1; + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + if (ForgeDirection.SOUTH == side) { + return FRONT; + } + + if (this.isPowered()) { + try { + if (this.getHandler(StorageChannel.ITEMS) != null) { + return SIDES; + } + } catch (final ChestNoHandler e) { + // nope! + } + } + return NO_SLOTS; + } + + private void tryToStoreContents() { + try { + if (this.getStackInSlot(0) != null) { + final IMEInventory cell = this.getHandler(StorageChannel.ITEMS); + + final IAEItemStack returns = Platform.poweredInsert( + this, cell, AEApi.instance().storage().createItemStack(this.inv.getStackInSlot(0)), this.mySrc); + + if (returns == null) { + this.inv.setInventorySlotContents(0, null); + } else { + this.inv.setInventorySlotContents(0, returns.getItemStack()); + } + } + } catch (final ChestNoHandler ignored) { + } + } + + @Override + public List getCellArray(final StorageChannel channel) { + if (this.getProxy().isActive()) { + try { + return Collections.singletonList(this.getHandler(channel)); + } catch (final ChestNoHandler e) { + // :P + } + } + return new ArrayList(); + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public void setPriority(final int newValue) { + this.priority = newValue; + + this.itemCell = null; + this.fluidCell = null; + this.isCached = false; // recalculate the storage cell. + + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } + + @Override + public void blinkCell(final int slot) { + final long now = this.worldObj.getTotalWorldTime(); + if (now - this.lastStateChange > 8) { + this.state = 0; + } + this.lastStateChange = now; + + this.state |= 1 << (slot * 3 + 2); + + this.recalculateDisplay(); + } + + @Override + public int fill(final ForgeDirection from, final FluidStack resource, final boolean doFill) { + final double req = resource.amount / 500.0; + final double available = this.extractAEPower(req, Actionable.SIMULATE, PowerMultiplier.CONFIG); + if (available >= req - 0.01) { + try { + final IMEInventoryHandler h = this.getHandler(StorageChannel.FLUIDS); + + this.extractAEPower(req, Actionable.MODULATE, PowerMultiplier.CONFIG); + final IAEStack results = h.injectItems( + AEFluidStack.create(resource), doFill ? Actionable.MODULATE : Actionable.SIMULATE, this.mySrc); + + if (results == null) { + return resource.amount; + } + + return resource.amount - (int) results.getStackSize(); + } catch (final ChestNoHandler ignored) { + } + } + return 0; + } + + @Override + public FluidStack drain(final ForgeDirection from, final FluidStack resource, final boolean doDrain) { + return null; + } + + @Override + public FluidStack drain(final ForgeDirection from, final int maxDrain, final boolean doDrain) { + return null; + } + + @Override + public boolean canFill(final ForgeDirection from, final Fluid fluid) { + try { + final IMEInventoryHandler h = this.getHandler(StorageChannel.FLUIDS); + return h.canAccept(AEFluidStack.create(new FluidStack(fluid, 1))); + } catch (final ChestNoHandler ignored) { + } + return false; + } + + @Override + public boolean canDrain(final ForgeDirection from, final Fluid fluid) { + return false; + } + + @Override + public FluidTankInfo[] getTankInfo(final ForgeDirection from) { + try { + final IMEInventoryHandler h = this.getHandler(StorageChannel.FLUIDS); + if (h.getChannel() == StorageChannel.FLUIDS) { + return new FluidTankInfo[] {new FluidTankInfo(null, 1)}; // eh? + } + } catch (final ChestNoHandler ignored) { + } + + return null; + } + + @Override + public IStorageMonitorable getMonitorable(final ForgeDirection side, final BaseActionSource src) { + if (Platform.canAccess(this.getProxy(), src) && side != this.getForward()) { + return this; + } + return null; + } + + public ItemStack getStorageType() { + if (this.isPowered()) { + return this.storageType; + } + return null; + } + + @Override + public IConfigManager getConfigManager() { + return this.config; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) {} + + public boolean openGui(final EntityPlayer p, final ICellHandler ch, final ItemStack cell, final int side) { + try { + final IMEInventoryHandler invHandler = this.getHandler(StorageChannel.ITEMS); + if (ch != null && invHandler != null) { + ch.openChestGui(p, this, ch, invHandler, cell, StorageChannel.ITEMS); + return true; + } + } catch (final ChestNoHandler e) { + // :P + } + + try { + final IMEInventoryHandler invHandler = this.getHandler(StorageChannel.FLUIDS); + if (ch != null && invHandler != null) { + ch.openChestGui(p, this, ch, invHandler, cell, StorageChannel.FLUIDS); + return true; + } + } catch (final ChestNoHandler e) { + // :P + } + + return false; + } + + @Override + public AEColor getColor() { + return this.paintedColor; + } + + @Override + public boolean recolourBlock(final ForgeDirection side, final AEColor newPaintedColor, final EntityPlayer who) { + if (this.paintedColor == newPaintedColor) { + return false; + } + + this.paintedColor = newPaintedColor; + this.markDirty(); + this.markForUpdate(); + return true; + } + + @Override + public void saveChanges(final IMEInventory cellInventory) { + this.worldObj.markTileEntityChunkModified(this.xCoord, this.yCoord, this.zCoord, this); + } + + private static class ChestNoHandler extends Exception { + private static final long serialVersionUID = 7995805326136526631L; + } + + private class ChestNetNotifier> implements IMEMonitorHandlerReceiver { + + private final StorageChannel chan; + + public ChestNetNotifier(final StorageChannel chan) { + this.chan = chan; + } + + @Override + public boolean isValid(final Object verificationToken) { + if (this.chan == StorageChannel.ITEMS) { + return verificationToken == TileChest.this.itemCell; + } + if (this.chan == StorageChannel.FLUIDS) { + return verificationToken == TileChest.this.fluidCell; + } + return false; + } + + @Override + public void postChange(final IBaseMonitor monitor, final Iterable change, final BaseActionSource source) { + if (source == TileChest.this.mySrc + || (source instanceof PlayerSource && ((PlayerSource) source).via == TileChest.this)) { + try { + if (TileChest.this.getProxy().isActive()) { + TileChest.this + .getProxy() + .getStorage() + .postAlterationOfStoredItems(this.chan, change, TileChest.this.mySrc); + } + } catch (final GridAccessException e) { + // :( + } + } + + TileChest.this.blinkCell(0); + } + + @Override + public void onListUpdate() { + // not used here + } + } + + private class ChestMonitorHandler extends MEMonitorHandler { + + public ChestMonitorHandler(final IMEInventoryHandler t) { + super(t); + } + + private IMEInventoryHandler getInternalHandler() { + final IMEInventoryHandler h = this.getHandler(); + if (h instanceof MEInventoryHandler) { + return (IMEInventoryHandler) ((MEInventoryHandler) h).getInternal(); + } + return this.getHandler(); + } + + @Override + public T injectItems(final T input, final Actionable mode, final BaseActionSource src) { + if (src.isPlayer() && !this.securityCheck(((PlayerSource) src).player, SecurityPermissions.INJECT)) { + return input; + } + return super.injectItems(input, mode, src); + } + + private boolean securityCheck(final EntityPlayer player, final SecurityPermissions requiredPermission) { + if (TileChest.this.getTile() instanceof IActionHost && requiredPermission != null) { + final IGridNode gn = ((IActionHost) TileChest.this.getTile()).getActionableNode(); + if (gn != null) { + final IGrid g = gn.getGrid(); + if (g != null) { + final boolean requirePower = false; + if (requirePower) { + final IEnergyGrid eg = g.getCache(IEnergyGrid.class); + if (!eg.isNetworkPowered()) { + return false; + } + } + + final ISecurityGrid sg = g.getCache(ISecurityGrid.class); + if (sg.hasPermission(player, requiredPermission)) { + return true; + } + } + } + + return false; + } + return true; + } + + @Override + public T extractItems(final T request, final Actionable mode, final BaseActionSource src) { + if (src.isPlayer() && !this.securityCheck(((PlayerSource) src).player, SecurityPermissions.EXTRACT)) { + return null; + } + return super.extractItems(request, mode, src); + } + } } diff --git a/src/main/java/appeng/tile/storage/TileDrive.java b/src/main/java/appeng/tile/storage/TileDrive.java index e9bd9564c21..1e42bdaa49e 100644 --- a/src/main/java/appeng/tile/storage/TileDrive.java +++ b/src/main/java/appeng/tile/storage/TileDrive.java @@ -18,7 +18,6 @@ package appeng.tile.storage; - import appeng.api.AEApi; import appeng.api.implementations.tiles.IChestOrDrive; import appeng.api.networking.GridFlags; @@ -47,373 +46,313 @@ import appeng.tile.inventory.InvOperation; import appeng.util.Platform; import io.netty.buffer.ByteBuf; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - - -public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPriorityHost -{ - - private final int[] sides = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 10 ); - private final ICellHandler[] handlersBySlot = new ICellHandler[10]; - private final DriveWatcher[] invBySlot = new DriveWatcher[10]; - private final BaseActionSource mySrc; - private boolean isCached = false; - private List items = new LinkedList(); - private List fluids = new LinkedList(); - private long lastStateChange = 0; - private int state = 0; - private int priority = 0; - private boolean wasActive = false; - - public TileDrive() - { - this.mySrc = new MachineSource( this ); - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileDrive( final ByteBuf data ) - { - if( this.worldObj.getTotalWorldTime() - this.lastStateChange > 8 ) - { - this.state = 0; - } - else - { - this.state &= 0x24924924; // just keep the blinks... - } - - if( this.getProxy().isActive() ) - { - this.state |= 0x80000000; - } - else - { - this.state &= ~0x80000000; - } - - for( int x = 0; x < this.getCellCount(); x++ ) - { - this.state |= ( this.getCellStatus( x ) << ( 3 * x ) ); - } - - data.writeInt( this.state ); - } - - @Override - public int getCellCount() - { - return 10; - } - - @Override - public int getCellStatus( final int slot ) - { - if( Platform.isClient() ) - { - return ( this.state >> ( slot * 3 ) ) & 3; - } - - final ItemStack cell = this.inv.getStackInSlot( 2 ); - final ICellHandler ch = this.handlersBySlot[slot]; - - final MEInventoryHandler handler = this.invBySlot[slot]; - if( handler == null ) - { - return 0; - } - - if( handler.getChannel() == StorageChannel.ITEMS ) - { - if( ch != null ) - { - return ch.getStatusForCell( cell, handler.getInternal() ); - } - } - - if( handler.getChannel() == StorageChannel.FLUIDS ) - { - if( ch != null ) - { - return ch.getStatusForCell( cell, handler.getInternal() ); - } - } - - return 0; - } - - @Override - public boolean isPowered() - { - if( Platform.isClient() ) - { - return ( this.state & 0x80000000 ) == 0x80000000; - } - - return this.getProxy().isActive(); - } - - @Override - public boolean isCellBlinking( final int slot ) - { - final long now = this.worldObj.getTotalWorldTime(); - if( now - this.lastStateChange > 8 ) - { - return false; - } - - return ( ( this.state >> ( slot * 3 + 2 ) ) & 0x01 ) == 0x01; - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileDrive( final ByteBuf data ) - { - final int oldState = this.state; - this.state = data.readInt(); - this.lastStateChange = this.worldObj.getTotalWorldTime(); - return ( this.state & 0xDB6DB6DB ) != ( oldState & 0xDB6DB6DB ); - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileDrive( final NBTTagCompound data ) - { - this.isCached = false; - this.priority = data.getInteger( "priority" ); - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileDrive( final NBTTagCompound data ) - { - data.setInteger( "priority", this.priority ); - } - - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.recalculateDisplay(); - } - - private void recalculateDisplay() - { - final boolean currentActive = this.getProxy().isActive(); - if( currentActive ) - { - this.state |= 0x80000000; - } - else - { - this.state &= ~0x80000000; - } - - if( this.wasActive != currentActive ) - { - this.wasActive = currentActive; - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - for( int x = 0; x < this.getCellCount(); x++ ) - { - this.state |= ( this.getCellStatus( x ) << ( 3 * x ) ); - } - - final int oldState = 0; - if( oldState != this.state ) - { - this.markForUpdate(); - } - } - - @MENetworkEventSubscribe - public void channelRender( final MENetworkChannelsChanged c ) - { - this.recalculateDisplay(); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return itemstack != null && AEApi.instance().registries().cell().isCellHandled( itemstack ); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( this.isCached ) - { - this.isCached = false; // recalculate the storage cell. - this.updateState(); - } - - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - - final IStorageGrid gs = this.getProxy().getStorage(); - Platform.postChanges( gs, removed, added, this.mySrc ); - } - catch( final GridAccessException ignored ) - { - } - - this.markForUpdate(); - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.sides; - } - - private void updateState() - { - if( !this.isCached ) - { - this.items = new LinkedList(); - this.fluids = new LinkedList(); - - double power = 2.0; - - for( int x = 0; x < this.inv.getSizeInventory(); x++ ) - { - final ItemStack is = this.inv.getStackInSlot( x ); - this.invBySlot[x] = null; - this.handlersBySlot[x] = null; - - if( is != null ) - { - this.handlersBySlot[x] = AEApi.instance().registries().cell().getHandler( is ); - - if( this.handlersBySlot[x] != null ) - { - IMEInventoryHandler cell = this.handlersBySlot[x].getCellInventory( is, this, StorageChannel.ITEMS ); - - if( cell != null ) - { - power += this.handlersBySlot[x].cellIdleDrain( is, cell ); - - final DriveWatcher ih = new DriveWatcher( cell, is, this.handlersBySlot[x], this ); - ih.setPriority( this.priority ); - this.invBySlot[x] = ih; - this.items.add( ih ); - } - else - { - cell = this.handlersBySlot[x].getCellInventory( is, this, StorageChannel.FLUIDS ); - - if( cell != null ) - { - power += this.handlersBySlot[x].cellIdleDrain( is, cell ); - - final DriveWatcher ih = new DriveWatcher( cell, is, this.handlersBySlot[x], this ); - ih.setPriority( this.priority ); - this.invBySlot[x] = ih; - this.fluids.add( ih ); - } - } - } - } - } - - this.getProxy().setIdlePowerUsage( power ); - - this.isCached = true; - } - } - - @Override - public void onReady() - { - super.onReady(); - this.updateState(); - } - - @Override - public List getCellArray( final StorageChannel channel ) - { - if( this.getProxy().isActive() ) - { - this.updateState(); - return (List) ( channel == StorageChannel.ITEMS ? this.items : this.fluids ); - } - return new ArrayList(); - } - - @Override - public int getPriority() - { - return this.priority; - } - - @Override - public void setPriority( final int newValue ) - { - this.priority = newValue; - this.markDirty(); - - this.isCached = false; // recalculate the storage cell. - this.updateState(); - - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - @Override - public void blinkCell( final int slot ) - { - final long now = this.worldObj.getTotalWorldTime(); - if( now - this.lastStateChange > 8 ) - { - this.state = 0; - } - this.lastStateChange = now; - - this.state |= 1 << ( slot * 3 + 2 ); - - this.recalculateDisplay(); - } - - @Override - public void saveChanges( final IMEInventory cellInventory ) - { - this.worldObj.markTileEntityChunkModified( this.xCoord, this.yCoord, this.zCoord, this ); - } +public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPriorityHost { + + private final int[] sides = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 10); + private final ICellHandler[] handlersBySlot = new ICellHandler[10]; + private final DriveWatcher[] invBySlot = new DriveWatcher[10]; + private final BaseActionSource mySrc; + private boolean isCached = false; + private List items = new LinkedList(); + private List fluids = new LinkedList(); + private long lastStateChange = 0; + private int state = 0; + private int priority = 0; + private boolean wasActive = false; + + public TileDrive() { + this.mySrc = new MachineSource(this); + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileDrive(final ByteBuf data) { + if (this.worldObj.getTotalWorldTime() - this.lastStateChange > 8) { + this.state = 0; + } else { + this.state &= 0x24924924; // just keep the blinks... + } + + if (this.getProxy().isActive()) { + this.state |= 0x80000000; + } else { + this.state &= ~0x80000000; + } + + for (int x = 0; x < this.getCellCount(); x++) { + this.state |= (this.getCellStatus(x) << (3 * x)); + } + + data.writeInt(this.state); + } + + @Override + public int getCellCount() { + return 10; + } + + @Override + public int getCellStatus(final int slot) { + if (Platform.isClient()) { + return (this.state >> (slot * 3)) & 3; + } + + final ItemStack cell = this.inv.getStackInSlot(2); + final ICellHandler ch = this.handlersBySlot[slot]; + + final MEInventoryHandler handler = this.invBySlot[slot]; + if (handler == null) { + return 0; + } + + if (handler.getChannel() == StorageChannel.ITEMS) { + if (ch != null) { + return ch.getStatusForCell(cell, handler.getInternal()); + } + } + + if (handler.getChannel() == StorageChannel.FLUIDS) { + if (ch != null) { + return ch.getStatusForCell(cell, handler.getInternal()); + } + } + + return 0; + } + + @Override + public boolean isPowered() { + if (Platform.isClient()) { + return (this.state & 0x80000000) == 0x80000000; + } + + return this.getProxy().isActive(); + } + + @Override + public boolean isCellBlinking(final int slot) { + final long now = this.worldObj.getTotalWorldTime(); + if (now - this.lastStateChange > 8) { + return false; + } + + return ((this.state >> (slot * 3 + 2)) & 0x01) == 0x01; + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileDrive(final ByteBuf data) { + final int oldState = this.state; + this.state = data.readInt(); + this.lastStateChange = this.worldObj.getTotalWorldTime(); + return (this.state & 0xDB6DB6DB) != (oldState & 0xDB6DB6DB); + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileDrive(final NBTTagCompound data) { + this.isCached = false; + this.priority = data.getInteger("priority"); + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileDrive(final NBTTagCompound data) { + data.setInteger("priority", this.priority); + } + + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.recalculateDisplay(); + } + + private void recalculateDisplay() { + final boolean currentActive = this.getProxy().isActive(); + if (currentActive) { + this.state |= 0x80000000; + } else { + this.state &= ~0x80000000; + } + + if (this.wasActive != currentActive) { + this.wasActive = currentActive; + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } + + for (int x = 0; x < this.getCellCount(); x++) { + this.state |= (this.getCellStatus(x) << (3 * x)); + } + + final int oldState = 0; + if (oldState != this.state) { + this.markForUpdate(); + } + } + + @MENetworkEventSubscribe + public void channelRender(final MENetworkChannelsChanged c) { + this.recalculateDisplay(); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + @Override + public IInventory getInternalInventory() { + return this.inv; + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return itemstack != null && AEApi.instance().registries().cell().isCellHandled(itemstack); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) { + if (this.isCached) { + this.isCached = false; // recalculate the storage cell. + this.updateState(); + } + + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + + final IStorageGrid gs = this.getProxy().getStorage(); + Platform.postChanges(gs, removed, added, this.mySrc); + } catch (final GridAccessException ignored) { + } + + this.markForUpdate(); + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return this.sides; + } + + private void updateState() { + if (!this.isCached) { + this.items = new LinkedList(); + this.fluids = new LinkedList(); + + double power = 2.0; + + for (int x = 0; x < this.inv.getSizeInventory(); x++) { + final ItemStack is = this.inv.getStackInSlot(x); + this.invBySlot[x] = null; + this.handlersBySlot[x] = null; + + if (is != null) { + this.handlersBySlot[x] = + AEApi.instance().registries().cell().getHandler(is); + + if (this.handlersBySlot[x] != null) { + IMEInventoryHandler cell = + this.handlersBySlot[x].getCellInventory(is, this, StorageChannel.ITEMS); + + if (cell != null) { + power += this.handlersBySlot[x].cellIdleDrain(is, cell); + + final DriveWatcher ih = + new DriveWatcher(cell, is, this.handlersBySlot[x], this); + ih.setPriority(this.priority); + this.invBySlot[x] = ih; + this.items.add(ih); + } else { + cell = this.handlersBySlot[x].getCellInventory(is, this, StorageChannel.FLUIDS); + + if (cell != null) { + power += this.handlersBySlot[x].cellIdleDrain(is, cell); + + final DriveWatcher ih = + new DriveWatcher(cell, is, this.handlersBySlot[x], this); + ih.setPriority(this.priority); + this.invBySlot[x] = ih; + this.fluids.add(ih); + } + } + } + } + } + + this.getProxy().setIdlePowerUsage(power); + + this.isCached = true; + } + } + + @Override + public void onReady() { + super.onReady(); + this.updateState(); + } + + @Override + public List getCellArray(final StorageChannel channel) { + if (this.getProxy().isActive()) { + this.updateState(); + return (List) (channel == StorageChannel.ITEMS ? this.items : this.fluids); + } + return new ArrayList(); + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public void setPriority(final int newValue) { + this.priority = newValue; + this.markDirty(); + + this.isCached = false; // recalculate the storage cell. + this.updateState(); + + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } + + @Override + public void blinkCell(final int slot) { + final long now = this.worldObj.getTotalWorldTime(); + if (now - this.lastStateChange > 8) { + this.state = 0; + } + this.lastStateChange = now; + + this.state |= 1 << (slot * 3 + 2); + + this.recalculateDisplay(); + } + + @Override + public void saveChanges(final IMEInventory cellInventory) { + this.worldObj.markTileEntityChunkModified(this.xCoord, this.yCoord, this.zCoord, this); + } } diff --git a/src/main/java/appeng/tile/storage/TileIOPort.java b/src/main/java/appeng/tile/storage/TileIOPort.java index 06a844a425b..6d95d7cb905 100644 --- a/src/main/java/appeng/tile/storage/TileIOPort.java +++ b/src/main/java/appeng/tile/storage/TileIOPort.java @@ -18,7 +18,6 @@ package appeng.tile.storage; - import appeng.api.AEApi; import appeng.api.config.*; import appeng.api.implementations.IUpgradeableHost; @@ -55,6 +54,7 @@ import appeng.util.InventoryAdaptor; import appeng.util.Platform; import appeng.util.inv.WrapperInventoryRange; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -62,511 +62,444 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.List; - - -public class TileIOPort extends AENetworkInvTile implements IUpgradeableHost, IConfigManagerHost, IGridTickable -{ - private static final int INPUT_SLOT_INDEX_TOP_LEFT = 0; - private static final int INPUT_SLOT_INDEX_TOP_RIGHT = 1; - private static final int INPUT_SLOT_INDEX_CENTER_LEFT = 2; - private static final int INPUT_SLOT_INDEX_CENTER_RIGHT = 3; - private static final int INPUT_SLOT_INDEX_BOTTOM_LEFT = 4; - private static final int INPUT_SLOT_INDEX_BOTTOM_RIGHT = 5; - - private static final int OUTPUT_SLOT_INDEX_TOP_LEFT = 6; - private static final int OUTPUT_SLOT_INDEX_TOP_RIGHT = 7; - private static final int OUTPUT_SLOT_INDEX_CENTER_LEFT = 8; - private static final int OUTPUT_SLOT_INDEX_CENTER_RIGHT = 9; - private static final int OUTPUT_SLOT_INDEX_BOTTOM_LEFT = 10; - private static final int OUTPUT_SLOT_INDEX_BOTTOM_RIGHT = 11; - - private final ConfigManager manager; - - private final int[] input = { INPUT_SLOT_INDEX_TOP_LEFT, INPUT_SLOT_INDEX_TOP_RIGHT, INPUT_SLOT_INDEX_CENTER_LEFT, INPUT_SLOT_INDEX_CENTER_RIGHT, INPUT_SLOT_INDEX_BOTTOM_LEFT, INPUT_SLOT_INDEX_BOTTOM_RIGHT }; - private final int[] output = { OUTPUT_SLOT_INDEX_TOP_LEFT, OUTPUT_SLOT_INDEX_TOP_RIGHT, OUTPUT_SLOT_INDEX_CENTER_LEFT, OUTPUT_SLOT_INDEX_CENTER_RIGHT, OUTPUT_SLOT_INDEX_BOTTOM_LEFT, OUTPUT_SLOT_INDEX_BOTTOM_RIGHT }; - - private final AppEngInternalInventory cells; - private final UpgradeInventory upgrades; - - private final BaseActionSource mySrc; - - private YesNo lastRedstoneState; - private ItemStack currentCell; - private IMEInventory cachedFluid; - private IMEInventory cachedItem; - - @Reflected - public TileIOPort() - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.manager = new ConfigManager( this ); - this.manager.registerSetting( Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.manager.registerSetting( Settings.FULLNESS_MODE, FullnessMode.EMPTY ); - this.manager.registerSetting( Settings.OPERATION_MODE, OperationMode.EMPTY ); - this.cells = new AppEngInternalInventory( this, 12 ); - this.mySrc = new MachineSource( this ); - this.lastRedstoneState = YesNo.UNDECIDED; - - final Block ioPortBlock = AEApi.instance().definitions().blocks().iOPort().maybeBlock().get(); - this.upgrades = new BlockUpgradeInventory( ioPortBlock, this, 3 ); - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileIOPort( final NBTTagCompound data ) - { - this.manager.writeToNBT( data ); - this.cells.writeToNBT( data, "cells" ); - this.upgrades.writeToNBT( data, "upgrades" ); - data.setInteger( "lastRedstoneState", this.lastRedstoneState.ordinal() ); - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileIOPort( final NBTTagCompound data ) - { - this.manager.readFromNBT( data ); - this.cells.readFromNBT( data, "cells" ); - this.upgrades.readFromNBT( data, "upgrades" ); - if( data.hasKey( "lastRedstoneState" ) ) - { - this.lastRedstoneState = YesNo.values()[data.getInteger( "lastRedstoneState" )]; - } - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - private void updateTask() - { - try - { - if( this.hasWork() ) - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - else - { - this.getProxy().getTick().sleepDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - - public void updateRedstoneState() - { - final YesNo currentState = this.worldObj.isBlockIndirectlyGettingPowered( this.xCoord, this.yCoord, this.zCoord ) ? YesNo.YES : YesNo.NO; - if( this.lastRedstoneState != currentState ) - { - this.lastRedstoneState = currentState; - this.updateTask(); - } - } - - private boolean getRedstoneState() - { - if( this.lastRedstoneState == YesNo.UNDECIDED ) - { - this.updateRedstoneState(); - } - - return this.lastRedstoneState == YesNo.YES; - } - - private boolean isEnabled() - { - if( this.getInstalledUpgrades( Upgrades.REDSTONE ) == 0 ) - { - return true; - } - - final RedstoneMode rs = (RedstoneMode) this.manager.getSetting( Settings.REDSTONE_CONTROLLED ); - if( rs == RedstoneMode.HIGH_SIGNAL ) - { - return this.getRedstoneState(); - } - return !this.getRedstoneState(); - } - - @Override - public IConfigManager getConfigManager() - { - return this.manager; - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "upgrades" ) ) - { - return this.upgrades; - } - - if( name.equals( "cells" ) ) - { - return this.cells; - } - - return null; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - this.updateTask(); - } - - private boolean hasWork() - { - if( this.isEnabled() ) - { - for( int x = 0; x < 6; x++ ) - { - if( this.cells.getStackInSlot( x ) != null ) - { - return true; - } - } - } - - return false; - } - - @Override - public IInventory getInternalInventory() - { - return this.cells; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( this.cells == inv ) - { - this.updateTask(); - } - } - - @Override - public boolean canInsertItem( final int slotIndex, final ItemStack insertingItem, final int side ) - { - for( final int inputSlotIndex : this.input ) - { - if( inputSlotIndex == slotIndex ) - { - return true; - } - } - - return false; - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - for( final int outputSlotIndex : this.output ) - { - if( outputSlotIndex == slotIndex ) - { - return true; - } - } - - return false; - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection d ) - { - if( d == ForgeDirection.UP || d == ForgeDirection.DOWN ) - { - return this.input; - } - - return this.output; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.IOPort.getMin(), TickRates.IOPort.getMax(), this.hasWork(), false ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( !this.getProxy().isActive() ) - { - return TickRateModulation.IDLE; - } - - long ItemsToMove = 256; - - switch( this.getInstalledUpgrades( Upgrades.SPEED ) ) - { - case 1: - ItemsToMove *= 2; - break; - case 2: - ItemsToMove *= 4; - break; - case 3: - ItemsToMove *= 8; - break; - } - - try - { - final IMEInventory itemNet = this.getProxy().getStorage().getItemInventory(); - final IMEInventory fluidNet = this.getProxy().getStorage().getFluidInventory(); - final IEnergySource energy = this.getProxy().getEnergy(); - for( int x = 0; x < 6; x++ ) - { - final ItemStack is = this.cells.getStackInSlot( x ); - if( is != null ) - { - if( ItemsToMove > 0 ) - { - final IMEInventory itemInv = this.getInv( is, StorageChannel.ITEMS ); - final IMEInventory fluidInv = this.getInv( is, StorageChannel.FLUIDS ); - - if( this.manager.getSetting( Settings.OPERATION_MODE ) == OperationMode.EMPTY ) - { - if( itemInv != null ) - { - ItemsToMove = this.transferContents( energy, itemInv, itemNet, ItemsToMove, StorageChannel.ITEMS ); - } - if( fluidInv != null ) - { - ItemsToMove = this.transferContents( energy, fluidInv, fluidNet, ItemsToMove, StorageChannel.FLUIDS ); - } - } - else - { - if( itemInv != null ) - { - ItemsToMove = this.transferContents( energy, itemNet, itemInv, ItemsToMove, StorageChannel.ITEMS ); - } - if( fluidInv != null ) - { - ItemsToMove = this.transferContents( energy, fluidNet, fluidInv, ItemsToMove, StorageChannel.FLUIDS ); - } - } - - if( ItemsToMove > 0 && this.shouldMove( itemInv, fluidInv ) && !this.moveSlot( x ) ) - { - return TickRateModulation.IDLE; - } - - return TickRateModulation.URGENT; - } - else - { - return TickRateModulation.URGENT; - } - } - } - } - catch( final GridAccessException e ) - { - return TickRateModulation.IDLE; - } - - // nothing left to do... - return TickRateModulation.SLEEP; - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.upgrades.getInstalledUpgrades( u ); - } - - private IMEInventory getInv( final ItemStack is, final StorageChannel chan ) - { - if( this.currentCell != is ) - { - this.currentCell = is; - this.cachedFluid = AEApi.instance().registries().cell().getCellInventory( is, null, StorageChannel.FLUIDS ); - this.cachedItem = AEApi.instance().registries().cell().getCellInventory( is, null, StorageChannel.ITEMS ); - } - - if( StorageChannel.ITEMS == chan ) - { - return this.cachedItem; - } - - return this.cachedFluid; - } - - private long transferContents( final IEnergySource energy, final IMEInventory src, final IMEInventory destination, long itemsToMove, final StorageChannel chan ) - { - final IItemList myList; - if( src instanceof IMEMonitor ) - { - myList = ( (IMEMonitor) src ).getStorageList(); - } - else - { - myList = src.getAvailableItems( src.getChannel().createList() ); - } - - boolean didStuff; - - do - { - didStuff = false; - - for( final IAEStack s : myList ) - { - final long totalStackSize = s.getStackSize(); - if( totalStackSize > 0 ) - { - final IAEStack stack = destination.injectItems( s, Actionable.SIMULATE, this.mySrc ); - - long possible = 0; - if( stack == null ) - { - possible = totalStackSize; - } - else - { - possible = totalStackSize - stack.getStackSize(); - } - - if( possible > 0 ) - { - possible = Math.min( possible, itemsToMove ); - s.setStackSize( possible ); - - final IAEStack extracted = src.extractItems( s, Actionable.MODULATE, this.mySrc ); - if( extracted != null ) - { - possible = extracted.getStackSize(); - final IAEStack failed = Platform.poweredInsert( energy, destination, extracted, this.mySrc ); - - if( failed != null ) - { - possible -= failed.getStackSize(); - src.injectItems( failed, Actionable.MODULATE, this.mySrc ); - } - - if( possible > 0 ) - { - itemsToMove -= possible; - didStuff = true; - } - - break; - } - } - } - } - } - while( itemsToMove > 0 && didStuff ); - - return itemsToMove; - } - - private boolean shouldMove( final IMEInventory itemInv, final IMEInventory fluidInv ) - { - final FullnessMode fm = (FullnessMode) this.manager.getSetting( Settings.FULLNESS_MODE ); - - if( itemInv != null && fluidInv != null ) - { - return this.matches( fm, itemInv ) && this.matches( fm, fluidInv ); - } - else if( itemInv != null ) - { - return this.matches( fm, itemInv ); - } - else if( fluidInv != null ) - { - return this.matches( fm, fluidInv ); - } - - return true; - } - - private boolean moveSlot( final int x ) - { - final WrapperInventoryRange wir = new WrapperInventoryRange( this, this.output, true ); - final ItemStack result = InventoryAdaptor.getAdaptor( wir, ForgeDirection.UNKNOWN ).addItems( this.getStackInSlot( x ) ); - - if( result == null ) - { - this.setInventorySlotContents( x, null ); - return true; - } - - return false; - } - - private boolean matches( final FullnessMode fm, final IMEInventory src ) - { - if( fm == FullnessMode.HALF ) - { - return true; - } - - final IItemList myList; - - if( src instanceof IMEMonitor ) - { - myList = ( (IMEMonitor) src ).getStorageList(); - } - else - { - myList = src.getAvailableItems( src.getChannel().createList() ); - } - - if( fm == FullnessMode.EMPTY ) - { - return myList.isEmpty(); - } - - final IAEStack test = myList.getFirstItem(); - if( test != null ) - { - test.setStackSize( 1 ); - return src.injectItems( test, Actionable.SIMULATE, this.mySrc ) != null; - } - return false; - } - - /** - * Adds the items in the upgrade slots to the drop list. - * - * @param w world - * @param x x pos of tile entity - * @param y y pos of tile entity - * @param z z pos of tile entity - * @param drops drops of tile entity - */ - @Override - public void getDrops( final World w, final int x, final int y, final int z, final List drops ) - { - super.getDrops( w, x, y, z, drops ); - - for( int upgradeIndex = 0; upgradeIndex < this.upgrades.getSizeInventory(); upgradeIndex++ ) - { - final ItemStack stackInSlot = this.upgrades.getStackInSlot( upgradeIndex ); - - if( stackInSlot != null ) - { - drops.add( stackInSlot ); - } - } - } +public class TileIOPort extends AENetworkInvTile implements IUpgradeableHost, IConfigManagerHost, IGridTickable { + private static final int INPUT_SLOT_INDEX_TOP_LEFT = 0; + private static final int INPUT_SLOT_INDEX_TOP_RIGHT = 1; + private static final int INPUT_SLOT_INDEX_CENTER_LEFT = 2; + private static final int INPUT_SLOT_INDEX_CENTER_RIGHT = 3; + private static final int INPUT_SLOT_INDEX_BOTTOM_LEFT = 4; + private static final int INPUT_SLOT_INDEX_BOTTOM_RIGHT = 5; + + private static final int OUTPUT_SLOT_INDEX_TOP_LEFT = 6; + private static final int OUTPUT_SLOT_INDEX_TOP_RIGHT = 7; + private static final int OUTPUT_SLOT_INDEX_CENTER_LEFT = 8; + private static final int OUTPUT_SLOT_INDEX_CENTER_RIGHT = 9; + private static final int OUTPUT_SLOT_INDEX_BOTTOM_LEFT = 10; + private static final int OUTPUT_SLOT_INDEX_BOTTOM_RIGHT = 11; + + private final ConfigManager manager; + + private final int[] input = { + INPUT_SLOT_INDEX_TOP_LEFT, + INPUT_SLOT_INDEX_TOP_RIGHT, + INPUT_SLOT_INDEX_CENTER_LEFT, + INPUT_SLOT_INDEX_CENTER_RIGHT, + INPUT_SLOT_INDEX_BOTTOM_LEFT, + INPUT_SLOT_INDEX_BOTTOM_RIGHT + }; + private final int[] output = { + OUTPUT_SLOT_INDEX_TOP_LEFT, + OUTPUT_SLOT_INDEX_TOP_RIGHT, + OUTPUT_SLOT_INDEX_CENTER_LEFT, + OUTPUT_SLOT_INDEX_CENTER_RIGHT, + OUTPUT_SLOT_INDEX_BOTTOM_LEFT, + OUTPUT_SLOT_INDEX_BOTTOM_RIGHT + }; + + private final AppEngInternalInventory cells; + private final UpgradeInventory upgrades; + + private final BaseActionSource mySrc; + + private YesNo lastRedstoneState; + private ItemStack currentCell; + private IMEInventory cachedFluid; + private IMEInventory cachedItem; + + @Reflected + public TileIOPort() { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.manager = new ConfigManager(this); + this.manager.registerSetting(Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.manager.registerSetting(Settings.FULLNESS_MODE, FullnessMode.EMPTY); + this.manager.registerSetting(Settings.OPERATION_MODE, OperationMode.EMPTY); + this.cells = new AppEngInternalInventory(this, 12); + this.mySrc = new MachineSource(this); + this.lastRedstoneState = YesNo.UNDECIDED; + + final Block ioPortBlock = + AEApi.instance().definitions().blocks().iOPort().maybeBlock().get(); + this.upgrades = new BlockUpgradeInventory(ioPortBlock, this, 3); + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileIOPort(final NBTTagCompound data) { + this.manager.writeToNBT(data); + this.cells.writeToNBT(data, "cells"); + this.upgrades.writeToNBT(data, "upgrades"); + data.setInteger("lastRedstoneState", this.lastRedstoneState.ordinal()); + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileIOPort(final NBTTagCompound data) { + this.manager.readFromNBT(data); + this.cells.readFromNBT(data, "cells"); + this.upgrades.readFromNBT(data, "upgrades"); + if (data.hasKey("lastRedstoneState")) { + this.lastRedstoneState = YesNo.values()[data.getInteger("lastRedstoneState")]; + } + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + private void updateTask() { + try { + if (this.hasWork()) { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } else { + this.getProxy().getTick().sleepDevice(this.getProxy().getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } + + public void updateRedstoneState() { + final YesNo currentState = this.worldObj.isBlockIndirectlyGettingPowered(this.xCoord, this.yCoord, this.zCoord) + ? YesNo.YES + : YesNo.NO; + if (this.lastRedstoneState != currentState) { + this.lastRedstoneState = currentState; + this.updateTask(); + } + } + + private boolean getRedstoneState() { + if (this.lastRedstoneState == YesNo.UNDECIDED) { + this.updateRedstoneState(); + } + + return this.lastRedstoneState == YesNo.YES; + } + + private boolean isEnabled() { + if (this.getInstalledUpgrades(Upgrades.REDSTONE) == 0) { + return true; + } + + final RedstoneMode rs = (RedstoneMode) this.manager.getSetting(Settings.REDSTONE_CONTROLLED); + if (rs == RedstoneMode.HIGH_SIGNAL) { + return this.getRedstoneState(); + } + return !this.getRedstoneState(); + } + + @Override + public IConfigManager getConfigManager() { + return this.manager; + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("upgrades")) { + return this.upgrades; + } + + if (name.equals("cells")) { + return this.cells; + } + + return null; + } + + @Override + public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) { + this.updateTask(); + } + + private boolean hasWork() { + if (this.isEnabled()) { + for (int x = 0; x < 6; x++) { + if (this.cells.getStackInSlot(x) != null) { + return true; + } + } + } + + return false; + } + + @Override + public IInventory getInternalInventory() { + return this.cells; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) { + if (this.cells == inv) { + this.updateTask(); + } + } + + @Override + public boolean canInsertItem(final int slotIndex, final ItemStack insertingItem, final int side) { + for (final int inputSlotIndex : this.input) { + if (inputSlotIndex == slotIndex) { + return true; + } + } + + return false; + } + + @Override + public boolean canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + for (final int outputSlotIndex : this.output) { + if (outputSlotIndex == slotIndex) { + return true; + } + } + + return false; + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection d) { + if (d == ForgeDirection.UP || d == ForgeDirection.DOWN) { + return this.input; + } + + return this.output; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(TickRates.IOPort.getMin(), TickRates.IOPort.getMax(), this.hasWork(), false); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (!this.getProxy().isActive()) { + return TickRateModulation.IDLE; + } + + long ItemsToMove = 256; + + switch (this.getInstalledUpgrades(Upgrades.SPEED)) { + case 1: + ItemsToMove *= 2; + break; + case 2: + ItemsToMove *= 4; + break; + case 3: + ItemsToMove *= 8; + break; + } + + try { + final IMEInventory itemNet = + this.getProxy().getStorage().getItemInventory(); + final IMEInventory fluidNet = + this.getProxy().getStorage().getFluidInventory(); + final IEnergySource energy = this.getProxy().getEnergy(); + for (int x = 0; x < 6; x++) { + final ItemStack is = this.cells.getStackInSlot(x); + if (is != null) { + if (ItemsToMove > 0) { + final IMEInventory itemInv = this.getInv(is, StorageChannel.ITEMS); + final IMEInventory fluidInv = this.getInv(is, StorageChannel.FLUIDS); + + if (this.manager.getSetting(Settings.OPERATION_MODE) == OperationMode.EMPTY) { + if (itemInv != null) { + ItemsToMove = this.transferContents( + energy, itemInv, itemNet, ItemsToMove, StorageChannel.ITEMS); + } + if (fluidInv != null) { + ItemsToMove = this.transferContents( + energy, fluidInv, fluidNet, ItemsToMove, StorageChannel.FLUIDS); + } + } else { + if (itemInv != null) { + ItemsToMove = this.transferContents( + energy, itemNet, itemInv, ItemsToMove, StorageChannel.ITEMS); + } + if (fluidInv != null) { + ItemsToMove = this.transferContents( + energy, fluidNet, fluidInv, ItemsToMove, StorageChannel.FLUIDS); + } + } + + if (ItemsToMove > 0 && this.shouldMove(itemInv, fluidInv) && !this.moveSlot(x)) { + return TickRateModulation.IDLE; + } + + return TickRateModulation.URGENT; + } else { + return TickRateModulation.URGENT; + } + } + } + } catch (final GridAccessException e) { + return TickRateModulation.IDLE; + } + + // nothing left to do... + return TickRateModulation.SLEEP; + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.upgrades.getInstalledUpgrades(u); + } + + private IMEInventory getInv(final ItemStack is, final StorageChannel chan) { + if (this.currentCell != is) { + this.currentCell = is; + this.cachedFluid = AEApi.instance().registries().cell().getCellInventory(is, null, StorageChannel.FLUIDS); + this.cachedItem = AEApi.instance().registries().cell().getCellInventory(is, null, StorageChannel.ITEMS); + } + + if (StorageChannel.ITEMS == chan) { + return this.cachedItem; + } + + return this.cachedFluid; + } + + private long transferContents( + final IEnergySource energy, + final IMEInventory src, + final IMEInventory destination, + long itemsToMove, + final StorageChannel chan) { + final IItemList myList; + if (src instanceof IMEMonitor) { + myList = ((IMEMonitor) src).getStorageList(); + } else { + myList = src.getAvailableItems(src.getChannel().createList()); + } + + boolean didStuff; + + do { + didStuff = false; + + for (final IAEStack s : myList) { + final long totalStackSize = s.getStackSize(); + if (totalStackSize > 0) { + final IAEStack stack = destination.injectItems(s, Actionable.SIMULATE, this.mySrc); + + long possible = 0; + if (stack == null) { + possible = totalStackSize; + } else { + possible = totalStackSize - stack.getStackSize(); + } + + if (possible > 0) { + possible = Math.min(possible, itemsToMove); + s.setStackSize(possible); + + final IAEStack extracted = src.extractItems(s, Actionable.MODULATE, this.mySrc); + if (extracted != null) { + possible = extracted.getStackSize(); + final IAEStack failed = Platform.poweredInsert(energy, destination, extracted, this.mySrc); + + if (failed != null) { + possible -= failed.getStackSize(); + src.injectItems(failed, Actionable.MODULATE, this.mySrc); + } + + if (possible > 0) { + itemsToMove -= possible; + didStuff = true; + } + + break; + } + } + } + } + } while (itemsToMove > 0 && didStuff); + + return itemsToMove; + } + + private boolean shouldMove(final IMEInventory itemInv, final IMEInventory fluidInv) { + final FullnessMode fm = (FullnessMode) this.manager.getSetting(Settings.FULLNESS_MODE); + + if (itemInv != null && fluidInv != null) { + return this.matches(fm, itemInv) && this.matches(fm, fluidInv); + } else if (itemInv != null) { + return this.matches(fm, itemInv); + } else if (fluidInv != null) { + return this.matches(fm, fluidInv); + } + + return true; + } + + private boolean moveSlot(final int x) { + final WrapperInventoryRange wir = new WrapperInventoryRange(this, this.output, true); + final ItemStack result = + InventoryAdaptor.getAdaptor(wir, ForgeDirection.UNKNOWN).addItems(this.getStackInSlot(x)); + + if (result == null) { + this.setInventorySlotContents(x, null); + return true; + } + + return false; + } + + private boolean matches(final FullnessMode fm, final IMEInventory src) { + if (fm == FullnessMode.HALF) { + return true; + } + + final IItemList myList; + + if (src instanceof IMEMonitor) { + myList = ((IMEMonitor) src).getStorageList(); + } else { + myList = src.getAvailableItems(src.getChannel().createList()); + } + + if (fm == FullnessMode.EMPTY) { + return myList.isEmpty(); + } + + final IAEStack test = myList.getFirstItem(); + if (test != null) { + test.setStackSize(1); + return src.injectItems(test, Actionable.SIMULATE, this.mySrc) != null; + } + return false; + } + + /** + * Adds the items in the upgrade slots to the drop list. + * + * @param w world + * @param x x pos of tile entity + * @param y y pos of tile entity + * @param z z pos of tile entity + * @param drops drops of tile entity + */ + @Override + public void getDrops(final World w, final int x, final int y, final int z, final List drops) { + super.getDrops(w, x, y, z, drops); + + for (int upgradeIndex = 0; upgradeIndex < this.upgrades.getSizeInventory(); upgradeIndex++) { + final ItemStack stackInSlot = this.upgrades.getStackInSlot(upgradeIndex); + + if (stackInSlot != null) { + drops.add(stackInSlot); + } + } + } } diff --git a/src/main/java/appeng/tile/storage/TileSkyChest.java b/src/main/java/appeng/tile/storage/TileSkyChest.java index cdf74f65e46..35fca822dcf 100644 --- a/src/main/java/appeng/tile/storage/TileSkyChest.java +++ b/src/main/java/appeng/tile/storage/TileSkyChest.java @@ -18,7 +18,6 @@ package appeng.tile.storage; - import appeng.tile.AEBaseInvTile; import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; @@ -30,128 +29,126 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; - -public class TileSkyChest extends AEBaseInvTile -{ - - private final int[] sides = { 0, 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 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 9 * 4 ); - // server - private int playerOpen; - // client.. - private long lastEvent; - private float lidAngle; - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileSkyChest( final ByteBuf data ) - { - data.writeBoolean( this.getPlayerOpen() > 0 ); - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileSkyChest( final ByteBuf data ) - { - final int wasOpen = this.getPlayerOpen(); - this.setPlayerOpen( data.readBoolean() ? 1 : 0 ); - - if( wasOpen != this.getPlayerOpen() ) - { - this.setLastEvent( System.currentTimeMillis() ); - } - - return false; // TESR yo! - } - - @Override - public boolean requiresTESR() - { - return true; - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - - @Override - public void openInventory() - { - if( Platform.isClient() ) - { - return; - } - - this.setPlayerOpen( this.getPlayerOpen() + 1 ); - - if( this.getPlayerOpen() == 1 ) - { - this.getWorldObj().playSoundEffect( this.xCoord + 0.5D, this.yCoord + 0.5D, this.zCoord + 0.5D, "random.chestopen", 0.5F, this.getWorldObj().rand.nextFloat() * 0.1F + 0.9F ); - this.markForUpdate(); - } - } - - @Override - public void closeInventory() - { - if( Platform.isClient() ) - { - return; - } - - this.setPlayerOpen( this.getPlayerOpen() - 1 ); - - if( this.getPlayerOpen() < 0 ) - { - this.setPlayerOpen( 0 ); - } - - if( this.getPlayerOpen() == 0 ) - { - this.getWorldObj().playSoundEffect( this.xCoord + 0.5D, this.yCoord + 0.5D, this.zCoord + 0.5D, "random.chestclosed", 0.5F, this.getWorldObj().rand.nextFloat() * 0.1F + 0.9F ); - this.markForUpdate(); - } - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.sides; - } - - public float getLidAngle() - { - return this.lidAngle; - } - - public void setLidAngle( final float lidAngle ) - { - this.lidAngle = lidAngle; - } - - public int getPlayerOpen() - { - return this.playerOpen; - } - - private void setPlayerOpen( final int playerOpen ) - { - this.playerOpen = playerOpen; - } - - public long getLastEvent() - { - return this.lastEvent; - } - - private void setLastEvent( final long lastEvent ) - { - this.lastEvent = lastEvent; - } +public class TileSkyChest extends AEBaseInvTile { + + private final int[] sides = { + 0, 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 + }; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 9 * 4); + // server + private int playerOpen; + // client.. + private long lastEvent; + private float lidAngle; + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileSkyChest(final ByteBuf data) { + data.writeBoolean(this.getPlayerOpen() > 0); + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileSkyChest(final ByteBuf data) { + final int wasOpen = this.getPlayerOpen(); + this.setPlayerOpen(data.readBoolean() ? 1 : 0); + + if (wasOpen != this.getPlayerOpen()) { + this.setLastEvent(System.currentTimeMillis()); + } + + return false; // TESR yo! + } + + @Override + public boolean requiresTESR() { + return true; + } + + @Override + public IInventory getInternalInventory() { + return this.inv; + } + + @Override + public void openInventory() { + if (Platform.isClient()) { + return; + } + + this.setPlayerOpen(this.getPlayerOpen() + 1); + + if (this.getPlayerOpen() == 1) { + this.getWorldObj() + .playSoundEffect( + this.xCoord + 0.5D, + this.yCoord + 0.5D, + this.zCoord + 0.5D, + "random.chestopen", + 0.5F, + this.getWorldObj().rand.nextFloat() * 0.1F + 0.9F); + this.markForUpdate(); + } + } + + @Override + public void closeInventory() { + if (Platform.isClient()) { + return; + } + + this.setPlayerOpen(this.getPlayerOpen() - 1); + + if (this.getPlayerOpen() < 0) { + this.setPlayerOpen(0); + } + + if (this.getPlayerOpen() == 0) { + this.getWorldObj() + .playSoundEffect( + this.xCoord + 0.5D, + this.yCoord + 0.5D, + this.zCoord + 0.5D, + "random.chestclosed", + 0.5F, + this.getWorldObj().rand.nextFloat() * 0.1F + 0.9F); + this.markForUpdate(); + } + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) {} + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return this.sides; + } + + public float getLidAngle() { + return this.lidAngle; + } + + public void setLidAngle(final float lidAngle) { + this.lidAngle = lidAngle; + } + + public int getPlayerOpen() { + return this.playerOpen; + } + + private void setPlayerOpen(final int playerOpen) { + this.playerOpen = playerOpen; + } + + public long getLastEvent() { + return this.lastEvent; + } + + private void setLastEvent(final long lastEvent) { + this.lastEvent = lastEvent; + } } diff --git a/src/main/java/appeng/transformer/AppEngCore.java b/src/main/java/appeng/transformer/AppEngCore.java index 1f76c6d01ec..d55516a0cbc 100644 --- a/src/main/java/appeng/transformer/AppEngCore.java +++ b/src/main/java/appeng/transformer/AppEngCore.java @@ -18,7 +18,6 @@ package appeng.transformer; - import appeng.core.AEConfig; import com.google.common.eventbus.EventBus; import cpw.mods.fml.common.DummyModContainer; @@ -29,99 +28,80 @@ import cpw.mods.fml.relauncher.FMLRelaunchLog; import cpw.mods.fml.relauncher.IFMLLoadingPlugin; import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; - -import javax.annotation.Nullable; import java.util.Map; +import javax.annotation.Nullable; - -@MCVersion( "1.7.10" ) -public final class AppEngCore extends DummyModContainer implements IFMLLoadingPlugin -{ - private final ModMetadata metadata = new ModMetadata(); - - public AppEngCore() - { - FMLRelaunchLog.info( "[AppEng] Core Init" ); - this.metadata.autogenerated = false; - this.metadata.authorList.add( "AlgorithmX2" ); - this.metadata.credits = "AlgorithmX2"; - this.metadata.modId = this.getModId(); - this.metadata.version = this.getVersion(); - this.metadata.name = this.getName(); - this.metadata.url = "http://ae2.ae-mod.info"; - this.metadata.logoFile = "assets/appliedenergistics2/meta/logo.png"; - this.metadata.description = "Embedded Coremod for Applied Energistics 2"; - } - - @EventHandler - public void load( final FMLInitializationEvent event ) - { - } - - @Override - public String[] getASMTransformerClass() - { - return new String[] { "appeng.transformer.asm.ASMIntegration", "appeng.transformer.asm.ApiRepairer" }; - } - - @Override - public String getModContainerClass() - { - return "appeng.transformer.AppEngCore"; - } - - @Nullable - @Override - public String getSetupClass() - { - return null; - } - - @Override - public void injectData( final Map data ) - { - - } - - @Override - public String getAccessTransformerClass() - { - return "appeng.transformer.asm.ASMTweaker"; - } - - @Override - public ModMetadata getMetadata() - { - return this.metadata; - } - - @Override - public String getModId() - { - return "appliedenergistics2-core"; - } - - @Override - public String getName() - { - return "Applied Energistics 2 Core"; - } - - @Override - public String getVersion() - { - return AEConfig.VERSION; - } - - @Override - public boolean registerBus( final EventBus bus, final LoadController controller ) - { - return true; - } - - @Override - public String getDisplayVersion() - { - return this.getVersion(); - } +@MCVersion("1.7.10") +public final class AppEngCore extends DummyModContainer implements IFMLLoadingPlugin { + private final ModMetadata metadata = new ModMetadata(); + + public AppEngCore() { + FMLRelaunchLog.info("[AppEng] Core Init"); + this.metadata.autogenerated = false; + this.metadata.authorList.add("AlgorithmX2"); + this.metadata.credits = "AlgorithmX2"; + this.metadata.modId = this.getModId(); + this.metadata.version = this.getVersion(); + this.metadata.name = this.getName(); + this.metadata.url = "http://ae2.ae-mod.info"; + this.metadata.logoFile = "assets/appliedenergistics2/meta/logo.png"; + this.metadata.description = "Embedded Coremod for Applied Energistics 2"; + } + + @EventHandler + public void load(final FMLInitializationEvent event) {} + + @Override + public String[] getASMTransformerClass() { + return new String[] {"appeng.transformer.asm.ASMIntegration", "appeng.transformer.asm.ApiRepairer"}; + } + + @Override + public String getModContainerClass() { + return "appeng.transformer.AppEngCore"; + } + + @Nullable + @Override + public String getSetupClass() { + return null; + } + + @Override + public void injectData(final Map data) {} + + @Override + public String getAccessTransformerClass() { + return "appeng.transformer.asm.ASMTweaker"; + } + + @Override + public ModMetadata getMetadata() { + return this.metadata; + } + + @Override + public String getModId() { + return "appliedenergistics2-core"; + } + + @Override + public String getName() { + return "Applied Energistics 2 Core"; + } + + @Override + public String getVersion() { + return AEConfig.VERSION; + } + + @Override + public boolean registerBus(final EventBus bus, final LoadController controller) { + return true; + } + + @Override + public String getDisplayVersion() { + return this.getVersion(); + } } diff --git a/src/main/java/appeng/transformer/MissingCoreMod.java b/src/main/java/appeng/transformer/MissingCoreMod.java index c981cb99ef7..d6df747fa14 100644 --- a/src/main/java/appeng/transformer/MissingCoreMod.java +++ b/src/main/java/appeng/transformer/MissingCoreMod.java @@ -18,83 +18,118 @@ package appeng.transformer; - import cpw.mods.fml.client.CustomModLoadingErrorDisplayException; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiErrorScreen; - -@SideOnly( Side.CLIENT ) -public final class MissingCoreMod extends CustomModLoadingErrorDisplayException -{ - private static final int SHADOW_WHITE = 0xeeeeee; - private static final int COLOR_WHITE = 0xffffff; - private static final long serialVersionUID = -966774766922821652L; - private static final int SCREEN_OFFSET = 15; - - private boolean deobf = false; - - @Override - public void initGui( final GuiErrorScreen errorScreen, final FontRenderer fontRenderer ) - { - final Class clz = errorScreen.getClass(); - try - { - clz.getField( "mc" ); - this.deobf = true; - } - catch( final Throwable ignored ) - { - - } - } - - @Override - public void drawScreen( final GuiErrorScreen errorScreen, final FontRenderer fontRenderer, final int mouseRelX, final int mouseRelY, final float tickTime ) - { - int offset = 10; - this.drawCenteredString( fontRenderer, "Sorry, couldn't load AE2 properly.", errorScreen.width / 2, offset, COLOR_WHITE ); - - offset += SCREEN_OFFSET; - this.drawCenteredString( fontRenderer, "Please make sure that AE2 is installed into your mods folder.", errorScreen.width / 2, offset, SHADOW_WHITE ); - - offset += 2 * SCREEN_OFFSET; - - if( this.deobf ) - { - offset += SCREEN_OFFSET; - this.drawCenteredString( fontRenderer, "In a developer environment add the following too your args,", errorScreen.width / 2, offset, COLOR_WHITE ); - - offset += SCREEN_OFFSET; - this.drawCenteredString( fontRenderer, "-Dfml.coreMods.load=appeng.transformer.AppEngCore", errorScreen.width / 2, offset, SHADOW_WHITE ); - } - else - { - this.drawCenteredString( fontRenderer, "You're launcher may refer to this by different names,", errorScreen.width / 2, offset, COLOR_WHITE ); - - offset += SCREEN_OFFSET + 5; - - this.drawCenteredString( fontRenderer, "MultiMC calls this tab \"Loader Mods\"", errorScreen.width / 2, offset, SHADOW_WHITE ); - - offset += SCREEN_OFFSET; - this.drawCenteredString( fontRenderer, "Magic Launcher calls this tab \"External Mods\"", errorScreen.width / 2, offset, SHADOW_WHITE ); - - offset += SCREEN_OFFSET; - this.drawCenteredString( fontRenderer, "Most other launchers refer to this tab as just \"Mods\"", errorScreen.width / 2, offset, SHADOW_WHITE ); - - offset += 2 * SCREEN_OFFSET; - this.drawCenteredString( fontRenderer, "Also make sure that the AE2 file is a .jar, and not a .zip", errorScreen.width / 2, offset, COLOR_WHITE ); - } - } - - private void drawCenteredString( final FontRenderer fontRenderer, final String string, final int x, final int y, final int colour ) - { - final String reEncoded = string.replaceAll( "\\P{InBasic_Latin}", "" ); - final int reEncodedWidth = fontRenderer.getStringWidth( reEncoded ); - final int centeredX = x - reEncodedWidth / 2; - - fontRenderer.drawStringWithShadow( string, centeredX, y, colour ); - } -} \ No newline at end of file +@SideOnly(Side.CLIENT) +public final class MissingCoreMod extends CustomModLoadingErrorDisplayException { + private static final int SHADOW_WHITE = 0xeeeeee; + private static final int COLOR_WHITE = 0xffffff; + private static final long serialVersionUID = -966774766922821652L; + private static final int SCREEN_OFFSET = 15; + + private boolean deobf = false; + + @Override + public void initGui(final GuiErrorScreen errorScreen, final FontRenderer fontRenderer) { + final Class clz = errorScreen.getClass(); + try { + clz.getField("mc"); + this.deobf = true; + } catch (final Throwable ignored) { + + } + } + + @Override + public void drawScreen( + final GuiErrorScreen errorScreen, + final FontRenderer fontRenderer, + final int mouseRelX, + final int mouseRelY, + final float tickTime) { + int offset = 10; + this.drawCenteredString( + fontRenderer, "Sorry, couldn't load AE2 properly.", errorScreen.width / 2, offset, COLOR_WHITE); + + offset += SCREEN_OFFSET; + this.drawCenteredString( + fontRenderer, + "Please make sure that AE2 is installed into your mods folder.", + errorScreen.width / 2, + offset, + SHADOW_WHITE); + + offset += 2 * SCREEN_OFFSET; + + if (this.deobf) { + offset += SCREEN_OFFSET; + this.drawCenteredString( + fontRenderer, + "In a developer environment add the following too your args,", + errorScreen.width / 2, + offset, + COLOR_WHITE); + + offset += SCREEN_OFFSET; + this.drawCenteredString( + fontRenderer, + "-Dfml.coreMods.load=appeng.transformer.AppEngCore", + errorScreen.width / 2, + offset, + SHADOW_WHITE); + } else { + this.drawCenteredString( + fontRenderer, + "You're launcher may refer to this by different names,", + errorScreen.width / 2, + offset, + COLOR_WHITE); + + offset += SCREEN_OFFSET + 5; + + this.drawCenteredString( + fontRenderer, + "MultiMC calls this tab \"Loader Mods\"", + errorScreen.width / 2, + offset, + SHADOW_WHITE); + + offset += SCREEN_OFFSET; + this.drawCenteredString( + fontRenderer, + "Magic Launcher calls this tab \"External Mods\"", + errorScreen.width / 2, + offset, + SHADOW_WHITE); + + offset += SCREEN_OFFSET; + this.drawCenteredString( + fontRenderer, + "Most other launchers refer to this tab as just \"Mods\"", + errorScreen.width / 2, + offset, + SHADOW_WHITE); + + offset += 2 * SCREEN_OFFSET; + this.drawCenteredString( + fontRenderer, + "Also make sure that the AE2 file is a .jar, and not a .zip", + errorScreen.width / 2, + offset, + COLOR_WHITE); + } + } + + private void drawCenteredString( + final FontRenderer fontRenderer, final String string, final int x, final int y, final int colour) { + final String reEncoded = string.replaceAll("\\P{InBasic_Latin}", ""); + final int reEncodedWidth = fontRenderer.getStringWidth(reEncoded); + final int centeredX = x - reEncodedWidth / 2; + + fontRenderer.drawStringWithShadow(string, centeredX, y, colour); + } +} diff --git a/src/main/java/appeng/transformer/annotations/Integration.java b/src/main/java/appeng/transformer/annotations/Integration.java index b84bd274cdb..8bb3cf78152 100644 --- a/src/main/java/appeng/transformer/annotations/Integration.java +++ b/src/main/java/appeng/transformer/annotations/Integration.java @@ -18,36 +18,30 @@ package appeng.transformer.annotations; - import appeng.integration.IntegrationType; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - -public @interface Integration -{ - @Retention( RetentionPolicy.RUNTIME ) - @Target( ElementType.TYPE ) @interface InterfaceList - { - Interface[] value(); - } - - - @Retention( RetentionPolicy.RUNTIME ) - @Target( ElementType.TYPE ) @interface Interface - { - String iface(); - - IntegrationType iname(); - } - - - @Retention( RetentionPolicy.RUNTIME ) - @Target( ElementType.METHOD ) @interface Method - { - IntegrationType iname(); - } -} \ No newline at end of file +public @interface Integration { + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE) + @interface InterfaceList { + Interface[] value(); + } + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE) + @interface Interface { + String iface(); + + IntegrationType iname(); + } + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.METHOD) + @interface Method { + IntegrationType iname(); + } +} diff --git a/src/main/java/appeng/transformer/asm/ASMIntegration.java b/src/main/java/appeng/transformer/asm/ASMIntegration.java index f9db8ec4edf..9bea8f1520c 100644 --- a/src/main/java/appeng/transformer/asm/ASMIntegration.java +++ b/src/main/java/appeng/transformer/asm/ASMIntegration.java @@ -18,12 +18,13 @@ package appeng.transformer.asm; - import appeng.helpers.Reflected; import appeng.integration.IntegrationRegistry; import appeng.integration.IntegrationType; import appeng.transformer.annotations.Integration; import cpw.mods.fml.relauncher.FMLRelaunchLog; +import java.util.Iterator; +import javax.annotation.Nullable; import net.minecraft.launchwrapper.IClassTransformer; import org.apache.logging.log4j.Level; import org.objectweb.asm.ClassReader; @@ -33,220 +34,174 @@ import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; -import javax.annotation.Nullable; -import java.util.Iterator; - - @Reflected -public final class ASMIntegration implements IClassTransformer -{ - @Reflected - public ASMIntegration() - { - - /** - * Side, Display Name, ModID ClassPostFix - */ - - for( final IntegrationType type : IntegrationType.values() ) - { - IntegrationRegistry.INSTANCE.add( type ); - } - - // integrationModules.add( IntegrationSide.BOTH, "Thermal Expansion", "ThermalExpansion", IntegrationType.TE ); - // integrationModules.add( IntegrationSide.BOTH, "Mystcraft", "Mystcraft", IntegrationType.Mystcraft ); - // integrationModules.add( IntegrationSide.BOTH, "Greg Tech", "gregtech_addon", IntegrationType.GT ); - // integrationModules.add( IntegrationSide.BOTH, "Universal Electricity", null, IntegrationType.UE ); - // integrationModules.add( IntegrationSide.BOTH, "Logistics Pipes", "LogisticsPipes|Main", IntegrationType.LP ); - // integrationModules.add( IntegrationSide.BOTH, "Better Storage", IntegrationType.betterstorage ); - // integrationModules.add( IntegrationSide.BOTH, "Forestry", "Forestry", IntegrationType.Forestry ); - // integrationModules.add( IntegrationSide.BOTH, "Mekanism", "Mekanism", IntegrationType.Mekanism ); - - } - - @Nullable - @Override - public byte[] transform( final String name, final String transformedName, final byte[] basicClass ) - { - if( basicClass == null || transformedName.startsWith( "appeng.transformer" ) ) - { - return basicClass; - } - - if( transformedName.startsWith( "appeng." ) ) - { - final ClassNode classNode = new ClassNode(); - final ClassReader classReader = new ClassReader( basicClass ); - classReader.accept( classNode, 0 ); - - try - { - final boolean reWrite = this.removeOptionals( classNode ); - - if( reWrite ) - { - final ClassWriter writer = new ClassWriter( ClassWriter.COMPUTE_MAXS ); - classNode.accept( writer ); - return writer.toByteArray(); - } - } - catch( final Throwable t ) - { - t.printStackTrace(); - } - } - return basicClass; - } - - private boolean removeOptionals( final ClassNode classNode ) - { - boolean changed = false; - - if( classNode.visibleAnnotations != null ) - { - for( final AnnotationNode an : classNode.visibleAnnotations ) - { - if( this.hasAnnotation( an, Integration.Interface.class ) ) - { - if( this.stripInterface( classNode, Integration.Interface.class, an ) ) - { - changed = true; - } - } - else if( this.hasAnnotation( an, Integration.InterfaceList.class ) ) - { - for( final Object o : ( (Iterable) an.values.get( 1 ) ) ) - { - if( this.stripInterface( classNode, Integration.InterfaceList.class, (AnnotationNode) o ) ) - { - changed = true; - } - } - } - } - } - - final Iterator i = classNode.methods.iterator(); - while( i.hasNext() ) - { - final MethodNode mn = i.next(); - - if( mn.visibleAnnotations != null ) - { - for( final AnnotationNode an : mn.visibleAnnotations ) - { - if( this.hasAnnotation( an, Integration.Method.class ) ) - { - if( this.stripMethod( classNode, mn, i, Integration.Method.class, an ) ) - { - changed = true; - } - } - } - } - } - - if( changed ) - { - this.log( "Updated " + classNode.name ); - } - - return changed; - } - - private boolean hasAnnotation( final AnnotationNode ann, final Class annotation ) - { - return ann.desc.equals( Type.getDescriptor( annotation ) ); - } - - private boolean stripInterface( final ClassNode classNode, final Class class1, final AnnotationNode an ) - { - if( an.values.size() != 4 ) - { - throw new IllegalArgumentException( "Unable to handle Interface annotation on " + classNode.name ); - } - - String iFace = null; - - if( an.values.get( 0 ).equals( "iface" ) ) - { - iFace = (String) an.values.get( 1 ); - } - else if( an.values.get( 2 ).equals( "iface" ) ) - { - iFace = (String) an.values.get( 3 ); - } - - String iName = null; - if( an.values.get( 0 ).equals( "iname" ) ) - { - iName = ( (String[]) an.values.get( 1 ) )[1]; - } - else if( an.values.get( 2 ).equals( "iname" ) ) - { - iName = ( (String[]) an.values.get( 3 ) )[1]; - } - - if( iName != null && iFace != null ) - { - final IntegrationType type = IntegrationType.valueOf( iName ); - if( !IntegrationRegistry.INSTANCE.isEnabled( type ) ) - { - this.log( "Removing Interface " + iFace + " from " + classNode.name + " because " + iName + " integration is disabled." ); - classNode.interfaces.remove( iFace.replace( '.', '/' ) ); - return true; - } - else - { - this.log( "Allowing Interface " + iFace + " from " + classNode.name + " because " + iName + " integration is enabled." ); - } - } - else - { - throw new IllegalStateException( "Unable to handle Method annotation on " + classNode.name ); - } - - return false; - } - - private boolean stripMethod( final ClassNode classNode, final MethodNode mn, final Iterator i, final Class class1, final AnnotationNode an ) - { - if( an.values.size() != 2 ) - { - throw new IllegalArgumentException( "Unable to handle Method annotation on " + classNode.name ); - } - - String iName = null; - - if( an.values.get( 0 ).equals( "iname" ) ) - { - iName = ( (String[]) an.values.get( 1 ) )[1]; - } - - if( iName != null ) - { - final IntegrationType type = IntegrationType.valueOf( iName ); - if( !IntegrationRegistry.INSTANCE.isEnabled( type ) ) - { - this.log( "Removing Method " + mn.name + " from " + classNode.name + " because " + iName + " integration is disabled." ); - i.remove(); - return true; - } - else - { - this.log( "Allowing Method " + mn.name + " from " + classNode.name + " because " + iName + " integration is enabled." ); - } - } - else - { - throw new IllegalStateException( "Unable to handle Method annotation on " + classNode.name ); - } - - return false; - } - - private void log( final String string ) - { - FMLRelaunchLog.log( "AE2-CORE", Level.INFO, string ); - } +public final class ASMIntegration implements IClassTransformer { + @Reflected + public ASMIntegration() { + + /** + * Side, Display Name, ModID ClassPostFix + */ + for (final IntegrationType type : IntegrationType.values()) { + IntegrationRegistry.INSTANCE.add(type); + } + + // integrationModules.add( IntegrationSide.BOTH, "Thermal Expansion", "ThermalExpansion", IntegrationType.TE ); + // integrationModules.add( IntegrationSide.BOTH, "Mystcraft", "Mystcraft", IntegrationType.Mystcraft ); + // integrationModules.add( IntegrationSide.BOTH, "Greg Tech", "gregtech_addon", IntegrationType.GT ); + // integrationModules.add( IntegrationSide.BOTH, "Universal Electricity", null, IntegrationType.UE ); + // integrationModules.add( IntegrationSide.BOTH, "Logistics Pipes", "LogisticsPipes|Main", IntegrationType.LP ); + // integrationModules.add( IntegrationSide.BOTH, "Better Storage", IntegrationType.betterstorage ); + // integrationModules.add( IntegrationSide.BOTH, "Forestry", "Forestry", IntegrationType.Forestry ); + // integrationModules.add( IntegrationSide.BOTH, "Mekanism", "Mekanism", IntegrationType.Mekanism ); + + } + + @Nullable + @Override + public byte[] transform(final String name, final String transformedName, final byte[] basicClass) { + if (basicClass == null || transformedName.startsWith("appeng.transformer")) { + return basicClass; + } + + if (transformedName.startsWith("appeng.")) { + final ClassNode classNode = new ClassNode(); + final ClassReader classReader = new ClassReader(basicClass); + classReader.accept(classNode, 0); + + try { + final boolean reWrite = this.removeOptionals(classNode); + + if (reWrite) { + final ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); + classNode.accept(writer); + return writer.toByteArray(); + } + } catch (final Throwable t) { + t.printStackTrace(); + } + } + return basicClass; + } + + private boolean removeOptionals(final ClassNode classNode) { + boolean changed = false; + + if (classNode.visibleAnnotations != null) { + for (final AnnotationNode an : classNode.visibleAnnotations) { + if (this.hasAnnotation(an, Integration.Interface.class)) { + if (this.stripInterface(classNode, Integration.Interface.class, an)) { + changed = true; + } + } else if (this.hasAnnotation(an, Integration.InterfaceList.class)) { + for (final Object o : ((Iterable) an.values.get(1))) { + if (this.stripInterface(classNode, Integration.InterfaceList.class, (AnnotationNode) o)) { + changed = true; + } + } + } + } + } + + final Iterator i = classNode.methods.iterator(); + while (i.hasNext()) { + final MethodNode mn = i.next(); + + if (mn.visibleAnnotations != null) { + for (final AnnotationNode an : mn.visibleAnnotations) { + if (this.hasAnnotation(an, Integration.Method.class)) { + if (this.stripMethod(classNode, mn, i, Integration.Method.class, an)) { + changed = true; + } + } + } + } + } + + if (changed) { + this.log("Updated " + classNode.name); + } + + return changed; + } + + private boolean hasAnnotation(final AnnotationNode ann, final Class annotation) { + return ann.desc.equals(Type.getDescriptor(annotation)); + } + + private boolean stripInterface(final ClassNode classNode, final Class class1, final AnnotationNode an) { + if (an.values.size() != 4) { + throw new IllegalArgumentException("Unable to handle Interface annotation on " + classNode.name); + } + + String iFace = null; + + if (an.values.get(0).equals("iface")) { + iFace = (String) an.values.get(1); + } else if (an.values.get(2).equals("iface")) { + iFace = (String) an.values.get(3); + } + + String iName = null; + if (an.values.get(0).equals("iname")) { + iName = ((String[]) an.values.get(1))[1]; + } else if (an.values.get(2).equals("iname")) { + iName = ((String[]) an.values.get(3))[1]; + } + + if (iName != null && iFace != null) { + final IntegrationType type = IntegrationType.valueOf(iName); + if (!IntegrationRegistry.INSTANCE.isEnabled(type)) { + this.log("Removing Interface " + iFace + " from " + classNode.name + " because " + iName + + " integration is disabled."); + classNode.interfaces.remove(iFace.replace('.', '/')); + return true; + } else { + this.log("Allowing Interface " + iFace + " from " + classNode.name + " because " + iName + + " integration is enabled."); + } + } else { + throw new IllegalStateException("Unable to handle Method annotation on " + classNode.name); + } + + return false; + } + + private boolean stripMethod( + final ClassNode classNode, + final MethodNode mn, + final Iterator i, + final Class class1, + final AnnotationNode an) { + if (an.values.size() != 2) { + throw new IllegalArgumentException("Unable to handle Method annotation on " + classNode.name); + } + + String iName = null; + + if (an.values.get(0).equals("iname")) { + iName = ((String[]) an.values.get(1))[1]; + } + + if (iName != null) { + final IntegrationType type = IntegrationType.valueOf(iName); + if (!IntegrationRegistry.INSTANCE.isEnabled(type)) { + this.log("Removing Method " + mn.name + " from " + classNode.name + " because " + iName + + " integration is disabled."); + i.remove(); + return true; + } else { + this.log("Allowing Method " + mn.name + " from " + classNode.name + " because " + iName + + " integration is enabled."); + } + } else { + throw new IllegalStateException("Unable to handle Method annotation on " + classNode.name); + } + + return false; + } + + private void log(final String string) { + FMLRelaunchLog.log("AE2-CORE", Level.INFO, string); + } } diff --git a/src/main/java/appeng/transformer/asm/ASMTweaker.java b/src/main/java/appeng/transformer/asm/ASMTweaker.java index d997bee8174..557c5f06b45 100644 --- a/src/main/java/appeng/transformer/asm/ASMTweaker.java +++ b/src/main/java/appeng/transformer/asm/ASMTweaker.java @@ -18,11 +18,12 @@ package appeng.transformer.asm; - import appeng.helpers.Reflected; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import cpw.mods.fml.relauncher.FMLRelaunchLog; +import java.util.Iterator; +import javax.annotation.Nullable; import net.minecraft.launchwrapper.IClassTransformer; import org.apache.logging.log4j.Level; import org.objectweb.asm.ClassReader; @@ -30,133 +31,122 @@ import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.*; -import javax.annotation.Nullable; -import java.util.Iterator; - - @Reflected -public final class ASMTweaker implements IClassTransformer -{ - private static final String[] EXCEPTIONS = new String[0]; - private final Multimap privateToPublicMethods = HashMultimap.create(); - - @Reflected - public ASMTweaker() - { - this.privateToPublicMethods.put( "net.minecraft.client.gui.inventory.GuiContainer", new PublicLine( "func_146977_a", "(Lnet/minecraft/inventory/Slot;)V" ) ); - this.privateToPublicMethods.put( "net.minecraft.client.gui.inventory.GuiContainer", new PublicLine( "a", "(Lzk;)V" ) ); - - this.privateToPublicMethods.put( "appeng.tile.AEBaseTile", new PublicLine( "writeToNBT", "(Lnet/minecraft/nbt/NBTTagCompound;)V" ) ); - this.privateToPublicMethods.put( "appeng.tile.AEBaseTile", new PublicLine( "func_145841_b", "(Lnet/minecraft/nbt/NBTTagCompound;)V" ) ); - this.privateToPublicMethods.put( "appeng.tile.AEBaseTile", new PublicLine( "b", "(Ldh;)V" ) ); - - this.privateToPublicMethods.put( "appeng.tile.AEBaseTile", new PublicLine( "readFromNBT", "(Lnet/minecraft/nbt/NBTTagCompound;)V" ) ); - this.privateToPublicMethods.put( "appeng.tile.AEBaseTile", new PublicLine( "func_145839_a", "(Lnet/minecraft/nbt/NBTTagCompound;)V" ) ); - this.privateToPublicMethods.put( "appeng.tile.AEBaseTile", new PublicLine( "a", "(Ldh;)V" ) ); - } - - @Nullable - @Override - public byte[] transform( final String name, final String transformedName, final byte[] basicClass ) - { - if( basicClass == null ) - { - return null; - } - - try - { - if( transformedName != null && this.privateToPublicMethods.containsKey( transformedName ) ) - { - final ClassNode classNode = new ClassNode(); - final ClassReader classReader = new ClassReader( basicClass ); - classReader.accept( classNode, 0 ); - - for( final PublicLine set : this.privateToPublicMethods.get( transformedName ) ) - { - this.makePublic( classNode, set ); - } - - // CALL VIRTUAL! - if( transformedName.equals( "net.minecraft.client.gui.inventory.GuiContainer" ) ) - { - for( final MethodNode mn : classNode.methods ) - { - if( mn.name.equals( "func_146977_a" ) || ( mn.name.equals( "a" ) && mn.desc.equals( "(Lzk;)V" ) ) ) - { - final MethodNode newNode = new MethodNode( Opcodes.ACC_PUBLIC, "func_146977_a_original", mn.desc, mn.signature, EXCEPTIONS ); - newNode.instructions.add( new VarInsnNode( Opcodes.ALOAD, 0 ) ); - newNode.instructions.add( new VarInsnNode( Opcodes.ALOAD, 1 ) ); - newNode.instructions.add( new MethodInsnNode( Opcodes.INVOKESPECIAL, classNode.name, mn.name, mn.desc, false ) ); - newNode.instructions.add( new InsnNode( Opcodes.RETURN ) ); - this.log( newNode.name + newNode.desc + " - New Method" ); - classNode.methods.add( newNode ); - break; - } - } - - for( final MethodNode mn : classNode.methods ) - { - if( mn.name.equals( "func_73863_a" ) || mn.name.equals( "drawScreen" ) || ( mn.name.equals( "a" ) && mn.desc.equals( "(IIF)V" ) ) ) - { - final Iterator i = mn.instructions.iterator(); - while( i.hasNext() ) - { - final AbstractInsnNode in = i.next(); - if( in.getOpcode() == Opcodes.INVOKESPECIAL ) - { - final MethodInsnNode n = (MethodInsnNode) in; - if( n.name.equals( "func_146977_a" ) || ( n.name.equals( "a" ) && n.desc.equals( "(Lzk;)V" ) ) ) - { - this.log( n.name + n.desc + " - Invoke Virtual" ); - mn.instructions.insertBefore( n, new MethodInsnNode( Opcodes.INVOKEVIRTUAL, n.owner, n.name, n.desc, false ) ); - mn.instructions.remove( in ); - break; - } - } - } - } - } - } - - final ClassWriter writer = new ClassWriter( ClassWriter.COMPUTE_MAXS ); - classNode.accept( writer ); - return writer.toByteArray(); - } - } - catch( final Throwable ignored ) - { - } - - return basicClass; - } - - private void makePublic( final ClassNode classNode, final PublicLine set ) - { - for( final MethodNode mn : classNode.methods ) - { - if( mn.name.equals( set.name ) && mn.desc.equals( set.desc ) ) - { - mn.access = ( mn.access & ( ~( Opcodes.ACC_FINAL | Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED ) ) ) | Opcodes.ACC_PUBLIC; - this.log( mn.name + mn.desc + " - Transformed" ); - } - } - } - - private void log( final String string ) - { - FMLRelaunchLog.log( "AE2-CORE", Level.INFO, string ); - } - - private static final class PublicLine - { - private final String name; - private final String desc; - - public PublicLine( final String name, final String desc ) - { - this.name = name; - this.desc = desc; - } - } +public final class ASMTweaker implements IClassTransformer { + private static final String[] EXCEPTIONS = new String[0]; + private final Multimap privateToPublicMethods = HashMultimap.create(); + + @Reflected + public ASMTweaker() { + this.privateToPublicMethods.put( + "net.minecraft.client.gui.inventory.GuiContainer", + new PublicLine("func_146977_a", "(Lnet/minecraft/inventory/Slot;)V")); + this.privateToPublicMethods.put( + "net.minecraft.client.gui.inventory.GuiContainer", new PublicLine("a", "(Lzk;)V")); + + this.privateToPublicMethods.put( + "appeng.tile.AEBaseTile", new PublicLine("writeToNBT", "(Lnet/minecraft/nbt/NBTTagCompound;)V")); + this.privateToPublicMethods.put( + "appeng.tile.AEBaseTile", new PublicLine("func_145841_b", "(Lnet/minecraft/nbt/NBTTagCompound;)V")); + this.privateToPublicMethods.put("appeng.tile.AEBaseTile", new PublicLine("b", "(Ldh;)V")); + + this.privateToPublicMethods.put( + "appeng.tile.AEBaseTile", new PublicLine("readFromNBT", "(Lnet/minecraft/nbt/NBTTagCompound;)V")); + this.privateToPublicMethods.put( + "appeng.tile.AEBaseTile", new PublicLine("func_145839_a", "(Lnet/minecraft/nbt/NBTTagCompound;)V")); + this.privateToPublicMethods.put("appeng.tile.AEBaseTile", new PublicLine("a", "(Ldh;)V")); + } + + @Nullable + @Override + public byte[] transform(final String name, final String transformedName, final byte[] basicClass) { + if (basicClass == null) { + return null; + } + + try { + if (transformedName != null && this.privateToPublicMethods.containsKey(transformedName)) { + final ClassNode classNode = new ClassNode(); + final ClassReader classReader = new ClassReader(basicClass); + classReader.accept(classNode, 0); + + for (final PublicLine set : this.privateToPublicMethods.get(transformedName)) { + this.makePublic(classNode, set); + } + + // CALL VIRTUAL! + if (transformedName.equals("net.minecraft.client.gui.inventory.GuiContainer")) { + for (final MethodNode mn : classNode.methods) { + if (mn.name.equals("func_146977_a") || (mn.name.equals("a") && mn.desc.equals("(Lzk;)V"))) { + final MethodNode newNode = new MethodNode( + Opcodes.ACC_PUBLIC, "func_146977_a_original", mn.desc, mn.signature, EXCEPTIONS); + newNode.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); + newNode.instructions.add(new VarInsnNode(Opcodes.ALOAD, 1)); + newNode.instructions.add( + new MethodInsnNode(Opcodes.INVOKESPECIAL, classNode.name, mn.name, mn.desc, false)); + newNode.instructions.add(new InsnNode(Opcodes.RETURN)); + this.log(newNode.name + newNode.desc + " - New Method"); + classNode.methods.add(newNode); + break; + } + } + + for (final MethodNode mn : classNode.methods) { + if (mn.name.equals("func_73863_a") + || mn.name.equals("drawScreen") + || (mn.name.equals("a") && mn.desc.equals("(IIF)V"))) { + final Iterator i = mn.instructions.iterator(); + while (i.hasNext()) { + final AbstractInsnNode in = i.next(); + if (in.getOpcode() == Opcodes.INVOKESPECIAL) { + final MethodInsnNode n = (MethodInsnNode) in; + if (n.name.equals("func_146977_a") + || (n.name.equals("a") && n.desc.equals("(Lzk;)V"))) { + this.log(n.name + n.desc + " - Invoke Virtual"); + mn.instructions.insertBefore( + n, + new MethodInsnNode( + Opcodes.INVOKEVIRTUAL, n.owner, n.name, n.desc, false)); + mn.instructions.remove(in); + break; + } + } + } + } + } + } + + final ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); + classNode.accept(writer); + return writer.toByteArray(); + } + } catch (final Throwable ignored) { + } + + return basicClass; + } + + private void makePublic(final ClassNode classNode, final PublicLine set) { + for (final MethodNode mn : classNode.methods) { + if (mn.name.equals(set.name) && mn.desc.equals(set.desc)) { + mn.access = (mn.access & (~(Opcodes.ACC_FINAL | Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED))) + | Opcodes.ACC_PUBLIC; + this.log(mn.name + mn.desc + " - Transformed"); + } + } + } + + private void log(final String string) { + FMLRelaunchLog.log("AE2-CORE", Level.INFO, string); + } + + private static final class PublicLine { + private final String name; + private final String desc; + + public PublicLine(final String name, final String desc) { + this.name = name; + this.desc = desc; + } + } } diff --git a/src/main/java/appeng/transformer/asm/ApiRepairer.java b/src/main/java/appeng/transformer/asm/ApiRepairer.java index c02d56125dd..3cf439af522 100644 --- a/src/main/java/appeng/transformer/asm/ApiRepairer.java +++ b/src/main/java/appeng/transformer/asm/ApiRepairer.java @@ -18,65 +18,62 @@ package appeng.transformer.asm; - import appeng.helpers.Reflected; import cpw.mods.fml.relauncher.FMLRelaunchLog; +import java.net.URL; +import java.net.URLConnection; import net.minecraft.launchwrapper.IClassTransformer; import net.minecraft.launchwrapper.LaunchClassLoader; import org.apache.logging.log4j.Level; -import java.net.URL; -import java.net.URLConnection; - - /* * It is a ClassTransformer which can transformer the older AE2 api class that some addons including, * which can occur the crash due to java.lang.NoSuchMethodError. * See also : https://github.com/xsun2001/Applied-Energistics-2-Unofficial/issues/1 */ @Reflected -public class ApiRepairer implements IClassTransformer -{ +public class ApiRepairer implements IClassTransformer { - private LaunchClassLoader launchClassLoader; + private LaunchClassLoader launchClassLoader; - public ApiRepairer() - { - launchClassLoader = (LaunchClassLoader) this.getClass().getClassLoader(); - FMLRelaunchLog.log( "AE2-ApiRepairer", Level.INFO, "AE2 ApiFixer Installed" ); - } + public ApiRepairer() { + launchClassLoader = (LaunchClassLoader) this.getClass().getClassLoader(); + FMLRelaunchLog.log("AE2-ApiRepairer", Level.INFO, "AE2 ApiFixer Installed"); + } - @Override public byte[] transform( String name, String transformedName, byte[] basicClass ) - { - if( transformedName.startsWith( "appeng.api" ) ) - { - try - { - String clazzurl = getClass().getResource( "" ).toString(); - clazzurl = clazzurl.substring( 0, clazzurl.length() - 23 ) + transformedName.replace( '.', '/' ) + ".class"; - //23 is "appeng/transformer/asm"'s length + 1 - URL url = new URL( clazzurl ); - URLConnection connection = url.openConnection(); - byte[] bytes = new byte[connection.getContentLength()]; - if( connection.getInputStream().read( bytes ) == -1 ) - { - FMLRelaunchLog.log( "AE2-ApiRepairer", Level.ERROR, "Failed to fix api class [%s] because the new class couldn't be read", transformedName ); - return basicClass; - } - for( IClassTransformer ct : launchClassLoader.getTransformers() ) - { - if( ct == this ) - continue; - bytes = ct.transform( name, transformedName, bytes ); - } - return bytes; - } - catch( Exception e ) - { - FMLRelaunchLog.log( "AE2-ApiRepairer", Level.ERROR, "Failed to fix api class [%s] because of [%s]", transformedName, e.getClass().getName() ); - return basicClass; - } - } - return basicClass; - } + @Override + public byte[] transform(String name, String transformedName, byte[] basicClass) { + if (transformedName.startsWith("appeng.api")) { + try { + String clazzurl = getClass().getResource("").toString(); + clazzurl = clazzurl.substring(0, clazzurl.length() - 23) + transformedName.replace('.', '/') + ".class"; + // 23 is "appeng/transformer/asm"'s length + 1 + URL url = new URL(clazzurl); + URLConnection connection = url.openConnection(); + byte[] bytes = new byte[connection.getContentLength()]; + if (connection.getInputStream().read(bytes) == -1) { + FMLRelaunchLog.log( + "AE2-ApiRepairer", + Level.ERROR, + "Failed to fix api class [%s] because the new class couldn't be read", + transformedName); + return basicClass; + } + for (IClassTransformer ct : launchClassLoader.getTransformers()) { + if (ct == this) continue; + bytes = ct.transform(name, transformedName, bytes); + } + return bytes; + } catch (Exception e) { + FMLRelaunchLog.log( + "AE2-ApiRepairer", + Level.ERROR, + "Failed to fix api class [%s] because of [%s]", + transformedName, + e.getClass().getName()); + return basicClass; + } + } + return basicClass; + } } diff --git a/src/main/java/appeng/util/BlockUpdate.java b/src/main/java/appeng/util/BlockUpdate.java index 16fa9851532..fbe4f934c32 100644 --- a/src/main/java/appeng/util/BlockUpdate.java +++ b/src/main/java/appeng/util/BlockUpdate.java @@ -18,32 +18,26 @@ package appeng.util; - import net.minecraft.world.World; +public class BlockUpdate implements IWorldCallable { -public class BlockUpdate implements IWorldCallable -{ - - private final int x; - private final int y; - private final int z; + private final int x; + private final int y; + private final int z; - public BlockUpdate( final int x, final int y, final int z ) - { - this.x = x; - this.y = y; - this.z = z; - } + public BlockUpdate(final int x, final int y, final int z) { + this.x = x; + this.y = y; + this.z = z; + } - @Override - public Boolean call( final World world ) throws Exception - { - if( world.blockExists( this.x, this.y, this.z ) ) - { - world.notifyBlocksOfNeighborChange( this.x, this.y, this.z, Platform.AIR_BLOCK ); - } + @Override + public Boolean call(final World world) throws Exception { + if (world.blockExists(this.x, this.y, this.z)) { + world.notifyBlocksOfNeighborChange(this.x, this.y, this.z, Platform.AIR_BLOCK); + } - return true; - } + return true; + } } diff --git a/src/main/java/appeng/util/ClassInstantiation.java b/src/main/java/appeng/util/ClassInstantiation.java index fdb2dcbbc84..5d35cecbfbd 100644 --- a/src/main/java/appeng/util/ClassInstantiation.java +++ b/src/main/java/appeng/util/ClassInstantiation.java @@ -18,103 +18,95 @@ package appeng.util; - import appeng.core.AELog; import com.google.common.base.Optional; - import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; - -public class ClassInstantiation -{ - private final Class template; - private final Object[] args; - - public ClassInstantiation( final Class template, final Object... args ) - { - this.template = template; - this.args = args; - } - - public Optional get() - { - @SuppressWarnings( "unchecked" ) final Constructor[] constructors = (Constructor[]) this.template.getConstructors(); - - for( final Constructor constructor : constructors ) - { - final Class[] paramTypes = constructor.getParameterTypes(); - if( paramTypes.length == this.args.length ) - { - boolean valid = true; - - for( int idx = 0; idx < paramTypes.length; idx++ ) - { - final Class cz = this.args[idx].getClass(); - if( !this.isClassMatch( paramTypes[idx], cz, this.args[idx] ) ) - { - valid = false; - } - } - - if( valid ) - { - try - { - return Optional.of( constructor.newInstance( this.args ) ); - } - catch( final InstantiationException e ) - { - e.printStackTrace(); - } - catch( final IllegalAccessException e ) - { - e.printStackTrace(); - } - catch( final InvocationTargetException e ) - { - e.printStackTrace(); - } - break; - } - } - } - - return Optional.absent(); - } - - private boolean isClassMatch( Class expected, Class got, final Object value ) - { - if( value == null && !expected.isPrimitive() ) - { - return true; - } - - expected = this.condense( expected, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class ); - got = this.condense( got, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class ); - - return expected == got || expected.isAssignableFrom( got ); - } - - private Class condense( final Class expected, final Class... wrappers ) - { - if( expected.isPrimitive() ) - { - for( final Class clz : wrappers ) - { - try - { - if( expected == clz.getField( "TYPE" ).get( null ) ) - { - return clz; - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - } - } - return expected; - } +public class ClassInstantiation { + private final Class template; + private final Object[] args; + + public ClassInstantiation(final Class template, final Object... args) { + this.template = template; + this.args = args; + } + + public Optional get() { + @SuppressWarnings("unchecked") + final Constructor[] constructors = (Constructor[]) this.template.getConstructors(); + + for (final Constructor constructor : constructors) { + final Class[] paramTypes = constructor.getParameterTypes(); + if (paramTypes.length == this.args.length) { + boolean valid = true; + + for (int idx = 0; idx < paramTypes.length; idx++) { + final Class cz = this.args[idx].getClass(); + if (!this.isClassMatch(paramTypes[idx], cz, this.args[idx])) { + valid = false; + } + } + + if (valid) { + try { + return Optional.of(constructor.newInstance(this.args)); + } catch (final InstantiationException e) { + e.printStackTrace(); + } catch (final IllegalAccessException e) { + e.printStackTrace(); + } catch (final InvocationTargetException e) { + e.printStackTrace(); + } + break; + } + } + } + + return Optional.absent(); + } + + private boolean isClassMatch(Class expected, Class got, final Object value) { + if (value == null && !expected.isPrimitive()) { + return true; + } + + expected = this.condense( + expected, + Boolean.class, + Character.class, + Byte.class, + Short.class, + Integer.class, + Long.class, + Float.class, + Double.class); + got = this.condense( + got, + Boolean.class, + Character.class, + Byte.class, + Short.class, + Integer.class, + Long.class, + Float.class, + Double.class); + + return expected == got || expected.isAssignableFrom(got); + } + + private Class condense(final Class expected, final Class... wrappers) { + if (expected.isPrimitive()) { + for (final Class clz : wrappers) { + try { + if (expected == clz.getField("TYPE").get(null)) { + return clz; + } + } catch (final Throwable t) { + AELog.debug(t); + } + } + } + return expected; + } } diff --git a/src/main/java/appeng/util/ConfigManager.java b/src/main/java/appeng/util/ConfigManager.java index c76ea8876e5..0c3fafc2fc2 100644 --- a/src/main/java/appeng/util/ConfigManager.java +++ b/src/main/java/appeng/util/ConfigManager.java @@ -18,114 +18,94 @@ package appeng.util; - import appeng.api.config.LevelEmitterMode; import appeng.api.config.Settings; import appeng.api.config.StorageFilter; import appeng.api.util.IConfigManager; import appeng.core.AELog; -import net.minecraft.nbt.NBTTagCompound; - import java.util.EnumMap; import java.util.Map; import java.util.Set; +import net.minecraft.nbt.NBTTagCompound; - -public final class ConfigManager implements IConfigManager -{ - private final Map> settings = new EnumMap>( Settings.class ); - private final IConfigManagerHost target; - - public ConfigManager( final IConfigManagerHost tile ) - { - this.target = tile; - } - - @Override - public Set getSettings() - { - return this.settings.keySet(); - } - - @Override - public void registerSetting( final Settings settingName, final Enum defaultValue ) - { - this.settings.put( settingName, defaultValue ); - } - - @Override - public Enum getSetting( final Settings settingName ) - { - final Enum oldValue = this.settings.get( settingName ); - - if( oldValue != null ) - { - return oldValue; - } - - throw new IllegalStateException( "Invalid Config setting. Expected a non-null value for " + settingName ); - } - - @Override - public Enum putSetting( final Settings settingName, final Enum newValue ) - { - final Enum oldValue = this.getSetting( settingName ); - this.settings.put( settingName, newValue ); - this.target.updateSetting( this, settingName, newValue ); - return oldValue; - } - - /** - * save all settings using config manager. - * - * @param tagCompound to be written to compound - */ - @Override - public void writeToNBT( final NBTTagCompound tagCompound ) - { - for( final Map.Entry> entry : this.settings.entrySet() ) - { - tagCompound.setString( entry.getKey().name(), this.settings.get( entry.getKey() ).toString() ); - } - } - - /** - * read all settings using config manager. - * - * @param tagCompound to be read from compound - */ - @Override - public void readFromNBT( final NBTTagCompound tagCompound ) - { - for( final Map.Entry> entry : this.settings.entrySet() ) - { - try - { - if( tagCompound.hasKey( entry.getKey().name() ) ) - { - String value = tagCompound.getString( entry.getKey().name() ); - - // Provides an upgrade path for the rename of this value in the API between rv1 and rv2 - if( value.equals( "EXTACTABLE_ONLY" ) ) - { - value = StorageFilter.EXTRACTABLE_ONLY.toString(); - } - else if( value.equals( "STOREABLE_AMOUNT" ) ) - { - value = LevelEmitterMode.STORABLE_AMOUNT.toString(); - } - - final Enum oldValue = this.settings.get( entry.getKey() ); - - final Enum newValue = Enum.valueOf( oldValue.getClass(), value ); - - this.putSetting( entry.getKey(), newValue ); - } - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - } - } +public final class ConfigManager implements IConfigManager { + private final Map> settings = new EnumMap>(Settings.class); + private final IConfigManagerHost target; + + public ConfigManager(final IConfigManagerHost tile) { + this.target = tile; + } + + @Override + public Set getSettings() { + return this.settings.keySet(); + } + + @Override + public void registerSetting(final Settings settingName, final Enum defaultValue) { + this.settings.put(settingName, defaultValue); + } + + @Override + public Enum getSetting(final Settings settingName) { + final Enum oldValue = this.settings.get(settingName); + + if (oldValue != null) { + return oldValue; + } + + throw new IllegalStateException("Invalid Config setting. Expected a non-null value for " + settingName); + } + + @Override + public Enum putSetting(final Settings settingName, final Enum newValue) { + final Enum oldValue = this.getSetting(settingName); + this.settings.put(settingName, newValue); + this.target.updateSetting(this, settingName, newValue); + return oldValue; + } + + /** + * save all settings using config manager. + * + * @param tagCompound to be written to compound + */ + @Override + public void writeToNBT(final NBTTagCompound tagCompound) { + for (final Map.Entry> entry : this.settings.entrySet()) { + tagCompound.setString( + entry.getKey().name(), this.settings.get(entry.getKey()).toString()); + } + } + + /** + * read all settings using config manager. + * + * @param tagCompound to be read from compound + */ + @Override + public void readFromNBT(final NBTTagCompound tagCompound) { + for (final Map.Entry> entry : this.settings.entrySet()) { + try { + if (tagCompound.hasKey(entry.getKey().name())) { + String value = tagCompound.getString(entry.getKey().name()); + + // Provides an upgrade path for the rename of this value in the API between rv1 and rv2 + if (value.equals("EXTACTABLE_ONLY")) { + value = StorageFilter.EXTRACTABLE_ONLY.toString(); + } else if (value.equals("STOREABLE_AMOUNT")) { + value = LevelEmitterMode.STORABLE_AMOUNT.toString(); + } + + final Enum oldValue = this.settings.get(entry.getKey()); + + final Enum newValue = Enum.valueOf(oldValue.getClass(), value); + + this.putSetting(entry.getKey(), newValue); + } + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } + } + } } diff --git a/src/main/java/appeng/util/IConfigManagerHost.java b/src/main/java/appeng/util/IConfigManagerHost.java index 1323a7df544..e9a02c54e18 100644 --- a/src/main/java/appeng/util/IConfigManagerHost.java +++ b/src/main/java/appeng/util/IConfigManagerHost.java @@ -18,12 +18,9 @@ package appeng.util; - import appeng.api.util.IConfigManager; +public interface IConfigManagerHost { -public interface IConfigManagerHost -{ - - void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ); + void updateSetting(IConfigManager manager, Enum settingName, Enum newValue); } diff --git a/src/main/java/appeng/util/ISlimReadableNumberConverter.java b/src/main/java/appeng/util/ISlimReadableNumberConverter.java index ed8cdb35684..6f1b230528a 100644 --- a/src/main/java/appeng/util/ISlimReadableNumberConverter.java +++ b/src/main/java/appeng/util/ISlimReadableNumberConverter.java @@ -1,9 +1,7 @@ package appeng.util; - import javax.annotation.Nonnegative; - /** * Limits a number converter to a char width of at max 3 characters. * This is generally used for players, who activated the large font extension. @@ -12,19 +10,18 @@ * @version rv2 * @since rv2 */ -public interface ISlimReadableNumberConverter -{ - /** - * Converts a number into a human readable form. It will not round the number, but down it. - * Will try to cut the number down 1 decimal later, but rarely because of the 3 width limitation. - * Can only handle non negative numbers - *

- * Example: - * 10000L -> 10K - * 9999L -> 9K, not 9.9K cause 4 width - * - * @param number to be converted number - * @return String in SI format cut down as far as possible - */ - String toSlimReadableForm( @Nonnegative long number ); +public interface ISlimReadableNumberConverter { + /** + * Converts a number into a human readable form. It will not round the number, but down it. + * Will try to cut the number down 1 decimal later, but rarely because of the 3 width limitation. + * Can only handle non negative numbers + *

+ * Example: + * 10000L -> 10K + * 9999L -> 9K, not 9.9K cause 4 width + * + * @param number to be converted number + * @return String in SI format cut down as far as possible + */ + String toSlimReadableForm(@Nonnegative long number); } diff --git a/src/main/java/appeng/util/IWideReadableNumberConverter.java b/src/main/java/appeng/util/IWideReadableNumberConverter.java index 56602c2fa62..6f003b605fd 100644 --- a/src/main/java/appeng/util/IWideReadableNumberConverter.java +++ b/src/main/java/appeng/util/IWideReadableNumberConverter.java @@ -1,9 +1,7 @@ package appeng.util; - import javax.annotation.Nonnegative; - /** * Limits a number converter to a char width of at max 4 characters * @@ -11,19 +9,18 @@ * @version rv2 * @since rv2 */ -public interface IWideReadableNumberConverter -{ - /** - * Converts a number into a human readable form. It will not round the number, but down it. - * Will try to cut the number down 1 decimal later if width can be below 4. - * Can only handle non negative numbers - *

- * Example: - * 10000L -> 10K - * 9999L -> 9999 - * - * @param number to be converted number - * @return String in SI format cut down as far as possible - */ - String toWideReadableForm( @Nonnegative long number ); +public interface IWideReadableNumberConverter { + /** + * Converts a number into a human readable form. It will not round the number, but down it. + * Will try to cut the number down 1 decimal later if width can be below 4. + * Can only handle non negative numbers + *

+ * Example: + * 10000L -> 10K + * 9999L -> 9999 + * + * @param number to be converted number + * @return String in SI format cut down as far as possible + */ + String toWideReadableForm(@Nonnegative long number); } diff --git a/src/main/java/appeng/util/IWorldCallable.java b/src/main/java/appeng/util/IWorldCallable.java index f81e4e45bfd..8e7b9cdcfaa 100644 --- a/src/main/java/appeng/util/IWorldCallable.java +++ b/src/main/java/appeng/util/IWorldCallable.java @@ -18,12 +18,9 @@ package appeng.util; - -import net.minecraft.world.World; - -import javax.annotation.Nullable; import java.util.concurrent.Callable; - +import javax.annotation.Nullable; +import net.minecraft.world.World; /** * An interface similar to {@link Callable}, but allowing to pass the {@link World} when calling. @@ -33,17 +30,16 @@ * @see Callable * @since rv3 */ -public interface IWorldCallable -{ - /** - * Similar to {@link Callable#call()} - * - * @param world this param is given to not hold a reference to the world but let the caller handle it. Do not expect a world here thus can be - * null. - * @return result of call on the world. Can be null. - * @throws Exception if the call fails - * @see Callable#call() - */ - @Nullable - T call( @Nullable World world ) throws Exception; +public interface IWorldCallable { + /** + * Similar to {@link Callable#call()} + * + * @param world this param is given to not hold a reference to the world but let the caller handle it. Do not expect a world here thus can be + * null. + * @return result of call on the world. Can be null. + * @throws Exception if the call fails + * @see Callable#call() + */ + @Nullable + T call(@Nullable World world) throws Exception; } diff --git a/src/main/java/appeng/util/InWorldToolOperationResult.java b/src/main/java/appeng/util/InWorldToolOperationResult.java index 304047bfdbc..a8b3c664d4d 100644 --- a/src/main/java/appeng/util/InWorldToolOperationResult.java +++ b/src/main/java/appeng/util/InWorldToolOperationResult.java @@ -18,70 +18,57 @@ package appeng.util; - +import java.util.ArrayList; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.BlockAir; import net.minecraft.item.ItemStack; -import java.util.ArrayList; -import java.util.List; - - -public class InWorldToolOperationResult -{ +public class InWorldToolOperationResult { - private final ItemStack BlockItem; - private final List Drops; + private final ItemStack BlockItem; + private final List Drops; - public InWorldToolOperationResult() - { - this.BlockItem = null; - this.Drops = null; - } + public InWorldToolOperationResult() { + this.BlockItem = null; + this.Drops = null; + } - public InWorldToolOperationResult( final ItemStack block, final List drops ) - { - this.BlockItem = block; - this.Drops = drops; - } + public InWorldToolOperationResult(final ItemStack block, final List drops) { + this.BlockItem = block; + this.Drops = drops; + } - public InWorldToolOperationResult( final ItemStack block ) - { - this.BlockItem = block; - this.Drops = null; - } + public InWorldToolOperationResult(final ItemStack block) { + this.BlockItem = block; + this.Drops = null; + } - public static InWorldToolOperationResult getBlockOperationResult( final ItemStack[] items ) - { - final List temp = new ArrayList(); - ItemStack b = null; + public static InWorldToolOperationResult getBlockOperationResult(final ItemStack[] items) { + final List temp = new ArrayList(); + ItemStack b = null; - for( final ItemStack l : items ) - { - if( b == null ) - { - final Block bl = Block.getBlockFromItem( l.getItem() ); + for (final ItemStack l : items) { + if (b == null) { + final Block bl = Block.getBlockFromItem(l.getItem()); - if( bl != null && !( bl instanceof BlockAir ) ) - { - b = l; - continue; - } - } + if (bl != null && !(bl instanceof BlockAir)) { + b = l; + continue; + } + } - temp.add( l ); - } + temp.add(l); + } - return new InWorldToolOperationResult( b, temp ); - } + return new InWorldToolOperationResult(b, temp); + } - public ItemStack getBlockItem() - { - return this.BlockItem; - } + public ItemStack getBlockItem() { + return this.BlockItem; + } - public List getDrops() - { - return this.Drops; - } + public List getDrops() { + return this.Drops; + } } diff --git a/src/main/java/appeng/util/InventoryAdaptor.java b/src/main/java/appeng/util/InventoryAdaptor.java index 2cd3537c86c..30caac25d36 100644 --- a/src/main/java/appeng/util/InventoryAdaptor.java +++ b/src/main/java/appeng/util/InventoryAdaptor.java @@ -18,13 +18,13 @@ package appeng.util; - import appeng.api.config.FuzzyMode; import appeng.api.config.InsertionMode; import appeng.integration.IntegrationRegistry; import appeng.integration.IntegrationType; import appeng.integration.abstraction.IBetterStorage; import appeng.util.inv.*; +import java.util.ArrayList; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; @@ -32,89 +32,76 @@ import net.minecraft.tileentity.TileEntityChest; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; - - -public abstract class InventoryAdaptor implements Iterable -{ - - // returns an appropriate adaptor, or null - public static InventoryAdaptor getAdaptor( final Object te, final ForgeDirection d ) - { - if( te == null ) - { - return null; - } - - final IBetterStorage bs = (IBetterStorage) ( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BetterStorage ) ? IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BetterStorage ) : null ); - - if( te instanceof EntityPlayer ) - { - return new AdaptorIInventory( new AdaptorPlayerInventory( ( (EntityPlayer) te ).inventory, false ) ); - } - else if( te instanceof ArrayList ) - { - @SuppressWarnings( "unchecked" ) final ArrayList list = (ArrayList) te; - - return new AdaptorList( list ); - } - else if( bs != null && bs.isStorageCrate( te ) ) - { - return bs.getAdaptor( te, d ); - } - else if( te instanceof TileEntityChest ) - { - return new AdaptorIInventory( Platform.GetChestInv( te ) ); - } - else if( te instanceof ISidedInventory ) - { - final ISidedInventory si = (ISidedInventory) te; - final int[] slots = si.getAccessibleSlotsFromSide( d.ordinal() ); - if( si.getSizeInventory() > 0 && slots != null && slots.length > 0 ) - { - return new AdaptorIInventory( new WrapperMCISidedInventory( si, d ) ); - } - } - else if( te instanceof IInventory ) - { - final IInventory i = (IInventory) te; - if( i.getSizeInventory() > 0 ) - { - return new AdaptorIInventory( i ); - } - } - - return null; - } - - // return what was extracted. - public abstract ItemStack removeItems( int amount, ItemStack filter, IInventoryDestination destination ); - - public abstract ItemStack simulateRemove( int amount, ItemStack filter, IInventoryDestination destination ); - - // return what was extracted. - public abstract ItemStack removeSimilarItems( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ); - - public abstract ItemStack simulateSimilarRemove( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ); - - // return what isn't used... - public abstract ItemStack addItems( ItemStack toBeAdded ); - - /** - * @param insertionMode advice implementation on how ItemStacks should be inserted. Might not has an effect whatsoever! - */ - public ItemStack addItems( ItemStack toBeAdded, InsertionMode insertionMode ) { - return addItems( toBeAdded ); - } - - public abstract ItemStack simulateAdd( ItemStack toBeSimulated ); - - /** - * @param insertionMode advice implementation on how ItemStacks should be inserted. Might not has an effect whatsoever! - */ - public ItemStack simulateAdd( ItemStack toBeSimulated, InsertionMode insertionMode ) { - return simulateAdd( toBeSimulated ); - } - - public abstract boolean containsItems(); +public abstract class InventoryAdaptor implements Iterable { + + // returns an appropriate adaptor, or null + public static InventoryAdaptor getAdaptor(final Object te, final ForgeDirection d) { + if (te == null) { + return null; + } + + final IBetterStorage bs = (IBetterStorage) + (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BetterStorage) + ? IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BetterStorage) + : null); + + if (te instanceof EntityPlayer) { + return new AdaptorIInventory(new AdaptorPlayerInventory(((EntityPlayer) te).inventory, false)); + } else if (te instanceof ArrayList) { + @SuppressWarnings("unchecked") + final ArrayList list = (ArrayList) te; + + return new AdaptorList(list); + } else if (bs != null && bs.isStorageCrate(te)) { + return bs.getAdaptor(te, d); + } else if (te instanceof TileEntityChest) { + return new AdaptorIInventory(Platform.GetChestInv(te)); + } else if (te instanceof ISidedInventory) { + final ISidedInventory si = (ISidedInventory) te; + final int[] slots = si.getAccessibleSlotsFromSide(d.ordinal()); + if (si.getSizeInventory() > 0 && slots != null && slots.length > 0) { + return new AdaptorIInventory(new WrapperMCISidedInventory(si, d)); + } + } else if (te instanceof IInventory) { + final IInventory i = (IInventory) te; + if (i.getSizeInventory() > 0) { + return new AdaptorIInventory(i); + } + } + + return null; + } + + // return what was extracted. + public abstract ItemStack removeItems(int amount, ItemStack filter, IInventoryDestination destination); + + public abstract ItemStack simulateRemove(int amount, ItemStack filter, IInventoryDestination destination); + + // return what was extracted. + public abstract ItemStack removeSimilarItems( + int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination); + + public abstract ItemStack simulateSimilarRemove( + int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination); + + // return what isn't used... + public abstract ItemStack addItems(ItemStack toBeAdded); + + /** + * @param insertionMode advice implementation on how ItemStacks should be inserted. Might not has an effect whatsoever! + */ + public ItemStack addItems(ItemStack toBeAdded, InsertionMode insertionMode) { + return addItems(toBeAdded); + } + + public abstract ItemStack simulateAdd(ItemStack toBeSimulated); + + /** + * @param insertionMode advice implementation on how ItemStacks should be inserted. Might not has an effect whatsoever! + */ + public ItemStack simulateAdd(ItemStack toBeSimulated, InsertionMode insertionMode) { + return simulateAdd(toBeSimulated); + } + + public abstract boolean containsItems(); } diff --git a/src/main/java/appeng/util/ItemSorters.java b/src/main/java/appeng/util/ItemSorters.java index 9da43efdfca..14e472f8554 100644 --- a/src/main/java/appeng/util/ItemSorters.java +++ b/src/main/java/appeng/util/ItemSorters.java @@ -18,159 +18,124 @@ package appeng.util; - import appeng.api.config.SortDir; import appeng.api.storage.data.IAEItemStack; import appeng.integration.IntegrationRegistry; import appeng.integration.IntegrationType; import appeng.integration.abstraction.IInvTweaks; import appeng.util.item.AEItemStack; - import java.util.Comparator; - -public class ItemSorters -{ - - private static SortDir Direction = SortDir.ASCENDING; - - public static final Comparator CONFIG_BASED_SORT_BY_NAME = new Comparator() - { - - @Override - public int compare( final IAEItemStack o1, final IAEItemStack o2 ) - { - if( getDirection() == SortDir.ASCENDING ) - { - return Platform.getItemDisplayName( o1 ).compareToIgnoreCase( Platform.getItemDisplayName( o2 ) ); - } - return Platform.getItemDisplayName( o2 ).compareToIgnoreCase( Platform.getItemDisplayName( o1 ) ); - } - }; - public static final Comparator CONFIG_BASED_SORT_BY_MOD = new Comparator() - { - - @Override - public int compare( final IAEItemStack o1, final IAEItemStack o2 ) - { - final AEItemStack op1 = (AEItemStack) o1; - final AEItemStack op2 = (AEItemStack) o2; - - if( getDirection() == SortDir.ASCENDING ) - { - return this.secondarySort( op2.getModID().compareToIgnoreCase( op1.getModID() ), o1, o2 ); - } - return this.secondarySort( op1.getModID().compareToIgnoreCase( op2.getModID() ), o2, o1 ); - } - - private int secondarySort( final int compareToIgnoreCase, final IAEItemStack o1, final IAEItemStack o2 ) - { - if( compareToIgnoreCase == 0 ) - { - return Platform.getItemDisplayName( o2 ).compareToIgnoreCase( Platform.getItemDisplayName( o1 ) ); - } - - return compareToIgnoreCase; - } - }; - public static final Comparator CONFIG_BASED_SORT_BY_SIZE = new Comparator() - { - - @Override - public int compare( final IAEItemStack o1, final IAEItemStack o2 ) - { - if( getDirection() == SortDir.ASCENDING ) - { - return compareLong( o2.getStackSize(), o1.getStackSize() ); - } - return compareLong( o1.getStackSize(), o2.getStackSize() ); - } - }; - private static IInvTweaks api; - public static final Comparator CONFIG_BASED_SORT_BY_INV_TWEAKS = new Comparator() - { - - @Override - public int compare( final IAEItemStack o1, final IAEItemStack o2 ) - { - if( api == null ) - { - return CONFIG_BASED_SORT_BY_NAME.compare( o1, o2 ); - } - - final int cmp = api.compareItems( o1.getItemStack(), o2.getItemStack() ); - - if( getDirection() == SortDir.ASCENDING ) - { - return cmp; - } - return -cmp; - } - }; - - public static void init() - { - if( api != null ) - { - return; - } - - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.InvTweaks ) ) - { - api = (IInvTweaks) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.InvTweaks ); - } - else - { - api = null; - } - } - - public static int compareInt( final int a, final int b ) - { - if( a == b ) - { - return 0; - } - if( a < b ) - { - return -1; - } - return 1; - } - - public static int compareLong( final long a, final long b ) - { - if( a == b ) - { - return 0; - } - if( a < b ) - { - return -1; - } - return 1; - } - - public static int compareDouble( final double a, final double b ) - { - if( a == b ) - { - return 0; - } - if( a < b ) - { - return -1; - } - return 1; - } - - private static SortDir getDirection() - { - return Direction; - } - - public static void setDirection( final SortDir direction ) - { - Direction = direction; - } +public class ItemSorters { + + private static SortDir Direction = SortDir.ASCENDING; + + public static final Comparator CONFIG_BASED_SORT_BY_NAME = new Comparator() { + + @Override + public int compare(final IAEItemStack o1, final IAEItemStack o2) { + if (getDirection() == SortDir.ASCENDING) { + return Platform.getItemDisplayName(o1).compareToIgnoreCase(Platform.getItemDisplayName(o2)); + } + return Platform.getItemDisplayName(o2).compareToIgnoreCase(Platform.getItemDisplayName(o1)); + } + }; + public static final Comparator CONFIG_BASED_SORT_BY_MOD = new Comparator() { + + @Override + public int compare(final IAEItemStack o1, final IAEItemStack o2) { + final AEItemStack op1 = (AEItemStack) o1; + final AEItemStack op2 = (AEItemStack) o2; + + if (getDirection() == SortDir.ASCENDING) { + return this.secondarySort(op2.getModID().compareToIgnoreCase(op1.getModID()), o1, o2); + } + return this.secondarySort(op1.getModID().compareToIgnoreCase(op2.getModID()), o2, o1); + } + + private int secondarySort(final int compareToIgnoreCase, final IAEItemStack o1, final IAEItemStack o2) { + if (compareToIgnoreCase == 0) { + return Platform.getItemDisplayName(o2).compareToIgnoreCase(Platform.getItemDisplayName(o1)); + } + + return compareToIgnoreCase; + } + }; + public static final Comparator CONFIG_BASED_SORT_BY_SIZE = new Comparator() { + + @Override + public int compare(final IAEItemStack o1, final IAEItemStack o2) { + if (getDirection() == SortDir.ASCENDING) { + return compareLong(o2.getStackSize(), o1.getStackSize()); + } + return compareLong(o1.getStackSize(), o2.getStackSize()); + } + }; + private static IInvTweaks api; + public static final Comparator CONFIG_BASED_SORT_BY_INV_TWEAKS = new Comparator() { + + @Override + public int compare(final IAEItemStack o1, final IAEItemStack o2) { + if (api == null) { + return CONFIG_BASED_SORT_BY_NAME.compare(o1, o2); + } + + final int cmp = api.compareItems(o1.getItemStack(), o2.getItemStack()); + + if (getDirection() == SortDir.ASCENDING) { + return cmp; + } + return -cmp; + } + }; + + public static void init() { + if (api != null) { + return; + } + + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.InvTweaks)) { + api = (IInvTweaks) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.InvTweaks); + } else { + api = null; + } + } + + public static int compareInt(final int a, final int b) { + if (a == b) { + return 0; + } + if (a < b) { + return -1; + } + return 1; + } + + public static int compareLong(final long a, final long b) { + if (a == b) { + return 0; + } + if (a < b) { + return -1; + } + return 1; + } + + public static int compareDouble(final double a, final double b) { + if (a == b) { + return 0; + } + if (a < b) { + return -1; + } + return 1; + } + + private static SortDir getDirection() { + return Direction; + } + + public static void setDirection(final SortDir direction) { + Direction = direction; + } } diff --git a/src/main/java/appeng/util/LookDirection.java b/src/main/java/appeng/util/LookDirection.java index a05cce613cf..e8bd6cde6f3 100644 --- a/src/main/java/appeng/util/LookDirection.java +++ b/src/main/java/appeng/util/LookDirection.java @@ -18,29 +18,23 @@ package appeng.util; - import net.minecraft.util.Vec3; +public class LookDirection { -public class LookDirection -{ - - private final Vec3 a; - private final Vec3 b; + private final Vec3 a; + private final Vec3 b; - public LookDirection( final Vec3 a, final Vec3 b ) - { - this.a = a; - this.b = b; - } + public LookDirection(final Vec3 a, final Vec3 b) { + this.a = a; + this.b = b; + } - public Vec3 getA() - { - return this.a; - } + public Vec3 getA() { + return this.a; + } - public Vec3 getB() - { - return this.b; - } + public Vec3 getB() { + return this.b; + } } diff --git a/src/main/java/appeng/util/Platform.java b/src/main/java/appeng/util/Platform.java index a0c70215856..f1feff50d6c 100644 --- a/src/main/java/appeng/util/Platform.java +++ b/src/main/java/appeng/util/Platform.java @@ -18,7 +18,6 @@ package appeng.util; - import appeng.api.AEApi; import appeng.api.config.*; import appeng.api.definitions.IItemDefinition; @@ -68,6 +67,13 @@ import cpw.mods.fml.relauncher.ReflectionHelper; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.security.InvalidParameterException; +import java.text.DecimalFormat; +import java.util.*; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; @@ -99,1990 +105,1710 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.oredict.OreDictionary; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.security.InvalidParameterException; -import java.text.DecimalFormat; -import java.util.*; - - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class Platform -{ - - public static final Block AIR_BLOCK = Blocks.air; - - public static final int DEF_OFFSET = 16; - - /* - * random source, use it for item drop locations... - */ - private static final Random RANDOM_GENERATOR = new Random(); - private static final WeakHashMap FAKE_PLAYERS = new WeakHashMap(); - private static Field tagList; - private static Class playerInstance; - private static Method getOrCreateChunkWatcher; - private static Method sendToAllPlayersWatchingChunk; - private static GameProfile fakeProfile = new GameProfile( UUID.fromString( "839eb18c-50bc-400c-8291-9383f09763e7" ), "[AE2Player]" ); - - public static Random getRandom() - { - return RANDOM_GENERATOR; - } - - public static float getRandomFloat() - { - return RANDOM_GENERATOR.nextFloat(); - } - - /** - * This displays the value for encoded longs ( double *100 ) - * - * @param n to be formatted long value - * @param isRate if true it adds a /t to the formatted string - * @return formatted long value - */ - public static String formatPowerLong( final long n, final boolean isRate ) - { - double p = ( (double) n ) / 100; - - final PowerUnits displayUnits = AEConfig.instance.selectedPowerUnit(); - p = PowerUnits.AE.convertTo( displayUnits, p ); - - String unitName = displayUnits.name(); - - if( displayUnits == PowerUnits.WA ) - { - unitName = "J"; - } - - if( displayUnits == PowerUnits.MK ) - { - unitName = "J"; - } - - final String[] preFixes = { - "k", - "M", - "G", - "T", - "P", - "T", - "P", - "E", - "Z", - "Y" - }; - String level = ""; - int offset = 0; - while( p > 1000 && offset < preFixes.length ) - { - p /= 1000; - level = preFixes[offset]; - offset++; - } - - final DecimalFormat df = new DecimalFormat( "#.##" ); - return df.format( p ) + ' ' + level + unitName + ( isRate ? "/t" : "" ); - } - - public static ForgeDirection crossProduct( final ForgeDirection forward, final ForgeDirection up ) - { - final int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; - final int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; - final int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; - - switch( west_x + west_y * 2 + west_z * 3 ) - { - case 1: - return ForgeDirection.EAST; - case -1: - return ForgeDirection.WEST; - - case 2: - return ForgeDirection.UP; - case -2: - return ForgeDirection.DOWN; - - case 3: - return ForgeDirection.SOUTH; - case -3: - return ForgeDirection.NORTH; - } - - return ForgeDirection.UNKNOWN; - } - - public static T rotateEnum( T ce, final boolean backwards, final EnumSet validOptions ) - { - do - { - if( backwards ) - { - ce = prevEnum( ce ); - } - else - { - ce = nextEnum( ce ); - } - } - while( !validOptions.contains( ce ) || isNotValidSetting( ce ) ); - - return ce; - } - - /* - * Simple way to cycle an enum... - */ - private static T prevEnum( final T ce ) - { - final EnumSet valList = EnumSet.allOf( ce.getClass() ); - - int pLoc = ce.ordinal() - 1; - if( pLoc < 0 ) - { - pLoc = valList.size() - 1; - } - - if( pLoc < 0 || pLoc >= valList.size() ) - { - pLoc = 0; - } - - int pos = 0; - for( final Object g : valList ) - { - if( pos == pLoc ) - { - return (T) g; - } - pos++; - } - - return null; - } - - /* - * Simple way to cycle an enum... - */ - public static T nextEnum( final T ce ) - { - final EnumSet valList = EnumSet.allOf( ce.getClass() ); - - int pLoc = ce.ordinal() + 1; - if( pLoc >= valList.size() ) - { - pLoc = 0; - } - - if( pLoc < 0 || pLoc >= valList.size() ) - { - pLoc = 0; - } - - int pos = 0; - for( final Object g : valList ) - { - if( pos == pLoc ) - { - return (T) g; - } - pos++; - } - - return null; - } - - private static boolean isNotValidSetting( final Enum e ) - { - if( e == SortOrder.INVTWEAKS && !IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.InvTweaks ) ) - { - return true; - } - - if( e == SearchBoxMode.NEI_AUTOSEARCH && !IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.NEI ) ) - { - return true; - } - - return e == SearchBoxMode.NEI_MANUAL_SEARCH && !IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.NEI ); - - } - - public static void openGUI( @Nonnull final EntityPlayer p, @Nullable final TileEntity tile, @Nullable final ForgeDirection side, @Nonnull final GuiBridge type ) - { - if( isClient() ) - { - return; - } - - int x = (int) p.posX; - int y = (int) p.posY; - int z = (int) p.posZ; - if( tile != null ) - { - x = tile.xCoord; - y = tile.yCoord; - z = tile.zCoord; - } - - if( ( type.getType().isItem() && tile == null ) || type.hasPermissions( tile, x, y, z, side, p ) ) - { - if( tile == null && type.getType() == GuiHostType.ITEM ) - { - p.openGui( AppEng.instance(), type.ordinal() << 5 | (1 << 4), p.getEntityWorld(), p.inventory.currentItem, 0, 0 ); - } - else if( tile == null || type.getType() == GuiHostType.ITEM ) - { - p.openGui( AppEng.instance(), type.ordinal() << 5 | ( 1 << 3 ), p.getEntityWorld(), x, y, z ); - } - else - { - p.openGui( AppEng.instance(), type.ordinal() << 5 | ( side.ordinal() ), tile.getWorldObj(), x, y, z ); - } - } - } - - /* - * returns true if the code is on the client. - */ - public static boolean isClient() - { - return FMLCommonHandler.instance().getEffectiveSide().isClient(); - } - - public static boolean hasPermissions( final DimensionalCoord dc, final EntityPlayer player ) - { - return dc.getWorld().canMineBlock( player, dc.x, dc.y, dc.z ); - } - - /* - * Checks to see if a block is air? - */ - public static boolean isBlockAir( final World w, final int x, final int y, final int z ) - { - try - { - return w.getBlock( x, y, z ).isAir( w, x, y, z ); - } - catch( final Throwable e ) - { - return false; - } - } - - /* - * Lots of silliness to try and account for weird tag related junk, basically requires that two tags have at least - * something in their tags before it wasts its time comparing them. - */ - private static boolean sameStackStags( final ItemStack a, final ItemStack b ) - { - if( a == null && b == null ) - { - return true; - } - if( a == null || b == null ) - { - return false; - } - if( a == b ) - { - return true; - } - - final NBTTagCompound ta = a.getTagCompound(); - final NBTTagCompound tb = b.getTagCompound(); - if( ta == tb ) - { - return true; - } - - if( ( ta == null && tb == null ) || ( ta != null && ta.hasNoTags() && tb == null ) || ( tb != null && tb.hasNoTags() && ta == null ) || ( ta != null && ta.hasNoTags() && tb != null && tb.hasNoTags() ) ) - { - return true; - } - - if( ( ta == null && tb != null ) || ( ta != null && tb == null ) ) - { - return false; - } - - // if both tags are shared this is easy... - if( AESharedNBT.isShared( ta ) && AESharedNBT.isShared( tb ) ) - { - return ta == tb; - } - - return NBTEqualityTest( ta, tb ); - } - - /* - * recursive test for NBT Equality, this was faster then trying to compare / generate hashes, its also more reliable - * then the vanilla version which likes to fail when NBT Compound data changes order, it is pretty expensive - * performance wise, so try an use shared tag compounds as long as the system remains in AE. - */ - public static boolean NBTEqualityTest( final NBTBase left, final NBTBase right ) - { - // same type? - final byte id = left.getId(); - if( id == right.getId() ) - { - switch( id ) - { - case 10: - { - final NBTTagCompound ctA = (NBTTagCompound) left; - final NBTTagCompound ctB = (NBTTagCompound) right; - - final Set cA = ctA.func_150296_c(); - final Set cB = ctB.func_150296_c(); - - if( cA.size() != cB.size() ) - { - return false; - } - - for( final String name : cA ) - { - final NBTBase tag = ctA.getTag( name ); - final NBTBase aTag = ctB.getTag( name ); - if( aTag == null ) - { - return false; - } - - if( !NBTEqualityTest( tag, aTag ) ) - { - return false; - } - } - - return true; - } - - case 9: // ) // A instanceof NBTTagList ) - { - final NBTTagList lA = (NBTTagList) left; - final NBTTagList lB = (NBTTagList) right; - if( lA.tagCount() != lB.tagCount() ) - { - return false; - } - - final List tag = tagList( lA ); - final List aTag = tagList( lB ); - if( tag.size() != aTag.size() ) - { - return false; - } - - for( int x = 0; x < tag.size(); x++ ) - { - if( aTag.get( x ) == null ) - { - return false; - } - - if( !NBTEqualityTest( tag.get( x ), aTag.get( x ) ) ) - { - return false; - } - } - - return true; - } - - case 1: // ( A instanceof NBTTagByte ) - return ( (NBTBase.NBTPrimitive) left ).func_150287_d() == ( (NBTBase.NBTPrimitive) right ).func_150287_d(); - - case 4: // else if ( A instanceof NBTTagLong ) - return ( (NBTBase.NBTPrimitive) left ).func_150291_c() == ( (NBTBase.NBTPrimitive) right ).func_150291_c(); - - case 8: // else if ( A instanceof NBTTagString ) - return ( (NBTTagString) left ).func_150285_a_().equals( ( (NBTTagString) right ).func_150285_a_() ) || ( (NBTTagString) left ).func_150285_a_().equals( ( (NBTTagString) right ).func_150285_a_() ); - - case 6: // else if ( A instanceof NBTTagDouble ) - return ( (NBTBase.NBTPrimitive) left ).func_150286_g() == ( (NBTBase.NBTPrimitive) right ).func_150286_g(); - - case 5: // else if ( A instanceof NBTTagFloat ) - return ( (NBTBase.NBTPrimitive) left ).func_150288_h() == ( (NBTBase.NBTPrimitive) right ).func_150288_h(); - - case 3: // else if ( A instanceof NBTTagInt ) - return ( (NBTBase.NBTPrimitive) left ).func_150287_d() == ( (NBTBase.NBTPrimitive) right ).func_150287_d(); - - default: - return left.equals( right ); - } - } - - return false; - } - - private static List tagList( final NBTTagList lB ) - { - if( tagList == null ) - { - try - { - tagList = lB.getClass().getDeclaredField( "tagList" ); - } - catch( final Throwable t ) - { - try - { - tagList = lB.getClass().getDeclaredField( "field_74747_a" ); - } - catch( final Throwable z ) - { - AELog.debug( t ); - AELog.debug( z ); - } - } - } - - try - { - tagList.setAccessible( true ); - return (List) tagList.get( lB ); - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - - return new ArrayList(); - } - - /* - * Orderless hash on NBT Data, used to work thought huge piles fast, but ignores the order just in case MC decided - * to change it... WHICH IS BAD... - */ - public static int NBTOrderlessHash( final NBTBase nbt ) - { - // same type? - int hash = 0; - final byte id = nbt.getId(); - hash += id; - switch( id ) - { - case 10: - { - final NBTTagCompound ctA = (NBTTagCompound) nbt; - - final Set cA = ctA.func_150296_c(); - - for( final String name : cA ) - { - hash += name.hashCode() ^ NBTOrderlessHash( ctA.getTag( name ) ); - } - - return hash; - } - - case 9: // ) // A instanceof NBTTagList ) - { - final NBTTagList lA = (NBTTagList) nbt; - hash += 9 * lA.tagCount(); - - final List l = tagList( lA ); - for( int x = 0; x < l.size(); x++ ) - { - hash += ( (Integer) x ).hashCode() ^ NBTOrderlessHash( l.get( x ) ); - } - - return hash; - } - - case 1: // ( A instanceof NBTTagByte ) - return hash + ( (NBTBase.NBTPrimitive) nbt ).func_150290_f(); - - case 4: // else if ( A instanceof NBTTagLong ) - return hash + (int) ( (NBTBase.NBTPrimitive) nbt ).func_150291_c(); - - case 8: // else if ( A instanceof NBTTagString ) - return hash + ( (NBTTagString) nbt ).func_150285_a_().hashCode(); - - case 6: // else if ( A instanceof NBTTagDouble ) - return hash + (int) ( (NBTBase.NBTPrimitive) nbt ).func_150286_g(); - - case 5: // else if ( A instanceof NBTTagFloat ) - return hash + (int) ( (NBTBase.NBTPrimitive) nbt ).func_150288_h(); - - case 3: // else if ( A instanceof NBTTagInt ) - return hash + ( (NBTBase.NBTPrimitive) nbt ).func_150287_d(); - - default: - return hash; - } - } - - private static IRecipe lastUsedRecipe = null; - - /* - * The usual version of this returns an ItemStack, this version returns the recipe. - */ - public static IRecipe findMatchingRecipe( final InventoryCrafting inventoryCrafting, final World par2World ) - { - if (lastUsedRecipe != null && lastUsedRecipe.matches(inventoryCrafting, par2World)) - return lastUsedRecipe; - - final CraftingManager cm = CraftingManager.getInstance(); - final List rl = cm.getRecipeList(); - - for( final IRecipe r : rl ) - { - if( r.matches( inventoryCrafting, par2World ) ) - { - lastUsedRecipe = r; - return r; - } - } - - return null; - } - - public static ItemStack[] getBlockDrops( final World w, final int x, final int y, final int z ) - { - List out = new ArrayList(); - final Block which = w.getBlock( x, y, z ); - - if( which != null ) - { - out = which.getDrops( w, x, y, z, w.getBlockMetadata( x, y, z ), 0 ); - } - - if( out == null ) - { - return new ItemStack[0]; - } - return out.toArray( new ItemStack[out.size()] ); - } - - public static ForgeDirection cycleOrientations( final ForgeDirection dir, final boolean upAndDown ) - { - if( upAndDown ) - { - switch( dir ) - { - case NORTH: - return ForgeDirection.SOUTH; - case SOUTH: - return ForgeDirection.EAST; - case EAST: - return ForgeDirection.WEST; - case WEST: - return ForgeDirection.NORTH; - case UP: - return ForgeDirection.UP; - case DOWN: - return ForgeDirection.DOWN; - case UNKNOWN: - return ForgeDirection.UNKNOWN; - } - } - else - { - switch( dir ) - { - case UP: - return ForgeDirection.DOWN; - case DOWN: - return ForgeDirection.NORTH; - case NORTH: - return ForgeDirection.SOUTH; - case SOUTH: - return ForgeDirection.EAST; - case EAST: - return ForgeDirection.WEST; - case WEST: - return ForgeDirection.UP; - case UNKNOWN: - return ForgeDirection.UNKNOWN; - } - } - - return ForgeDirection.UNKNOWN; - } - - /* - * Creates / or loads previous NBT Data on items, used for editing items owned by AE. - */ - public static NBTTagCompound openNbtData( final ItemStack i ) - { - NBTTagCompound compound = i.getTagCompound(); - - if( compound == null ) - { - i.setTagCompound( compound = new NBTTagCompound() ); - } - - return compound; - } - - /* - * Generates Item entities in the world similar to how items are generally dropped. - */ - public static void spawnDrops( final World w, final int x, final int y, final int z, final List drops ) - { - if( isServer() ) - { - for( final ItemStack i : drops ) - { - if( i != null ) - { - if( i.stackSize > 0 ) - { - final double offset_x = ( getRandomInt() % 32 - 16 ) / 82; - final double offset_y = ( getRandomInt() % 32 - 16 ) / 82; - final double offset_z = ( getRandomInt() % 32 - 16 ) / 82; - final EntityItem ei = new EntityItem( w, 0.5 + offset_x + x, 0.5 + offset_y + y, 0.2 + offset_z + z, i.copy() ); - w.spawnEntityInWorld( ei ); - } - } - } - } - } - - /* - * returns true if the code is on the server. - */ - public static boolean isServer() - { - return FMLCommonHandler.instance().getEffectiveSide().isServer(); - } - - public static int getRandomInt() - { - return Math.abs( RANDOM_GENERATOR.nextInt() ); - } - - /* - * Utility function to get the full inventory for a Double Chest in the World. - */ - public static IInventory GetChestInv( final Object te ) - { - TileEntityChest teA = (TileEntityChest) te; - TileEntity teB = null; - final Block myBlockID = teA.getWorldObj().getBlock( teA.xCoord, teA.yCoord, teA.zCoord ); - - if( teA.getWorldObj().getBlock( teA.xCoord + 1, teA.yCoord, teA.zCoord ) == myBlockID ) - { - teB = teA.getWorldObj().getTileEntity( teA.xCoord + 1, teA.yCoord, teA.zCoord ); - if( !( teB instanceof TileEntityChest ) ) - { - teB = null; - } - } - - if( teB == null ) - { - if( teA.getWorldObj().getBlock( teA.xCoord - 1, teA.yCoord, teA.zCoord ) == myBlockID ) - { - teB = teA.getWorldObj().getTileEntity( teA.xCoord - 1, teA.yCoord, teA.zCoord ); - if( !( teB instanceof TileEntityChest ) ) - { - teB = null; - } - else - { - final TileEntityChest x = teA; - teA = (TileEntityChest) teB; - teB = x; - } - } - } - - if( teB == null ) - { - if( teA.getWorldObj().getBlock( teA.xCoord, teA.yCoord, teA.zCoord + 1 ) == myBlockID ) - { - teB = teA.getWorldObj().getTileEntity( teA.xCoord, teA.yCoord, teA.zCoord + 1 ); - if( !( teB instanceof TileEntityChest ) ) - { - teB = null; - } - } - } - - if( teB == null ) - { - if( teA.getWorldObj().getBlock( teA.xCoord, teA.yCoord, teA.zCoord - 1 ) == myBlockID ) - { - teB = teA.getWorldObj().getTileEntity( teA.xCoord, teA.yCoord, teA.zCoord - 1 ); - if( !( teB instanceof TileEntityChest ) ) - { - teB = null; - } - else - { - final TileEntityChest x = teA; - teA = (TileEntityChest) teB; - teB = x; - } - } - } - - if( teB == null ) - { - return teA; - } - - return new InventoryLargeChest( "", teA, (IInventory) teB ); - } - - public static boolean isModLoaded( final String modid ) - { - try - { - // if this fails for some reason, try the other method. - return Loader.isModLoaded( modid ); - } - catch( final Throwable ignored ) - { - } - - for( final ModContainer f : Loader.instance().getActiveModList() ) - { - if( f.getModId().equals( modid ) ) - { - return true; - } - } - return false; - } - - public static ItemStack findMatchingRecipeOutput( final InventoryCrafting ic, final World worldObj ) - { - return CraftingManager.getInstance().findMatchingRecipe( ic, worldObj ); - } - - @SideOnly( Side.CLIENT ) - public static List getTooltip( final Object o ) - { - if( o == null ) - { - return new ArrayList(); - } - - ItemStack itemStack = null; - if( o instanceof AEItemStack ) - { - final AEItemStack ais = (AEItemStack) o; - return ais.getToolTip(); - } - else if( o instanceof ItemStack ) - { - itemStack = (ItemStack) o; - } - else - { - return new ArrayList(); - } - - try - { - return itemStack.getTooltip( Minecraft.getMinecraft().thePlayer, false ); - } - catch( final Exception errB ) - { - return new ArrayList(); - } - } - - public static String getModId( final IAEItemStack is ) - { - if( is == null ) - { - return "** Null"; - } - - final String n = ( (AEItemStack) is ).getModID(); - return n == null ? "** Null" : n; - } - - public static String getItemDisplayName( final Object o ) - { - if( o == null ) - { - return "** Null"; - } - - ItemStack itemStack = null; - if( o instanceof AEItemStack ) - { - final String n = ( (AEItemStack) o ).getDisplayName(); - return n == null ? "** Null" : n; - } - else if( o instanceof ItemStack ) - { - itemStack = (ItemStack) o; - } - else - { - return "**Invalid Object"; - } - - try - { - String name = itemStack.getDisplayName(); - if( name == null || name.isEmpty() ) - { - name = itemStack.getItem().getUnlocalizedName( itemStack ); - } - return name == null ? "** Null" : name; - } - catch( final Exception errA ) - { - try - { - final String n = itemStack.getUnlocalizedName(); - return n == null ? "** Null" : n; - } - catch( final Exception errB ) - { - return "** Exception"; - } - } - } - - public static boolean hasSpecialComparison( final IAEItemStack willAdd ) - { - if( willAdd == null ) - { - return false; - } - final IAETagCompound tag = willAdd.getTagCompound(); - return tag != null && tag.getSpecialComparison() != null; - } - - public static boolean hasSpecialComparison( final ItemStack willAdd ) - { - if( AESharedNBT.isShared( willAdd.getTagCompound() ) ) - { - if( ( (IAETagCompound) willAdd.getTagCompound() ).getSpecialComparison() != null ) - { - return true; - } - } - return false; - } - - public static boolean isWrench( final EntityPlayer player, final ItemStack eq, final int x, final int y, final int z ) - { - if( eq != null ) - { - try - { - if( eq.getItem() instanceof IToolWrench ) - { - final IToolWrench wrench = (IToolWrench) eq.getItem(); - return wrench.canWrench( player, x, y, z ); - } - } - catch( final Throwable ignore ) - { // explodes without BC - - } - - if( eq.getItem() instanceof IAEWrench ) - { - final IAEWrench wrench = (IAEWrench) eq.getItem(); - return wrench.canWrench( eq, player, x, y, z ); - } - } - return false; - } - - public static boolean isChargeable( final ItemStack i ) - { - if( i == null ) - { - return false; - } - final Item it = i.getItem(); - if( it instanceof IAEItemPowerStorage ) - { - return ( (IAEItemPowerStorage) it ).getPowerFlow( i ) != AccessRestriction.READ; - } - return false; - } - - public static EntityPlayer getPlayer( final WorldServer w ) - { - if( w == null ) - { - throw new InvalidParameterException( "World is null." ); - } - - final EntityPlayer wrp = FAKE_PLAYERS.get( w ); - if( wrp != null ) - { - return wrp; - } - - final EntityPlayer p = FakePlayerFactory.get( w, fakeProfile ); - FAKE_PLAYERS.put( w, p ); - return p; - } - - public static int MC2MEColor( final int color ) - { - switch( color ) - { - case 4: // "blue" - return 0; - case 0: // "black" - return 1; - case 15: // "white" - return 2; - case 3: // "brown" - return 3; - case 1: // "red" - return 4; - case 11: // "yellow" - return 5; - case 2: // "green" - return 6; - - case 5: // "purple" - case 6: // "cyan" - case 7: // "silver" - case 8: // "gray" - case 9: // "pink" - case 10: // "lime" - case 12: // "lightBlue" - case 13: // "magenta" - case 14: // "orange" - } - return -1; - } - - public static int findEmpty( final Object[] l ) - { - for( int x = 0; x < l.length; x++ ) - { - if( l[x] == null ) - { - return x; - } - } - return -1; - } - - public static T pickRandom( final Collection outs ) - { - int index = RANDOM_GENERATOR.nextInt( outs.size() ); - final Iterator i = outs.iterator(); - while( i.hasNext() && index > 0 ) - { - index--; - i.next(); - } - index--; - if( i.hasNext() ) - { - return i.next(); - } - return null; // wtf? - } - - public static ForgeDirection rotateAround( final ForgeDirection forward, final ForgeDirection axis ) - { - if( axis == ForgeDirection.UNKNOWN || forward == ForgeDirection.UNKNOWN ) - { - return forward; - } - - switch( forward ) - { - case DOWN: - switch( axis ) - { - case DOWN: - return forward; - case UP: - return forward; - case NORTH: - return ForgeDirection.EAST; - case SOUTH: - return ForgeDirection.WEST; - case EAST: - return ForgeDirection.NORTH; - case WEST: - return ForgeDirection.SOUTH; - default: - break; - } - break; - case UP: - switch( axis ) - { - case NORTH: - return ForgeDirection.WEST; - case SOUTH: - return ForgeDirection.EAST; - case EAST: - return ForgeDirection.SOUTH; - case WEST: - return ForgeDirection.NORTH; - default: - break; - } - break; - case NORTH: - switch( axis ) - { - case UP: - return ForgeDirection.WEST; - case DOWN: - return ForgeDirection.EAST; - case EAST: - return ForgeDirection.UP; - case WEST: - return ForgeDirection.DOWN; - default: - break; - } - break; - case SOUTH: - switch( axis ) - { - case UP: - return ForgeDirection.EAST; - case DOWN: - return ForgeDirection.WEST; - case EAST: - return ForgeDirection.DOWN; - case WEST: - return ForgeDirection.UP; - default: - break; - } - break; - case EAST: - switch( axis ) - { - case UP: - return ForgeDirection.NORTH; - case DOWN: - return ForgeDirection.SOUTH; - case NORTH: - return ForgeDirection.UP; - case SOUTH: - return ForgeDirection.DOWN; - default: - break; - } - case WEST: - switch( axis ) - { - case UP: - return ForgeDirection.SOUTH; - case DOWN: - return ForgeDirection.NORTH; - case NORTH: - return ForgeDirection.DOWN; - case SOUTH: - return ForgeDirection.UP; - default: - break; - } - default: - break; - } - return forward; - } - - @SideOnly( Side.CLIENT ) - public static String gui_localize( final String string ) - { - return StatCollector.translateToLocal( string ); - } - - public static boolean isSameItemPrecise( @Nullable final ItemStack is, @Nullable final ItemStack filter ) - { - return isSameItem( is, filter ) && sameStackStags( is, filter ); - } - - public static boolean isSameItemFuzzy( final ItemStack a, final ItemStack b, final FuzzyMode mode ) - { - if( a == null && b == null ) - { - return true; - } - - if( a == null ) - { - return false; - } - - if( b == null ) - { - return false; - } - - /* - * if ( a.itemID != 0 && b.itemID != 0 && a.isItemStackDamageable() && ! a.getHasSubtypes() && a.itemID == - * b.itemID ) { return (a.getItemDamage() > 0) == (b.getItemDamage() > 0); } - */ - - // test damageable items.. - if( a.getItem() != null && b.getItem() != null && a.getItem().isDamageable() && a.getItem() == b.getItem() ) - { - try - { - if( mode == FuzzyMode.IGNORE_ALL ) - { - return true; - } - else if( mode == FuzzyMode.PERCENT_99 ) - { - return ( a.getItemDamageForDisplay() > 1 ) == ( b.getItemDamageForDisplay() > 1 ); - } - else - { - final float percentDamagedOfA = 1.0f - (float) a.getItemDamageForDisplay() / (float) a.getMaxDamage(); - final float percentDamagedOfB = 1.0f - (float) b.getItemDamageForDisplay() / (float) b.getMaxDamage(); - - return ( percentDamagedOfA > mode.breakPoint ) == ( percentDamagedOfB > mode.breakPoint ); - } - } - catch( final Throwable e ) - { - if( mode == FuzzyMode.IGNORE_ALL ) - { - return true; - } - else if( mode == FuzzyMode.PERCENT_99 ) - { - return ( a.getItemDamage() > 1 ) == ( b.getItemDamage() > 1 ); - } - else - { - final float percentDamagedOfA = (float) a.getItemDamage() / (float) a.getMaxDamage(); - final float percentDamagedOfB = (float) b.getItemDamage() / (float) b.getMaxDamage(); - - return ( percentDamagedOfA > mode.breakPoint ) == ( percentDamagedOfB > mode.breakPoint ); - } - } - } - - final OreReference aOR = OreHelper.INSTANCE.isOre( a ); - final OreReference bOR = OreHelper.INSTANCE.isOre( b ); - - if( OreHelper.INSTANCE.sameOre( aOR, bOR ) ) - { - return true; - } - - /* - * // test ore dictionary.. int OreID = getOreID( a ); if ( OreID != -1 ) return OreID == getOreID( b ); - * if ( Mode != FuzzyMode.IGNORE_ALL ) { if ( a.hasTagCompound() && !isShared( a.getTagCompound() ) ) { a = - * Platform.getSharedItemStack( AEItemStack.create( a ) ); } - * if ( b.hasTagCompound() && !isShared( b.getTagCompound() ) ) { b = Platform.getSharedItemStack( - * AEItemStack.create( b ) ); } - * // test regular items with damage values and what not... if ( isShared( a.getTagCompound() ) && isShared( - * b.getTagCompound() ) && a.itemID == b.itemID ) { return ((AppEngSharedNBTTagCompound) - * a.getTagCompound()).compareFuzzyWithRegistry( (AppEngSharedNBTTagCompound) b.getTagCompound() ); } } - */ - - return a.isItemEqual( b ); - } - - public static LookDirection getPlayerRay( final EntityPlayer player, final float eyeOffset ) - { - final float f = 1.0F; - final float f1 = player.prevRotationPitch + ( player.rotationPitch - player.prevRotationPitch ) * f; - final float f2 = player.prevRotationYaw + ( player.rotationYaw - player.prevRotationYaw ) * f; - final double d0 = player.prevPosX + ( player.posX - player.prevPosX ) * f; - final double d1 = eyeOffset; - final double d2 = player.prevPosZ + ( player.posZ - player.prevPosZ ) * f; - - final Vec3 vec3 = Vec3.createVectorHelper( d0, d1, d2 ); - final float f3 = MathHelper.cos( -f2 * 0.017453292F - (float) Math.PI ); - final float f4 = MathHelper.sin( -f2 * 0.017453292F - (float) Math.PI ); - final float f5 = -MathHelper.cos( -f1 * 0.017453292F ); - final float f6 = MathHelper.sin( -f1 * 0.017453292F ); - final float f7 = f4 * f5; - final float f8 = f3 * f5; - double d3 = 5.0D; - - if( player instanceof EntityPlayerMP ) - { - d3 = ( (EntityPlayerMP) player ).theItemInWorldManager.getBlockReachDistance(); - } - final Vec3 vec31 = vec3.addVector( f7 * d3, f6 * d3, f8 * d3 ); - return new LookDirection( vec3, vec31 ); - } - - public static MovingObjectPosition rayTrace( final EntityPlayer p, final boolean hitBlocks, final boolean hitEntities ) - { - final World w = p.getEntityWorld(); - - final float f = 1.0F; - float f1 = p.prevRotationPitch + ( p.rotationPitch - p.prevRotationPitch ) * f; - final float f2 = p.prevRotationYaw + ( p.rotationYaw - p.prevRotationYaw ) * f; - final double d0 = p.prevPosX + ( p.posX - p.prevPosX ) * f; - final double d1 = p.prevPosY + ( p.posY - p.prevPosY ) * f + 1.62D - p.yOffset; - final double d2 = p.prevPosZ + ( p.posZ - p.prevPosZ ) * f; - final Vec3 vec3 = Vec3.createVectorHelper( d0, d1, d2 ); - final float f3 = MathHelper.cos( -f2 * 0.017453292F - (float) Math.PI ); - final float f4 = MathHelper.sin( -f2 * 0.017453292F - (float) Math.PI ); - final float f5 = -MathHelper.cos( -f1 * 0.017453292F ); - final float f6 = MathHelper.sin( -f1 * 0.017453292F ); - final float f7 = f4 * f5; - final float f8 = f3 * f5; - final double d3 = 32.0D; - - final Vec3 vec31 = vec3.addVector( f7 * d3, f6 * d3, f8 * d3 ); - - final AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( Math.min( vec3.xCoord, vec31.xCoord ), Math.min( vec3.yCoord, vec31.yCoord ), Math.min( vec3.zCoord, vec31.zCoord ), Math.max( vec3.xCoord, vec31.xCoord ), Math.max( vec3.yCoord, vec31.yCoord ), Math.max( vec3.zCoord, vec31.zCoord ) ).expand( 16, 16, 16 ); - - Entity entity = null; - double closest = 9999999.0D; - if( hitEntities ) - { - final List list = w.getEntitiesWithinAABBExcludingEntity( p, bb ); - - for( int l = 0; l < list.size(); ++l ) - { - final Entity entity1 = (Entity) list.get( l ); - - if( !entity1.isDead && entity1 != p && !( entity1 instanceof EntityItem ) ) - { - if( entity1.isEntityAlive() ) - { - // prevent killing / flying of mounts. - if( entity1.riddenByEntity == p ) - { - continue; - } - - f1 = 0.3F; - final AxisAlignedBB boundingBox = entity1.boundingBox.expand( f1, f1, f1 ); - final MovingObjectPosition movingObjectPosition = boundingBox.calculateIntercept( vec3, vec31 ); - - if( movingObjectPosition != null ) - { - final double nd = vec3.squareDistanceTo( movingObjectPosition.hitVec ); - - if( nd < closest ) - { - entity = entity1; - closest = nd; - } - } - } - } - } - } - - MovingObjectPosition pos = null; - Vec3 vec = null; - - if( hitBlocks ) - { - vec = Vec3.createVectorHelper( d0, d1, d2 ); - pos = w.rayTraceBlocks( vec3, vec31, true ); - } - - if( entity != null && pos != null && pos.hitVec.squareDistanceTo( vec ) > closest ) - { - pos = new MovingObjectPosition( entity ); - } - else if( entity != null && pos == null ) - { - pos = new MovingObjectPosition( entity ); - } - - return pos; - } - - public static long nanoTime() - { - // if ( Configuration.INSTANCE.enableNetworkProfiler ) - // return System.nanoTime(); - return 0; - } - - public static StackType poweredExtraction( final IEnergySource energy, final IMEInventory cell, final StackType request, final BaseActionSource src ) - { - final StackType possible = cell.extractItems( (StackType) request.copy(), Actionable.SIMULATE, src ); - - long retrieved = 0; - if( possible != null ) - { - retrieved = possible.getStackSize(); - } - - final double availablePower = energy.extractAEPower( retrieved, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - - final long itemToExtract = Math.min( (long) ( availablePower + 0.9 ), retrieved ); - - if( itemToExtract > 0 ) - { - energy.extractAEPower( retrieved, Actionable.MODULATE, PowerMultiplier.CONFIG ); - - possible.setStackSize( itemToExtract ); - final StackType ret = cell.extractItems( possible, Actionable.MODULATE, src ); - - if( ret != null && src.isPlayer() ) - { - Stats.ItemsExtracted.addToPlayer( ( (PlayerSource) src ).player, (int) ret.getStackSize() ); - } - - return ret; - } - - return null; - } - - public static StackType poweredInsert( final IEnergySource energy, final IMEInventory cell, final StackType input, final BaseActionSource src ) - { - final StackType possible = cell.injectItems( (StackType) input.copy(), Actionable.SIMULATE, src ); - - long stored = input.getStackSize(); - if( possible != null ) - { - stored -= possible.getStackSize(); - } - - final double availablePower = energy.extractAEPower( stored, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - - final long itemToAdd = Math.min( (long) ( availablePower + 0.9 ), stored ); - - if( itemToAdd > 0 ) - { - energy.extractAEPower( stored, Actionable.MODULATE, PowerMultiplier.CONFIG ); - - if( itemToAdd < input.getStackSize() ) - { - final long original = input.getStackSize(); - final StackType split = (StackType) input.copy(); - split.decStackSize( itemToAdd ); - input.setStackSize( itemToAdd ); - split.add( cell.injectItems( input, Actionable.MODULATE, src ) ); - - if( src.isPlayer() ) - { - final long diff = original - split.getStackSize(); - Stats.ItemsInserted.addToPlayer( ( (PlayerSource) src ).player, (int) diff ); - } - - return split; - } - - final StackType ret = cell.injectItems( input, Actionable.MODULATE, src ); - - if( src.isPlayer() ) - { - final long diff = ret == null ? input.getStackSize() : input.getStackSize() - ret.getStackSize(); - Stats.ItemsInserted.addToPlayer( ( (PlayerSource) src ).player, (int) diff ); - } - - return ret; - } - - return input; - } - - public static void postChanges( final IStorageGrid gs, final ItemStack removed, final ItemStack added, final BaseActionSource src ) - { - final IItemList itemChanges = AEApi.instance().storage().createItemList(); - final IItemList fluidChanges = AEApi.instance().storage().createFluidList(); - - if( removed != null ) - { - final IMEInventory myItems = AEApi.instance().registries().cell().getCellInventory( removed, null, StorageChannel.ITEMS ); - - if( myItems != null ) - { - for( final IAEItemStack is : myItems.getAvailableItems( itemChanges ) ) - { - is.setStackSize( -is.getStackSize() ); - } - } - - final IMEInventory myFluids = AEApi.instance().registries().cell().getCellInventory( removed, null, StorageChannel.FLUIDS ); - - if( myFluids != null ) - { - for( final IAEFluidStack is : myFluids.getAvailableItems( fluidChanges ) ) - { - is.setStackSize( -is.getStackSize() ); - } - } - } - - if( added != null ) - { - final IMEInventory myItems = AEApi.instance().registries().cell().getCellInventory( added, null, StorageChannel.ITEMS ); - - if( myItems != null ) - { - myItems.getAvailableItems( itemChanges ); - } - - final IMEInventory myFluids = AEApi.instance().registries().cell().getCellInventory( added, null, StorageChannel.FLUIDS ); - - if( myFluids != null ) - { - myFluids.getAvailableItems( fluidChanges ); - } - } - - gs.postAlterationOfStoredItems( StorageChannel.ITEMS, itemChanges, src ); - } - - public static > void postListChanges( final IItemList before, final IItemList after, final IMEMonitorHandlerReceiver meMonitorPassthrough, final BaseActionSource source ) - { - final LinkedList changes = new LinkedList(); - - for( final T is : before ) - { - is.setStackSize( -is.getStackSize() ); - } - - for( final T is : after ) - { - before.add( is ); - } - - for( final T is : before ) - { - if( is.getStackSize() != 0 ) - { - changes.add( is ); - } - } - - if( !changes.isEmpty() ) - { - meMonitorPassthrough.postChange( null, changes, source ); - } - } - - public static int generateTileHash( final TileEntity target ) - { - if( target == null ) - { - return 0; - } - - int hash = target.hashCode(); - - if( target instanceof ITileStorageMonitorable ) - { - return 0; - } - else if( target instanceof TileEntityChest ) - { - final TileEntityChest chest = (TileEntityChest) target; - chest.checkForAdjacentChests(); - if( chest.adjacentChestZNeg != null ) - { - hash ^= chest.adjacentChestZNeg.hashCode(); - } - else if( chest.adjacentChestZPos != null ) - { - hash ^= chest.adjacentChestZPos.hashCode(); - } - else if( chest.adjacentChestXPos != null ) - { - hash ^= chest.adjacentChestXPos.hashCode(); - } - else if( chest.adjacentChestXNeg != null ) - { - hash ^= chest.adjacentChestXNeg.hashCode(); - } - } - else if( target instanceof IInventory ) - { - hash ^= ( (IInventory) target ).getSizeInventory(); - - if( target instanceof ISidedInventory ) - { - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - - final int[] sides = ( (ISidedInventory) target ).getAccessibleSlotsFromSide( dir.ordinal() ); - - if( sides == null ) - { - return 0; - } - - int offset = 0; - for( final int side : sides ) - { - final int c = ( side << ( offset % 8 ) ) ^ ( 1 << dir.ordinal() ); - offset++; - hash = c + ( hash << 6 ) + ( hash << 16 ) - hash; - } - } - } - } - - return hash; - } - - public static boolean securityCheck( final GridNode a, final GridNode b ) - { - if( a.getLastSecurityKey() == -1 && b.getLastSecurityKey() == -1 ) - { - return false; - } - else if( a.getLastSecurityKey() == b.getLastSecurityKey() ) - { - return false; - } - - final boolean a_isSecure = isPowered( a.getGrid() ) && a.getLastSecurityKey() != -1; - final boolean b_isSecure = isPowered( b.getGrid() ) && b.getLastSecurityKey() != -1; - - if( AEConfig.instance.isFeatureEnabled( AEFeature.LogSecurityAudits ) ) - { - AELog.info( "Audit: " + a_isSecure + " : " + b_isSecure + " @ " + a.getLastSecurityKey() + " vs " + b.getLastSecurityKey() + " & " + a.getPlayerID() + " vs " + b.getPlayerID() ); - } - - // can't do that son... - if( a_isSecure && b_isSecure ) - { - return true; - } - - if( !a_isSecure && b_isSecure ) - { - return checkPlayerPermissions( b.getGrid(), a.getPlayerID() ); - } - - if( a_isSecure && !b_isSecure ) - { - return checkPlayerPermissions( a.getGrid(), b.getPlayerID() ); - } - - return false; - } - - private static boolean isPowered( final IGrid grid ) - { - if( grid == null ) - { - return false; - } - - final IEnergyGrid eg = grid.getCache( IEnergyGrid.class ); - return eg.isNetworkPowered(); - } - - private static boolean checkPlayerPermissions( final IGrid grid, final int playerID ) - { - if( grid == null ) - { - return false; - } - - final ISecurityGrid gs = grid.getCache( ISecurityGrid.class ); - - if( gs == null ) - { - return false; - } - - if( !gs.isAvailable() ) - { - return false; - } - - return !gs.hasPermission( playerID, SecurityPermissions.BUILD ); - } - - public static void configurePlayer( final EntityPlayer player, final ForgeDirection side, final TileEntity tile ) - { - player.yOffset = 1.8f; - - float yaw = 0.0f; - float pitch = 0.0f; - switch( side ) - { - case DOWN: - pitch = 90.0f; - player.yOffset = -1.8f; - break; - case EAST: - yaw = -90.0f; - break; - case NORTH: - yaw = 180.0f; - break; - case SOUTH: - yaw = 0.0f; - break; - case UNKNOWN: - break; - case UP: - pitch = 90.0f; - break; - case WEST: - yaw = 90.0f; - break; - } - - player.posX = tile.xCoord + 0.5; - player.posY = tile.yCoord + 0.5; - player.posZ = tile.zCoord + 0.5; - - player.rotationPitch = player.prevCameraPitch = player.cameraPitch = pitch; - player.rotationYaw = player.prevCameraYaw = player.cameraYaw = yaw; - } - - public static boolean canAccess( final AENetworkProxy gridProxy, final BaseActionSource src ) - { - try - { - if( src.isPlayer() ) - { - return gridProxy.getSecurity().hasPermission( ( (PlayerSource) src ).player, SecurityPermissions.BUILD ); - } - else if( src.isMachine() ) - { - final IActionHost te = ( (MachineSource) src ).via; - final IGridNode n = te.getActionableNode(); - if( n == null ) - { - return false; - } - - final int playerID = n.getPlayerID(); - return gridProxy.getSecurity().hasPermission( playerID, SecurityPermissions.BUILD ); - } - else - { - return false; - } - } - catch( final GridAccessException gae ) - { - return false; - } - } - - public static ItemStack extractItemsByRecipe( final IEnergySource energySrc, final BaseActionSource mySrc, final IMEMonitor src, final World w, final IRecipe r, final ItemStack output, final InventoryCrafting ci, final ItemStack providedTemplate, final int slot, final IItemList items, final Actionable realForFake, final IPartitionList filter ) - { - return extractItemsByRecipe(energySrc, mySrc, src, w, r, output, ci, providedTemplate, slot, items, realForFake, filter, 1); - } - public static ItemStack extractItemsByRecipe( final IEnergySource energySrc, final BaseActionSource mySrc, final IMEMonitor src, final World w, final IRecipe r, final ItemStack output, final InventoryCrafting ci, final ItemStack providedTemplate, final int slot, final IItemList items, final Actionable realForFake, final IPartitionList filter, int multiple ) - { - if( energySrc.extractAEPower( multiple, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0.9 ) - { - if( providedTemplate == null ) - { - return null; - } - - final AEItemStack ae_req = AEItemStack.create( providedTemplate ); - ae_req.setStackSize( multiple ); - - if( filter == null || filter.isListed( ae_req ) ) - { - final IAEItemStack ae_ext = src.extractItems( ae_req, realForFake, mySrc ); - if( ae_ext != null ) - { - final ItemStack extracted = ae_ext.getItemStack(); - if( extracted != null ) - { - energySrc.extractAEPower( multiple, realForFake, PowerMultiplier.CONFIG ); - return extracted; - } - } - } - - final boolean checkFuzzy = ae_req.isOre() || providedTemplate.getItemDamage() == OreDictionary.WILDCARD_VALUE || providedTemplate.hasTagCompound() || providedTemplate.isItemStackDamageable(); - - if( items != null && checkFuzzy ) - { - for( final IAEItemStack x : items ) - { - final ItemStack sh = x.getItemStack(); - if( ( Platform.isSameItemType( providedTemplate, sh ) || ae_req.sameOre( x ) ) && !Platform.isSameItem( sh, output ) ) - { // Platform.isSameItemType( sh, providedTemplate ) - final ItemStack cp = Platform.cloneItemStack( sh ); - cp.stackSize = 1; - ci.setInventorySlotContents( slot, cp ); - if( r.matches( ci, w ) && Platform.isSameItem( r.getCraftingResult( ci ), output ) ) - { - final IAEItemStack ax = x.copy(); - ax.setStackSize( multiple ); - if( filter == null || filter.isListed( ax ) ) - { - final IAEItemStack ex = src.extractItems( ax, realForFake, mySrc ); - if( ex != null ) - { - energySrc.extractAEPower( multiple, realForFake, PowerMultiplier.CONFIG ); - return ex.getItemStack(); - } - } - } - ci.setInventorySlotContents( slot, providedTemplate ); - } - } - } - } - return null; - } - - public static boolean isSameItemType( final ItemStack that, final ItemStack other ) - { - if( that != null && other != null && that.getItem() == other.getItem() ) - { - if( that.isItemStackDamageable() ) - { - return true; - } - return that.getItemDamage() == other.getItemDamage(); - } - return false; - } - - public static boolean isSameItem( @Nullable final ItemStack left, @Nullable final ItemStack right ) - { - return left != null && right != null && left.isItemEqual( right ); - } - - public static ItemStack cloneItemStack( final ItemStack a ) - { - return a.copy(); - } - - public static ItemStack getContainerItem( final ItemStack stackInSlot ) - { - if( stackInSlot == null ) - { - return null; - } - - final Item i = stackInSlot.getItem(); - if( i == null || !i.hasContainerItem( stackInSlot ) ) - { - if( stackInSlot.stackSize > 1 ) - { - stackInSlot.stackSize--; - return stackInSlot; - } - return null; - } - - ItemStack ci = i.getContainerItem( stackInSlot.copy() ); - if( ci != null && ci.isItemStackDamageable() && ci.getItemDamage() == ci.getMaxDamage() ) - { - ci = null; - } - - return ci; - } - - public static void notifyBlocksOfNeighbors( final World worldObj, final int xCoord, final int yCoord, final int zCoord ) - { - if( !worldObj.isRemote ) - { - TickHandler.INSTANCE.addCallable( worldObj, new BlockUpdate( xCoord, yCoord, zCoord ) ); - } - } - - public static boolean canRepair( final AEFeature type, final ItemStack a, final ItemStack b ) - { - if( b == null || a == null ) - { - return false; - } - - if( type == AEFeature.CertusQuartzTools ) - { - final IItemDefinition certusQuartzCrystal = AEApi.instance().definitions().materials().certusQuartzCrystal(); - - return certusQuartzCrystal.isSameAs( b ); - } - - if( type == AEFeature.NetherQuartzTools ) - { - return Items.quartz == b.getItem(); - } - - return false; - } - - public static Object findPreferred( final ItemStack[] is ) - { - final IParts parts = AEApi.instance().definitions().parts(); - - for( final ItemStack stack : is ) - { - if( parts.cableGlass().sameAs( AEColor.Transparent, stack ) ) - { - return stack; - } - - if( parts.cableCovered().sameAs( AEColor.Transparent, stack ) ) - { - return stack; - } - - if( parts.cableSmart().sameAs( AEColor.Transparent, stack ) ) - { - return stack; - } - - if( parts.cableDense().sameAs( AEColor.Transparent, stack ) ) - { - return stack; - } - - if( parts.cableDenseCovered().sameAs( AEColor.Transparent, stack ) ) - { - return stack; - } - - if( parts.cableUltraDenseCovered().sameAs( AEColor.Transparent, stack ) ) - { - return stack; - } - - if( parts.cableUltraDenseSmart().sameAs( AEColor.Transparent, stack ) ) - { - return stack; - } - } - - return is; - } - - public static void sendChunk( final Chunk c, final int verticalBits ) - { - try - { - final WorldServer ws = (WorldServer) c.worldObj; - final PlayerManager pm = ws.getPlayerManager(); - - if( getOrCreateChunkWatcher == null ) - { - getOrCreateChunkWatcher = ReflectionHelper.findMethod( PlayerManager.class, pm, new String[] { "getOrCreateChunkWatcher", "func_72690_a" }, int.class, int.class, boolean.class ); - } - - if( getOrCreateChunkWatcher != null ) - { - final Object playerInstance = getOrCreateChunkWatcher.invoke( pm, c.xPosition, c.zPosition, false ); - if( playerInstance != null ) - { - Platform.playerInstance = playerInstance.getClass(); - - if( sendToAllPlayersWatchingChunk == null ) - { - sendToAllPlayersWatchingChunk = ReflectionHelper.findMethod( Platform.playerInstance, playerInstance, new String[] { "sendToAllPlayersWatchingChunk", "func_151251_a" }, Packet.class ); - } - - if( sendToAllPlayersWatchingChunk != null ) - { - sendToAllPlayersWatchingChunk.invoke( playerInstance, new S21PacketChunkData( c, false, verticalBits ) ); - } - } - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - } - - public static AxisAlignedBB getPrimaryBox( final ForgeDirection side, final int facadeThickness ) - { - switch( side ) - { - case DOWN: - return AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, 1.0, ( facadeThickness ) / 16.0, 1.0 ); - case EAST: - return AxisAlignedBB.getBoundingBox( ( 16.0 - facadeThickness ) / 16.0, 0.0, 0.0, 1.0, 1.0, 1.0 ); - case NORTH: - return AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, 1.0, 1.0, ( facadeThickness ) / 16.0 ); - case SOUTH: - return AxisAlignedBB.getBoundingBox( 0.0, 0.0, ( 16.0 - facadeThickness ) / 16.0, 1.0, 1.0, 1.0 ); - case UP: - return AxisAlignedBB.getBoundingBox( 0.0, ( 16.0 - facadeThickness ) / 16.0, 0.0, 1.0, 1.0, 1.0 ); - case WEST: - return AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, ( facadeThickness ) / 16.0, 1.0, 1.0 ); - default: - break; - } - return AxisAlignedBB.getBoundingBox( 0, 0, 0, 1, 1, 1 ); - } - - public static float getEyeOffset( final EntityPlayer player ) - { - assert player.worldObj.isRemote : "Valid only on client"; - return (float) ( player.posY + player.getEyeHeight() - player.getDefaultEyeHeight() ); - } - - public static void addStat( final int playerID, final Achievement achievement ) - { - final EntityPlayer p = AEApi.instance().registries().players().findPlayer( playerID ); - if( p != null ) - { - p.addStat( achievement, 1 ); - } - } - - public static boolean isRecipePrioritized( final ItemStack what ) - { - final IMaterials materials = AEApi.instance().definitions().materials(); - - boolean isPurified = materials.purifiedCertusQuartzCrystal().isSameAs( what ); - isPurified |= materials.purifiedFluixCrystal().isSameAs( what ); - isPurified |= materials.purifiedNetherQuartzCrystal().isSameAs( what ); - - return isPurified; - } - - public static ItemStack loadItemStackFromNBT( NBTTagCompound tagCompound ) - { - ItemStack stack = ItemStack.loadItemStackFromNBT( tagCompound ); - if( stack != null ) - { - stack.stackSize = tagCompound.getInteger( "Count" ); +public class Platform { + + public static final Block AIR_BLOCK = Blocks.air; + + public static final int DEF_OFFSET = 16; + + /* + * random source, use it for item drop locations... + */ + private static final Random RANDOM_GENERATOR = new Random(); + private static final WeakHashMap FAKE_PLAYERS = new WeakHashMap(); + private static Field tagList; + private static Class playerInstance; + private static Method getOrCreateChunkWatcher; + private static Method sendToAllPlayersWatchingChunk; + private static GameProfile fakeProfile = + new GameProfile(UUID.fromString("839eb18c-50bc-400c-8291-9383f09763e7"), "[AE2Player]"); + + public static Random getRandom() { + return RANDOM_GENERATOR; + } + + public static float getRandomFloat() { + return RANDOM_GENERATOR.nextFloat(); + } + + /** + * This displays the value for encoded longs ( double *100 ) + * + * @param n to be formatted long value + * @param isRate if true it adds a /t to the formatted string + * @return formatted long value + */ + public static String formatPowerLong(final long n, final boolean isRate) { + double p = ((double) n) / 100; + + final PowerUnits displayUnits = AEConfig.instance.selectedPowerUnit(); + p = PowerUnits.AE.convertTo(displayUnits, p); + + String unitName = displayUnits.name(); + + if (displayUnits == PowerUnits.WA) { + unitName = "J"; + } + + if (displayUnits == PowerUnits.MK) { + unitName = "J"; + } + + final String[] preFixes = {"k", "M", "G", "T", "P", "T", "P", "E", "Z", "Y"}; + String level = ""; + int offset = 0; + while (p > 1000 && offset < preFixes.length) { + p /= 1000; + level = preFixes[offset]; + offset++; + } + + final DecimalFormat df = new DecimalFormat("#.##"); + return df.format(p) + ' ' + level + unitName + (isRate ? "/t" : ""); + } + + public static ForgeDirection crossProduct(final ForgeDirection forward, final ForgeDirection up) { + final int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; + final int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; + final int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; + + switch (west_x + west_y * 2 + west_z * 3) { + case 1: + return ForgeDirection.EAST; + case -1: + return ForgeDirection.WEST; + + case 2: + return ForgeDirection.UP; + case -2: + return ForgeDirection.DOWN; + + case 3: + return ForgeDirection.SOUTH; + case -3: + return ForgeDirection.NORTH; + } + + return ForgeDirection.UNKNOWN; + } + + public static T rotateEnum(T ce, final boolean backwards, final EnumSet validOptions) { + do { + if (backwards) { + ce = prevEnum(ce); + } else { + ce = nextEnum(ce); + } + } while (!validOptions.contains(ce) || isNotValidSetting(ce)); + + return ce; + } + + /* + * Simple way to cycle an enum... + */ + private static T prevEnum(final T ce) { + final EnumSet valList = EnumSet.allOf(ce.getClass()); + + int pLoc = ce.ordinal() - 1; + if (pLoc < 0) { + pLoc = valList.size() - 1; + } + + if (pLoc < 0 || pLoc >= valList.size()) { + pLoc = 0; + } + + int pos = 0; + for (final Object g : valList) { + if (pos == pLoc) { + return (T) g; + } + pos++; + } + + return null; + } + + /* + * Simple way to cycle an enum... + */ + public static T nextEnum(final T ce) { + final EnumSet valList = EnumSet.allOf(ce.getClass()); + + int pLoc = ce.ordinal() + 1; + if (pLoc >= valList.size()) { + pLoc = 0; + } + + if (pLoc < 0 || pLoc >= valList.size()) { + pLoc = 0; + } + + int pos = 0; + for (final Object g : valList) { + if (pos == pLoc) { + return (T) g; + } + pos++; + } + + return null; + } + + private static boolean isNotValidSetting(final Enum e) { + if (e == SortOrder.INVTWEAKS && !IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.InvTweaks)) { + return true; + } + + if (e == SearchBoxMode.NEI_AUTOSEARCH && !IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.NEI)) { + return true; + } + + return e == SearchBoxMode.NEI_MANUAL_SEARCH && !IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.NEI); + } + + public static void openGUI( + @Nonnull final EntityPlayer p, + @Nullable final TileEntity tile, + @Nullable final ForgeDirection side, + @Nonnull final GuiBridge type) { + if (isClient()) { + return; + } + + int x = (int) p.posX; + int y = (int) p.posY; + int z = (int) p.posZ; + if (tile != null) { + x = tile.xCoord; + y = tile.yCoord; + z = tile.zCoord; + } + + if ((type.getType().isItem() && tile == null) || type.hasPermissions(tile, x, y, z, side, p)) { + if (tile == null && type.getType() == GuiHostType.ITEM) { + p.openGui( + AppEng.instance(), + type.ordinal() << 5 | (1 << 4), + p.getEntityWorld(), + p.inventory.currentItem, + 0, + 0); + } else if (tile == null || type.getType() == GuiHostType.ITEM) { + p.openGui(AppEng.instance(), type.ordinal() << 5 | (1 << 3), p.getEntityWorld(), x, y, z); + } else { + p.openGui(AppEng.instance(), type.ordinal() << 5 | (side.ordinal()), tile.getWorldObj(), x, y, z); + } + } + } + + /* + * returns true if the code is on the client. + */ + public static boolean isClient() { + return FMLCommonHandler.instance().getEffectiveSide().isClient(); + } + + public static boolean hasPermissions(final DimensionalCoord dc, final EntityPlayer player) { + return dc.getWorld().canMineBlock(player, dc.x, dc.y, dc.z); + } + + /* + * Checks to see if a block is air? + */ + public static boolean isBlockAir(final World w, final int x, final int y, final int z) { + try { + return w.getBlock(x, y, z).isAir(w, x, y, z); + } catch (final Throwable e) { + return false; + } + } + + /* + * Lots of silliness to try and account for weird tag related junk, basically requires that two tags have at least + * something in their tags before it wasts its time comparing them. + */ + private static boolean sameStackStags(final ItemStack a, final ItemStack b) { + if (a == null && b == null) { + return true; + } + if (a == null || b == null) { + return false; + } + if (a == b) { + return true; + } + + final NBTTagCompound ta = a.getTagCompound(); + final NBTTagCompound tb = b.getTagCompound(); + if (ta == tb) { + return true; + } + + if ((ta == null && tb == null) + || (ta != null && ta.hasNoTags() && tb == null) + || (tb != null && tb.hasNoTags() && ta == null) + || (ta != null && ta.hasNoTags() && tb != null && tb.hasNoTags())) { + return true; + } + + if ((ta == null && tb != null) || (ta != null && tb == null)) { + return false; + } + + // if both tags are shared this is easy... + if (AESharedNBT.isShared(ta) && AESharedNBT.isShared(tb)) { + return ta == tb; + } + + return NBTEqualityTest(ta, tb); + } + + /* + * recursive test for NBT Equality, this was faster then trying to compare / generate hashes, its also more reliable + * then the vanilla version which likes to fail when NBT Compound data changes order, it is pretty expensive + * performance wise, so try an use shared tag compounds as long as the system remains in AE. + */ + public static boolean NBTEqualityTest(final NBTBase left, final NBTBase right) { + // same type? + final byte id = left.getId(); + if (id == right.getId()) { + switch (id) { + case 10: { + final NBTTagCompound ctA = (NBTTagCompound) left; + final NBTTagCompound ctB = (NBTTagCompound) right; + + final Set cA = ctA.func_150296_c(); + final Set cB = ctB.func_150296_c(); + + if (cA.size() != cB.size()) { + return false; + } + + for (final String name : cA) { + final NBTBase tag = ctA.getTag(name); + final NBTBase aTag = ctB.getTag(name); + if (aTag == null) { + return false; + } + + if (!NBTEqualityTest(tag, aTag)) { + return false; + } + } + + return true; + } + + case 9: // ) // A instanceof NBTTagList ) + { + final NBTTagList lA = (NBTTagList) left; + final NBTTagList lB = (NBTTagList) right; + if (lA.tagCount() != lB.tagCount()) { + return false; + } + + final List tag = tagList(lA); + final List aTag = tagList(lB); + if (tag.size() != aTag.size()) { + return false; + } + + for (int x = 0; x < tag.size(); x++) { + if (aTag.get(x) == null) { + return false; + } + + if (!NBTEqualityTest(tag.get(x), aTag.get(x))) { + return false; + } + } + + return true; + } + + case 1: // ( A instanceof NBTTagByte ) + return ((NBTBase.NBTPrimitive) left).func_150287_d() + == ((NBTBase.NBTPrimitive) right).func_150287_d(); + + case 4: // else if ( A instanceof NBTTagLong ) + return ((NBTBase.NBTPrimitive) left).func_150291_c() + == ((NBTBase.NBTPrimitive) right).func_150291_c(); + + case 8: // else if ( A instanceof NBTTagString ) + return ((NBTTagString) left).func_150285_a_().equals(((NBTTagString) right).func_150285_a_()) + || ((NBTTagString) left).func_150285_a_().equals(((NBTTagString) right).func_150285_a_()); + + case 6: // else if ( A instanceof NBTTagDouble ) + return ((NBTBase.NBTPrimitive) left).func_150286_g() + == ((NBTBase.NBTPrimitive) right).func_150286_g(); + + case 5: // else if ( A instanceof NBTTagFloat ) + return ((NBTBase.NBTPrimitive) left).func_150288_h() + == ((NBTBase.NBTPrimitive) right).func_150288_h(); + + case 3: // else if ( A instanceof NBTTagInt ) + return ((NBTBase.NBTPrimitive) left).func_150287_d() + == ((NBTBase.NBTPrimitive) right).func_150287_d(); + + default: + return left.equals(right); + } + } + + return false; + } + + private static List tagList(final NBTTagList lB) { + if (tagList == null) { + try { + tagList = lB.getClass().getDeclaredField("tagList"); + } catch (final Throwable t) { + try { + tagList = lB.getClass().getDeclaredField("field_74747_a"); + } catch (final Throwable z) { + AELog.debug(t); + AELog.debug(z); + } + } + } + + try { + tagList.setAccessible(true); + return (List) tagList.get(lB); + } catch (final Throwable t) { + AELog.debug(t); + } + + return new ArrayList(); + } + + /* + * Orderless hash on NBT Data, used to work thought huge piles fast, but ignores the order just in case MC decided + * to change it... WHICH IS BAD... + */ + public static int NBTOrderlessHash(final NBTBase nbt) { + // same type? + int hash = 0; + final byte id = nbt.getId(); + hash += id; + switch (id) { + case 10: { + final NBTTagCompound ctA = (NBTTagCompound) nbt; + + final Set cA = ctA.func_150296_c(); + + for (final String name : cA) { + hash += name.hashCode() ^ NBTOrderlessHash(ctA.getTag(name)); + } + + return hash; + } + + case 9: // ) // A instanceof NBTTagList ) + { + final NBTTagList lA = (NBTTagList) nbt; + hash += 9 * lA.tagCount(); + + final List l = tagList(lA); + for (int x = 0; x < l.size(); x++) { + hash += ((Integer) x).hashCode() ^ NBTOrderlessHash(l.get(x)); + } + + return hash; + } + + case 1: // ( A instanceof NBTTagByte ) + return hash + ((NBTBase.NBTPrimitive) nbt).func_150290_f(); + + case 4: // else if ( A instanceof NBTTagLong ) + return hash + (int) ((NBTBase.NBTPrimitive) nbt).func_150291_c(); + + case 8: // else if ( A instanceof NBTTagString ) + return hash + ((NBTTagString) nbt).func_150285_a_().hashCode(); + + case 6: // else if ( A instanceof NBTTagDouble ) + return hash + (int) ((NBTBase.NBTPrimitive) nbt).func_150286_g(); + + case 5: // else if ( A instanceof NBTTagFloat ) + return hash + (int) ((NBTBase.NBTPrimitive) nbt).func_150288_h(); + + case 3: // else if ( A instanceof NBTTagInt ) + return hash + ((NBTBase.NBTPrimitive) nbt).func_150287_d(); + + default: + return hash; + } + } + + private static IRecipe lastUsedRecipe = null; + + /* + * The usual version of this returns an ItemStack, this version returns the recipe. + */ + public static IRecipe findMatchingRecipe(final InventoryCrafting inventoryCrafting, final World par2World) { + if (lastUsedRecipe != null && lastUsedRecipe.matches(inventoryCrafting, par2World)) return lastUsedRecipe; + + final CraftingManager cm = CraftingManager.getInstance(); + final List rl = cm.getRecipeList(); + + for (final IRecipe r : rl) { + if (r.matches(inventoryCrafting, par2World)) { + lastUsedRecipe = r; + return r; + } + } + + return null; + } + + public static ItemStack[] getBlockDrops(final World w, final int x, final int y, final int z) { + List out = new ArrayList(); + final Block which = w.getBlock(x, y, z); + + if (which != null) { + out = which.getDrops(w, x, y, z, w.getBlockMetadata(x, y, z), 0); + } + + if (out == null) { + return new ItemStack[0]; + } + return out.toArray(new ItemStack[out.size()]); + } + + public static ForgeDirection cycleOrientations(final ForgeDirection dir, final boolean upAndDown) { + if (upAndDown) { + switch (dir) { + case NORTH: + return ForgeDirection.SOUTH; + case SOUTH: + return ForgeDirection.EAST; + case EAST: + return ForgeDirection.WEST; + case WEST: + return ForgeDirection.NORTH; + case UP: + return ForgeDirection.UP; + case DOWN: + return ForgeDirection.DOWN; + case UNKNOWN: + return ForgeDirection.UNKNOWN; + } + } else { + switch (dir) { + case UP: + return ForgeDirection.DOWN; + case DOWN: + return ForgeDirection.NORTH; + case NORTH: + return ForgeDirection.SOUTH; + case SOUTH: + return ForgeDirection.EAST; + case EAST: + return ForgeDirection.WEST; + case WEST: + return ForgeDirection.UP; + case UNKNOWN: + return ForgeDirection.UNKNOWN; + } + } + + return ForgeDirection.UNKNOWN; + } + + /* + * Creates / or loads previous NBT Data on items, used for editing items owned by AE. + */ + public static NBTTagCompound openNbtData(final ItemStack i) { + NBTTagCompound compound = i.getTagCompound(); + + if (compound == null) { + i.setTagCompound(compound = new NBTTagCompound()); + } + + return compound; + } + + /* + * Generates Item entities in the world similar to how items are generally dropped. + */ + public static void spawnDrops(final World w, final int x, final int y, final int z, final List drops) { + if (isServer()) { + for (final ItemStack i : drops) { + if (i != null) { + if (i.stackSize > 0) { + final double offset_x = (getRandomInt() % 32 - 16) / 82; + final double offset_y = (getRandomInt() % 32 - 16) / 82; + final double offset_z = (getRandomInt() % 32 - 16) / 82; + final EntityItem ei = + new EntityItem(w, 0.5 + offset_x + x, 0.5 + offset_y + y, 0.2 + offset_z + z, i.copy()); + w.spawnEntityInWorld(ei); + } + } + } + } + } + + /* + * returns true if the code is on the server. + */ + public static boolean isServer() { + return FMLCommonHandler.instance().getEffectiveSide().isServer(); + } + + public static int getRandomInt() { + return Math.abs(RANDOM_GENERATOR.nextInt()); + } + + /* + * Utility function to get the full inventory for a Double Chest in the World. + */ + public static IInventory GetChestInv(final Object te) { + TileEntityChest teA = (TileEntityChest) te; + TileEntity teB = null; + final Block myBlockID = teA.getWorldObj().getBlock(teA.xCoord, teA.yCoord, teA.zCoord); + + if (teA.getWorldObj().getBlock(teA.xCoord + 1, teA.yCoord, teA.zCoord) == myBlockID) { + teB = teA.getWorldObj().getTileEntity(teA.xCoord + 1, teA.yCoord, teA.zCoord); + if (!(teB instanceof TileEntityChest)) { + teB = null; + } + } + + if (teB == null) { + if (teA.getWorldObj().getBlock(teA.xCoord - 1, teA.yCoord, teA.zCoord) == myBlockID) { + teB = teA.getWorldObj().getTileEntity(teA.xCoord - 1, teA.yCoord, teA.zCoord); + if (!(teB instanceof TileEntityChest)) { + teB = null; + } else { + final TileEntityChest x = teA; + teA = (TileEntityChest) teB; + teB = x; + } + } + } + + if (teB == null) { + if (teA.getWorldObj().getBlock(teA.xCoord, teA.yCoord, teA.zCoord + 1) == myBlockID) { + teB = teA.getWorldObj().getTileEntity(teA.xCoord, teA.yCoord, teA.zCoord + 1); + if (!(teB instanceof TileEntityChest)) { + teB = null; + } + } + } + + if (teB == null) { + if (teA.getWorldObj().getBlock(teA.xCoord, teA.yCoord, teA.zCoord - 1) == myBlockID) { + teB = teA.getWorldObj().getTileEntity(teA.xCoord, teA.yCoord, teA.zCoord - 1); + if (!(teB instanceof TileEntityChest)) { + teB = null; + } else { + final TileEntityChest x = teA; + teA = (TileEntityChest) teB; + teB = x; + } + } + } + + if (teB == null) { + return teA; + } + + return new InventoryLargeChest("", teA, (IInventory) teB); + } + + public static boolean isModLoaded(final String modid) { + try { + // if this fails for some reason, try the other method. + return Loader.isModLoaded(modid); + } catch (final Throwable ignored) { + } + + for (final ModContainer f : Loader.instance().getActiveModList()) { + if (f.getModId().equals(modid)) { + return true; + } + } + return false; + } + + public static ItemStack findMatchingRecipeOutput(final InventoryCrafting ic, final World worldObj) { + return CraftingManager.getInstance().findMatchingRecipe(ic, worldObj); + } + + @SideOnly(Side.CLIENT) + public static List getTooltip(final Object o) { + if (o == null) { + return new ArrayList(); + } + + ItemStack itemStack = null; + if (o instanceof AEItemStack) { + final AEItemStack ais = (AEItemStack) o; + return ais.getToolTip(); + } else if (o instanceof ItemStack) { + itemStack = (ItemStack) o; + } else { + return new ArrayList(); + } + + try { + return itemStack.getTooltip(Minecraft.getMinecraft().thePlayer, false); + } catch (final Exception errB) { + return new ArrayList(); + } + } + + public static String getModId(final IAEItemStack is) { + if (is == null) { + return "** Null"; + } + + final String n = ((AEItemStack) is).getModID(); + return n == null ? "** Null" : n; + } + + public static String getItemDisplayName(final Object o) { + if (o == null) { + return "** Null"; + } + + ItemStack itemStack = null; + if (o instanceof AEItemStack) { + final String n = ((AEItemStack) o).getDisplayName(); + return n == null ? "** Null" : n; + } else if (o instanceof ItemStack) { + itemStack = (ItemStack) o; + } else { + return "**Invalid Object"; + } + + try { + String name = itemStack.getDisplayName(); + if (name == null || name.isEmpty()) { + name = itemStack.getItem().getUnlocalizedName(itemStack); + } + return name == null ? "** Null" : name; + } catch (final Exception errA) { + try { + final String n = itemStack.getUnlocalizedName(); + return n == null ? "** Null" : n; + } catch (final Exception errB) { + return "** Exception"; + } + } + } + + public static boolean hasSpecialComparison(final IAEItemStack willAdd) { + if (willAdd == null) { + return false; + } + final IAETagCompound tag = willAdd.getTagCompound(); + return tag != null && tag.getSpecialComparison() != null; + } + + public static boolean hasSpecialComparison(final ItemStack willAdd) { + if (AESharedNBT.isShared(willAdd.getTagCompound())) { + if (((IAETagCompound) willAdd.getTagCompound()).getSpecialComparison() != null) { + return true; + } + } + return false; + } + + public static boolean isWrench( + final EntityPlayer player, final ItemStack eq, final int x, final int y, final int z) { + if (eq != null) { + try { + if (eq.getItem() instanceof IToolWrench) { + final IToolWrench wrench = (IToolWrench) eq.getItem(); + return wrench.canWrench(player, x, y, z); + } + } catch (final Throwable ignore) { // explodes without BC + + } + + if (eq.getItem() instanceof IAEWrench) { + final IAEWrench wrench = (IAEWrench) eq.getItem(); + return wrench.canWrench(eq, player, x, y, z); + } + } + return false; + } + + public static boolean isChargeable(final ItemStack i) { + if (i == null) { + return false; + } + final Item it = i.getItem(); + if (it instanceof IAEItemPowerStorage) { + return ((IAEItemPowerStorage) it).getPowerFlow(i) != AccessRestriction.READ; + } + return false; + } + + public static EntityPlayer getPlayer(final WorldServer w) { + if (w == null) { + throw new InvalidParameterException("World is null."); + } + + final EntityPlayer wrp = FAKE_PLAYERS.get(w); + if (wrp != null) { + return wrp; + } + + final EntityPlayer p = FakePlayerFactory.get(w, fakeProfile); + FAKE_PLAYERS.put(w, p); + return p; + } + + public static int MC2MEColor(final int color) { + switch (color) { + case 4: // "blue" + return 0; + case 0: // "black" + return 1; + case 15: // "white" + return 2; + case 3: // "brown" + return 3; + case 1: // "red" + return 4; + case 11: // "yellow" + return 5; + case 2: // "green" + return 6; + + case 5: // "purple" + case 6: // "cyan" + case 7: // "silver" + case 8: // "gray" + case 9: // "pink" + case 10: // "lime" + case 12: // "lightBlue" + case 13: // "magenta" + case 14: // "orange" + } + return -1; + } + + public static int findEmpty(final Object[] l) { + for (int x = 0; x < l.length; x++) { + if (l[x] == null) { + return x; + } + } + return -1; + } + + public static T pickRandom(final Collection outs) { + int index = RANDOM_GENERATOR.nextInt(outs.size()); + final Iterator i = outs.iterator(); + while (i.hasNext() && index > 0) { + index--; + i.next(); + } + index--; + if (i.hasNext()) { + return i.next(); + } + return null; // wtf? + } + + public static ForgeDirection rotateAround(final ForgeDirection forward, final ForgeDirection axis) { + if (axis == ForgeDirection.UNKNOWN || forward == ForgeDirection.UNKNOWN) { + return forward; + } + + switch (forward) { + case DOWN: + switch (axis) { + case DOWN: + return forward; + case UP: + return forward; + case NORTH: + return ForgeDirection.EAST; + case SOUTH: + return ForgeDirection.WEST; + case EAST: + return ForgeDirection.NORTH; + case WEST: + return ForgeDirection.SOUTH; + default: + break; + } + break; + case UP: + switch (axis) { + case NORTH: + return ForgeDirection.WEST; + case SOUTH: + return ForgeDirection.EAST; + case EAST: + return ForgeDirection.SOUTH; + case WEST: + return ForgeDirection.NORTH; + default: + break; + } + break; + case NORTH: + switch (axis) { + case UP: + return ForgeDirection.WEST; + case DOWN: + return ForgeDirection.EAST; + case EAST: + return ForgeDirection.UP; + case WEST: + return ForgeDirection.DOWN; + default: + break; + } + break; + case SOUTH: + switch (axis) { + case UP: + return ForgeDirection.EAST; + case DOWN: + return ForgeDirection.WEST; + case EAST: + return ForgeDirection.DOWN; + case WEST: + return ForgeDirection.UP; + default: + break; + } + break; + case EAST: + switch (axis) { + case UP: + return ForgeDirection.NORTH; + case DOWN: + return ForgeDirection.SOUTH; + case NORTH: + return ForgeDirection.UP; + case SOUTH: + return ForgeDirection.DOWN; + default: + break; + } + case WEST: + switch (axis) { + case UP: + return ForgeDirection.SOUTH; + case DOWN: + return ForgeDirection.NORTH; + case NORTH: + return ForgeDirection.DOWN; + case SOUTH: + return ForgeDirection.UP; + default: + break; + } + default: + break; + } + return forward; + } + + @SideOnly(Side.CLIENT) + public static String gui_localize(final String string) { + return StatCollector.translateToLocal(string); + } + + public static boolean isSameItemPrecise(@Nullable final ItemStack is, @Nullable final ItemStack filter) { + return isSameItem(is, filter) && sameStackStags(is, filter); + } + + public static boolean isSameItemFuzzy(final ItemStack a, final ItemStack b, final FuzzyMode mode) { + if (a == null && b == null) { + return true; + } + + if (a == null) { + return false; + } + + if (b == null) { + return false; + } + + /* + * if ( a.itemID != 0 && b.itemID != 0 && a.isItemStackDamageable() && ! a.getHasSubtypes() && a.itemID == + * b.itemID ) { return (a.getItemDamage() > 0) == (b.getItemDamage() > 0); } + */ + + // test damageable items.. + if (a.getItem() != null && b.getItem() != null && a.getItem().isDamageable() && a.getItem() == b.getItem()) { + try { + if (mode == FuzzyMode.IGNORE_ALL) { + return true; + } else if (mode == FuzzyMode.PERCENT_99) { + return (a.getItemDamageForDisplay() > 1) == (b.getItemDamageForDisplay() > 1); + } else { + final float percentDamagedOfA = + 1.0f - (float) a.getItemDamageForDisplay() / (float) a.getMaxDamage(); + final float percentDamagedOfB = + 1.0f - (float) b.getItemDamageForDisplay() / (float) b.getMaxDamage(); + + return (percentDamagedOfA > mode.breakPoint) == (percentDamagedOfB > mode.breakPoint); + } + } catch (final Throwable e) { + if (mode == FuzzyMode.IGNORE_ALL) { + return true; + } else if (mode == FuzzyMode.PERCENT_99) { + return (a.getItemDamage() > 1) == (b.getItemDamage() > 1); + } else { + final float percentDamagedOfA = (float) a.getItemDamage() / (float) a.getMaxDamage(); + final float percentDamagedOfB = (float) b.getItemDamage() / (float) b.getMaxDamage(); + + return (percentDamagedOfA > mode.breakPoint) == (percentDamagedOfB > mode.breakPoint); + } + } + } + + final OreReference aOR = OreHelper.INSTANCE.isOre(a); + final OreReference bOR = OreHelper.INSTANCE.isOre(b); + + if (OreHelper.INSTANCE.sameOre(aOR, bOR)) { + return true; + } + + /* + * // test ore dictionary.. int OreID = getOreID( a ); if ( OreID != -1 ) return OreID == getOreID( b ); + * if ( Mode != FuzzyMode.IGNORE_ALL ) { if ( a.hasTagCompound() && !isShared( a.getTagCompound() ) ) { a = + * Platform.getSharedItemStack( AEItemStack.create( a ) ); } + * if ( b.hasTagCompound() && !isShared( b.getTagCompound() ) ) { b = Platform.getSharedItemStack( + * AEItemStack.create( b ) ); } + * // test regular items with damage values and what not... if ( isShared( a.getTagCompound() ) && isShared( + * b.getTagCompound() ) && a.itemID == b.itemID ) { return ((AppEngSharedNBTTagCompound) + * a.getTagCompound()).compareFuzzyWithRegistry( (AppEngSharedNBTTagCompound) b.getTagCompound() ); } } + */ + + return a.isItemEqual(b); + } + + public static LookDirection getPlayerRay(final EntityPlayer player, final float eyeOffset) { + final float f = 1.0F; + final float f1 = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * f; + final float f2 = player.prevRotationYaw + (player.rotationYaw - player.prevRotationYaw) * f; + final double d0 = player.prevPosX + (player.posX - player.prevPosX) * f; + final double d1 = eyeOffset; + final double d2 = player.prevPosZ + (player.posZ - player.prevPosZ) * f; + + final Vec3 vec3 = Vec3.createVectorHelper(d0, d1, d2); + final float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI); + final float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI); + final float f5 = -MathHelper.cos(-f1 * 0.017453292F); + final float f6 = MathHelper.sin(-f1 * 0.017453292F); + final float f7 = f4 * f5; + final float f8 = f3 * f5; + double d3 = 5.0D; + + if (player instanceof EntityPlayerMP) { + d3 = ((EntityPlayerMP) player).theItemInWorldManager.getBlockReachDistance(); + } + final Vec3 vec31 = vec3.addVector(f7 * d3, f6 * d3, f8 * d3); + return new LookDirection(vec3, vec31); + } + + public static MovingObjectPosition rayTrace( + final EntityPlayer p, final boolean hitBlocks, final boolean hitEntities) { + final World w = p.getEntityWorld(); + + final float f = 1.0F; + float f1 = p.prevRotationPitch + (p.rotationPitch - p.prevRotationPitch) * f; + final float f2 = p.prevRotationYaw + (p.rotationYaw - p.prevRotationYaw) * f; + final double d0 = p.prevPosX + (p.posX - p.prevPosX) * f; + final double d1 = p.prevPosY + (p.posY - p.prevPosY) * f + 1.62D - p.yOffset; + final double d2 = p.prevPosZ + (p.posZ - p.prevPosZ) * f; + final Vec3 vec3 = Vec3.createVectorHelper(d0, d1, d2); + final float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI); + final float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI); + final float f5 = -MathHelper.cos(-f1 * 0.017453292F); + final float f6 = MathHelper.sin(-f1 * 0.017453292F); + final float f7 = f4 * f5; + final float f8 = f3 * f5; + final double d3 = 32.0D; + + final Vec3 vec31 = vec3.addVector(f7 * d3, f6 * d3, f8 * d3); + + final AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( + Math.min(vec3.xCoord, vec31.xCoord), + Math.min(vec3.yCoord, vec31.yCoord), + Math.min(vec3.zCoord, vec31.zCoord), + Math.max(vec3.xCoord, vec31.xCoord), + Math.max(vec3.yCoord, vec31.yCoord), + Math.max(vec3.zCoord, vec31.zCoord)) + .expand(16, 16, 16); + + Entity entity = null; + double closest = 9999999.0D; + if (hitEntities) { + final List list = w.getEntitiesWithinAABBExcludingEntity(p, bb); + + for (int l = 0; l < list.size(); ++l) { + final Entity entity1 = (Entity) list.get(l); + + if (!entity1.isDead && entity1 != p && !(entity1 instanceof EntityItem)) { + if (entity1.isEntityAlive()) { + // prevent killing / flying of mounts. + if (entity1.riddenByEntity == p) { + continue; + } + + f1 = 0.3F; + final AxisAlignedBB boundingBox = entity1.boundingBox.expand(f1, f1, f1); + final MovingObjectPosition movingObjectPosition = boundingBox.calculateIntercept(vec3, vec31); + + if (movingObjectPosition != null) { + final double nd = vec3.squareDistanceTo(movingObjectPosition.hitVec); + + if (nd < closest) { + entity = entity1; + closest = nd; + } + } + } + } + } + } + + MovingObjectPosition pos = null; + Vec3 vec = null; + + if (hitBlocks) { + vec = Vec3.createVectorHelper(d0, d1, d2); + pos = w.rayTraceBlocks(vec3, vec31, true); + } + + if (entity != null && pos != null && pos.hitVec.squareDistanceTo(vec) > closest) { + pos = new MovingObjectPosition(entity); + } else if (entity != null && pos == null) { + pos = new MovingObjectPosition(entity); + } + + return pos; + } + + public static long nanoTime() { + // if ( Configuration.INSTANCE.enableNetworkProfiler ) + // return System.nanoTime(); + return 0; + } + + public static StackType poweredExtraction( + final IEnergySource energy, + final IMEInventory cell, + final StackType request, + final BaseActionSource src) { + final StackType possible = cell.extractItems((StackType) request.copy(), Actionable.SIMULATE, src); + + long retrieved = 0; + if (possible != null) { + retrieved = possible.getStackSize(); + } + + final double availablePower = energy.extractAEPower(retrieved, Actionable.SIMULATE, PowerMultiplier.CONFIG); + + final long itemToExtract = Math.min((long) (availablePower + 0.9), retrieved); + + if (itemToExtract > 0) { + energy.extractAEPower(retrieved, Actionable.MODULATE, PowerMultiplier.CONFIG); + + possible.setStackSize(itemToExtract); + final StackType ret = cell.extractItems(possible, Actionable.MODULATE, src); + + if (ret != null && src.isPlayer()) { + Stats.ItemsExtracted.addToPlayer(((PlayerSource) src).player, (int) ret.getStackSize()); + } + + return ret; + } + + return null; + } + + public static StackType poweredInsert( + final IEnergySource energy, + final IMEInventory cell, + final StackType input, + final BaseActionSource src) { + final StackType possible = cell.injectItems((StackType) input.copy(), Actionable.SIMULATE, src); + + long stored = input.getStackSize(); + if (possible != null) { + stored -= possible.getStackSize(); + } + + final double availablePower = energy.extractAEPower(stored, Actionable.SIMULATE, PowerMultiplier.CONFIG); + + final long itemToAdd = Math.min((long) (availablePower + 0.9), stored); + + if (itemToAdd > 0) { + energy.extractAEPower(stored, Actionable.MODULATE, PowerMultiplier.CONFIG); + + if (itemToAdd < input.getStackSize()) { + final long original = input.getStackSize(); + final StackType split = (StackType) input.copy(); + split.decStackSize(itemToAdd); + input.setStackSize(itemToAdd); + split.add(cell.injectItems(input, Actionable.MODULATE, src)); + + if (src.isPlayer()) { + final long diff = original - split.getStackSize(); + Stats.ItemsInserted.addToPlayer(((PlayerSource) src).player, (int) diff); + } + + return split; + } + + final StackType ret = cell.injectItems(input, Actionable.MODULATE, src); + + if (src.isPlayer()) { + final long diff = ret == null ? input.getStackSize() : input.getStackSize() - ret.getStackSize(); + Stats.ItemsInserted.addToPlayer(((PlayerSource) src).player, (int) diff); + } + + return ret; + } + + return input; + } + + public static void postChanges( + final IStorageGrid gs, final ItemStack removed, final ItemStack added, final BaseActionSource src) { + final IItemList itemChanges = AEApi.instance().storage().createItemList(); + final IItemList fluidChanges = AEApi.instance().storage().createFluidList(); + + if (removed != null) { + final IMEInventory myItems = + AEApi.instance().registries().cell().getCellInventory(removed, null, StorageChannel.ITEMS); + + if (myItems != null) { + for (final IAEItemStack is : myItems.getAvailableItems(itemChanges)) { + is.setStackSize(-is.getStackSize()); + } + } + + final IMEInventory myFluids = + AEApi.instance().registries().cell().getCellInventory(removed, null, StorageChannel.FLUIDS); + + if (myFluids != null) { + for (final IAEFluidStack is : myFluids.getAvailableItems(fluidChanges)) { + is.setStackSize(-is.getStackSize()); + } + } + } + + if (added != null) { + final IMEInventory myItems = + AEApi.instance().registries().cell().getCellInventory(added, null, StorageChannel.ITEMS); + + if (myItems != null) { + myItems.getAvailableItems(itemChanges); + } + + final IMEInventory myFluids = + AEApi.instance().registries().cell().getCellInventory(added, null, StorageChannel.FLUIDS); + + if (myFluids != null) { + myFluids.getAvailableItems(fluidChanges); + } + } + + gs.postAlterationOfStoredItems(StorageChannel.ITEMS, itemChanges, src); + } + + public static > void postListChanges( + final IItemList before, + final IItemList after, + final IMEMonitorHandlerReceiver meMonitorPassthrough, + final BaseActionSource source) { + final LinkedList changes = new LinkedList(); + + for (final T is : before) { + is.setStackSize(-is.getStackSize()); + } + + for (final T is : after) { + before.add(is); + } + + for (final T is : before) { + if (is.getStackSize() != 0) { + changes.add(is); + } + } + + if (!changes.isEmpty()) { + meMonitorPassthrough.postChange(null, changes, source); + } + } + + public static int generateTileHash(final TileEntity target) { + if (target == null) { + return 0; + } + + int hash = target.hashCode(); + + if (target instanceof ITileStorageMonitorable) { + return 0; + } else if (target instanceof TileEntityChest) { + final TileEntityChest chest = (TileEntityChest) target; + chest.checkForAdjacentChests(); + if (chest.adjacentChestZNeg != null) { + hash ^= chest.adjacentChestZNeg.hashCode(); + } else if (chest.adjacentChestZPos != null) { + hash ^= chest.adjacentChestZPos.hashCode(); + } else if (chest.adjacentChestXPos != null) { + hash ^= chest.adjacentChestXPos.hashCode(); + } else if (chest.adjacentChestXNeg != null) { + hash ^= chest.adjacentChestXNeg.hashCode(); + } + } else if (target instanceof IInventory) { + hash ^= ((IInventory) target).getSizeInventory(); + + if (target instanceof ISidedInventory) { + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + + final int[] sides = ((ISidedInventory) target).getAccessibleSlotsFromSide(dir.ordinal()); + + if (sides == null) { + return 0; + } + + int offset = 0; + for (final int side : sides) { + final int c = (side << (offset % 8)) ^ (1 << dir.ordinal()); + offset++; + hash = c + (hash << 6) + (hash << 16) - hash; + } + } + } + } + + return hash; + } + + public static boolean securityCheck(final GridNode a, final GridNode b) { + if (a.getLastSecurityKey() == -1 && b.getLastSecurityKey() == -1) { + return false; + } else if (a.getLastSecurityKey() == b.getLastSecurityKey()) { + return false; + } + + final boolean a_isSecure = isPowered(a.getGrid()) && a.getLastSecurityKey() != -1; + final boolean b_isSecure = isPowered(b.getGrid()) && b.getLastSecurityKey() != -1; + + if (AEConfig.instance.isFeatureEnabled(AEFeature.LogSecurityAudits)) { + AELog.info("Audit: " + a_isSecure + " : " + b_isSecure + " @ " + a.getLastSecurityKey() + " vs " + + b.getLastSecurityKey() + " & " + a.getPlayerID() + " vs " + b.getPlayerID()); + } + + // can't do that son... + if (a_isSecure && b_isSecure) { + return true; + } + + if (!a_isSecure && b_isSecure) { + return checkPlayerPermissions(b.getGrid(), a.getPlayerID()); + } + + if (a_isSecure && !b_isSecure) { + return checkPlayerPermissions(a.getGrid(), b.getPlayerID()); + } + + return false; + } + + private static boolean isPowered(final IGrid grid) { + if (grid == null) { + return false; + } + + final IEnergyGrid eg = grid.getCache(IEnergyGrid.class); + return eg.isNetworkPowered(); + } + + private static boolean checkPlayerPermissions(final IGrid grid, final int playerID) { + if (grid == null) { + return false; + } + + final ISecurityGrid gs = grid.getCache(ISecurityGrid.class); + + if (gs == null) { + return false; + } + + if (!gs.isAvailable()) { + return false; + } + + return !gs.hasPermission(playerID, SecurityPermissions.BUILD); + } + + public static void configurePlayer(final EntityPlayer player, final ForgeDirection side, final TileEntity tile) { + player.yOffset = 1.8f; + + float yaw = 0.0f; + float pitch = 0.0f; + switch (side) { + case DOWN: + pitch = 90.0f; + player.yOffset = -1.8f; + break; + case EAST: + yaw = -90.0f; + break; + case NORTH: + yaw = 180.0f; + break; + case SOUTH: + yaw = 0.0f; + break; + case UNKNOWN: + break; + case UP: + pitch = 90.0f; + break; + case WEST: + yaw = 90.0f; + break; + } + + player.posX = tile.xCoord + 0.5; + player.posY = tile.yCoord + 0.5; + player.posZ = tile.zCoord + 0.5; + + player.rotationPitch = player.prevCameraPitch = player.cameraPitch = pitch; + player.rotationYaw = player.prevCameraYaw = player.cameraYaw = yaw; + } + + public static boolean canAccess(final AENetworkProxy gridProxy, final BaseActionSource src) { + try { + if (src.isPlayer()) { + return gridProxy.getSecurity().hasPermission(((PlayerSource) src).player, SecurityPermissions.BUILD); + } else if (src.isMachine()) { + final IActionHost te = ((MachineSource) src).via; + final IGridNode n = te.getActionableNode(); + if (n == null) { + return false; + } + + final int playerID = n.getPlayerID(); + return gridProxy.getSecurity().hasPermission(playerID, SecurityPermissions.BUILD); + } else { + return false; + } + } catch (final GridAccessException gae) { + return false; + } + } + + public static ItemStack extractItemsByRecipe( + final IEnergySource energySrc, + final BaseActionSource mySrc, + final IMEMonitor src, + final World w, + final IRecipe r, + final ItemStack output, + final InventoryCrafting ci, + final ItemStack providedTemplate, + final int slot, + final IItemList items, + final Actionable realForFake, + final IPartitionList filter) { + return extractItemsByRecipe( + energySrc, mySrc, src, w, r, output, ci, providedTemplate, slot, items, realForFake, filter, 1); + } + + public static ItemStack extractItemsByRecipe( + final IEnergySource energySrc, + final BaseActionSource mySrc, + final IMEMonitor src, + final World w, + final IRecipe r, + final ItemStack output, + final InventoryCrafting ci, + final ItemStack providedTemplate, + final int slot, + final IItemList items, + final Actionable realForFake, + final IPartitionList filter, + int multiple) { + if (energySrc.extractAEPower(multiple, Actionable.SIMULATE, PowerMultiplier.CONFIG) > 0.9) { + if (providedTemplate == null) { + return null; + } + + final AEItemStack ae_req = AEItemStack.create(providedTemplate); + ae_req.setStackSize(multiple); + + if (filter == null || filter.isListed(ae_req)) { + final IAEItemStack ae_ext = src.extractItems(ae_req, realForFake, mySrc); + if (ae_ext != null) { + final ItemStack extracted = ae_ext.getItemStack(); + if (extracted != null) { + energySrc.extractAEPower(multiple, realForFake, PowerMultiplier.CONFIG); + return extracted; + } + } + } + + final boolean checkFuzzy = ae_req.isOre() + || providedTemplate.getItemDamage() == OreDictionary.WILDCARD_VALUE + || providedTemplate.hasTagCompound() + || providedTemplate.isItemStackDamageable(); + + if (items != null && checkFuzzy) { + for (final IAEItemStack x : items) { + final ItemStack sh = x.getItemStack(); + if ((Platform.isSameItemType(providedTemplate, sh) || ae_req.sameOre(x)) + && !Platform.isSameItem(sh, output)) { // Platform.isSameItemType( sh, providedTemplate ) + final ItemStack cp = Platform.cloneItemStack(sh); + cp.stackSize = 1; + ci.setInventorySlotContents(slot, cp); + if (r.matches(ci, w) && Platform.isSameItem(r.getCraftingResult(ci), output)) { + final IAEItemStack ax = x.copy(); + ax.setStackSize(multiple); + if (filter == null || filter.isListed(ax)) { + final IAEItemStack ex = src.extractItems(ax, realForFake, mySrc); + if (ex != null) { + energySrc.extractAEPower(multiple, realForFake, PowerMultiplier.CONFIG); + return ex.getItemStack(); + } + } + } + ci.setInventorySlotContents(slot, providedTemplate); + } + } + } + } + return null; + } + + public static boolean isSameItemType(final ItemStack that, final ItemStack other) { + if (that != null && other != null && that.getItem() == other.getItem()) { + if (that.isItemStackDamageable()) { + return true; + } + return that.getItemDamage() == other.getItemDamage(); + } + return false; + } + + public static boolean isSameItem(@Nullable final ItemStack left, @Nullable final ItemStack right) { + return left != null && right != null && left.isItemEqual(right); + } + + public static ItemStack cloneItemStack(final ItemStack a) { + return a.copy(); + } + + public static ItemStack getContainerItem(final ItemStack stackInSlot) { + if (stackInSlot == null) { + return null; + } + + final Item i = stackInSlot.getItem(); + if (i == null || !i.hasContainerItem(stackInSlot)) { + if (stackInSlot.stackSize > 1) { + stackInSlot.stackSize--; + return stackInSlot; + } + return null; + } + + ItemStack ci = i.getContainerItem(stackInSlot.copy()); + if (ci != null && ci.isItemStackDamageable() && ci.getItemDamage() == ci.getMaxDamage()) { + ci = null; + } + + return ci; + } + + public static void notifyBlocksOfNeighbors( + final World worldObj, final int xCoord, final int yCoord, final int zCoord) { + if (!worldObj.isRemote) { + TickHandler.INSTANCE.addCallable(worldObj, new BlockUpdate(xCoord, yCoord, zCoord)); + } + } + + public static boolean canRepair(final AEFeature type, final ItemStack a, final ItemStack b) { + if (b == null || a == null) { + return false; + } + + if (type == AEFeature.CertusQuartzTools) { + final IItemDefinition certusQuartzCrystal = + AEApi.instance().definitions().materials().certusQuartzCrystal(); + + return certusQuartzCrystal.isSameAs(b); + } + + if (type == AEFeature.NetherQuartzTools) { + return Items.quartz == b.getItem(); + } + + return false; + } + + public static Object findPreferred(final ItemStack[] is) { + final IParts parts = AEApi.instance().definitions().parts(); + + for (final ItemStack stack : is) { + if (parts.cableGlass().sameAs(AEColor.Transparent, stack)) { + return stack; + } + + if (parts.cableCovered().sameAs(AEColor.Transparent, stack)) { + return stack; + } + + if (parts.cableSmart().sameAs(AEColor.Transparent, stack)) { + return stack; + } + + if (parts.cableDense().sameAs(AEColor.Transparent, stack)) { + return stack; + } + + if (parts.cableDenseCovered().sameAs(AEColor.Transparent, stack)) { + return stack; + } + + if (parts.cableUltraDenseCovered().sameAs(AEColor.Transparent, stack)) { + return stack; + } + + if (parts.cableUltraDenseSmart().sameAs(AEColor.Transparent, stack)) { + return stack; + } + } + + return is; + } + + public static void sendChunk(final Chunk c, final int verticalBits) { + try { + final WorldServer ws = (WorldServer) c.worldObj; + final PlayerManager pm = ws.getPlayerManager(); + + if (getOrCreateChunkWatcher == null) { + getOrCreateChunkWatcher = ReflectionHelper.findMethod( + PlayerManager.class, + pm, + new String[] {"getOrCreateChunkWatcher", "func_72690_a"}, + int.class, + int.class, + boolean.class); + } + + if (getOrCreateChunkWatcher != null) { + final Object playerInstance = getOrCreateChunkWatcher.invoke(pm, c.xPosition, c.zPosition, false); + if (playerInstance != null) { + Platform.playerInstance = playerInstance.getClass(); + + if (sendToAllPlayersWatchingChunk == null) { + sendToAllPlayersWatchingChunk = ReflectionHelper.findMethod( + Platform.playerInstance, + playerInstance, + new String[] {"sendToAllPlayersWatchingChunk", "func_151251_a"}, + Packet.class); + } + + if (sendToAllPlayersWatchingChunk != null) { + sendToAllPlayersWatchingChunk.invoke( + playerInstance, new S21PacketChunkData(c, false, verticalBits)); + } + } + } + } catch (final Throwable t) { + AELog.debug(t); + } + } + + public static AxisAlignedBB getPrimaryBox(final ForgeDirection side, final int facadeThickness) { + switch (side) { + case DOWN: + return AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.0, 1.0, (facadeThickness) / 16.0, 1.0); + case EAST: + return AxisAlignedBB.getBoundingBox((16.0 - facadeThickness) / 16.0, 0.0, 0.0, 1.0, 1.0, 1.0); + case NORTH: + return AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.0, 1.0, 1.0, (facadeThickness) / 16.0); + case SOUTH: + return AxisAlignedBB.getBoundingBox(0.0, 0.0, (16.0 - facadeThickness) / 16.0, 1.0, 1.0, 1.0); + case UP: + return AxisAlignedBB.getBoundingBox(0.0, (16.0 - facadeThickness) / 16.0, 0.0, 1.0, 1.0, 1.0); + case WEST: + return AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.0, (facadeThickness) / 16.0, 1.0, 1.0); + default: + break; + } + return AxisAlignedBB.getBoundingBox(0, 0, 0, 1, 1, 1); + } + + public static float getEyeOffset(final EntityPlayer player) { + assert player.worldObj.isRemote : "Valid only on client"; + return (float) (player.posY + player.getEyeHeight() - player.getDefaultEyeHeight()); + } + + public static void addStat(final int playerID, final Achievement achievement) { + final EntityPlayer p = AEApi.instance().registries().players().findPlayer(playerID); + if (p != null) { + p.addStat(achievement, 1); + } + } + + public static boolean isRecipePrioritized(final ItemStack what) { + final IMaterials materials = AEApi.instance().definitions().materials(); + + boolean isPurified = materials.purifiedCertusQuartzCrystal().isSameAs(what); + isPurified |= materials.purifiedFluixCrystal().isSameAs(what); + isPurified |= materials.purifiedNetherQuartzCrystal().isSameAs(what); + + return isPurified; + } + + public static ItemStack loadItemStackFromNBT(NBTTagCompound tagCompound) { + ItemStack stack = ItemStack.loadItemStackFromNBT(tagCompound); + if (stack != null) { + stack.stackSize = tagCompound.getInteger("Count"); } return stack; } - public static NBTTagCompound writeItemStackToNBT( ItemStack is, NBTTagCompound tagCompound ) - { - is.writeToNBT( tagCompound ); - tagCompound.setInteger( "Count" , is.stackSize); + public static NBTTagCompound writeItemStackToNBT(ItemStack is, NBTTagCompound tagCompound) { + is.writeToNBT(tagCompound); + tagCompound.setInteger("Count", is.stackSize); return tagCompound; } - public static IAEItemStack getAEStackInSlot( Slot slot ) - { - if( slot == null || !slot.getHasStack() ) - { + public static IAEItemStack getAEStackInSlot(Slot slot) { + if (slot == null || !slot.getHasStack()) { return null; } - if( slot instanceof SlotME ) - { - return ( (SlotME) slot ).getAEStack(); + if (slot instanceof SlotME) { + return ((SlotME) slot).getAEStack(); } - if(slot instanceof SlotFake ) - { - return ( (SlotFake) slot ).getAEStack(); + if (slot instanceof SlotFake) { + return ((SlotFake) slot).getAEStack(); } - return AEItemStack.create( slot.getStack() ); + return AEItemStack.create(slot.getStack()); } - } diff --git a/src/main/java/appeng/util/ReadOnlyCollection.java b/src/main/java/appeng/util/ReadOnlyCollection.java index b059e3f121e..2cfb6bdeeb2 100644 --- a/src/main/java/appeng/util/ReadOnlyCollection.java +++ b/src/main/java/appeng/util/ReadOnlyCollection.java @@ -18,44 +18,35 @@ package appeng.util; - import appeng.api.util.IReadOnlyCollection; - import java.util.Collection; import java.util.Iterator; +public class ReadOnlyCollection implements IReadOnlyCollection { -public class ReadOnlyCollection implements IReadOnlyCollection -{ - - private final Collection c; + private final Collection c; - public ReadOnlyCollection( final Collection in ) - { - this.c = in; - } + public ReadOnlyCollection(final Collection in) { + this.c = in; + } - @Override - public Iterator iterator() - { - return this.c.iterator(); - } + @Override + public Iterator iterator() { + return this.c.iterator(); + } - @Override - public int size() - { - return this.c.size(); - } + @Override + public int size() { + return this.c.size(); + } - @Override - public boolean isEmpty() - { - return this.c.isEmpty(); - } + @Override + public boolean isEmpty() { + return this.c.isEmpty(); + } - @Override - public boolean contains( final Object node ) - { - return this.c.contains( node ); - } + @Override + public boolean contains(final Object node) { + return this.c.contains(node); + } } diff --git a/src/main/java/appeng/util/ReadableNumberConverter.java b/src/main/java/appeng/util/ReadableNumberConverter.java index 6714a881976..a10d8c91903 100644 --- a/src/main/java/appeng/util/ReadableNumberConverter.java +++ b/src/main/java/appeng/util/ReadableNumberConverter.java @@ -1,12 +1,10 @@ package appeng.util; - import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.Format; - /** * Converter class to convert a large number into a SI system. * @@ -14,92 +12,85 @@ * @version rv2 * @since rv2 */ -public enum ReadableNumberConverter implements ISlimReadableNumberConverter, IWideReadableNumberConverter -{ - INSTANCE; - - /** - * Defines the base for a division, non-si standard could be 1024 for kilobytes - */ - private static final int DIVISION_BASE = 1000; - - /** - * String representation of the sorted postfixes - */ - private static final char[] ENCODED_POSTFIXES = "KMGTPE".toCharArray(); - - private final Format format; - - /** - * Initializes the specific decimal format with special format for negative and positive numbers - */ - ReadableNumberConverter() - { - final DecimalFormatSymbols symbols = new DecimalFormatSymbols(); - symbols.setDecimalSeparator( '.' ); - final DecimalFormat format = new DecimalFormat( ".#;0.#" ); - format.setDecimalFormatSymbols( symbols ); - format.setRoundingMode( RoundingMode.DOWN ); - - this.format = format; - } - - @Override - public String toSlimReadableForm( final long number ) - { - return this.toReadableFormRestrictedByWidth( number, 3 ); - } - - /** - * restricts a string representation of a number to a specific width - * - * @param number to be formatted number - * @param width width limitation of the resulting number - * @return formatted number restricted by the width limitation - */ - private String toReadableFormRestrictedByWidth( final long number, final int width ) - { - assert number >= 0; - - // handles low numbers more efficiently since no format is needed - final String numberString = Long.toString( number ); - int numberSize = numberString.length(); - if( numberSize <= width ) - { - return numberString; - } - - long base = number; - double last = base * 1000; - int exponent = -1; - String postFix = ""; - - while( numberSize > width ) - { - last = base; - base /= DIVISION_BASE; - - exponent++; - - // adds +1 due to the postfix - numberSize = Long.toString( base ).length() + 1; - postFix = String.valueOf( ENCODED_POSTFIXES[exponent] ); - } - - final String withPrecision = this.format.format( last / DIVISION_BASE ) + postFix; - final String withoutPrecision = Long.toString( base ) + postFix; - - final String slimResult = ( withPrecision.length() <= width ) ? withPrecision : withoutPrecision; - - // post condition - assert slimResult.length() <= width; - - return slimResult; - } - - @Override - public String toWideReadableForm( final long number ) - { - return this.toReadableFormRestrictedByWidth( number, 4 ); - } +public enum ReadableNumberConverter implements ISlimReadableNumberConverter, IWideReadableNumberConverter { + INSTANCE; + + /** + * Defines the base for a division, non-si standard could be 1024 for kilobytes + */ + private static final int DIVISION_BASE = 1000; + + /** + * String representation of the sorted postfixes + */ + private static final char[] ENCODED_POSTFIXES = "KMGTPE".toCharArray(); + + private final Format format; + + /** + * Initializes the specific decimal format with special format for negative and positive numbers + */ + ReadableNumberConverter() { + final DecimalFormatSymbols symbols = new DecimalFormatSymbols(); + symbols.setDecimalSeparator('.'); + final DecimalFormat format = new DecimalFormat(".#;0.#"); + format.setDecimalFormatSymbols(symbols); + format.setRoundingMode(RoundingMode.DOWN); + + this.format = format; + } + + @Override + public String toSlimReadableForm(final long number) { + return this.toReadableFormRestrictedByWidth(number, 3); + } + + /** + * restricts a string representation of a number to a specific width + * + * @param number to be formatted number + * @param width width limitation of the resulting number + * @return formatted number restricted by the width limitation + */ + private String toReadableFormRestrictedByWidth(final long number, final int width) { + assert number >= 0; + + // handles low numbers more efficiently since no format is needed + final String numberString = Long.toString(number); + int numberSize = numberString.length(); + if (numberSize <= width) { + return numberString; + } + + long base = number; + double last = base * 1000; + int exponent = -1; + String postFix = ""; + + while (numberSize > width) { + last = base; + base /= DIVISION_BASE; + + exponent++; + + // adds +1 due to the postfix + numberSize = Long.toString(base).length() + 1; + postFix = String.valueOf(ENCODED_POSTFIXES[exponent]); + } + + final String withPrecision = this.format.format(last / DIVISION_BASE) + postFix; + final String withoutPrecision = Long.toString(base) + postFix; + + final String slimResult = (withPrecision.length() <= width) ? withPrecision : withoutPrecision; + + // post condition + assert slimResult.length() <= width; + + return slimResult; + } + + @Override + public String toWideReadableForm(final long number) { + return this.toReadableFormRestrictedByWidth(number, 4); + } } diff --git a/src/main/java/appeng/util/SettingsFrom.java b/src/main/java/appeng/util/SettingsFrom.java index f187f994819..5efa2d0244f 100644 --- a/src/main/java/appeng/util/SettingsFrom.java +++ b/src/main/java/appeng/util/SettingsFrom.java @@ -18,12 +18,10 @@ package appeng.util; +public enum SettingsFrom { + // moved the item, and replaced it. + DISMANTLE_ITEM, -public enum SettingsFrom -{ - // moved the item, and replaced it. - DISMANTLE_ITEM, - - // used memory card? - MEMORY_CARD + // used memory card? + MEMORY_CARD } diff --git a/src/main/java/appeng/util/UUIDMatcher.java b/src/main/java/appeng/util/UUIDMatcher.java index 91d8c83f942..d1cad0c9269 100644 --- a/src/main/java/appeng/util/UUIDMatcher.java +++ b/src/main/java/appeng/util/UUIDMatcher.java @@ -18,33 +18,29 @@ package appeng.util; - import java.util.regex.Pattern; - /** * Regex wrapper for {@link java.util.UUID}s to not rely on try catch */ -public final class UUIDMatcher -{ - /** - * String which is the regular expression for {@link java.util.UUID}s - */ - private static final String UUID_REGEX = "[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"; +public final class UUIDMatcher { + /** + * String which is the regular expression for {@link java.util.UUID}s + */ + private static final String UUID_REGEX = "[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"; - /** - * Pattern which pre-compiles the {@link appeng.util.UUIDMatcher#UUID_REGEX} - */ - private static final Pattern PATTERN = Pattern.compile( UUID_REGEX ); + /** + * Pattern which pre-compiles the {@link appeng.util.UUIDMatcher#UUID_REGEX} + */ + private static final Pattern PATTERN = Pattern.compile(UUID_REGEX); - /** - * Checks if a potential {@link java.util.UUID} is an {@link java.util.UUID} by applying a regular expression on it. - * - * @param potential to be checked potential {@link java.util.UUID} - * @return true, if the potential {@link java.util.UUID} is indeed an {@link java.util.UUID} - */ - public boolean isUUID( final CharSequence potential ) - { - return PATTERN.matcher( potential ).matches(); - } + /** + * Checks if a potential {@link java.util.UUID} is an {@link java.util.UUID} by applying a regular expression on it. + * + * @param potential to be checked potential {@link java.util.UUID} + * @return true, if the potential {@link java.util.UUID} is indeed an {@link java.util.UUID} + */ + public boolean isUUID(final CharSequence potential) { + return PATTERN.matcher(potential).matches(); + } } diff --git a/src/main/java/appeng/util/calculators/ArithHelper.java b/src/main/java/appeng/util/calculators/ArithHelper.java index b67da33f911..8660e6d5423 100644 --- a/src/main/java/appeng/util/calculators/ArithHelper.java +++ b/src/main/java/appeng/util/calculators/ArithHelper.java @@ -4,8 +4,7 @@ public class ArithHelper { private static final int DEF_DIV_SCALE = 16; - private ArithHelper() { - } + private ArithHelper() {} /** * addition @@ -87,5 +86,4 @@ public static String round(String v, int scale) { java.math.BigDecimal one = new java.math.BigDecimal("1"); return String.valueOf(b.divide(one, scale, java.math.BigDecimal.ROUND_HALF_UP)); } - } diff --git a/src/main/java/appeng/util/calculators/Calculator.java b/src/main/java/appeng/util/calculators/Calculator.java index 5ed29fef29f..4f66e675a9c 100644 --- a/src/main/java/appeng/util/calculators/Calculator.java +++ b/src/main/java/appeng/util/calculators/Calculator.java @@ -1,25 +1,23 @@ package appeng.util.calculators; -import java.math.BigDecimal; import java.util.Collections; import java.util.Stack; public class Calculator { private final Stack postfixStack = new Stack<>(); private final Stack opStack = new Stack<>(); - private final int[] operatPriority = new int[] { 0, 3, 2, 1, -1, 1, 0, 2 }; + private final int[] operatPriority = new int[] {0, 3, 2, 1, -1, 1, 0, 2}; public static double conversion(String expression) { double result = 0; - if( expression == null ) - return Double.NaN; + if (expression == null) return Double.NaN; - expression = expression.replace( " ", "" ); + expression = expression.replace(" ", ""); Calculator cal = new Calculator(); - if( expression.length() == 1 && Character.isDigit( expression.charAt( 0 ) ) ) { - return expression.charAt( 0 ) - '0'; + if (expression.length() == 1 && Character.isDigit(expression.charAt(0))) { + return expression.charAt(0) - '0'; } try { expression = transform(expression); @@ -52,8 +50,8 @@ private static String transform(String expression) { } } } - if(arr[0]=='~'||arr[1]=='(') { - arr[0]='-'; + if (arr[0] == '~' || arr[1] == '(') { + arr[0] = '-'; return "0" + new String(arr); } else { return new String(arr); @@ -187,5 +185,4 @@ private String calculate(String firstValue, String secondValue, char currentOp) } return result; } - } diff --git a/src/main/java/appeng/util/inv/AdaptorBCPipe.java b/src/main/java/appeng/util/inv/AdaptorBCPipe.java index ed08d23e3fa..f5b165296e5 100644 --- a/src/main/java/appeng/util/inv/AdaptorBCPipe.java +++ b/src/main/java/appeng/util/inv/AdaptorBCPipe.java @@ -18,108 +18,98 @@ package appeng.util.inv; - import appeng.api.config.FuzzyMode; import appeng.integration.IntegrationRegistry; import appeng.integration.IntegrationType; import appeng.integration.abstraction.IBuildCraftTransport; import appeng.util.InventoryAdaptor; import appeng.util.iterators.NullIterator; +import java.util.Iterator; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Iterator; - - -public class AdaptorBCPipe extends InventoryAdaptor -{ - private final IBuildCraftTransport buildCraft; - private final TileEntity i; - private final ForgeDirection d; - - public AdaptorBCPipe( final TileEntity s, final ForgeDirection dd ) - { - this.buildCraft = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - if( this.buildCraft.isPipe( s, dd ) ) - { - this.i = s; - this.d = dd; - return; - } - } - this.i = null; - this.d = null; - } - - @Override - public ItemStack removeItems( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - return null; - } - - @Override - public ItemStack simulateRemove( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - return null; - } - - @Override - public ItemStack removeSimilarItems( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - return null; - } - - @Override - public ItemStack simulateSimilarRemove( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - return null; - } - - @Override - public ItemStack addItems( final ItemStack toBeAdded ) - { - if( this.i == null ) - { - return toBeAdded; - } - if( toBeAdded == null ) - { - return null; - } - if( toBeAdded.stackSize == 0 ) - { - return null; - } - - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) && this.buildCraft.addItemsToPipe( this.i, toBeAdded, this.d ) ) - { - return null; - } - return toBeAdded; - } - - @Override - public ItemStack simulateAdd( final ItemStack toBeSimulated ) - { - if( this.i == null ) - { - return toBeSimulated; - } - return null; - } - - @Override - public boolean containsItems() - { - return false; - } - - @Override - public Iterator iterator() - { - return new NullIterator(); - } +public class AdaptorBCPipe extends InventoryAdaptor { + private final IBuildCraftTransport buildCraft; + private final TileEntity i; + private final ForgeDirection d; + + public AdaptorBCPipe(final TileEntity s, final ForgeDirection dd) { + this.buildCraft = + (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport); + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport)) { + if (this.buildCraft.isPipe(s, dd)) { + this.i = s; + this.d = dd; + return; + } + } + this.i = null; + this.d = null; + } + + @Override + public ItemStack removeItems(final int amount, final ItemStack filter, final IInventoryDestination destination) { + return null; + } + + @Override + public ItemStack simulateRemove(final int amount, final ItemStack filter, final IInventoryDestination destination) { + return null; + } + + @Override + public ItemStack removeSimilarItems( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination) { + return null; + } + + @Override + public ItemStack simulateSimilarRemove( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination) { + return null; + } + + @Override + public ItemStack addItems(final ItemStack toBeAdded) { + if (this.i == null) { + return toBeAdded; + } + if (toBeAdded == null) { + return null; + } + if (toBeAdded.stackSize == 0) { + return null; + } + + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport) + && this.buildCraft.addItemsToPipe(this.i, toBeAdded, this.d)) { + return null; + } + return toBeAdded; + } + + @Override + public ItemStack simulateAdd(final ItemStack toBeSimulated) { + if (this.i == null) { + return toBeSimulated; + } + return null; + } + + @Override + public boolean containsItems() { + return false; + } + + @Override + public Iterator iterator() { + return new NullIterator(); + } } diff --git a/src/main/java/appeng/util/inv/AdaptorIInventory.java b/src/main/java/appeng/util/inv/AdaptorIInventory.java index ea1910976d6..07d97026298 100644 --- a/src/main/java/appeng/util/inv/AdaptorIInventory.java +++ b/src/main/java/appeng/util/inv/AdaptorIInventory.java @@ -18,393 +18,340 @@ package appeng.util.inv; - import appeng.api.config.FuzzyMode; import appeng.api.config.InsertionMode; import appeng.util.InventoryAdaptor; import appeng.util.Platform; +import java.util.Iterator; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.util.Iterator; - - -public class AdaptorIInventory extends InventoryAdaptor -{ +public class AdaptorIInventory extends InventoryAdaptor { - private final IInventory i; - private final boolean wrapperEnabled; + private final IInventory i; + private final boolean wrapperEnabled; private final boolean skipStackSizeCheck; - public AdaptorIInventory( final IInventory s ) - { - this.i = s; - skipStackSizeCheck = i.getClass().toString().equals("class wanion.avaritiaddons.block.chest.infinity.TileEntityInfinityChest"); - this.wrapperEnabled = s instanceof IInventoryWrapper; - } - - @Override - public ItemStack removeItems( int amount, ItemStack filter, final IInventoryDestination destination ) - { - final int s = this.i.getSizeInventory(); - ItemStack rv = null; - - for( int x = 0; x < s && amount > 0; x++ ) - { - final ItemStack is = this.i.getStackInSlot( x ); - if( is != null && this.canRemoveStackFromSlot( x, is ) && ( filter == null || Platform.isSameItemPrecise( is, filter ) ) ) - { - int boundAmounts = amount; - if( boundAmounts > is.stackSize ) - { - boundAmounts = is.stackSize; - } - if( destination != null && !destination.canInsert( is ) ) - { - boundAmounts = 0; - } - - if( boundAmounts > 0 ) - { - if( rv == null ) - { - rv = is.copy(); - filter = rv; - rv.stackSize = boundAmounts; - amount -= boundAmounts; - } - else - { - rv.stackSize += boundAmounts; - amount -= boundAmounts; - } - - if( is.stackSize == boundAmounts ) - { - this.i.setInventorySlotContents( x, null ); - this.i.markDirty(); - } - else - { - final ItemStack po = is.copy(); - po.stackSize -= boundAmounts; - this.i.setInventorySlotContents( x, po ); - this.i.markDirty(); - } - } - } - } - - // if ( rv != null ) - // i.markDirty(); - - return rv; - } - - @Override - public ItemStack simulateRemove( int amount, final ItemStack filter, final IInventoryDestination destination ) - { - final int s = this.i.getSizeInventory(); - ItemStack rv = null; - - for( int x = 0; x < s && amount > 0; x++ ) - { - final ItemStack is = this.i.getStackInSlot( x ); - if( is != null && this.canRemoveStackFromSlot( x, is ) && ( filter == null || Platform.isSameItemPrecise( is, filter ) ) ) - { - int boundAmount = amount; - if( boundAmount > is.stackSize ) - { - boundAmount = is.stackSize; - } - if( destination != null && !destination.canInsert( is ) ) - { - boundAmount = 0; - } - - if( boundAmount > 0 ) - { - if( rv == null ) - { - rv = is.copy(); - rv.stackSize = boundAmount; - amount -= boundAmount; - } - else - { - rv.stackSize += boundAmount; - amount -= boundAmount; - } - } - } - } - - return rv; - } - - @Override - public ItemStack removeSimilarItems( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - final int s = this.i.getSizeInventory(); - for( int x = 0; x < s; x++ ) - { - final ItemStack is = this.i.getStackInSlot( x ); - if( is != null && this.canRemoveStackFromSlot( x, is ) && ( filter == null || Platform.isSameItemFuzzy( is, filter, fuzzyMode ) ) ) - { - int newAmount = amount; - if( newAmount > is.stackSize ) - { - newAmount = is.stackSize; - } - if( destination != null && !destination.canInsert( is ) ) - { - newAmount = 0; - } - - ItemStack rv = null; - if( newAmount > 0 ) - { - rv = is.copy(); - rv.stackSize = newAmount; - - if( is.stackSize == rv.stackSize ) - { - this.i.setInventorySlotContents( x, null ); - this.i.markDirty(); - } - else - { - final ItemStack po = is.copy(); - po.stackSize -= rv.stackSize; - this.i.setInventorySlotContents( x, po ); - this.i.markDirty(); - } - } - - if( rv != null ) - { - // i.markDirty(); - return rv; - } - } - } - return null; - } - - @Override - public ItemStack simulateSimilarRemove( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - final int s = this.i.getSizeInventory(); - for( int x = 0; x < s; x++ ) - { - final ItemStack is = this.i.getStackInSlot( x ); - - if( is != null && this.canRemoveStackFromSlot( x, is ) && ( filter == null || Platform.isSameItemFuzzy( is, filter, fuzzyMode ) ) ) - { - int boundAmount = amount; - if( boundAmount > is.stackSize ) - { - boundAmount = is.stackSize; - } - if( destination != null && !destination.canInsert( is ) ) - { - boundAmount = 0; - } - - if( boundAmount > 0 ) - { - final ItemStack rv = is.copy(); - rv.stackSize = boundAmount; - return rv; - } - } - } - return null; - } - - @Override - public ItemStack addItems( final ItemStack toBeAdded ) - { - return this.addItems( toBeAdded, true, InsertionMode.DEFAULT ); - } - - @Override - public ItemStack addItems( ItemStack toBeAdded, InsertionMode insertionMode ) - { - return this.addItems( toBeAdded, true, insertionMode ); - } - - @Override - public ItemStack simulateAdd( final ItemStack toBeSimulated ) - { - return this.addItems( toBeSimulated, false, InsertionMode.DEFAULT ); - } - - @Override - public ItemStack simulateAdd( ItemStack toBeSimulated, InsertionMode insertionMode ) - { - return this.addItems( toBeSimulated, false, insertionMode ); - } - - @Override - public boolean containsItems() - { - final int s = this.i.getSizeInventory(); - for( int x = 0; x < s; x++ ) - { - if( this.i.getStackInSlot( x ) != null ) - { - return true; - } - } - return false; - } - - /** - * Adds an {@link ItemStack} to the adapted {@link IInventory}. - *

- * It respects the inventories stack limit, which can result in not all items added and some left ones are returned. - * The ItemStack next is required for inventories, which will fail on isItemValidForSlot() for stacksizes larger - * than the limit. - * - * @param itemsToAdd itemStack to add to the inventory - * @param modulate true to modulate, false for simulate - * @param insertionMode - * @return the left itemstack, which could not be added - */ - private ItemStack addItems( final ItemStack itemsToAdd, final boolean modulate, final InsertionMode insertionMode ) - { - if( itemsToAdd == null || itemsToAdd.stackSize == 0 ) - { - return null; - } - - final ItemStack left = itemsToAdd.copy(); - final int perOperationLimit = this.skipStackSizeCheck ? - this.i.getInventoryStackLimit() : Math.min( this.i.getInventoryStackLimit(), itemsToAdd.getMaxStackSize() ); - final int inventorySize = this.i.getSizeInventory(); - - // go over empty slots first if needed - if (insertionMode != InsertionMode.DEFAULT) - { - for( int slot = 0; slot < inventorySize; slot++ ) - { - final ItemStack next = left.copy(); - next.stackSize = Math.min( perOperationLimit, next.stackSize ); - - if( this.i.isItemValidForSlot( slot, next ) && this.i.getStackInSlot( slot ) == null ) - { - if( modulate ) - { - this.i.setInventorySlotContents( slot, next ); - this.i.markDirty(); - } - left.stackSize -= next.stackSize; - - if( left.stackSize <= 0 ) - { - return null; - } - } - } - } - - // exit early if only empty slots are desired - if (insertionMode == InsertionMode.ONLY_EMPTY) - { - return left; - } - - for( int slot = 0; slot < inventorySize; slot++ ) - { - final ItemStack next = left.copy(); - next.stackSize = Math.min( perOperationLimit, next.stackSize ); - - if( this.i.isItemValidForSlot( slot, next ) ) - { - final ItemStack is = this.i.getStackInSlot( slot ); - if( is == null ) - { - left.stackSize -= next.stackSize; - - if( modulate ) - { - this.i.setInventorySlotContents( slot, next ); - this.i.markDirty(); - } - - if( left.stackSize <= 0 ) - { - return null; - } - } - else if( Platform.isSameItemPrecise( is, left ) && is.stackSize < perOperationLimit ) - { - final int room = perOperationLimit - is.stackSize; - final int used = Math.min( left.stackSize, room ); - - if( modulate ) - { - is.stackSize += used; - this.i.setInventorySlotContents( slot, is ); - this.i.markDirty(); - } - - left.stackSize -= used; - if( left.stackSize <= 0 ) - { - return null; - } - } - } - } - - return left; - } - - private boolean canRemoveStackFromSlot( final int x, final ItemStack is ) - { - if( this.wrapperEnabled ) - { - return ( (IInventoryWrapper) this.i ).canRemoveItemFromSlot( x, is ); - } - return true; - } - - @Override - public Iterator iterator() - { - return new InvIterator(); - } - - private class InvIterator implements Iterator - { - - private final ItemSlot is = new ItemSlot(); - private int x = 0; - - @Override - public boolean hasNext() - { - return this.x < AdaptorIInventory.this.i.getSizeInventory(); - } - - @Override - public ItemSlot next() - { - final ItemStack iss = AdaptorIInventory.this.i.getStackInSlot( this.x ); - - this.is.setExtractable( AdaptorIInventory.this.canRemoveStackFromSlot( this.x, iss ) ); - this.is.setItemStack( iss ); - - this.is.setSlot( this.x ); - this.x++; - return this.is; - } - - @Override - public void remove() - { - // nothing! - } - } + + public AdaptorIInventory(final IInventory s) { + this.i = s; + skipStackSizeCheck = i.getClass() + .toString() + .equals("class wanion.avaritiaddons.block.chest.infinity.TileEntityInfinityChest"); + this.wrapperEnabled = s instanceof IInventoryWrapper; + } + + @Override + public ItemStack removeItems(int amount, ItemStack filter, final IInventoryDestination destination) { + final int s = this.i.getSizeInventory(); + ItemStack rv = null; + + for (int x = 0; x < s && amount > 0; x++) { + final ItemStack is = this.i.getStackInSlot(x); + if (is != null + && this.canRemoveStackFromSlot(x, is) + && (filter == null || Platform.isSameItemPrecise(is, filter))) { + int boundAmounts = amount; + if (boundAmounts > is.stackSize) { + boundAmounts = is.stackSize; + } + if (destination != null && !destination.canInsert(is)) { + boundAmounts = 0; + } + + if (boundAmounts > 0) { + if (rv == null) { + rv = is.copy(); + filter = rv; + rv.stackSize = boundAmounts; + amount -= boundAmounts; + } else { + rv.stackSize += boundAmounts; + amount -= boundAmounts; + } + + if (is.stackSize == boundAmounts) { + this.i.setInventorySlotContents(x, null); + this.i.markDirty(); + } else { + final ItemStack po = is.copy(); + po.stackSize -= boundAmounts; + this.i.setInventorySlotContents(x, po); + this.i.markDirty(); + } + } + } + } + + // if ( rv != null ) + // i.markDirty(); + + return rv; + } + + @Override + public ItemStack simulateRemove(int amount, final ItemStack filter, final IInventoryDestination destination) { + final int s = this.i.getSizeInventory(); + ItemStack rv = null; + + for (int x = 0; x < s && amount > 0; x++) { + final ItemStack is = this.i.getStackInSlot(x); + if (is != null + && this.canRemoveStackFromSlot(x, is) + && (filter == null || Platform.isSameItemPrecise(is, filter))) { + int boundAmount = amount; + if (boundAmount > is.stackSize) { + boundAmount = is.stackSize; + } + if (destination != null && !destination.canInsert(is)) { + boundAmount = 0; + } + + if (boundAmount > 0) { + if (rv == null) { + rv = is.copy(); + rv.stackSize = boundAmount; + amount -= boundAmount; + } else { + rv.stackSize += boundAmount; + amount -= boundAmount; + } + } + } + } + + return rv; + } + + @Override + public ItemStack removeSimilarItems( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination) { + final int s = this.i.getSizeInventory(); + for (int x = 0; x < s; x++) { + final ItemStack is = this.i.getStackInSlot(x); + if (is != null + && this.canRemoveStackFromSlot(x, is) + && (filter == null || Platform.isSameItemFuzzy(is, filter, fuzzyMode))) { + int newAmount = amount; + if (newAmount > is.stackSize) { + newAmount = is.stackSize; + } + if (destination != null && !destination.canInsert(is)) { + newAmount = 0; + } + + ItemStack rv = null; + if (newAmount > 0) { + rv = is.copy(); + rv.stackSize = newAmount; + + if (is.stackSize == rv.stackSize) { + this.i.setInventorySlotContents(x, null); + this.i.markDirty(); + } else { + final ItemStack po = is.copy(); + po.stackSize -= rv.stackSize; + this.i.setInventorySlotContents(x, po); + this.i.markDirty(); + } + } + + if (rv != null) { + // i.markDirty(); + return rv; + } + } + } + return null; + } + + @Override + public ItemStack simulateSimilarRemove( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination) { + final int s = this.i.getSizeInventory(); + for (int x = 0; x < s; x++) { + final ItemStack is = this.i.getStackInSlot(x); + + if (is != null + && this.canRemoveStackFromSlot(x, is) + && (filter == null || Platform.isSameItemFuzzy(is, filter, fuzzyMode))) { + int boundAmount = amount; + if (boundAmount > is.stackSize) { + boundAmount = is.stackSize; + } + if (destination != null && !destination.canInsert(is)) { + boundAmount = 0; + } + + if (boundAmount > 0) { + final ItemStack rv = is.copy(); + rv.stackSize = boundAmount; + return rv; + } + } + } + return null; + } + + @Override + public ItemStack addItems(final ItemStack toBeAdded) { + return this.addItems(toBeAdded, true, InsertionMode.DEFAULT); + } + + @Override + public ItemStack addItems(ItemStack toBeAdded, InsertionMode insertionMode) { + return this.addItems(toBeAdded, true, insertionMode); + } + + @Override + public ItemStack simulateAdd(final ItemStack toBeSimulated) { + return this.addItems(toBeSimulated, false, InsertionMode.DEFAULT); + } + + @Override + public ItemStack simulateAdd(ItemStack toBeSimulated, InsertionMode insertionMode) { + return this.addItems(toBeSimulated, false, insertionMode); + } + + @Override + public boolean containsItems() { + final int s = this.i.getSizeInventory(); + for (int x = 0; x < s; x++) { + if (this.i.getStackInSlot(x) != null) { + return true; + } + } + return false; + } + + /** + * Adds an {@link ItemStack} to the adapted {@link IInventory}. + *

+ * It respects the inventories stack limit, which can result in not all items added and some left ones are returned. + * The ItemStack next is required for inventories, which will fail on isItemValidForSlot() for stacksizes larger + * than the limit. + * + * @param itemsToAdd itemStack to add to the inventory + * @param modulate true to modulate, false for simulate + * @param insertionMode + * @return the left itemstack, which could not be added + */ + private ItemStack addItems(final ItemStack itemsToAdd, final boolean modulate, final InsertionMode insertionMode) { + if (itemsToAdd == null || itemsToAdd.stackSize == 0) { + return null; + } + + final ItemStack left = itemsToAdd.copy(); + final int perOperationLimit = this.skipStackSizeCheck + ? this.i.getInventoryStackLimit() + : Math.min(this.i.getInventoryStackLimit(), itemsToAdd.getMaxStackSize()); + final int inventorySize = this.i.getSizeInventory(); + + // go over empty slots first if needed + if (insertionMode != InsertionMode.DEFAULT) { + for (int slot = 0; slot < inventorySize; slot++) { + final ItemStack next = left.copy(); + next.stackSize = Math.min(perOperationLimit, next.stackSize); + + if (this.i.isItemValidForSlot(slot, next) && this.i.getStackInSlot(slot) == null) { + if (modulate) { + this.i.setInventorySlotContents(slot, next); + this.i.markDirty(); + } + left.stackSize -= next.stackSize; + + if (left.stackSize <= 0) { + return null; + } + } + } + } + + // exit early if only empty slots are desired + if (insertionMode == InsertionMode.ONLY_EMPTY) { + return left; + } + + for (int slot = 0; slot < inventorySize; slot++) { + final ItemStack next = left.copy(); + next.stackSize = Math.min(perOperationLimit, next.stackSize); + + if (this.i.isItemValidForSlot(slot, next)) { + final ItemStack is = this.i.getStackInSlot(slot); + if (is == null) { + left.stackSize -= next.stackSize; + + if (modulate) { + this.i.setInventorySlotContents(slot, next); + this.i.markDirty(); + } + + if (left.stackSize <= 0) { + return null; + } + } else if (Platform.isSameItemPrecise(is, left) && is.stackSize < perOperationLimit) { + final int room = perOperationLimit - is.stackSize; + final int used = Math.min(left.stackSize, room); + + if (modulate) { + is.stackSize += used; + this.i.setInventorySlotContents(slot, is); + this.i.markDirty(); + } + + left.stackSize -= used; + if (left.stackSize <= 0) { + return null; + } + } + } + } + + return left; + } + + private boolean canRemoveStackFromSlot(final int x, final ItemStack is) { + if (this.wrapperEnabled) { + return ((IInventoryWrapper) this.i).canRemoveItemFromSlot(x, is); + } + return true; + } + + @Override + public Iterator iterator() { + return new InvIterator(); + } + + private class InvIterator implements Iterator { + + private final ItemSlot is = new ItemSlot(); + private int x = 0; + + @Override + public boolean hasNext() { + return this.x < AdaptorIInventory.this.i.getSizeInventory(); + } + + @Override + public ItemSlot next() { + final ItemStack iss = AdaptorIInventory.this.i.getStackInSlot(this.x); + + this.is.setExtractable(AdaptorIInventory.this.canRemoveStackFromSlot(this.x, iss)); + this.is.setItemStack(iss); + + this.is.setSlot(this.x); + this.x++; + return this.is; + } + + @Override + public void remove() { + // nothing! + } + } } diff --git a/src/main/java/appeng/util/inv/AdaptorList.java b/src/main/java/appeng/util/inv/AdaptorList.java index 7511e116a21..df2263946bb 100644 --- a/src/main/java/appeng/util/inv/AdaptorList.java +++ b/src/main/java/appeng/util/inv/AdaptorList.java @@ -18,204 +18,165 @@ package appeng.util.inv; - import appeng.api.config.FuzzyMode; import appeng.util.InventoryAdaptor; import appeng.util.Platform; import appeng.util.iterators.StackToSlotIterator; -import net.minecraft.item.ItemStack; - import java.util.Iterator; import java.util.List; +import net.minecraft.item.ItemStack; - -public class AdaptorList extends InventoryAdaptor -{ - - private final List i; - - public AdaptorList( final List s ) - { - this.i = s; - } - - @Override - public ItemStack removeItems( int amount, final ItemStack filter, final IInventoryDestination destination ) - { - final int s = this.i.size(); - for( int x = 0; x < s; x++ ) - { - final ItemStack is = this.i.get( x ); - if( is != null && ( filter == null || Platform.isSameItemPrecise( is, filter ) ) ) - { - if( amount > is.stackSize ) - { - amount = is.stackSize; - } - if( destination != null && !destination.canInsert( is ) ) - { - amount = 0; - } - - if( amount > 0 ) - { - final ItemStack rv = is.copy(); - rv.stackSize = amount; - is.stackSize -= amount; - - // remove it.. - if( is.stackSize <= 0 ) - { - this.i.remove( x ); - } - - return rv; - } - } - } - return null; - } - - @Override - public ItemStack simulateRemove( int amount, final ItemStack filter, final IInventoryDestination destination ) - { - for( final ItemStack is : this.i ) - { - if( is != null && ( filter == null || Platform.isSameItemPrecise( is, filter ) ) ) - { - if( amount > is.stackSize ) - { - amount = is.stackSize; - } - if( destination != null && !destination.canInsert( is ) ) - { - amount = 0; - } - - if( amount > 0 ) - { - final ItemStack rv = is.copy(); - rv.stackSize = amount; - return rv; - } - } - } - return null; - } - - @Override - public ItemStack removeSimilarItems( int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - final int s = this.i.size(); - for( int x = 0; x < s; x++ ) - { - final ItemStack is = this.i.get( x ); - if( is != null && ( filter == null || Platform.isSameItemFuzzy( is, filter, fuzzyMode ) ) ) - { - if( amount > is.stackSize ) - { - amount = is.stackSize; - } - if( destination != null && !destination.canInsert( is ) ) - { - amount = 0; - } - - if( amount > 0 ) - { - final ItemStack rv = is.copy(); - rv.stackSize = amount; - is.stackSize -= amount; - - // remove it.. - if( is.stackSize <= 0 ) - { - this.i.remove( x ); - } - - return rv; - } - } - } - return null; - } - - @Override - public ItemStack simulateSimilarRemove( int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - for( final ItemStack is : this.i ) - { - if( is != null && ( filter == null || Platform.isSameItemFuzzy( is, filter, fuzzyMode ) ) ) - { - if( amount > is.stackSize ) - { - amount = is.stackSize; - } - if( destination != null && !destination.canInsert( is ) ) - { - amount = 0; - } - - if( amount > 0 ) - { - final ItemStack rv = is.copy(); - rv.stackSize = amount; - return rv; - } - } - } - return null; - } - - @Override - public ItemStack addItems( final ItemStack toBeAdded ) - { - if( toBeAdded == null ) - { - return null; - } - if( toBeAdded.stackSize == 0 ) - { - return null; - } - - final ItemStack left = toBeAdded.copy(); - - for( final ItemStack is : this.i ) - { - if( Platform.isSameItem( is, left ) ) - { - is.stackSize += left.stackSize; - return null; - } - } - - this.i.add( left ); - return null; - } - - @Override - public ItemStack simulateAdd( final ItemStack toBeSimulated ) - { - return null; - } - - @Override - public boolean containsItems() - { - for( final ItemStack is : this.i ) - { - if( is != null ) - { - return true; - } - } - return false; - } - - @Override - public Iterator iterator() - { - return new StackToSlotIterator( this.i.iterator() ); - } +public class AdaptorList extends InventoryAdaptor { + + private final List i; + + public AdaptorList(final List s) { + this.i = s; + } + + @Override + public ItemStack removeItems(int amount, final ItemStack filter, final IInventoryDestination destination) { + final int s = this.i.size(); + for (int x = 0; x < s; x++) { + final ItemStack is = this.i.get(x); + if (is != null && (filter == null || Platform.isSameItemPrecise(is, filter))) { + if (amount > is.stackSize) { + amount = is.stackSize; + } + if (destination != null && !destination.canInsert(is)) { + amount = 0; + } + + if (amount > 0) { + final ItemStack rv = is.copy(); + rv.stackSize = amount; + is.stackSize -= amount; + + // remove it.. + if (is.stackSize <= 0) { + this.i.remove(x); + } + + return rv; + } + } + } + return null; + } + + @Override + public ItemStack simulateRemove(int amount, final ItemStack filter, final IInventoryDestination destination) { + for (final ItemStack is : this.i) { + if (is != null && (filter == null || Platform.isSameItemPrecise(is, filter))) { + if (amount > is.stackSize) { + amount = is.stackSize; + } + if (destination != null && !destination.canInsert(is)) { + amount = 0; + } + + if (amount > 0) { + final ItemStack rv = is.copy(); + rv.stackSize = amount; + return rv; + } + } + } + return null; + } + + @Override + public ItemStack removeSimilarItems( + int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination) { + final int s = this.i.size(); + for (int x = 0; x < s; x++) { + final ItemStack is = this.i.get(x); + if (is != null && (filter == null || Platform.isSameItemFuzzy(is, filter, fuzzyMode))) { + if (amount > is.stackSize) { + amount = is.stackSize; + } + if (destination != null && !destination.canInsert(is)) { + amount = 0; + } + + if (amount > 0) { + final ItemStack rv = is.copy(); + rv.stackSize = amount; + is.stackSize -= amount; + + // remove it.. + if (is.stackSize <= 0) { + this.i.remove(x); + } + + return rv; + } + } + } + return null; + } + + @Override + public ItemStack simulateSimilarRemove( + int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination) { + for (final ItemStack is : this.i) { + if (is != null && (filter == null || Platform.isSameItemFuzzy(is, filter, fuzzyMode))) { + if (amount > is.stackSize) { + amount = is.stackSize; + } + if (destination != null && !destination.canInsert(is)) { + amount = 0; + } + + if (amount > 0) { + final ItemStack rv = is.copy(); + rv.stackSize = amount; + return rv; + } + } + } + return null; + } + + @Override + public ItemStack addItems(final ItemStack toBeAdded) { + if (toBeAdded == null) { + return null; + } + if (toBeAdded.stackSize == 0) { + return null; + } + + final ItemStack left = toBeAdded.copy(); + + for (final ItemStack is : this.i) { + if (Platform.isSameItem(is, left)) { + is.stackSize += left.stackSize; + return null; + } + } + + this.i.add(left); + return null; + } + + @Override + public ItemStack simulateAdd(final ItemStack toBeSimulated) { + return null; + } + + @Override + public boolean containsItems() { + for (final ItemStack is : this.i) { + if (is != null) { + return true; + } + } + return false; + } + + @Override + public Iterator iterator() { + return new StackToSlotIterator(this.i.iterator()); + } } diff --git a/src/main/java/appeng/util/inv/AdaptorPlayerHand.java b/src/main/java/appeng/util/inv/AdaptorPlayerHand.java index fee2366ca56..44ed881f710 100644 --- a/src/main/java/appeng/util/inv/AdaptorPlayerHand.java +++ b/src/main/java/appeng/util/inv/AdaptorPlayerHand.java @@ -18,219 +18,189 @@ package appeng.util.inv; - import appeng.api.config.FuzzyMode; import appeng.util.InventoryAdaptor; import appeng.util.Platform; import appeng.util.iterators.NullIterator; +import java.util.Iterator; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; -import java.util.Iterator; - - /* * Lets you do simply tests with the players cursor, without messing with the specifics. */ -public class AdaptorPlayerHand extends InventoryAdaptor -{ - - private final EntityPlayer player; - - public AdaptorPlayerHand( final EntityPlayer player ) - { - this.player = player; - } - - @Override - public ItemStack removeItems( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - final ItemStack hand = this.player.inventory.getItemStack(); - if( hand == null ) - { - return null; - } - - if( filter == null || Platform.isSameItemPrecise( filter, hand ) ) - { - final ItemStack result = hand.copy(); - result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; - hand.stackSize -= amount; - if( hand.stackSize <= 0 ) - { - this.player.inventory.setItemStack( null ); - } - return result; - } - - return null; - } - - @Override - public ItemStack simulateRemove( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - - final ItemStack hand = this.player.inventory.getItemStack(); - if( hand == null ) - { - return null; - } - - if( filter == null || Platform.isSameItemPrecise( filter, hand ) ) - { - final ItemStack result = hand.copy(); - result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; - return result; - } - - return null; - } - - @Override - public ItemStack removeSimilarItems( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - final ItemStack hand = this.player.inventory.getItemStack(); - if( hand == null ) - { - return null; - } - - if( filter == null || Platform.isSameItemFuzzy( filter, hand, fuzzyMode ) ) - { - final ItemStack result = hand.copy(); - result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; - hand.stackSize -= amount; - if( hand.stackSize <= 0 ) - { - this.player.inventory.setItemStack( null ); - } - return result; - } - - return null; - } - - @Override - public ItemStack simulateSimilarRemove( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - - final ItemStack hand = this.player.inventory.getItemStack(); - if( hand == null ) - { - return null; - } - - if( filter == null || Platform.isSameItemFuzzy( filter, hand, fuzzyMode ) ) - { - final ItemStack result = hand.copy(); - result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; - return result; - } - - return null; - } - - @Override - public ItemStack addItems( final ItemStack toBeAdded ) - { - - if( toBeAdded == null ) - { - return null; - } - if( toBeAdded.stackSize == 0 ) - { - return null; - } - if( this.player == null ) - { - return toBeAdded; - } - if( this.player.inventory == null ) - { - return toBeAdded; - } - - final ItemStack hand = this.player.inventory.getItemStack(); - - if( hand != null && !Platform.isSameItemPrecise( toBeAdded, hand ) ) - { - return toBeAdded; - } - - int original = 0; - ItemStack newHand = null; - if( hand == null ) - { - newHand = toBeAdded.copy(); - } - else - { - newHand = hand; - original = hand.stackSize; - newHand.stackSize += toBeAdded.stackSize; - } - - if( newHand.stackSize > newHand.getMaxStackSize() ) - { - newHand.stackSize = newHand.getMaxStackSize(); - final ItemStack B = toBeAdded.copy(); - B.stackSize -= newHand.stackSize - original; - this.player.inventory.setItemStack( newHand ); - return B; - } - - this.player.inventory.setItemStack( newHand ); - return null; - } - - @Override - public ItemStack simulateAdd( final ItemStack toBeSimulated ) - { - final ItemStack hand = this.player.inventory.getItemStack(); - if( toBeSimulated == null ) - { - return null; - } - - if( hand != null && !Platform.isSameItem( toBeSimulated, hand ) ) - { - return toBeSimulated; - } - - int original = 0; - ItemStack newHand = null; - if( hand == null ) - { - newHand = toBeSimulated.copy(); - } - else - { - newHand = hand.copy(); - original = hand.stackSize; - newHand.stackSize += toBeSimulated.stackSize; - } - - if( newHand.stackSize > newHand.getMaxStackSize() ) - { - newHand.stackSize = newHand.getMaxStackSize(); - final ItemStack B = toBeSimulated.copy(); - B.stackSize -= newHand.stackSize - original; - return B; - } - - return null; - } - - @Override - public boolean containsItems() - { - return this.player.inventory.getItemStack() != null; - } - - @Override - public Iterator iterator() - { - return new NullIterator(); - } +public class AdaptorPlayerHand extends InventoryAdaptor { + + private final EntityPlayer player; + + public AdaptorPlayerHand(final EntityPlayer player) { + this.player = player; + } + + @Override + public ItemStack removeItems(final int amount, final ItemStack filter, final IInventoryDestination destination) { + final ItemStack hand = this.player.inventory.getItemStack(); + if (hand == null) { + return null; + } + + if (filter == null || Platform.isSameItemPrecise(filter, hand)) { + final ItemStack result = hand.copy(); + result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; + hand.stackSize -= amount; + if (hand.stackSize <= 0) { + this.player.inventory.setItemStack(null); + } + return result; + } + + return null; + } + + @Override + public ItemStack simulateRemove(final int amount, final ItemStack filter, final IInventoryDestination destination) { + + final ItemStack hand = this.player.inventory.getItemStack(); + if (hand == null) { + return null; + } + + if (filter == null || Platform.isSameItemPrecise(filter, hand)) { + final ItemStack result = hand.copy(); + result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; + return result; + } + + return null; + } + + @Override + public ItemStack removeSimilarItems( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination) { + final ItemStack hand = this.player.inventory.getItemStack(); + if (hand == null) { + return null; + } + + if (filter == null || Platform.isSameItemFuzzy(filter, hand, fuzzyMode)) { + final ItemStack result = hand.copy(); + result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; + hand.stackSize -= amount; + if (hand.stackSize <= 0) { + this.player.inventory.setItemStack(null); + } + return result; + } + + return null; + } + + @Override + public ItemStack simulateSimilarRemove( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination) { + + final ItemStack hand = this.player.inventory.getItemStack(); + if (hand == null) { + return null; + } + + if (filter == null || Platform.isSameItemFuzzy(filter, hand, fuzzyMode)) { + final ItemStack result = hand.copy(); + result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; + return result; + } + + return null; + } + + @Override + public ItemStack addItems(final ItemStack toBeAdded) { + + if (toBeAdded == null) { + return null; + } + if (toBeAdded.stackSize == 0) { + return null; + } + if (this.player == null) { + return toBeAdded; + } + if (this.player.inventory == null) { + return toBeAdded; + } + + final ItemStack hand = this.player.inventory.getItemStack(); + + if (hand != null && !Platform.isSameItemPrecise(toBeAdded, hand)) { + return toBeAdded; + } + + int original = 0; + ItemStack newHand = null; + if (hand == null) { + newHand = toBeAdded.copy(); + } else { + newHand = hand; + original = hand.stackSize; + newHand.stackSize += toBeAdded.stackSize; + } + + if (newHand.stackSize > newHand.getMaxStackSize()) { + newHand.stackSize = newHand.getMaxStackSize(); + final ItemStack B = toBeAdded.copy(); + B.stackSize -= newHand.stackSize - original; + this.player.inventory.setItemStack(newHand); + return B; + } + + this.player.inventory.setItemStack(newHand); + return null; + } + + @Override + public ItemStack simulateAdd(final ItemStack toBeSimulated) { + final ItemStack hand = this.player.inventory.getItemStack(); + if (toBeSimulated == null) { + return null; + } + + if (hand != null && !Platform.isSameItem(toBeSimulated, hand)) { + return toBeSimulated; + } + + int original = 0; + ItemStack newHand = null; + if (hand == null) { + newHand = toBeSimulated.copy(); + } else { + newHand = hand.copy(); + original = hand.stackSize; + newHand.stackSize += toBeSimulated.stackSize; + } + + if (newHand.stackSize > newHand.getMaxStackSize()) { + newHand.stackSize = newHand.getMaxStackSize(); + final ItemStack B = toBeSimulated.copy(); + B.stackSize -= newHand.stackSize - original; + return B; + } + + return null; + } + + @Override + public boolean containsItems() { + return this.player.inventory.getItemStack() != null; + } + + @Override + public Iterator iterator() { + return new NullIterator(); + } } diff --git a/src/main/java/appeng/util/inv/AdaptorPlayerInventory.java b/src/main/java/appeng/util/inv/AdaptorPlayerInventory.java index 57144fd537d..69606931f45 100644 --- a/src/main/java/appeng/util/inv/AdaptorPlayerInventory.java +++ b/src/main/java/appeng/util/inv/AdaptorPlayerInventory.java @@ -18,107 +18,89 @@ package appeng.util.inv; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - -public class AdaptorPlayerInventory implements IInventory -{ - - private final IInventory src; - private final int min = 0; - private final int size = 36; - - public AdaptorPlayerInventory( final IInventory playerInv, final boolean swap ) - { - - if( swap ) - { - this.src = new WrapperChainedInventory( new WrapperInventoryRange( playerInv, 9, this.size - 9, false ), new WrapperInventoryRange( playerInv, 0, 9, false ) ); - } - else - { - this.src = playerInv; - } - } - - @Override - public int getSizeInventory() - { - return this.size; - } - - @Override - public ItemStack getStackInSlot( final int var1 ) - { - return this.src.getStackInSlot( var1 + this.min ); - } - - @Override - public ItemStack decrStackSize( final int var1, final int var2 ) - { - return this.src.decrStackSize( this.min + var1, var2 ); - } - - @Override - public ItemStack getStackInSlotOnClosing( final int var1 ) - { - return this.src.getStackInSlotOnClosing( this.min + var1 ); - } - - @Override - public void setInventorySlotContents( final int var1, final ItemStack var2 ) - { - this.src.setInventorySlotContents( var1 + this.min, var2 ); - } - - @Override - public String getInventoryName() - { - return this.src.getInventoryName(); - } - - @Override - public boolean hasCustomInventoryName() - { - return false; - } - - @Override - public int getInventoryStackLimit() - { - return this.src.getInventoryStackLimit(); - } - - @Override - public void markDirty() - { - this.src.markDirty(); - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer var1 ) - { - return this.src.isUseableByPlayer( var1 ); - } - - @Override - public void openInventory() - { - this.src.openInventory(); - } - - @Override - public void closeInventory() - { - this.src.closeInventory(); - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return this.src.isItemValidForSlot( i, itemstack ); - } +public class AdaptorPlayerInventory implements IInventory { + + private final IInventory src; + private final int min = 0; + private final int size = 36; + + public AdaptorPlayerInventory(final IInventory playerInv, final boolean swap) { + + if (swap) { + this.src = new WrapperChainedInventory( + new WrapperInventoryRange(playerInv, 9, this.size - 9, false), + new WrapperInventoryRange(playerInv, 0, 9, false)); + } else { + this.src = playerInv; + } + } + + @Override + public int getSizeInventory() { + return this.size; + } + + @Override + public ItemStack getStackInSlot(final int var1) { + return this.src.getStackInSlot(var1 + this.min); + } + + @Override + public ItemStack decrStackSize(final int var1, final int var2) { + return this.src.decrStackSize(this.min + var1, var2); + } + + @Override + public ItemStack getStackInSlotOnClosing(final int var1) { + return this.src.getStackInSlotOnClosing(this.min + var1); + } + + @Override + public void setInventorySlotContents(final int var1, final ItemStack var2) { + this.src.setInventorySlotContents(var1 + this.min, var2); + } + + @Override + public String getInventoryName() { + return this.src.getInventoryName(); + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public int getInventoryStackLimit() { + return this.src.getInventoryStackLimit(); + } + + @Override + public void markDirty() { + this.src.markDirty(); + } + + @Override + public boolean isUseableByPlayer(final EntityPlayer var1) { + return this.src.isUseableByPlayer(var1); + } + + @Override + public void openInventory() { + this.src.openInventory(); + } + + @Override + public void closeInventory() { + this.src.closeInventory(); + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return this.src.isItemValidForSlot(i, itemstack); + } } diff --git a/src/main/java/appeng/util/inv/IInventoryDestination.java b/src/main/java/appeng/util/inv/IInventoryDestination.java index 61a3cf8b90f..9479d00745b 100644 --- a/src/main/java/appeng/util/inv/IInventoryDestination.java +++ b/src/main/java/appeng/util/inv/IInventoryDestination.java @@ -18,12 +18,9 @@ package appeng.util.inv; - import net.minecraft.item.ItemStack; +public interface IInventoryDestination { -public interface IInventoryDestination -{ - - boolean canInsert( ItemStack stack ); + boolean canInsert(ItemStack stack); } diff --git a/src/main/java/appeng/util/inv/IInventoryWrapper.java b/src/main/java/appeng/util/inv/IInventoryWrapper.java index eedab2a70f0..27db4533286 100644 --- a/src/main/java/appeng/util/inv/IInventoryWrapper.java +++ b/src/main/java/appeng/util/inv/IInventoryWrapper.java @@ -18,12 +18,9 @@ package appeng.util.inv; - import net.minecraft.item.ItemStack; +public interface IInventoryWrapper { -public interface IInventoryWrapper -{ - - boolean canRemoveItemFromSlot( int x, ItemStack is ); + boolean canRemoveItemFromSlot(int x, ItemStack is); } diff --git a/src/main/java/appeng/util/inv/IMEAdaptor.java b/src/main/java/appeng/util/inv/IMEAdaptor.java index b58216a4d78..ab525870406 100644 --- a/src/main/java/appeng/util/inv/IMEAdaptor.java +++ b/src/main/java/appeng/util/inv/IMEAdaptor.java @@ -18,7 +18,6 @@ package appeng.util.inv; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.FuzzyMode; @@ -29,169 +28,150 @@ import appeng.util.InventoryAdaptor; import appeng.util.item.AEItemStack; import com.google.common.collect.ImmutableList; -import net.minecraft.item.ItemStack; - import java.util.Iterator; +import net.minecraft.item.ItemStack; - -public class IMEAdaptor extends InventoryAdaptor -{ - - private final IMEInventory target; - private final BaseActionSource src; - private int maxSlots = 0; - - public IMEAdaptor( final IMEInventory input, final BaseActionSource src ) - { - this.target = input; - this.src = src; - } - - @Override - public Iterator iterator() - { - return new IMEAdaptorIterator( this, this.getList() ); - } - - private IItemList getList() - { - return this.target.getAvailableItems( AEApi.instance().storage().createItemList() ); - } - - @Override - public ItemStack removeItems( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - return this.doRemoveItems( amount, filter, destination, Actionable.MODULATE ); - } - - private ItemStack doRemoveItems( final int amount, final ItemStack filter, final IInventoryDestination destination, final Actionable type ) - { - IAEItemStack req = null; - - if( filter == null ) - { - final IItemList list = this.getList(); - if( !list.isEmpty() ) - { - req = list.getFirstItem(); - } - } - else - { - req = AEItemStack.create( filter ); - } - - IAEItemStack out = null; - - if( req != null ) - { - req.setStackSize( amount ); - out = this.target.extractItems( req, type, this.src ); - } - - if( out != null ) - { - return out.getItemStack(); - } - - return null; - } - - @Override - public ItemStack simulateRemove( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - return this.doRemoveItems( amount, filter, destination, Actionable.SIMULATE ); - } - - @Override - public ItemStack removeSimilarItems( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - if( filter == null ) - { - return this.doRemoveItems( amount, null, destination, Actionable.MODULATE ); - } - return this.doRemoveItemsFuzzy( amount, filter, destination, Actionable.MODULATE, fuzzyMode ); - } - - private ItemStack doRemoveItemsFuzzy( final int amount, final ItemStack filter, final IInventoryDestination destination, final Actionable type, final FuzzyMode fuzzyMode ) - { - final IAEItemStack reqFilter = AEItemStack.create( filter ); - if( reqFilter == null ) - { - return null; - } - - IAEItemStack out = null; - - for( final IAEItemStack req : ImmutableList.copyOf( this.getList().findFuzzy( reqFilter, fuzzyMode ) ) ) - { - if( req != null ) - { - req.setStackSize( amount ); - out = this.target.extractItems( req, type, this.src ); - if( out != null ) - { - return out.getItemStack(); - } - } - } - - return null; - } - - @Override - public ItemStack simulateSimilarRemove( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - if( filter == null ) - { - return this.doRemoveItems( amount, null, destination, Actionable.SIMULATE ); - } - return this.doRemoveItemsFuzzy( amount, filter, destination, Actionable.SIMULATE, fuzzyMode ); - } - - @Override - public ItemStack addItems( final ItemStack toBeAdded ) - { - final IAEItemStack in = AEItemStack.create( toBeAdded ); - if( in != null ) - { - final IAEItemStack out = this.target.injectItems( in, Actionable.MODULATE, this.src ); - if( out != null ) - { - return out.getItemStack(); - } - } - return null; - } - - @Override - public ItemStack simulateAdd( final ItemStack toBeSimulated ) - { - final IAEItemStack in = AEItemStack.create( toBeSimulated ); - if( in != null ) - { - final IAEItemStack out = this.target.injectItems( in, Actionable.SIMULATE, this.src ); - if( out != null ) - { - return out.getItemStack(); - } - } - return null; - } - - @Override - public boolean containsItems() - { - return !this.getList().isEmpty(); - } - - int getMaxSlots() - { - return this.maxSlots; - } - - void setMaxSlots( final int maxSlots ) - { - this.maxSlots = maxSlots; - } +public class IMEAdaptor extends InventoryAdaptor { + + private final IMEInventory target; + private final BaseActionSource src; + private int maxSlots = 0; + + public IMEAdaptor(final IMEInventory input, final BaseActionSource src) { + this.target = input; + this.src = src; + } + + @Override + public Iterator iterator() { + return new IMEAdaptorIterator(this, this.getList()); + } + + private IItemList getList() { + return this.target.getAvailableItems(AEApi.instance().storage().createItemList()); + } + + @Override + public ItemStack removeItems(final int amount, final ItemStack filter, final IInventoryDestination destination) { + return this.doRemoveItems(amount, filter, destination, Actionable.MODULATE); + } + + private ItemStack doRemoveItems( + final int amount, final ItemStack filter, final IInventoryDestination destination, final Actionable type) { + IAEItemStack req = null; + + if (filter == null) { + final IItemList list = this.getList(); + if (!list.isEmpty()) { + req = list.getFirstItem(); + } + } else { + req = AEItemStack.create(filter); + } + + IAEItemStack out = null; + + if (req != null) { + req.setStackSize(amount); + out = this.target.extractItems(req, type, this.src); + } + + if (out != null) { + return out.getItemStack(); + } + + return null; + } + + @Override + public ItemStack simulateRemove(final int amount, final ItemStack filter, final IInventoryDestination destination) { + return this.doRemoveItems(amount, filter, destination, Actionable.SIMULATE); + } + + @Override + public ItemStack removeSimilarItems( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination) { + if (filter == null) { + return this.doRemoveItems(amount, null, destination, Actionable.MODULATE); + } + return this.doRemoveItemsFuzzy(amount, filter, destination, Actionable.MODULATE, fuzzyMode); + } + + private ItemStack doRemoveItemsFuzzy( + final int amount, + final ItemStack filter, + final IInventoryDestination destination, + final Actionable type, + final FuzzyMode fuzzyMode) { + final IAEItemStack reqFilter = AEItemStack.create(filter); + if (reqFilter == null) { + return null; + } + + IAEItemStack out = null; + + for (final IAEItemStack req : ImmutableList.copyOf(this.getList().findFuzzy(reqFilter, fuzzyMode))) { + if (req != null) { + req.setStackSize(amount); + out = this.target.extractItems(req, type, this.src); + if (out != null) { + return out.getItemStack(); + } + } + } + + return null; + } + + @Override + public ItemStack simulateSimilarRemove( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination) { + if (filter == null) { + return this.doRemoveItems(amount, null, destination, Actionable.SIMULATE); + } + return this.doRemoveItemsFuzzy(amount, filter, destination, Actionable.SIMULATE, fuzzyMode); + } + + @Override + public ItemStack addItems(final ItemStack toBeAdded) { + final IAEItemStack in = AEItemStack.create(toBeAdded); + if (in != null) { + final IAEItemStack out = this.target.injectItems(in, Actionable.MODULATE, this.src); + if (out != null) { + return out.getItemStack(); + } + } + return null; + } + + @Override + public ItemStack simulateAdd(final ItemStack toBeSimulated) { + final IAEItemStack in = AEItemStack.create(toBeSimulated); + if (in != null) { + final IAEItemStack out = this.target.injectItems(in, Actionable.SIMULATE, this.src); + if (out != null) { + return out.getItemStack(); + } + } + return null; + } + + @Override + public boolean containsItems() { + return !this.getList().isEmpty(); + } + + int getMaxSlots() { + return this.maxSlots; + } + + void setMaxSlots(final int maxSlots) { + this.maxSlots = maxSlots; + } } diff --git a/src/main/java/appeng/util/inv/IMEAdaptorIterator.java b/src/main/java/appeng/util/inv/IMEAdaptorIterator.java index 2e422002735..2606c45581e 100644 --- a/src/main/java/appeng/util/inv/IMEAdaptorIterator.java +++ b/src/main/java/appeng/util/inv/IMEAdaptorIterator.java @@ -18,63 +18,53 @@ package appeng.util.inv; - import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; - import java.util.Iterator; +public final class IMEAdaptorIterator implements Iterator { + private final Iterator stack; + private final ItemSlot slot = new ItemSlot(); + private final IMEAdaptor parent; + private final int containerSize; -public final class IMEAdaptorIterator implements Iterator -{ - private final Iterator stack; - private final ItemSlot slot = new ItemSlot(); - private final IMEAdaptor parent; - private final int containerSize; - - private int offset = 0; - private boolean hasNext; + private int offset = 0; + private boolean hasNext; - public IMEAdaptorIterator( final IMEAdaptor parent, final IItemList availableItems ) - { - this.stack = availableItems.iterator(); - this.containerSize = parent.getMaxSlots(); - this.parent = parent; - } + public IMEAdaptorIterator(final IMEAdaptor parent, final IItemList availableItems) { + this.stack = availableItems.iterator(); + this.containerSize = parent.getMaxSlots(); + this.parent = parent; + } - @Override - public boolean hasNext() - { - this.hasNext = this.stack.hasNext(); - return this.offset < this.containerSize || this.hasNext; - } + @Override + public boolean hasNext() { + this.hasNext = this.stack.hasNext(); + return this.offset < this.containerSize || this.hasNext; + } - @Override - public ItemSlot next() - { - this.slot.setSlot( this.offset ); - this.offset++; - this.slot.setExtractable( true ); + @Override + public ItemSlot next() { + this.slot.setSlot(this.offset); + this.offset++; + this.slot.setExtractable(true); - if( this.parent.getMaxSlots() < this.offset ) - { - this.parent.setMaxSlots( this.offset ); - } + if (this.parent.getMaxSlots() < this.offset) { + this.parent.setMaxSlots(this.offset); + } - if( this.hasNext ) - { - final IAEItemStack item = this.stack.next(); - this.slot.setAEItemStack( item ); - return this.slot; - } + if (this.hasNext) { + final IAEItemStack item = this.stack.next(); + this.slot.setAEItemStack(item); + return this.slot; + } - this.slot.setItemStack( null ); - return this.slot; - } + this.slot.setItemStack(null); + return this.slot; + } - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/inv/IMEInventoryDestination.java b/src/main/java/appeng/util/inv/IMEInventoryDestination.java index 112cc49112d..5f93bf57fd0 100644 --- a/src/main/java/appeng/util/inv/IMEInventoryDestination.java +++ b/src/main/java/appeng/util/inv/IMEInventoryDestination.java @@ -18,39 +18,32 @@ package appeng.util.inv; - import appeng.api.config.Actionable; import appeng.api.storage.IMEInventory; import appeng.api.storage.data.IAEItemStack; import appeng.util.item.AEItemStack; import net.minecraft.item.ItemStack; +public class IMEInventoryDestination implements IInventoryDestination { -public class IMEInventoryDestination implements IInventoryDestination -{ - - private final IMEInventory me; + private final IMEInventory me; - public IMEInventoryDestination( final IMEInventory o ) - { - this.me = o; - } + public IMEInventoryDestination(final IMEInventory o) { + this.me = o; + } - @Override - public boolean canInsert( final ItemStack stack ) - { + @Override + public boolean canInsert(final ItemStack stack) { - if( stack == null ) - { - return false; - } + if (stack == null) { + return false; + } - final IAEItemStack failed = this.me.injectItems( AEItemStack.create( stack ), Actionable.SIMULATE, null ); + final IAEItemStack failed = this.me.injectItems(AEItemStack.create(stack), Actionable.SIMULATE, null); - if( failed == null ) - { - return true; - } - return failed.getStackSize() != stack.stackSize; - } + if (failed == null) { + return true; + } + return failed.getStackSize() != stack.stackSize; + } } diff --git a/src/main/java/appeng/util/inv/ItemListIgnoreCrafting.java b/src/main/java/appeng/util/inv/ItemListIgnoreCrafting.java index 5de6f6eeabd..332103dd6a2 100644 --- a/src/main/java/appeng/util/inv/ItemListIgnoreCrafting.java +++ b/src/main/java/appeng/util/inv/ItemListIgnoreCrafting.java @@ -18,94 +18,77 @@ package appeng.util.inv; - import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; - import java.util.Collection; import java.util.Iterator; - -public class ItemListIgnoreCrafting implements IItemList -{ - - private final IItemList target; - - public ItemListIgnoreCrafting( final IItemList cla ) - { - this.target = cla; - } - - @Override - public void add( T option ) - { - if( option != null && option.isCraftable() ) - { - option = (T) option.copy(); - option.setCraftable( false ); - } - - this.target.add( option ); - } - - @Override - public T findPrecise( final T i ) - { - return this.target.findPrecise( i ); - } - - @Override - public Collection findFuzzy( final T input, final FuzzyMode fuzzy ) - { - return this.target.findFuzzy( input, fuzzy ); - } - - @Override - public boolean isEmpty() - { - return this.target.isEmpty(); - } - - @Override - public void addStorage( final T option ) - { - this.target.addStorage( option ); - } - - @Override - public void addCrafting( final T option ) - { - // nothing. - } - - @Override - public void addRequestable( final T option ) - { - this.target.addRequestable( option ); - } - - @Override - public T getFirstItem() - { - return this.target.getFirstItem(); - } - - @Override - public int size() - { - return this.target.size(); - } - - @Override - public Iterator iterator() - { - return this.target.iterator(); - } - - @Override - public void resetStatus() - { - this.target.resetStatus(); - } +public class ItemListIgnoreCrafting implements IItemList { + + private final IItemList target; + + public ItemListIgnoreCrafting(final IItemList cla) { + this.target = cla; + } + + @Override + public void add(T option) { + if (option != null && option.isCraftable()) { + option = (T) option.copy(); + option.setCraftable(false); + } + + this.target.add(option); + } + + @Override + public T findPrecise(final T i) { + return this.target.findPrecise(i); + } + + @Override + public Collection findFuzzy(final T input, final FuzzyMode fuzzy) { + return this.target.findFuzzy(input, fuzzy); + } + + @Override + public boolean isEmpty() { + return this.target.isEmpty(); + } + + @Override + public void addStorage(final T option) { + this.target.addStorage(option); + } + + @Override + public void addCrafting(final T option) { + // nothing. + } + + @Override + public void addRequestable(final T option) { + this.target.addRequestable(option); + } + + @Override + public T getFirstItem() { + return this.target.getFirstItem(); + } + + @Override + public int size() { + return this.target.size(); + } + + @Override + public Iterator iterator() { + return this.target.iterator(); + } + + @Override + public void resetStatus() { + this.target.resetStatus(); + } } diff --git a/src/main/java/appeng/util/inv/ItemSlot.java b/src/main/java/appeng/util/inv/ItemSlot.java index 00095927be5..fc30573a51f 100644 --- a/src/main/java/appeng/util/inv/ItemSlot.java +++ b/src/main/java/appeng/util/inv/ItemSlot.java @@ -18,60 +18,53 @@ package appeng.util.inv; - import appeng.api.storage.data.IAEItemStack; import appeng.util.item.AEItemStack; import net.minecraft.item.ItemStack; +public class ItemSlot { -public class ItemSlot -{ - - private int slot; - private boolean isExtractable; - // one or the other.. - private IAEItemStack aeItemStack; - private ItemStack itemStack; + private int slot; + private boolean isExtractable; + // one or the other.. + private IAEItemStack aeItemStack; + private ItemStack itemStack; - public ItemStack getItemStack() - { - return this.itemStack == null ? ( this.aeItemStack == null ? null : ( this.itemStack = this.aeItemStack.getItemStack() ) ) : this.itemStack; - } + public ItemStack getItemStack() { + return this.itemStack == null + ? (this.aeItemStack == null ? null : (this.itemStack = this.aeItemStack.getItemStack())) + : this.itemStack; + } - public void setItemStack( final ItemStack is ) - { - this.aeItemStack = null; - this.itemStack = is; - } + public void setItemStack(final ItemStack is) { + this.aeItemStack = null; + this.itemStack = is; + } - public IAEItemStack getAEItemStack() - { - return this.aeItemStack == null ? ( this.itemStack == null ? null : ( this.aeItemStack = AEItemStack.create( this.itemStack ) ) ) : this.aeItemStack; - } + public IAEItemStack getAEItemStack() { + return this.aeItemStack == null + ? (this.itemStack == null ? null : (this.aeItemStack = AEItemStack.create(this.itemStack))) + : this.aeItemStack; + } - void setAEItemStack( final IAEItemStack is ) - { - this.aeItemStack = is; - this.itemStack = null; - } + void setAEItemStack(final IAEItemStack is) { + this.aeItemStack = is; + this.itemStack = null; + } - public boolean isExtractable() - { - return this.isExtractable; - } + public boolean isExtractable() { + return this.isExtractable; + } - void setExtractable( final boolean isExtractable ) - { - this.isExtractable = isExtractable; - } + void setExtractable(final boolean isExtractable) { + this.isExtractable = isExtractable; + } - public int getSlot() - { - return this.slot; - } + public int getSlot() { + return this.slot; + } - public void setSlot( final int slot ) - { - this.slot = slot; - } + public void setSlot(final int slot) { + this.slot = slot; + } } diff --git a/src/main/java/appeng/util/inv/WrapperBCPipe.java b/src/main/java/appeng/util/inv/WrapperBCPipe.java index 2c27d1ab88d..4d13cb2e9e2 100644 --- a/src/main/java/appeng/util/inv/WrapperBCPipe.java +++ b/src/main/java/appeng/util/inv/WrapperBCPipe.java @@ -18,7 +18,6 @@ package appeng.util.inv; - import appeng.integration.IntegrationRegistry; import appeng.integration.IntegrationType; import appeng.integration.abstraction.IBuildCraftTransport; @@ -28,99 +27,76 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; - -public class WrapperBCPipe implements IInventory -{ - - private final IBuildCraftTransport bc; - private final TileEntity ad; - private final ForgeDirection dir; - - public WrapperBCPipe( final TileEntity te, final ForgeDirection d ) - { - this.bc = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - this.ad = te; - this.dir = d; - } - - @Override - public int getSizeInventory() - { - return 1; - } - - @Override - public ItemStack getStackInSlot( final int i ) - { - return null; - } - - @Override - public ItemStack decrStackSize( final int i, final int j ) - { - return null; - } - - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - return null; - } - - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - this.bc.addItemsToPipe( this.ad, itemstack, this.dir ); - } - } - - @Override - public String getInventoryName() - { - return "BC Pipe Wrapper"; - } - - @Override - public boolean hasCustomInventoryName() - { - return false; - } - - @Override - public int getInventoryStackLimit() - { - return 64; - } - - @Override - public void markDirty() - { - - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return false; - } - - @Override - public void openInventory() - { - - } - - @Override - public void closeInventory() - { - - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return this.bc.canAddItemsToPipe( this.ad, itemstack, this.dir ); - } +public class WrapperBCPipe implements IInventory { + + private final IBuildCraftTransport bc; + private final TileEntity ad; + private final ForgeDirection dir; + + public WrapperBCPipe(final TileEntity te, final ForgeDirection d) { + this.bc = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport); + this.ad = te; + this.dir = d; + } + + @Override + public int getSizeInventory() { + return 1; + } + + @Override + public ItemStack getStackInSlot(final int i) { + return null; + } + + @Override + public ItemStack decrStackSize(final int i, final int j) { + return null; + } + + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + return null; + } + + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport)) { + this.bc.addItemsToPipe(this.ad, itemstack, this.dir); + } + } + + @Override + public String getInventoryName() { + return "BC Pipe Wrapper"; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public int getInventoryStackLimit() { + return 64; + } + + @Override + public void markDirty() {} + + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return false; + } + + @Override + public void openInventory() {} + + @Override + public void closeInventory() {} + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return this.bc.canAddItemsToPipe(this.ad, itemstack, this.dir); + } } diff --git a/src/main/java/appeng/util/inv/WrapperChainedInventory.java b/src/main/java/appeng/util/inv/WrapperChainedInventory.java index 6e76bf0b59b..873b0293b3a 100644 --- a/src/main/java/appeng/util/inv/WrapperChainedInventory.java +++ b/src/main/java/appeng/util/inv/WrapperChainedInventory.java @@ -18,219 +18,178 @@ package appeng.util.inv; - import com.google.common.collect.ImmutableList; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; - -public class WrapperChainedInventory implements IInventory -{ - - private int fullSize = 0; - private List l; - private Map offsets; - - public WrapperChainedInventory( final IInventory... inventories ) - { - this.setInventory( inventories ); - } - - private void setInventory( final IInventory... a ) - { - this.l = ImmutableList.copyOf( a ); - this.calculateSizes(); - } - - private void calculateSizes() - { - this.offsets = new HashMap(); - - int offset = 0; - for( final IInventory in : this.l ) - { - final InvOffset io = new InvOffset(); - io.offset = offset; - io.size = in.getSizeInventory(); - io.i = in; - - for( int y = 0; y < io.size; y++ ) - { - this.offsets.put( y + io.offset, io ); - } - - offset += io.size; - } - - this.fullSize = offset; - } - - public WrapperChainedInventory( final List inventories ) - { - this.setInventory( inventories ); - } - - private void setInventory( final List a ) - { - this.l = a; - this.calculateSizes(); - } - - public void cycleOrder() - { - if( this.l.size() > 1 ) - { - final List newOrder = new ArrayList( this.l.size() ); - newOrder.add( this.l.get( this.l.size() - 1 ) ); - for( int x = 0; x < this.l.size() - 1; x++ ) - { - newOrder.add( this.l.get( x ) ); - } - this.setInventory( newOrder ); - } - } - - public IInventory getInv( final int idx ) - { - final InvOffset io = this.offsets.get( idx ); - if( io != null ) - { - return io.i; - } - return null; - } - - public int getInvSlot( final int idx ) - { - final InvOffset io = this.offsets.get( idx ); - if( io != null ) - { - return idx - io.offset; - } - return 0; - } - - @Override - public int getSizeInventory() - { - return this.fullSize; - } - - @Override - public ItemStack getStackInSlot( final int idx ) - { - final InvOffset io = this.offsets.get( idx ); - if( io != null ) - { - return io.i.getStackInSlot( idx - io.offset ); - } - return null; - } - - @Override - public ItemStack decrStackSize( final int idx, final int var2 ) - { - final InvOffset io = this.offsets.get( idx ); - if( io != null ) - { - return io.i.decrStackSize( idx - io.offset, var2 ); - } - return null; - } - - @Override - public ItemStack getStackInSlotOnClosing( final int idx ) - { - final InvOffset io = this.offsets.get( idx ); - if( io != null ) - { - return io.i.getStackInSlotOnClosing( idx - io.offset ); - } - return null; - } - - @Override - public void setInventorySlotContents( final int idx, final ItemStack var2 ) - { - final InvOffset io = this.offsets.get( idx ); - if( io != null ) - { - io.i.setInventorySlotContents( idx - io.offset, var2 ); - } - } - - @Override - public String getInventoryName() - { - return "ChainedInv"; - } - - @Override - public boolean hasCustomInventoryName() - { - return false; - } - - @Override - public int getInventoryStackLimit() - { - int smallest = 64; - - for( final IInventory i : this.l ) - { - smallest = Math.min( smallest, i.getInventoryStackLimit() ); - } - - return smallest; - } - - @Override - public void markDirty() - { - for( final IInventory i : this.l ) - { - i.markDirty(); - } - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer var1 ) - { - return false; - } - - @Override - public void openInventory() - { - } - - @Override - public void closeInventory() - { - } - - @Override - public boolean isItemValidForSlot( final int idx, final ItemStack itemstack ) - { - final InvOffset io = this.offsets.get( idx ); - if( io != null ) - { - return io.i.isItemValidForSlot( idx - io.offset, itemstack ); - } - return false; - } - - private static class InvOffset - { - - private int offset; - private int size; - private IInventory i; - } +public class WrapperChainedInventory implements IInventory { + + private int fullSize = 0; + private List l; + private Map offsets; + + public WrapperChainedInventory(final IInventory... inventories) { + this.setInventory(inventories); + } + + private void setInventory(final IInventory... a) { + this.l = ImmutableList.copyOf(a); + this.calculateSizes(); + } + + private void calculateSizes() { + this.offsets = new HashMap(); + + int offset = 0; + for (final IInventory in : this.l) { + final InvOffset io = new InvOffset(); + io.offset = offset; + io.size = in.getSizeInventory(); + io.i = in; + + for (int y = 0; y < io.size; y++) { + this.offsets.put(y + io.offset, io); + } + + offset += io.size; + } + + this.fullSize = offset; + } + + public WrapperChainedInventory(final List inventories) { + this.setInventory(inventories); + } + + private void setInventory(final List a) { + this.l = a; + this.calculateSizes(); + } + + public void cycleOrder() { + if (this.l.size() > 1) { + final List newOrder = new ArrayList(this.l.size()); + newOrder.add(this.l.get(this.l.size() - 1)); + for (int x = 0; x < this.l.size() - 1; x++) { + newOrder.add(this.l.get(x)); + } + this.setInventory(newOrder); + } + } + + public IInventory getInv(final int idx) { + final InvOffset io = this.offsets.get(idx); + if (io != null) { + return io.i; + } + return null; + } + + public int getInvSlot(final int idx) { + final InvOffset io = this.offsets.get(idx); + if (io != null) { + return idx - io.offset; + } + return 0; + } + + @Override + public int getSizeInventory() { + return this.fullSize; + } + + @Override + public ItemStack getStackInSlot(final int idx) { + final InvOffset io = this.offsets.get(idx); + if (io != null) { + return io.i.getStackInSlot(idx - io.offset); + } + return null; + } + + @Override + public ItemStack decrStackSize(final int idx, final int var2) { + final InvOffset io = this.offsets.get(idx); + if (io != null) { + return io.i.decrStackSize(idx - io.offset, var2); + } + return null; + } + + @Override + public ItemStack getStackInSlotOnClosing(final int idx) { + final InvOffset io = this.offsets.get(idx); + if (io != null) { + return io.i.getStackInSlotOnClosing(idx - io.offset); + } + return null; + } + + @Override + public void setInventorySlotContents(final int idx, final ItemStack var2) { + final InvOffset io = this.offsets.get(idx); + if (io != null) { + io.i.setInventorySlotContents(idx - io.offset, var2); + } + } + + @Override + public String getInventoryName() { + return "ChainedInv"; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public int getInventoryStackLimit() { + int smallest = 64; + + for (final IInventory i : this.l) { + smallest = Math.min(smallest, i.getInventoryStackLimit()); + } + + return smallest; + } + + @Override + public void markDirty() { + for (final IInventory i : this.l) { + i.markDirty(); + } + } + + @Override + public boolean isUseableByPlayer(final EntityPlayer var1) { + return false; + } + + @Override + public void openInventory() {} + + @Override + public void closeInventory() {} + + @Override + public boolean isItemValidForSlot(final int idx, final ItemStack itemstack) { + final InvOffset io = this.offsets.get(idx); + if (io != null) { + return io.i.isItemValidForSlot(idx - io.offset, itemstack); + } + return false; + } + + private static class InvOffset { + + private int offset; + private int size; + private IInventory i; + } } diff --git a/src/main/java/appeng/util/inv/WrapperInvSlot.java b/src/main/java/appeng/util/inv/WrapperInvSlot.java index 14c3f21bed4..34e62cc699e 100644 --- a/src/main/java/appeng/util/inv/WrapperInvSlot.java +++ b/src/main/java/appeng/util/inv/WrapperInvSlot.java @@ -18,120 +18,99 @@ package appeng.util.inv; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - -public class WrapperInvSlot -{ - - private final IInventory inv; - - public WrapperInvSlot( final IInventory inv ) - { - this.inv = inv; - } - - public IInventory getWrapper( final int slot ) - { - return new InternalInterfaceWrapper( this.inv, slot ); - } - - protected boolean isItemValid( final ItemStack itemstack ) - { - return true; - } - - private class InternalInterfaceWrapper implements IInventory - { - - private final IInventory inv; - private final int slot; - - public InternalInterfaceWrapper( final IInventory target, final int slot ) - { - this.inv = target; - this.slot = slot; - } - - @Override - public int getSizeInventory() - { - return 1; - } - - @Override - public ItemStack getStackInSlot( final int i ) - { - return this.inv.getStackInSlot( this.slot ); - } - - @Override - public ItemStack decrStackSize( final int i, final int num ) - { - return this.inv.decrStackSize( this.slot, num ); - } - - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - return this.inv.getStackInSlotOnClosing( this.slot ); - } - - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - this.inv.setInventorySlotContents( this.slot, itemstack ); - } - - @Override - public String getInventoryName() - { - return this.inv.getInventoryName(); - } - - @Override - public boolean hasCustomInventoryName() - { - return this.inv.hasCustomInventoryName(); - } - - @Override - public int getInventoryStackLimit() - { - return this.inv.getInventoryStackLimit(); - } - - @Override - public void markDirty() - { - this.inv.markDirty(); - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return this.inv.isUseableByPlayer( entityplayer ); - } - - @Override - public void openInventory() - { - this.inv.openInventory(); - } - - @Override - public void closeInventory() - { - this.inv.closeInventory(); - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return WrapperInvSlot.this.isItemValid( itemstack ) && this.inv.isItemValidForSlot( this.slot, itemstack ); - } - } +public class WrapperInvSlot { + + private final IInventory inv; + + public WrapperInvSlot(final IInventory inv) { + this.inv = inv; + } + + public IInventory getWrapper(final int slot) { + return new InternalInterfaceWrapper(this.inv, slot); + } + + protected boolean isItemValid(final ItemStack itemstack) { + return true; + } + + private class InternalInterfaceWrapper implements IInventory { + + private final IInventory inv; + private final int slot; + + public InternalInterfaceWrapper(final IInventory target, final int slot) { + this.inv = target; + this.slot = slot; + } + + @Override + public int getSizeInventory() { + return 1; + } + + @Override + public ItemStack getStackInSlot(final int i) { + return this.inv.getStackInSlot(this.slot); + } + + @Override + public ItemStack decrStackSize(final int i, final int num) { + return this.inv.decrStackSize(this.slot, num); + } + + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + return this.inv.getStackInSlotOnClosing(this.slot); + } + + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + this.inv.setInventorySlotContents(this.slot, itemstack); + } + + @Override + public String getInventoryName() { + return this.inv.getInventoryName(); + } + + @Override + public boolean hasCustomInventoryName() { + return this.inv.hasCustomInventoryName(); + } + + @Override + public int getInventoryStackLimit() { + return this.inv.getInventoryStackLimit(); + } + + @Override + public void markDirty() { + this.inv.markDirty(); + } + + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return this.inv.isUseableByPlayer(entityplayer); + } + + @Override + public void openInventory() { + this.inv.openInventory(); + } + + @Override + public void closeInventory() { + this.inv.closeInventory(); + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return WrapperInvSlot.this.isItemValid(itemstack) && this.inv.isItemValidForSlot(this.slot, itemstack); + } + } } diff --git a/src/main/java/appeng/util/inv/WrapperInventoryRange.java b/src/main/java/appeng/util/inv/WrapperInventoryRange.java index 987463da12e..a65caac51bc 100644 --- a/src/main/java/appeng/util/inv/WrapperInventoryRange.java +++ b/src/main/java/appeng/util/inv/WrapperInventoryRange.java @@ -18,161 +18,132 @@ package appeng.util.inv; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; - -public class WrapperInventoryRange implements IInventory -{ - - private final IInventory src; - private boolean ignoreValidItems = false; - private int[] slots; - - public WrapperInventoryRange( final IInventory a, final int[] s, final boolean ignoreValid ) - { - this.src = a; - this.setSlots( s ); - - if( this.getSlots() == null ) - { - this.setSlots( new int[0] ); - } - - this.setIgnoreValidItems( ignoreValid ); - } - - public WrapperInventoryRange( final IInventory a, final int min, final int size, final boolean ignoreValid ) - { - this.src = a; - this.setSlots( new int[size] ); - for( int x = 0; x < size; x++ ) - { - this.getSlots()[x] = min + x; - } - this.setIgnoreValidItems( ignoreValid ); - } - - public static String concatLines( final int[] s, final String separator ) - { - if( s.length > 0 ) - { - final StringBuilder sb = new StringBuilder(); - for( final int value : s ) - { - if( sb.length() > 0 ) - { - sb.append( separator ); - } - sb.append( value ); - } - return sb.toString(); - } - return ""; - } - - @Override - public int getSizeInventory() - { - return this.getSlots().length; - } - - @Override - public ItemStack getStackInSlot( final int var1 ) - { - return this.src.getStackInSlot( this.getSlots()[var1] ); - } - - @Override - public ItemStack decrStackSize( final int var1, final int var2 ) - { - return this.src.decrStackSize( this.getSlots()[var1], var2 ); - } - - @Override - public ItemStack getStackInSlotOnClosing( final int var1 ) - { - return this.src.getStackInSlotOnClosing( this.getSlots()[var1] ); - } - - @Override - public void setInventorySlotContents( final int var1, final ItemStack var2 ) - { - this.src.setInventorySlotContents( this.getSlots()[var1], var2 ); - } - - @Override - public String getInventoryName() - { - return this.src.getInventoryName(); - } - - @Override - public boolean hasCustomInventoryName() - { - return false; - } - - @Override - public int getInventoryStackLimit() - { - return this.src.getInventoryStackLimit(); - } - - @Override - public void markDirty() - { - this.src.markDirty(); - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer var1 ) - { - return this.src.isUseableByPlayer( var1 ); - } - - @Override - public void openInventory() - { - this.src.openInventory(); - } - - @Override - public void closeInventory() - { - this.src.closeInventory(); - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - if( this.isIgnoreValidItems() ) - { - return true; - } - - return this.src.isItemValidForSlot( this.getSlots()[i], itemstack ); - } - - boolean isIgnoreValidItems() - { - return this.ignoreValidItems; - } - - private void setIgnoreValidItems( final boolean ignoreValidItems ) - { - this.ignoreValidItems = ignoreValidItems; - } - - int[] getSlots() - { - return this.slots; - } - - private void setSlots( final int[] slots ) - { - this.slots = slots; - } +public class WrapperInventoryRange implements IInventory { + + private final IInventory src; + private boolean ignoreValidItems = false; + private int[] slots; + + public WrapperInventoryRange(final IInventory a, final int[] s, final boolean ignoreValid) { + this.src = a; + this.setSlots(s); + + if (this.getSlots() == null) { + this.setSlots(new int[0]); + } + + this.setIgnoreValidItems(ignoreValid); + } + + public WrapperInventoryRange(final IInventory a, final int min, final int size, final boolean ignoreValid) { + this.src = a; + this.setSlots(new int[size]); + for (int x = 0; x < size; x++) { + this.getSlots()[x] = min + x; + } + this.setIgnoreValidItems(ignoreValid); + } + + public static String concatLines(final int[] s, final String separator) { + if (s.length > 0) { + final StringBuilder sb = new StringBuilder(); + for (final int value : s) { + if (sb.length() > 0) { + sb.append(separator); + } + sb.append(value); + } + return sb.toString(); + } + return ""; + } + + @Override + public int getSizeInventory() { + return this.getSlots().length; + } + + @Override + public ItemStack getStackInSlot(final int var1) { + return this.src.getStackInSlot(this.getSlots()[var1]); + } + + @Override + public ItemStack decrStackSize(final int var1, final int var2) { + return this.src.decrStackSize(this.getSlots()[var1], var2); + } + + @Override + public ItemStack getStackInSlotOnClosing(final int var1) { + return this.src.getStackInSlotOnClosing(this.getSlots()[var1]); + } + + @Override + public void setInventorySlotContents(final int var1, final ItemStack var2) { + this.src.setInventorySlotContents(this.getSlots()[var1], var2); + } + + @Override + public String getInventoryName() { + return this.src.getInventoryName(); + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public int getInventoryStackLimit() { + return this.src.getInventoryStackLimit(); + } + + @Override + public void markDirty() { + this.src.markDirty(); + } + + @Override + public boolean isUseableByPlayer(final EntityPlayer var1) { + return this.src.isUseableByPlayer(var1); + } + + @Override + public void openInventory() { + this.src.openInventory(); + } + + @Override + public void closeInventory() { + this.src.closeInventory(); + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + if (this.isIgnoreValidItems()) { + return true; + } + + return this.src.isItemValidForSlot(this.getSlots()[i], itemstack); + } + + boolean isIgnoreValidItems() { + return this.ignoreValidItems; + } + + private void setIgnoreValidItems(final boolean ignoreValidItems) { + this.ignoreValidItems = ignoreValidItems; + } + + int[] getSlots() { + return this.slots; + } + + private void setSlots(final int[] slots) { + this.slots = slots; + } } diff --git a/src/main/java/appeng/util/inv/WrapperMCISidedInventory.java b/src/main/java/appeng/util/inv/WrapperMCISidedInventory.java index 78b58a9a89c..c37007193ed 100644 --- a/src/main/java/appeng/util/inv/WrapperMCISidedInventory.java +++ b/src/main/java/appeng/util/inv/WrapperMCISidedInventory.java @@ -18,60 +18,49 @@ package appeng.util.inv; - import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; +public class WrapperMCISidedInventory extends WrapperInventoryRange implements IInventoryWrapper { -public class WrapperMCISidedInventory extends WrapperInventoryRange implements IInventoryWrapper -{ - - private final ISidedInventory side; - private final ForgeDirection dir; + private final ISidedInventory side; + private final ForgeDirection dir; - public WrapperMCISidedInventory( final ISidedInventory a, final ForgeDirection d ) - { - super( a, a.getAccessibleSlotsFromSide( d.ordinal() ), false ); - this.side = a; - this.dir = d; - } + public WrapperMCISidedInventory(final ISidedInventory a, final ForgeDirection d) { + super(a, a.getAccessibleSlotsFromSide(d.ordinal()), false); + this.side = a; + this.dir = d; + } - @Override - public ItemStack decrStackSize( final int var1, final int var2 ) - { - if( this.canRemoveItemFromSlot( var1, this.getStackInSlot( var1 ) ) ) - { - return super.decrStackSize( var1, var2 ); - } - return null; - } + @Override + public ItemStack decrStackSize(final int var1, final int var2) { + if (this.canRemoveItemFromSlot(var1, this.getStackInSlot(var1))) { + return super.decrStackSize(var1, var2); + } + return null; + } - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { - if( this.isIgnoreValidItems() ) - { - return true; - } + if (this.isIgnoreValidItems()) { + return true; + } - if( this.side.isItemValidForSlot( this.getSlots()[i], itemstack ) ) - { - return this.side.canInsertItem( this.getSlots()[i], itemstack, this.dir.ordinal() ); - } + if (this.side.isItemValidForSlot(this.getSlots()[i], itemstack)) { + return this.side.canInsertItem(this.getSlots()[i], itemstack, this.dir.ordinal()); + } - return false; - } + return false; + } - @Override - public boolean canRemoveItemFromSlot( final int i, final ItemStack is ) - { - if( is == null ) - { - return false; - } + @Override + public boolean canRemoveItemFromSlot(final int i, final ItemStack is) { + if (is == null) { + return false; + } - return this.side.canExtractItem( this.getSlots()[i], is, this.dir.ordinal() ); - } + return this.side.canExtractItem(this.getSlots()[i], is, this.dir.ordinal()); + } } diff --git a/src/main/java/appeng/util/item/AEFluidStack.java b/src/main/java/appeng/util/item/AEFluidStack.java index d4b05a118f9..a0842ac2fa2 100644 --- a/src/main/java/appeng/util/item/AEFluidStack.java +++ b/src/main/java/appeng/util/item/AEFluidStack.java @@ -18,7 +18,6 @@ package appeng.util.item; - import appeng.api.config.FuzzyMode; import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEFluidStack; @@ -26,6 +25,8 @@ import appeng.api.storage.data.IAETagCompound; import appeng.util.Platform; import io.netty.buffer.ByteBuf; +import java.io.*; +import javax.annotation.Nonnull; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTBase; @@ -33,352 +34,305 @@ import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; -import javax.annotation.Nonnull; -import java.io.*; - - -public final class AEFluidStack extends AEStack implements IAEFluidStack, Comparable -{ - - private final int myHash; - private final Fluid fluid; - private IAETagCompound tagCompound; - - private AEFluidStack( final AEFluidStack is ) - { - - this.fluid = is.fluid; - this.setStackSize( is.getStackSize() ); - - // priority = is.priority; - this.setCraftable( is.isCraftable() ); - this.setCountRequestable( is.getCountRequestable() ); - - this.myHash = is.myHash; - } - - private AEFluidStack( @Nonnull final FluidStack is ) - { - this.fluid = is.getFluid(); - - if( this.fluid == null ) - { - throw new IllegalArgumentException( "Fluid is null." ); - } - - this.setStackSize( is.amount ); - this.setCraftable( false ); - this.setCountRequestable( 0 ); - - this.myHash = this.fluid.hashCode() ^ ( this.tagCompound == null ? 0 : System.identityHashCode( this.tagCompound ) ); - } - - public static IAEFluidStack loadFluidStackFromNBT( final NBTTagCompound i ) - { - final ItemStack itemstack = ItemStack.loadItemStackFromNBT( i ); - if( itemstack == null ) - { - return null; - } - final AEFluidStack fluid = AEFluidStack.create( itemstack ); - // fluid.priority = i.getInteger( "Priority" ); - fluid.setStackSize( i.getLong( "Cnt" ) ); - fluid.setCountRequestable( i.getLong( "Req" ) ); - fluid.setCraftable( i.getBoolean( "Craft" ) ); - return fluid; - } - - public static AEFluidStack create( final Object a ) - { - if( a == null ) - { - return null; - } - if( a instanceof AEFluidStack ) - { - ( (IAEStack) a ).copy(); - } - if( a instanceof FluidStack ) - { - return new AEFluidStack( (FluidStack) a ); - } - return null; - } - - public static IAEFluidStack loadFluidStackFromPacket( final ByteBuf data ) throws IOException - { - final byte mask = data.readByte(); - // byte PriorityType = (byte) (mask & 0x03); - final byte stackType = (byte) ( ( mask & 0x0C ) >> 2 ); - final byte countReqType = (byte) ( ( mask & 0x30 ) >> 4 ); - final boolean isCraftable = ( mask & 0x40 ) > 0; - final boolean hasTagCompound = ( mask & 0x80 ) > 0; - - // don't send this... - final NBTTagCompound d = new NBTTagCompound(); - - final byte len2 = data.readByte(); - final byte[] name = new byte[len2]; - data.readBytes( name, 0, len2 ); - - d.setString( "FluidName", new String( name, "UTF-8" ) ); - d.setByte( "Count", (byte) 0 ); - - if( hasTagCompound ) - { - final int len = data.readInt(); - - final byte[] bd = new byte[len]; - data.readBytes( bd ); - - final DataInputStream di = new DataInputStream( new ByteArrayInputStream( bd ) ); - d.setTag( "tag", CompressedStreamTools.read( di ) ); - } - - // long priority = getPacketValue( PriorityType, data ); - final long stackSize = getPacketValue( stackType, data ); - final long countRequestable = getPacketValue( countReqType, data ); - - final FluidStack fluidStack = FluidStack.loadFluidStackFromNBT( d ); - if( fluidStack == null ) - { - return null; - } - - final AEFluidStack fluid = AEFluidStack.create( fluidStack ); - // fluid.priority = (int) priority; - fluid.setStackSize( stackSize ); - fluid.setCountRequestable( countRequestable ); - fluid.setCraftable( isCraftable ); - return fluid; - } - - @Override - public void add( final IAEFluidStack option ) - { - if( option == null ) - { - return; - } - - // if ( priority < ((AEFluidStack) option).priority ) - // priority = ((AEFluidStack) option).priority; - - this.incStackSize( option.getStackSize() ); - this.setCountRequestable( this.getCountRequestable() + option.getCountRequestable() ); - this.setCraftable( this.isCraftable() || option.isCraftable() ); - } - - @Override - public void writeToNBT( final NBTTagCompound i ) - { - /* - * Mojang Fucked this over ; GC Optimization - Ugly Yes, but it saves a lot in the memory department. - */ - - /* - * NBTBase FluidName = i.getTag( "FluidName" ); NBTBase Count = i.getTag( "Count" ); NBTBase Cnt = i.getTag( - * "Cnt" ); NBTBase Req = i.getTag( "Req" ); NBTBase Craft = i.getTag( "Craft" ); - */ - - /* - * if ( FluidName != null && FluidName instanceof NBTTagString ) ((NBTTagString) FluidName).data = (String) - * this.fluid.getName(); else - */ - i.setString( "FluidName", this.fluid.getName() ); - - /* - * if ( Count != null && Count instanceof NBTTagByte ) ((NBTTagByte) Count).data = (byte) 0; else - */ - i.setByte( "Count", (byte) 0 ); - - /* - * if ( Cnt != null && Cnt instanceof NBTTagLong ) ((NBTTagLong) Cnt).data = this.stackSize; else - */ - i.setLong( "Cnt", this.getStackSize() ); - - /* - * if ( Req != null && Req instanceof NBTTagLong ) ((NBTTagLong) Req).data = this.stackSize; else - */ - i.setLong( "Req", this.getCountRequestable() ); - - /* - * if ( Craft != null && Craft instanceof NBTTagByte ) ((NBTTagByte) Craft).data = (byte) (this.isCraftable() ? - * 1 : 0); else - */ - i.setBoolean( "Craft", this.isCraftable() ); - - if( this.tagCompound != null ) - { - i.setTag( "tag", (NBTBase) this.tagCompound ); - } - else - { - i.removeTag( "tag" ); - } - } - - @Override - public boolean fuzzyComparison( final Object st, final FuzzyMode mode ) - { - if( st instanceof FluidStack ) - { - return ( (FluidStack) st ).getFluid() == this.fluid; - } - - if( st instanceof IAEFluidStack ) - { - return ( (IAEFluidStack) st ).getFluid() == this.fluid; - } - - return false; - } - - @Override - public IAEFluidStack copy() - { - return new AEFluidStack( this ); - } - - @Override - public IAEFluidStack empty() - { - final IAEFluidStack dup = this.copy(); - dup.reset(); - return dup; - } - - @Override - public IAETagCompound getTagCompound() - { - return this.tagCompound; - } - - @Override - public boolean isItem() - { - return false; - } - - @Override - public boolean isFluid() - { - return true; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.FLUIDS; - } - - @Override - public int compareTo( final AEFluidStack b ) - { - final int diff = this.hashCode() - b.hashCode(); - return diff > 0 ? 1 : ( diff < 0 ? -1 : 0 ); - } - - @Override - public int hashCode() - { - return this.myHash; - } - - @Override - public boolean equals( final Object ia ) - { - if( ia instanceof AEFluidStack ) - { - return ( (AEFluidStack) ia ).fluid == this.fluid && this.tagCompound == ( (AEFluidStack) ia ).tagCompound; - } - else if( ia instanceof FluidStack ) - { - final FluidStack is = (FluidStack) ia; - - if( is.getFluidID() == this.fluid.getID() ) - { - final NBTTagCompound ta = (NBTTagCompound) this.tagCompound; - final NBTTagCompound tb = is.tag; - if( ta == tb ) - { - return true; - } - - if( ( ta == null && tb == null ) || ( ta != null && ta.hasNoTags() && tb == null ) || ( tb != null && tb.hasNoTags() && ta == null ) || ( ta != null && ta.hasNoTags() && tb != null && tb.hasNoTags() ) ) - { - return true; - } - - if( ( ta == null && tb != null ) || ( ta != null && tb == null ) ) - { - return false; - } - - if( AESharedNBT.isShared( tb ) ) - { - return ta == tb; - } - - return Platform.NBTEqualityTest( ta, tb ); - } - } - return false; - } - - @Override - public String toString() - { - return this.getFluidStack().toString(); - } - - @Override - public boolean hasTagCompound() - { - return this.tagCompound != null; - } - - @Override - void writeIdentity( final ByteBuf i ) throws IOException - { - final byte[] name = this.fluid.getName().getBytes( "UTF-8" ); - i.writeByte( (byte) name.length ); - i.writeBytes( name ); - } - - @Override - void readNBT( final ByteBuf i ) throws IOException - { - if( this.hasTagCompound() ) - { - final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - final DataOutputStream data = new DataOutputStream( bytes ); - - CompressedStreamTools.write( (NBTTagCompound) this.tagCompound, data ); - - final byte[] tagBytes = bytes.toByteArray(); - final int size = tagBytes.length; - - i.writeInt( size ); - i.writeBytes( tagBytes ); - } - } - - @Override - public FluidStack getFluidStack() - { - final FluidStack is = new FluidStack( this.fluid, (int) Math.min( Integer.MAX_VALUE, this.getStackSize() ) ); - if( this.tagCompound != null ) - { - is.tag = this.tagCompound.getNBTTagCompoundCopy(); - } - - return is; - } - - @Override - public Fluid getFluid() - { - return this.fluid; - } +public final class AEFluidStack extends AEStack implements IAEFluidStack, Comparable { + + private final int myHash; + private final Fluid fluid; + private IAETagCompound tagCompound; + + private AEFluidStack(final AEFluidStack is) { + + this.fluid = is.fluid; + this.setStackSize(is.getStackSize()); + + // priority = is.priority; + this.setCraftable(is.isCraftable()); + this.setCountRequestable(is.getCountRequestable()); + + this.myHash = is.myHash; + } + + private AEFluidStack(@Nonnull final FluidStack is) { + this.fluid = is.getFluid(); + + if (this.fluid == null) { + throw new IllegalArgumentException("Fluid is null."); + } + + this.setStackSize(is.amount); + this.setCraftable(false); + this.setCountRequestable(0); + + this.myHash = + this.fluid.hashCode() ^ (this.tagCompound == null ? 0 : System.identityHashCode(this.tagCompound)); + } + + public static IAEFluidStack loadFluidStackFromNBT(final NBTTagCompound i) { + final ItemStack itemstack = ItemStack.loadItemStackFromNBT(i); + if (itemstack == null) { + return null; + } + final AEFluidStack fluid = AEFluidStack.create(itemstack); + // fluid.priority = i.getInteger( "Priority" ); + fluid.setStackSize(i.getLong("Cnt")); + fluid.setCountRequestable(i.getLong("Req")); + fluid.setCraftable(i.getBoolean("Craft")); + return fluid; + } + + public static AEFluidStack create(final Object a) { + if (a == null) { + return null; + } + if (a instanceof AEFluidStack) { + ((IAEStack) a).copy(); + } + if (a instanceof FluidStack) { + return new AEFluidStack((FluidStack) a); + } + return null; + } + + public static IAEFluidStack loadFluidStackFromPacket(final ByteBuf data) throws IOException { + final byte mask = data.readByte(); + // byte PriorityType = (byte) (mask & 0x03); + final byte stackType = (byte) ((mask & 0x0C) >> 2); + final byte countReqType = (byte) ((mask & 0x30) >> 4); + final boolean isCraftable = (mask & 0x40) > 0; + final boolean hasTagCompound = (mask & 0x80) > 0; + + // don't send this... + final NBTTagCompound d = new NBTTagCompound(); + + final byte len2 = data.readByte(); + final byte[] name = new byte[len2]; + data.readBytes(name, 0, len2); + + d.setString("FluidName", new String(name, "UTF-8")); + d.setByte("Count", (byte) 0); + + if (hasTagCompound) { + final int len = data.readInt(); + + final byte[] bd = new byte[len]; + data.readBytes(bd); + + final DataInputStream di = new DataInputStream(new ByteArrayInputStream(bd)); + d.setTag("tag", CompressedStreamTools.read(di)); + } + + // long priority = getPacketValue( PriorityType, data ); + final long stackSize = getPacketValue(stackType, data); + final long countRequestable = getPacketValue(countReqType, data); + + final FluidStack fluidStack = FluidStack.loadFluidStackFromNBT(d); + if (fluidStack == null) { + return null; + } + + final AEFluidStack fluid = AEFluidStack.create(fluidStack); + // fluid.priority = (int) priority; + fluid.setStackSize(stackSize); + fluid.setCountRequestable(countRequestable); + fluid.setCraftable(isCraftable); + return fluid; + } + + @Override + public void add(final IAEFluidStack option) { + if (option == null) { + return; + } + + // if ( priority < ((AEFluidStack) option).priority ) + // priority = ((AEFluidStack) option).priority; + + this.incStackSize(option.getStackSize()); + this.setCountRequestable(this.getCountRequestable() + option.getCountRequestable()); + this.setCraftable(this.isCraftable() || option.isCraftable()); + } + + @Override + public void writeToNBT(final NBTTagCompound i) { + /* + * Mojang Fucked this over ; GC Optimization - Ugly Yes, but it saves a lot in the memory department. + */ + + /* + * NBTBase FluidName = i.getTag( "FluidName" ); NBTBase Count = i.getTag( "Count" ); NBTBase Cnt = i.getTag( + * "Cnt" ); NBTBase Req = i.getTag( "Req" ); NBTBase Craft = i.getTag( "Craft" ); + */ + + /* + * if ( FluidName != null && FluidName instanceof NBTTagString ) ((NBTTagString) FluidName).data = (String) + * this.fluid.getName(); else + */ + i.setString("FluidName", this.fluid.getName()); + + /* + * if ( Count != null && Count instanceof NBTTagByte ) ((NBTTagByte) Count).data = (byte) 0; else + */ + i.setByte("Count", (byte) 0); + + /* + * if ( Cnt != null && Cnt instanceof NBTTagLong ) ((NBTTagLong) Cnt).data = this.stackSize; else + */ + i.setLong("Cnt", this.getStackSize()); + + /* + * if ( Req != null && Req instanceof NBTTagLong ) ((NBTTagLong) Req).data = this.stackSize; else + */ + i.setLong("Req", this.getCountRequestable()); + + /* + * if ( Craft != null && Craft instanceof NBTTagByte ) ((NBTTagByte) Craft).data = (byte) (this.isCraftable() ? + * 1 : 0); else + */ + i.setBoolean("Craft", this.isCraftable()); + + if (this.tagCompound != null) { + i.setTag("tag", (NBTBase) this.tagCompound); + } else { + i.removeTag("tag"); + } + } + + @Override + public boolean fuzzyComparison(final Object st, final FuzzyMode mode) { + if (st instanceof FluidStack) { + return ((FluidStack) st).getFluid() == this.fluid; + } + + if (st instanceof IAEFluidStack) { + return ((IAEFluidStack) st).getFluid() == this.fluid; + } + + return false; + } + + @Override + public IAEFluidStack copy() { + return new AEFluidStack(this); + } + + @Override + public IAEFluidStack empty() { + final IAEFluidStack dup = this.copy(); + dup.reset(); + return dup; + } + + @Override + public IAETagCompound getTagCompound() { + return this.tagCompound; + } + + @Override + public boolean isItem() { + return false; + } + + @Override + public boolean isFluid() { + return true; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.FLUIDS; + } + + @Override + public int compareTo(final AEFluidStack b) { + final int diff = this.hashCode() - b.hashCode(); + return diff > 0 ? 1 : (diff < 0 ? -1 : 0); + } + + @Override + public int hashCode() { + return this.myHash; + } + + @Override + public boolean equals(final Object ia) { + if (ia instanceof AEFluidStack) { + return ((AEFluidStack) ia).fluid == this.fluid && this.tagCompound == ((AEFluidStack) ia).tagCompound; + } else if (ia instanceof FluidStack) { + final FluidStack is = (FluidStack) ia; + + if (is.getFluidID() == this.fluid.getID()) { + final NBTTagCompound ta = (NBTTagCompound) this.tagCompound; + final NBTTagCompound tb = is.tag; + if (ta == tb) { + return true; + } + + if ((ta == null && tb == null) + || (ta != null && ta.hasNoTags() && tb == null) + || (tb != null && tb.hasNoTags() && ta == null) + || (ta != null && ta.hasNoTags() && tb != null && tb.hasNoTags())) { + return true; + } + + if ((ta == null && tb != null) || (ta != null && tb == null)) { + return false; + } + + if (AESharedNBT.isShared(tb)) { + return ta == tb; + } + + return Platform.NBTEqualityTest(ta, tb); + } + } + return false; + } + + @Override + public String toString() { + return this.getFluidStack().toString(); + } + + @Override + public boolean hasTagCompound() { + return this.tagCompound != null; + } + + @Override + void writeIdentity(final ByteBuf i) throws IOException { + final byte[] name = this.fluid.getName().getBytes("UTF-8"); + i.writeByte((byte) name.length); + i.writeBytes(name); + } + + @Override + void readNBT(final ByteBuf i) throws IOException { + if (this.hasTagCompound()) { + final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + final DataOutputStream data = new DataOutputStream(bytes); + + CompressedStreamTools.write((NBTTagCompound) this.tagCompound, data); + + final byte[] tagBytes = bytes.toByteArray(); + final int size = tagBytes.length; + + i.writeInt(size); + i.writeBytes(tagBytes); + } + } + + @Override + public FluidStack getFluidStack() { + final FluidStack is = new FluidStack(this.fluid, (int) Math.min(Integer.MAX_VALUE, this.getStackSize())); + if (this.tagCompound != null) { + is.tag = this.tagCompound.getNBTTagCompoundCopy(); + } + + return is; + } + + @Override + public Fluid getFluid() { + return this.fluid; + } } diff --git a/src/main/java/appeng/util/item/AEItemDef.java b/src/main/java/appeng/util/item/AEItemDef.java index ed25ac84a4a..39174459790 100644 --- a/src/main/java/appeng/util/item/AEItemDef.java +++ b/src/main/java/appeng/util/item/AEItemDef.java @@ -18,205 +18,176 @@ package appeng.util.item; - import appeng.util.Platform; import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import java.util.List; - - -public class AEItemDef -{ - - static final AESharedNBT LOW_TAG = new AESharedNBT( Integer.MIN_VALUE ); - static final AESharedNBT HIGH_TAG = new AESharedNBT( Integer.MAX_VALUE ); - - private final int itemID; - private final Item item; - private int myHash; - private int def; - private int damageValue; - private int displayDamage; - private int maxDamage; - private AESharedNBT tagCompound; - @SideOnly( Side.CLIENT ) - private String displayName; - @SideOnly( Side.CLIENT ) - private List tooltip; - @SideOnly( Side.CLIENT ) - private UniqueIdentifier uniqueID; - private OreReference isOre; - - public AEItemDef( final Item it ) - { - this.item = it; - this.itemID = Item.getIdFromItem( it ); - } - - AEItemDef copy() - { - final AEItemDef t = new AEItemDef( this.getItem() ); - t.def = this.def; - t.setDamageValue( this.getDamageValue() ); - t.setDisplayDamage( this.getDisplayDamage() ); - t.setMaxDamage( this.getMaxDamage() ); - t.setTagCompound( this.getTagCompound() ); - t.setIsOre( this.getIsOre() ); - return t; - } - - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - final AEItemDef other = (AEItemDef) obj; - return other.getDamageValue() == this.getDamageValue() && other.getItem() == this.getItem() && this.getTagCompound() == other.getTagCompound(); - } - - boolean isItem( final ItemStack otherStack ) - { - // hackery! - final int dmg = this.getDamageValueHack( otherStack ); - - if( this.getItem() == otherStack.getItem() && dmg == this.getDamageValue() ) - { - if( ( this.getTagCompound() != null ) != otherStack.hasTagCompound() ) - { - return false; - } - - if( this.getTagCompound() != null && otherStack.hasTagCompound() ) - { - return Platform.NBTEqualityTest( this.getTagCompound(), otherStack.getTagCompound() ); - } - - return true; - } - return false; - } - - int getDamageValueHack( final ItemStack is ) - { - return Items.blaze_rod.getDamage( is ); - } - - void reHash() - { - this.def = this.getItemID() << Platform.DEF_OFFSET | this.getDamageValue(); - this.myHash = this.def ^ ( this.getTagCompound() == null ? 0 : System.identityHashCode( this.getTagCompound() ) ); - } - - AESharedNBT getTagCompound() - { - return this.tagCompound; - } - - void setTagCompound( final AESharedNBT tagCompound ) - { - this.tagCompound = tagCompound; - } - - int getDamageValue() - { - return this.damageValue; - } - - int setDamageValue( final int damageValue ) - { - this.damageValue = damageValue; - return damageValue; - } - - Item getItem() - { - return this.item; - } - - int getDisplayDamage() - { - return this.displayDamage; - } - - void setDisplayDamage( final int displayDamage ) - { - this.displayDamage = displayDamage; - } - - String getDisplayName() - { - return this.displayName; - } - - void setDisplayName( final String displayName ) - { - this.displayName = displayName; - } - - List getTooltip() - { - return this.tooltip; - } - - List setTooltip( final List tooltip ) - { - this.tooltip = tooltip; - return tooltip; - } - - UniqueIdentifier getUniqueID() - { - return this.uniqueID; - } - - UniqueIdentifier setUniqueID( final UniqueIdentifier uniqueID ) - { - this.uniqueID = uniqueID; - return uniqueID; - } - - OreReference getIsOre() - { - return this.isOre; - } - - void setIsOre( final OreReference isOre ) - { - this.isOre = isOre; - } - - int getItemID() - { - return this.itemID; - } - - int getMaxDamage() - { - return this.maxDamage; - } - - void setMaxDamage( final int maxDamage ) - { - this.maxDamage = maxDamage; - } - - /** - * TODO: Check if replaceable by hashCode(); - */ - int getMyHash() - { - return this.myHash; - } - +public class AEItemDef { + + static final AESharedNBT LOW_TAG = new AESharedNBT(Integer.MIN_VALUE); + static final AESharedNBT HIGH_TAG = new AESharedNBT(Integer.MAX_VALUE); + + private final int itemID; + private final Item item; + private int myHash; + private int def; + private int damageValue; + private int displayDamage; + private int maxDamage; + private AESharedNBT tagCompound; + + @SideOnly(Side.CLIENT) + private String displayName; + + @SideOnly(Side.CLIENT) + private List tooltip; + + @SideOnly(Side.CLIENT) + private UniqueIdentifier uniqueID; + + private OreReference isOre; + + public AEItemDef(final Item it) { + this.item = it; + this.itemID = Item.getIdFromItem(it); + } + + AEItemDef copy() { + final AEItemDef t = new AEItemDef(this.getItem()); + t.def = this.def; + t.setDamageValue(this.getDamageValue()); + t.setDisplayDamage(this.getDisplayDamage()); + t.setMaxDamage(this.getMaxDamage()); + t.setTagCompound(this.getTagCompound()); + t.setIsOre(this.getIsOre()); + return t; + } + + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final AEItemDef other = (AEItemDef) obj; + return other.getDamageValue() == this.getDamageValue() + && other.getItem() == this.getItem() + && this.getTagCompound() == other.getTagCompound(); + } + + boolean isItem(final ItemStack otherStack) { + // hackery! + final int dmg = this.getDamageValueHack(otherStack); + + if (this.getItem() == otherStack.getItem() && dmg == this.getDamageValue()) { + if ((this.getTagCompound() != null) != otherStack.hasTagCompound()) { + return false; + } + + if (this.getTagCompound() != null && otherStack.hasTagCompound()) { + return Platform.NBTEqualityTest(this.getTagCompound(), otherStack.getTagCompound()); + } + + return true; + } + return false; + } + + int getDamageValueHack(final ItemStack is) { + return Items.blaze_rod.getDamage(is); + } + + void reHash() { + this.def = this.getItemID() << Platform.DEF_OFFSET | this.getDamageValue(); + this.myHash = this.def ^ (this.getTagCompound() == null ? 0 : System.identityHashCode(this.getTagCompound())); + } + + AESharedNBT getTagCompound() { + return this.tagCompound; + } + + void setTagCompound(final AESharedNBT tagCompound) { + this.tagCompound = tagCompound; + } + + int getDamageValue() { + return this.damageValue; + } + + int setDamageValue(final int damageValue) { + this.damageValue = damageValue; + return damageValue; + } + + Item getItem() { + return this.item; + } + + int getDisplayDamage() { + return this.displayDamage; + } + + void setDisplayDamage(final int displayDamage) { + this.displayDamage = displayDamage; + } + + String getDisplayName() { + return this.displayName; + } + + void setDisplayName(final String displayName) { + this.displayName = displayName; + } + + List getTooltip() { + return this.tooltip; + } + + List setTooltip(final List tooltip) { + this.tooltip = tooltip; + return tooltip; + } + + UniqueIdentifier getUniqueID() { + return this.uniqueID; + } + + UniqueIdentifier setUniqueID(final UniqueIdentifier uniqueID) { + this.uniqueID = uniqueID; + return uniqueID; + } + + OreReference getIsOre() { + return this.isOre; + } + + void setIsOre(final OreReference isOre) { + this.isOre = isOre; + } + + int getItemID() { + return this.itemID; + } + + int getMaxDamage() { + return this.maxDamage; + } + + void setMaxDamage(final int maxDamage) { + this.maxDamage = maxDamage; + } + + /** + * TODO: Check if replaceable by hashCode(); + */ + int getMyHash() { + return this.myHash; + } } diff --git a/src/main/java/appeng/util/item/AEItemStack.java b/src/main/java/appeng/util/item/AEItemStack.java index 5c216792990..7349a3b3b7a 100644 --- a/src/main/java/appeng/util/item/AEItemStack.java +++ b/src/main/java/appeng/util/item/AEItemStack.java @@ -18,7 +18,6 @@ package appeng.util.item; - import appeng.api.config.FuzzyMode; import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEItemStack; @@ -29,702 +28,604 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.*; +import java.security.InvalidParameterException; +import java.util.List; +import javax.annotation.Nullable; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; -import javax.annotation.Nullable; -import java.io.*; -import java.security.InvalidParameterException; -import java.util.List; - - -public final class AEItemStack extends AEStack implements IAEItemStack, Comparable -{ - - private AEItemDef def; - - private AEItemStack( final AEItemStack is ) - { - this.setDefinition( is.getDefinition() ); - this.setStackSize( is.getStackSize() ); - this.setCraftable( is.isCraftable() ); - this.setCountRequestable( is.getCountRequestable() ); - } - - private AEItemStack( final ItemStack is ) - { - if( is == null ) - { - throw new InvalidParameterException( "null is not a valid ItemStack for AEItemStack." ); - } - - final Item item = is.getItem(); - if( item == null ) - { - throw new InvalidParameterException( "Contained item is null, thus not a valid ItemStack for AEItemStack." ); - } - - this.setDefinition( new AEItemDef( item ) ); - - if( this.getDefinition().getItem() == null ) - { - throw new InvalidParameterException( "This ItemStack is bad, it has a null item." ); - } - - /* - * Prevent an Item from changing the damage value on me... Either, this or a core mod. - */ - - /* - * Super hackery. - * is.itemID = appeng.api.Materials.matQuartz.itemID; damageValue = is.getItemDamage(); is.itemID = itemID; - */ - - /* - * Kinda hackery - */ - this.getDefinition().setDamageValue( this.getDefinition().getDamageValueHack( is ) ); - this.getDefinition().setDisplayDamage( is.getItemDamageForDisplay() ); - this.getDefinition().setMaxDamage( is.getMaxDamage() ); - - final NBTTagCompound tagCompound = is.getTagCompound(); - if( tagCompound != null ) - { - this.getDefinition().setTagCompound( (AESharedNBT) AESharedNBT.getSharedTagCompound( tagCompound, is ) ); - } - - this.setStackSize( is.stackSize ); - this.setCraftable( false ); - this.setCountRequestable( 0 ); - - this.getDefinition().reHash(); - this.getDefinition().setIsOre( OreHelper.INSTANCE.isOre( is ) ); - } - - public static IAEItemStack loadItemStackFromNBT( final NBTTagCompound i ) - { - if( i == null ) - { - return null; - } - - final ItemStack itemstack = ItemStack.loadItemStackFromNBT( i ); - if( itemstack == null ) - { - return null; - } - - final AEItemStack item = AEItemStack.create( itemstack ); - // item.priority = i.getInteger( "Priority" ); - item.setStackSize( i.getLong( "Cnt" ) ); - item.setCountRequestable( i.getLong( "Req" ) ); - item.setCraftable( i.getBoolean( "Craft" ) ); - return item; - } - - @Nullable - public static AEItemStack create( final ItemStack stack ) - { - if( stack == null ) - { - return null; - } - - return new AEItemStack( stack ); - } - - public static IAEItemStack loadItemStackFromPacket( final ByteBuf data ) throws IOException - { - final byte mask = data.readByte(); - // byte PriorityType = (byte) (mask & 0x03); - final byte stackType = (byte) ( ( mask & 0x0C ) >> 2 ); - final byte countReqType = (byte) ( ( mask & 0x30 ) >> 4 ); - final boolean isCraftable = ( mask & 0x40 ) > 0; - final boolean hasTagCompound = ( mask & 0x80 ) > 0; - - // don't send this... - final NBTTagCompound d = new NBTTagCompound(); - - d.setShort( "id", data.readShort() ); - d.setShort( "Damage", data.readShort() ); - d.setByte( "Count", (byte) 0 ); - - if( hasTagCompound ) - { - final int len = data.readInt(); - - final byte[] bd = new byte[len]; - data.readBytes( bd ); - - final ByteArrayInputStream di = new ByteArrayInputStream( bd ); - d.setTag( "tag", CompressedStreamTools.read( new DataInputStream( di ) ) ); - } - - // long priority = getPacketValue( PriorityType, data ); - final long stackSize = getPacketValue( stackType, data ); - final long countRequestable = getPacketValue( countReqType, data ); - - final ItemStack itemstack = ItemStack.loadItemStackFromNBT( d ); - if( itemstack == null ) - { - return null; - } - - final AEItemStack item = AEItemStack.create( itemstack ); - // item.priority = (int) priority; - item.setStackSize( stackSize ); - item.setCountRequestable( countRequestable ); - item.setCraftable( isCraftable ); - return item; - } - - @Override - public void add( final IAEItemStack option ) - { - if( option == null ) - { - return; - } - - // if ( priority < ((AEItemStack) option).priority ) - // priority = ((AEItemStack) option).priority; - - this.incStackSize( option.getStackSize() ); - this.setCountRequestable( this.getCountRequestable() + option.getCountRequestable() ); - this.setCraftable( this.isCraftable() || option.isCraftable() ); - } - - @Override - public void writeToNBT( final NBTTagCompound i ) - { - /* - * Mojang Fucked this over ; GC Optimization - Ugly Yes, but it saves a lot in the memory department. - */ - - /* - * NBTBase id = i.getTag( "id" ); NBTBase Count = i.getTag( "Count" ); NBTBase Cnt = i.getTag( "Cnt" ); NBTBase - * Req = i.getTag( "Req" ); NBTBase Craft = i.getTag( "Craft" ); NBTBase Damage = i.getTag( "Damage" ); - */ - - /* - * if ( id != null && id instanceof NBTTagShort ) ((NBTTagShort) id).data = (short) this.def.item.itemID; else - */ - i.setShort( "id", (short) Item.itemRegistry.getIDForObject( this.getDefinition().getItem() ) ); - - /* - * if ( Count != null && Count instanceof NBTTagByte ) ((NBTTagByte) Count).data = (byte) 0; else - */ - i.setByte( "Count", (byte) 0 ); - - /* - * if ( Cnt != null && Cnt instanceof NBTTagLong ) ((NBTTagLong) Cnt).data = this.stackSize; else - */ - i.setLong( "Cnt", this.getStackSize() ); - - /* - * if ( Req != null && Req instanceof NBTTagLong ) ((NBTTagLong) Req).data = this.stackSize; else - */ - i.setLong( "Req", this.getCountRequestable() ); - - /* - * if ( Craft != null && Craft instanceof NBTTagByte ) ((NBTTagByte) Craft).data = (byte) (this.isCraftable() ? - * 1 : 0); else - */ - i.setBoolean( "Craft", this.isCraftable() ); - - /* - * if ( Damage != null && Damage instanceof NBTTagShort ) ((NBTTagShort) Damage).data = (short) - * this.def.damageValue; else - */ - i.setShort( "Damage", (short) this.getDefinition().getDamageValue() ); - - if( this.getDefinition().getTagCompound() != null ) - { - i.setTag( "tag", this.getDefinition().getTagCompound() ); - } - else - { - i.removeTag( "tag" ); - } - } - - @Override - public boolean fuzzyComparison( final Object st, final FuzzyMode mode ) - { - if( st instanceof IAEItemStack ) - { - final IAEItemStack o = (IAEItemStack) st; - - if( this.sameOre( o ) ) - { - return true; - } - - if( o.getItem() == this.getItem() ) - { - if( this.getDefinition().getItem().isDamageable() ) - { - final ItemStack a = this.getItemStack(); - final ItemStack b = o.getItemStack(); - - try - { - if( mode == FuzzyMode.IGNORE_ALL ) - { - return true; - } - else if( mode == FuzzyMode.PERCENT_99 ) - { - return ( a.getItemDamageForDisplay() > 1 ) == ( b.getItemDamageForDisplay() > 1 ); - } - else - { - final float percentDamageOfA = 1.0f - (float) a.getItemDamageForDisplay() / (float) a.getMaxDamage(); - final float percentDamageOfB = 1.0f - (float) b.getItemDamageForDisplay() / (float) b.getMaxDamage(); - - return ( percentDamageOfA > mode.breakPoint ) == ( percentDamageOfB > mode.breakPoint ); - } - } - catch( final Throwable e ) - { - if( mode == FuzzyMode.IGNORE_ALL ) - { - return true; - } - else if( mode == FuzzyMode.PERCENT_99 ) - { - return ( a.getItemDamage() > 1 ) == ( b.getItemDamage() > 1 ); - } - else - { - final float percentDamageOfA = (float) a.getItemDamage() / (float) a.getMaxDamage(); - final float percentDamageOfB = (float) b.getItemDamage() / (float) b.getMaxDamage(); - - return ( percentDamageOfA > mode.breakPoint ) == ( percentDamageOfB > mode.breakPoint ); - } - } - } - - return this.getItemDamage() == o.getItemDamage(); - } - } - - if( st instanceof ItemStack ) - { - final ItemStack o = (ItemStack) st; - - OreHelper.INSTANCE.sameOre( this, o ); - - if( o.getItem() == this.getItem() ) - { - if( this.getDefinition().getItem().isDamageable() ) - { - final ItemStack a = this.getItemStack(); - - try - { - if( mode == FuzzyMode.IGNORE_ALL ) - { - return true; - } - else if( mode == FuzzyMode.PERCENT_99 ) - { - return ( a.getItemDamageForDisplay() > 1 ) == ( o.getItemDamageForDisplay() > 1 ); - } - else - { - final float percentDamageOfA = 1.0f - (float) a.getItemDamageForDisplay() / (float) a.getMaxDamage(); - final float percentDamageOfB = 1.0f - (float) o.getItemDamageForDisplay() / (float) o.getMaxDamage(); - - return ( percentDamageOfA > mode.breakPoint ) == ( percentDamageOfB > mode.breakPoint ); - } - } - catch( final Throwable e ) - { - if( mode == FuzzyMode.IGNORE_ALL ) - { - return true; - } - else if( mode == FuzzyMode.PERCENT_99 ) - { - return ( a.getItemDamage() > 1 ) == ( o.getItemDamage() > 1 ); - } - else - { - final float percentDamageOfA = (float) a.getItemDamage() / (float) a.getMaxDamage(); - final float percentDamageOfB = (float) o.getItemDamage() / (float) o.getMaxDamage(); - - return ( percentDamageOfA > mode.breakPoint ) == ( percentDamageOfB > mode.breakPoint ); - } - } - } - - return this.getItemDamage() == o.getItemDamage(); - } - } - - return false; - } - - @Override - public IAEItemStack copy() - { - return new AEItemStack( this ); - } - - @Override - public IAEItemStack empty() - { - final IAEItemStack dup = this.copy(); - dup.reset(); - return dup; - } - - @Override - public IAETagCompound getTagCompound() - { - return this.getDefinition().getTagCompound(); - } - - @Override - public boolean isItem() - { - return true; - } - - @Override - public boolean isFluid() - { - return false; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public ItemStack getItemStack() - { - final ItemStack is = new ItemStack( this.getDefinition().getItem(), (int) Math.min( Integer.MAX_VALUE, this.getStackSize() ), this.getDefinition().getDamageValue() ); - if( this.getDefinition().getTagCompound() != null ) - { - is.setTagCompound( this.getDefinition().getTagCompound().getNBTTagCompoundCopy() ); - } - - return is; - } - - @Override - public Item getItem() - { - return this.getDefinition().getItem(); - } - - @Override - public int getItemDamage() - { - return this.getDefinition().getDamageValue(); - } - - @Override - public boolean sameOre( final IAEItemStack is ) - { - return OreHelper.INSTANCE.sameOre( this, is ); - } - - @Override - public boolean isSameType( final IAEItemStack otherStack ) - { - if( otherStack == null ) - { - return false; - } - - return this.getDefinition().equals( ( (AEItemStack) otherStack ).getDefinition() ); - } - - @Override - public boolean isSameType( final ItemStack otherStack ) - { - if( otherStack == null ) - { - return false; - } - - return this.getDefinition().isItem( otherStack ); - } - - @Override - public int hashCode() - { - return this.getDefinition().getMyHash(); - } - - @Override - public boolean equals( final Object ia ) - { - if( ia instanceof AEItemStack ) - { - return ( (AEItemStack) ia ).getDefinition().equals( this.getDefinition() );// && def.tagCompound == - // ((AEItemStack) - // ia).def.tagCompound; - } - else if( ia instanceof ItemStack ) - { - final ItemStack is = (ItemStack) ia; - - if( is.getItem() == this.getDefinition().getItem() && is.getItemDamage() == this.getDefinition().getDamageValue() ) - { - final NBTTagCompound ta = this.getDefinition().getTagCompound(); - final NBTTagCompound tb = is.getTagCompound(); - if( ta == tb ) - { - return true; - } - - if( ( ta == null && tb == null ) || ( ta != null && ta.hasNoTags() && tb == null ) || ( tb != null && tb.hasNoTags() && ta == null ) || ( ta != null && ta.hasNoTags() && tb != null && tb.hasNoTags() ) ) - { - return true; - } - - if( ( ta == null && tb != null ) || ( ta != null && tb == null ) ) - { - return false; - } - - if( AESharedNBT.isShared( tb ) ) - { - return ta == tb; - } - - return Platform.NBTEqualityTest( ta, tb ); - } - } - return false; - } - - @Override - public String toString() - { - return this.getItemStack().toString(); - } - - @Override - public int compareTo( final AEItemStack b ) - { - final int id = this.getDefinition().getItemID() - b.getDefinition().getItemID(); - if( id != 0 ) - { - return id; - } - - final int damageValue = this.getDefinition().getDamageValue() - b.getDefinition().getDamageValue(); - if( damageValue != 0 ) - { - return damageValue; - } - - final int displayDamage = this.getDefinition().getDisplayDamage() - b.getDefinition().getDisplayDamage(); - if( displayDamage != 0 ) - { - return displayDamage; - } - - return ( this.getDefinition().getTagCompound() == b.getDefinition().getTagCompound() ) ? 0 : this.compareNBT( b.getDefinition() ); - } - - private int compareNBT( final AEItemDef b ) - { - final int nbt = this.compare( ( this.getDefinition().getTagCompound() == null ? 0 : this.getDefinition().getTagCompound().getHash() ), ( b.getTagCompound() == null ? 0 : b.getTagCompound().getHash() ) ); - if( nbt == 0 ) - { - return this.compare( System.identityHashCode( this.getDefinition().getTagCompound() ), System.identityHashCode( b.getTagCompound() ) ); - } - return nbt; - } - - private int compare( final int l, final int m ) - { - return l < m ? -1 : ( l > m ? 1 : 0 ); - } - - @SideOnly( Side.CLIENT ) - public List getToolTip() - { - if( this.getDefinition().getTooltip() != null ) - { - return this.getDefinition().getTooltip(); - } - - return this.getDefinition().setTooltip( Platform.getTooltip( this.getItemStack() ) ); - } - - @SideOnly( Side.CLIENT ) - public String getDisplayName() - { - if( this.getDefinition().getDisplayName() == null ) - { - this.getDefinition().setDisplayName( Platform.getItemDisplayName( this.getItemStack() ) ); - } - - return this.getDefinition().getDisplayName(); - } - - @SideOnly( Side.CLIENT ) - public String getModID() - { - if( this.getDefinition().getUniqueID() != null ) - { - return this.getModName( this.getDefinition().getUniqueID() ); - } - - return this.getModName( this.getDefinition().setUniqueID( GameRegistry.findUniqueIdentifierFor( this.getDefinition().getItem() ) ) ); - } - - private String getModName( final UniqueIdentifier uniqueIdentifier ) - { - if( uniqueIdentifier == null ) - { - return "** Null"; - } - - return uniqueIdentifier.modId == null ? "** Null" : uniqueIdentifier.modId; - } - - IAEItemStack getLow( final FuzzyMode fuzzy, final boolean ignoreMeta ) - { - final AEItemStack bottom = new AEItemStack( this ); - final AEItemDef newDef = bottom.setDefinition( bottom.getDefinition().copy() ); - - if( ignoreMeta ) - { - newDef.setDisplayDamage( newDef.setDamageValue( 0 ) ); - newDef.reHash(); - return bottom; - } - - if( newDef.getItem().isDamageable() ) - { - if( fuzzy == FuzzyMode.IGNORE_ALL ) - { - newDef.setDisplayDamage( 0 ); - } - else if( fuzzy == FuzzyMode.PERCENT_99 ) - { - if( this.getDefinition().getDamageValue() == 0 ) - { - newDef.setDisplayDamage( 0 ); - } - else - { - newDef.setDisplayDamage( 1 ); - } - } - else - { - final int breakpoint = fuzzy.calculateBreakPoint( this.getDefinition().getMaxDamage() ); - newDef.setDisplayDamage( breakpoint <= this.getDefinition().getDisplayDamage() ? breakpoint : 0 ); - } - - newDef.setDamageValue( newDef.getDisplayDamage() ); - } - - newDef.setTagCompound( AEItemDef.LOW_TAG ); - newDef.reHash(); - return bottom; - } - - IAEItemStack getHigh( final FuzzyMode fuzzy, final boolean ignoreMeta ) - { - final AEItemStack top = new AEItemStack( this ); - final AEItemDef newDef = top.setDefinition( top.getDefinition().copy() ); - - if( ignoreMeta ) - { - newDef.setDisplayDamage( newDef.setDamageValue( Integer.MAX_VALUE ) ); - newDef.reHash(); - return top; - } - - if( newDef.getItem().isDamageable() ) - { - if( fuzzy == FuzzyMode.IGNORE_ALL ) - { - newDef.setDisplayDamage( this.getDefinition().getMaxDamage() + 1 ); - } - else if( fuzzy == FuzzyMode.PERCENT_99 ) - { - if( this.getDefinition().getDamageValue() == 0 ) - { - newDef.setDisplayDamage( 0 ); - } - else - { - newDef.setDisplayDamage( this.getDefinition().getMaxDamage() + 1 ); - } - } - else - { - final int breakpoint = fuzzy.calculateBreakPoint( this.getDefinition().getMaxDamage() ); - newDef.setDisplayDamage( this.getDefinition().getDisplayDamage() < breakpoint ? breakpoint - 1 : this.getDefinition().getMaxDamage() + 1 ); - } - - newDef.setDamageValue( newDef.getDisplayDamage() ); - } - - newDef.setTagCompound( AEItemDef.HIGH_TAG ); - newDef.reHash(); - return top; - } - - public boolean isOre() - { - return this.getDefinition().getIsOre() != null; - } - - @Override - void writeIdentity( final ByteBuf i ) throws IOException - { - i.writeShort( Item.itemRegistry.getIDForObject( this.getDefinition().getItem() ) ); - i.writeShort( this.getItemDamage() ); - } - - @Override - void readNBT( final ByteBuf i ) throws IOException - { - if( this.hasTagCompound() ) - { - final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - final DataOutputStream data = new DataOutputStream( bytes ); - - CompressedStreamTools.write( (NBTTagCompound) this.getTagCompound(), data ); - - final byte[] tagBytes = bytes.toByteArray(); - final int size = tagBytes.length; - - i.writeInt( size ); - i.writeBytes( tagBytes ); - } - } - - @Override - public boolean hasTagCompound() - { - return this.getDefinition().getTagCompound() != null; - } - - AEItemDef getDefinition() - { - return this.def; - } - - private AEItemDef setDefinition( final AEItemDef def ) - { - this.def = def; - return def; - } +public final class AEItemStack extends AEStack implements IAEItemStack, Comparable { + + private AEItemDef def; + + private AEItemStack(final AEItemStack is) { + this.setDefinition(is.getDefinition()); + this.setStackSize(is.getStackSize()); + this.setCraftable(is.isCraftable()); + this.setCountRequestable(is.getCountRequestable()); + } + + private AEItemStack(final ItemStack is) { + if (is == null) { + throw new InvalidParameterException("null is not a valid ItemStack for AEItemStack."); + } + + final Item item = is.getItem(); + if (item == null) { + throw new InvalidParameterException("Contained item is null, thus not a valid ItemStack for AEItemStack."); + } + + this.setDefinition(new AEItemDef(item)); + + if (this.getDefinition().getItem() == null) { + throw new InvalidParameterException("This ItemStack is bad, it has a null item."); + } + + /* + * Prevent an Item from changing the damage value on me... Either, this or a core mod. + */ + + /* + * Super hackery. + * is.itemID = appeng.api.Materials.matQuartz.itemID; damageValue = is.getItemDamage(); is.itemID = itemID; + */ + + /* + * Kinda hackery + */ + this.getDefinition().setDamageValue(this.getDefinition().getDamageValueHack(is)); + this.getDefinition().setDisplayDamage(is.getItemDamageForDisplay()); + this.getDefinition().setMaxDamage(is.getMaxDamage()); + + final NBTTagCompound tagCompound = is.getTagCompound(); + if (tagCompound != null) { + this.getDefinition().setTagCompound((AESharedNBT) AESharedNBT.getSharedTagCompound(tagCompound, is)); + } + + this.setStackSize(is.stackSize); + this.setCraftable(false); + this.setCountRequestable(0); + + this.getDefinition().reHash(); + this.getDefinition().setIsOre(OreHelper.INSTANCE.isOre(is)); + } + + public static IAEItemStack loadItemStackFromNBT(final NBTTagCompound i) { + if (i == null) { + return null; + } + + final ItemStack itemstack = ItemStack.loadItemStackFromNBT(i); + if (itemstack == null) { + return null; + } + + final AEItemStack item = AEItemStack.create(itemstack); + // item.priority = i.getInteger( "Priority" ); + item.setStackSize(i.getLong("Cnt")); + item.setCountRequestable(i.getLong("Req")); + item.setCraftable(i.getBoolean("Craft")); + return item; + } + + @Nullable + public static AEItemStack create(final ItemStack stack) { + if (stack == null) { + return null; + } + + return new AEItemStack(stack); + } + + public static IAEItemStack loadItemStackFromPacket(final ByteBuf data) throws IOException { + final byte mask = data.readByte(); + // byte PriorityType = (byte) (mask & 0x03); + final byte stackType = (byte) ((mask & 0x0C) >> 2); + final byte countReqType = (byte) ((mask & 0x30) >> 4); + final boolean isCraftable = (mask & 0x40) > 0; + final boolean hasTagCompound = (mask & 0x80) > 0; + + // don't send this... + final NBTTagCompound d = new NBTTagCompound(); + + d.setShort("id", data.readShort()); + d.setShort("Damage", data.readShort()); + d.setByte("Count", (byte) 0); + + if (hasTagCompound) { + final int len = data.readInt(); + + final byte[] bd = new byte[len]; + data.readBytes(bd); + + final ByteArrayInputStream di = new ByteArrayInputStream(bd); + d.setTag("tag", CompressedStreamTools.read(new DataInputStream(di))); + } + + // long priority = getPacketValue( PriorityType, data ); + final long stackSize = getPacketValue(stackType, data); + final long countRequestable = getPacketValue(countReqType, data); + + final ItemStack itemstack = ItemStack.loadItemStackFromNBT(d); + if (itemstack == null) { + return null; + } + + final AEItemStack item = AEItemStack.create(itemstack); + // item.priority = (int) priority; + item.setStackSize(stackSize); + item.setCountRequestable(countRequestable); + item.setCraftable(isCraftable); + return item; + } + + @Override + public void add(final IAEItemStack option) { + if (option == null) { + return; + } + + // if ( priority < ((AEItemStack) option).priority ) + // priority = ((AEItemStack) option).priority; + + this.incStackSize(option.getStackSize()); + this.setCountRequestable(this.getCountRequestable() + option.getCountRequestable()); + this.setCraftable(this.isCraftable() || option.isCraftable()); + } + + @Override + public void writeToNBT(final NBTTagCompound i) { + /* + * Mojang Fucked this over ; GC Optimization - Ugly Yes, but it saves a lot in the memory department. + */ + + /* + * NBTBase id = i.getTag( "id" ); NBTBase Count = i.getTag( "Count" ); NBTBase Cnt = i.getTag( "Cnt" ); NBTBase + * Req = i.getTag( "Req" ); NBTBase Craft = i.getTag( "Craft" ); NBTBase Damage = i.getTag( "Damage" ); + */ + + /* + * if ( id != null && id instanceof NBTTagShort ) ((NBTTagShort) id).data = (short) this.def.item.itemID; else + */ + i.setShort("id", (short) + Item.itemRegistry.getIDForObject(this.getDefinition().getItem())); + + /* + * if ( Count != null && Count instanceof NBTTagByte ) ((NBTTagByte) Count).data = (byte) 0; else + */ + i.setByte("Count", (byte) 0); + + /* + * if ( Cnt != null && Cnt instanceof NBTTagLong ) ((NBTTagLong) Cnt).data = this.stackSize; else + */ + i.setLong("Cnt", this.getStackSize()); + + /* + * if ( Req != null && Req instanceof NBTTagLong ) ((NBTTagLong) Req).data = this.stackSize; else + */ + i.setLong("Req", this.getCountRequestable()); + + /* + * if ( Craft != null && Craft instanceof NBTTagByte ) ((NBTTagByte) Craft).data = (byte) (this.isCraftable() ? + * 1 : 0); else + */ + i.setBoolean("Craft", this.isCraftable()); + + /* + * if ( Damage != null && Damage instanceof NBTTagShort ) ((NBTTagShort) Damage).data = (short) + * this.def.damageValue; else + */ + i.setShort("Damage", (short) this.getDefinition().getDamageValue()); + + if (this.getDefinition().getTagCompound() != null) { + i.setTag("tag", this.getDefinition().getTagCompound()); + } else { + i.removeTag("tag"); + } + } + + @Override + public boolean fuzzyComparison(final Object st, final FuzzyMode mode) { + if (st instanceof IAEItemStack) { + final IAEItemStack o = (IAEItemStack) st; + + if (this.sameOre(o)) { + return true; + } + + if (o.getItem() == this.getItem()) { + if (this.getDefinition().getItem().isDamageable()) { + final ItemStack a = this.getItemStack(); + final ItemStack b = o.getItemStack(); + + try { + if (mode == FuzzyMode.IGNORE_ALL) { + return true; + } else if (mode == FuzzyMode.PERCENT_99) { + return (a.getItemDamageForDisplay() > 1) == (b.getItemDamageForDisplay() > 1); + } else { + final float percentDamageOfA = + 1.0f - (float) a.getItemDamageForDisplay() / (float) a.getMaxDamage(); + final float percentDamageOfB = + 1.0f - (float) b.getItemDamageForDisplay() / (float) b.getMaxDamage(); + + return (percentDamageOfA > mode.breakPoint) == (percentDamageOfB > mode.breakPoint); + } + } catch (final Throwable e) { + if (mode == FuzzyMode.IGNORE_ALL) { + return true; + } else if (mode == FuzzyMode.PERCENT_99) { + return (a.getItemDamage() > 1) == (b.getItemDamage() > 1); + } else { + final float percentDamageOfA = (float) a.getItemDamage() / (float) a.getMaxDamage(); + final float percentDamageOfB = (float) b.getItemDamage() / (float) b.getMaxDamage(); + + return (percentDamageOfA > mode.breakPoint) == (percentDamageOfB > mode.breakPoint); + } + } + } + + return this.getItemDamage() == o.getItemDamage(); + } + } + + if (st instanceof ItemStack) { + final ItemStack o = (ItemStack) st; + + OreHelper.INSTANCE.sameOre(this, o); + + if (o.getItem() == this.getItem()) { + if (this.getDefinition().getItem().isDamageable()) { + final ItemStack a = this.getItemStack(); + + try { + if (mode == FuzzyMode.IGNORE_ALL) { + return true; + } else if (mode == FuzzyMode.PERCENT_99) { + return (a.getItemDamageForDisplay() > 1) == (o.getItemDamageForDisplay() > 1); + } else { + final float percentDamageOfA = + 1.0f - (float) a.getItemDamageForDisplay() / (float) a.getMaxDamage(); + final float percentDamageOfB = + 1.0f - (float) o.getItemDamageForDisplay() / (float) o.getMaxDamage(); + + return (percentDamageOfA > mode.breakPoint) == (percentDamageOfB > mode.breakPoint); + } + } catch (final Throwable e) { + if (mode == FuzzyMode.IGNORE_ALL) { + return true; + } else if (mode == FuzzyMode.PERCENT_99) { + return (a.getItemDamage() > 1) == (o.getItemDamage() > 1); + } else { + final float percentDamageOfA = (float) a.getItemDamage() / (float) a.getMaxDamage(); + final float percentDamageOfB = (float) o.getItemDamage() / (float) o.getMaxDamage(); + + return (percentDamageOfA > mode.breakPoint) == (percentDamageOfB > mode.breakPoint); + } + } + } + + return this.getItemDamage() == o.getItemDamage(); + } + } + + return false; + } + + @Override + public IAEItemStack copy() { + return new AEItemStack(this); + } + + @Override + public IAEItemStack empty() { + final IAEItemStack dup = this.copy(); + dup.reset(); + return dup; + } + + @Override + public IAETagCompound getTagCompound() { + return this.getDefinition().getTagCompound(); + } + + @Override + public boolean isItem() { + return true; + } + + @Override + public boolean isFluid() { + return false; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } + + @Override + public ItemStack getItemStack() { + final ItemStack is = new ItemStack( + this.getDefinition().getItem(), + (int) Math.min(Integer.MAX_VALUE, this.getStackSize()), + this.getDefinition().getDamageValue()); + if (this.getDefinition().getTagCompound() != null) { + is.setTagCompound(this.getDefinition().getTagCompound().getNBTTagCompoundCopy()); + } + + return is; + } + + @Override + public Item getItem() { + return this.getDefinition().getItem(); + } + + @Override + public int getItemDamage() { + return this.getDefinition().getDamageValue(); + } + + @Override + public boolean sameOre(final IAEItemStack is) { + return OreHelper.INSTANCE.sameOre(this, is); + } + + @Override + public boolean isSameType(final IAEItemStack otherStack) { + if (otherStack == null) { + return false; + } + + return this.getDefinition().equals(((AEItemStack) otherStack).getDefinition()); + } + + @Override + public boolean isSameType(final ItemStack otherStack) { + if (otherStack == null) { + return false; + } + + return this.getDefinition().isItem(otherStack); + } + + @Override + public int hashCode() { + return this.getDefinition().getMyHash(); + } + + @Override + public boolean equals(final Object ia) { + if (ia instanceof AEItemStack) { + return ((AEItemStack) ia).getDefinition().equals(this.getDefinition()); // && def.tagCompound == + // ((AEItemStack) + // ia).def.tagCompound; + } else if (ia instanceof ItemStack) { + final ItemStack is = (ItemStack) ia; + + if (is.getItem() == this.getDefinition().getItem() + && is.getItemDamage() == this.getDefinition().getDamageValue()) { + final NBTTagCompound ta = this.getDefinition().getTagCompound(); + final NBTTagCompound tb = is.getTagCompound(); + if (ta == tb) { + return true; + } + + if ((ta == null && tb == null) + || (ta != null && ta.hasNoTags() && tb == null) + || (tb != null && tb.hasNoTags() && ta == null) + || (ta != null && ta.hasNoTags() && tb != null && tb.hasNoTags())) { + return true; + } + + if ((ta == null && tb != null) || (ta != null && tb == null)) { + return false; + } + + if (AESharedNBT.isShared(tb)) { + return ta == tb; + } + + return Platform.NBTEqualityTest(ta, tb); + } + } + return false; + } + + @Override + public String toString() { + return this.getItemStack().toString(); + } + + @Override + public int compareTo(final AEItemStack b) { + final int id = this.getDefinition().getItemID() - b.getDefinition().getItemID(); + if (id != 0) { + return id; + } + + final int damageValue = + this.getDefinition().getDamageValue() - b.getDefinition().getDamageValue(); + if (damageValue != 0) { + return damageValue; + } + + final int displayDamage = + this.getDefinition().getDisplayDamage() - b.getDefinition().getDisplayDamage(); + if (displayDamage != 0) { + return displayDamage; + } + + return (this.getDefinition().getTagCompound() == b.getDefinition().getTagCompound()) + ? 0 + : this.compareNBT(b.getDefinition()); + } + + private int compareNBT(final AEItemDef b) { + final int nbt = this.compare( + (this.getDefinition().getTagCompound() == null + ? 0 + : this.getDefinition().getTagCompound().getHash()), + (b.getTagCompound() == null ? 0 : b.getTagCompound().getHash())); + if (nbt == 0) { + return this.compare( + System.identityHashCode(this.getDefinition().getTagCompound()), + System.identityHashCode(b.getTagCompound())); + } + return nbt; + } + + private int compare(final int l, final int m) { + return l < m ? -1 : (l > m ? 1 : 0); + } + + @SideOnly(Side.CLIENT) + public List getToolTip() { + if (this.getDefinition().getTooltip() != null) { + return this.getDefinition().getTooltip(); + } + + return this.getDefinition().setTooltip(Platform.getTooltip(this.getItemStack())); + } + + @SideOnly(Side.CLIENT) + public String getDisplayName() { + if (this.getDefinition().getDisplayName() == null) { + this.getDefinition().setDisplayName(Platform.getItemDisplayName(this.getItemStack())); + } + + return this.getDefinition().getDisplayName(); + } + + @SideOnly(Side.CLIENT) + public String getModID() { + if (this.getDefinition().getUniqueID() != null) { + return this.getModName(this.getDefinition().getUniqueID()); + } + + return this.getModName(this.getDefinition() + .setUniqueID(GameRegistry.findUniqueIdentifierFor( + this.getDefinition().getItem()))); + } + + private String getModName(final UniqueIdentifier uniqueIdentifier) { + if (uniqueIdentifier == null) { + return "** Null"; + } + + return uniqueIdentifier.modId == null ? "** Null" : uniqueIdentifier.modId; + } + + IAEItemStack getLow(final FuzzyMode fuzzy, final boolean ignoreMeta) { + final AEItemStack bottom = new AEItemStack(this); + final AEItemDef newDef = bottom.setDefinition(bottom.getDefinition().copy()); + + if (ignoreMeta) { + newDef.setDisplayDamage(newDef.setDamageValue(0)); + newDef.reHash(); + return bottom; + } + + if (newDef.getItem().isDamageable()) { + if (fuzzy == FuzzyMode.IGNORE_ALL) { + newDef.setDisplayDamage(0); + } else if (fuzzy == FuzzyMode.PERCENT_99) { + if (this.getDefinition().getDamageValue() == 0) { + newDef.setDisplayDamage(0); + } else { + newDef.setDisplayDamage(1); + } + } else { + final int breakpoint = + fuzzy.calculateBreakPoint(this.getDefinition().getMaxDamage()); + newDef.setDisplayDamage(breakpoint <= this.getDefinition().getDisplayDamage() ? breakpoint : 0); + } + + newDef.setDamageValue(newDef.getDisplayDamage()); + } + + newDef.setTagCompound(AEItemDef.LOW_TAG); + newDef.reHash(); + return bottom; + } + + IAEItemStack getHigh(final FuzzyMode fuzzy, final boolean ignoreMeta) { + final AEItemStack top = new AEItemStack(this); + final AEItemDef newDef = top.setDefinition(top.getDefinition().copy()); + + if (ignoreMeta) { + newDef.setDisplayDamage(newDef.setDamageValue(Integer.MAX_VALUE)); + newDef.reHash(); + return top; + } + + if (newDef.getItem().isDamageable()) { + if (fuzzy == FuzzyMode.IGNORE_ALL) { + newDef.setDisplayDamage(this.getDefinition().getMaxDamage() + 1); + } else if (fuzzy == FuzzyMode.PERCENT_99) { + if (this.getDefinition().getDamageValue() == 0) { + newDef.setDisplayDamage(0); + } else { + newDef.setDisplayDamage(this.getDefinition().getMaxDamage() + 1); + } + } else { + final int breakpoint = + fuzzy.calculateBreakPoint(this.getDefinition().getMaxDamage()); + newDef.setDisplayDamage( + this.getDefinition().getDisplayDamage() < breakpoint + ? breakpoint - 1 + : this.getDefinition().getMaxDamage() + 1); + } + + newDef.setDamageValue(newDef.getDisplayDamage()); + } + + newDef.setTagCompound(AEItemDef.HIGH_TAG); + newDef.reHash(); + return top; + } + + public boolean isOre() { + return this.getDefinition().getIsOre() != null; + } + + @Override + void writeIdentity(final ByteBuf i) throws IOException { + i.writeShort(Item.itemRegistry.getIDForObject(this.getDefinition().getItem())); + i.writeShort(this.getItemDamage()); + } + + @Override + void readNBT(final ByteBuf i) throws IOException { + if (this.hasTagCompound()) { + final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + final DataOutputStream data = new DataOutputStream(bytes); + + CompressedStreamTools.write((NBTTagCompound) this.getTagCompound(), data); + + final byte[] tagBytes = bytes.toByteArray(); + final int size = tagBytes.length; + + i.writeInt(size); + i.writeBytes(tagBytes); + } + } + + @Override + public boolean hasTagCompound() { + return this.getDefinition().getTagCompound() != null; + } + + AEItemDef getDefinition() { + return this.def; + } + + private AEItemDef setDefinition(final AEItemDef def) { + this.def = def; + return def; + } } diff --git a/src/main/java/appeng/util/item/AESharedNBT.java b/src/main/java/appeng/util/item/AESharedNBT.java index 2dc1469198d..bd22390ebbc 100644 --- a/src/main/java/appeng/util/item/AESharedNBT.java +++ b/src/main/java/appeng/util/item/AESharedNBT.java @@ -18,200 +18,171 @@ package appeng.util.item; - import appeng.api.AEApi; import appeng.api.features.IItemComparison; import appeng.api.storage.data.IAETagCompound; import appeng.util.Platform; +import java.lang.ref.WeakReference; +import java.util.WeakHashMap; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.lang.ref.WeakReference; -import java.util.WeakHashMap; - - /* * this is used for the shared NBT Cache. */ -public class AESharedNBT extends NBTTagCompound implements IAETagCompound -{ - - /* - * Shared Tag Compound Cache. - */ - private static final WeakHashMap> SHARED_TAG_COMPOUND = new WeakHashMap>(); - private final Item item; - private final int meta; - private SharedSearchObject sso; - private int hash; - private IItemComparison comp; - - private AESharedNBT( final Item itemID, final int damageValue ) - { - this.item = itemID; - this.meta = damageValue; - } - - public AESharedNBT( final int fakeValue ) - { - this.item = null; - this.meta = 0; - this.hash = fakeValue; - } - - /* - * Debug purposes. - */ - public static int sharedTagLoad() - { - return SHARED_TAG_COMPOUND.size(); - } - - /* - * Returns an NBT Compound that is used for accelerating comparisons. - */ - static synchronized NBTTagCompound getSharedTagCompound( final NBTTagCompound tagCompound, final ItemStack s ) - { - if( tagCompound.hasNoTags() ) - { - return null; - } - - final Item item = s.getItem(); - int meta = -1; - if( s.getItem() != null && s.isItemStackDamageable() && s.getHasSubtypes() ) - { - meta = s.getItemDamage(); - } - - if( isShared( tagCompound ) ) - { - return tagCompound; - } - - final SharedSearchObject sso = new SharedSearchObject( item, meta, tagCompound ); - - final WeakReference c = SHARED_TAG_COMPOUND.get( sso ); - if( c != null ) - { - final SharedSearchObject cg = c.get(); - if( cg != null ) - { - return cg.getShared(); // I don't think I really need to check this - } - // as its already certain to exist.. - } - - final AESharedNBT clone = AESharedNBT.createFromCompound( item, meta, tagCompound ); - sso.setCompound( (NBTTagCompound) sso.getCompound().copy() ); // prevent - // modification - // of data based - // on original - // item. - sso.setShared( clone ); - clone.sso = sso; - - SHARED_TAG_COMPOUND.put( sso, new WeakReference( sso ) ); - return clone; - } - - /* - * returns true if the compound is part of the shared compound system ( and can thus be compared directly ). - */ - public static boolean isShared( final NBTTagCompound ta ) - { - return ta instanceof AESharedNBT; - } - - private static AESharedNBT createFromCompound( final Item itemID, final int damageValue, final NBTTagCompound c ) - { - final AESharedNBT x = new AESharedNBT( itemID, damageValue ); - - // c.getTags() - for( final Object o : c.func_150296_c() ) - { - final String name = (String) o; - x.setTag( name, c.getTag( name ).copy() ); - } - - x.hash = Platform.NBTOrderlessHash( c ); - - final ItemStack isc = new ItemStack( itemID, 1, damageValue ); - isc.setTagCompound( c ); - x.comp = AEApi.instance().registries().specialComparison().getSpecialComparison( isc ); - - return x; - } - - int getHash() - { - return this.hash; - } - - @Override - public NBTTagCompound getNBTTagCompoundCopy() - { - return (NBTTagCompound) this.copy(); - } - - @Override - public IItemComparison getSpecialComparison() - { - return this.comp; - } - - @Override - public boolean equals( final Object par1Obj ) - { - if( par1Obj instanceof AESharedNBT ) - { - return this == par1Obj; - } - return super.equals( par1Obj ); - } - - public boolean matches( final Item item, final int meta, final int orderlessHash ) - { - return item == this.item && this.meta == meta && this.hash == orderlessHash; - } - - public boolean comparePreciseWithRegistry( final AESharedNBT tagCompound ) - { - if( this == tagCompound ) - { - return true; - } - - if( this.comp != null && tagCompound.comp != null ) - { - return this.comp.sameAsPrecise( tagCompound.comp ); - } - - return false; - } - - public boolean compareFuzzyWithRegistry( final AESharedNBT tagCompound ) - { - if( this == tagCompound ) - { - return true; - } - if( tagCompound == null ) - { - return false; - } - - if( this.comp == tagCompound.comp ) - { - return true; - } - - if( this.comp != null ) - { - return this.comp.sameAsFuzzy( tagCompound.comp ); - } - - return false; - } +public class AESharedNBT extends NBTTagCompound implements IAETagCompound { + + /* + * Shared Tag Compound Cache. + */ + private static final WeakHashMap> SHARED_TAG_COMPOUND = + new WeakHashMap>(); + private final Item item; + private final int meta; + private SharedSearchObject sso; + private int hash; + private IItemComparison comp; + + private AESharedNBT(final Item itemID, final int damageValue) { + this.item = itemID; + this.meta = damageValue; + } + + public AESharedNBT(final int fakeValue) { + this.item = null; + this.meta = 0; + this.hash = fakeValue; + } + + /* + * Debug purposes. + */ + public static int sharedTagLoad() { + return SHARED_TAG_COMPOUND.size(); + } + + /* + * Returns an NBT Compound that is used for accelerating comparisons. + */ + static synchronized NBTTagCompound getSharedTagCompound(final NBTTagCompound tagCompound, final ItemStack s) { + if (tagCompound.hasNoTags()) { + return null; + } + + final Item item = s.getItem(); + int meta = -1; + if (s.getItem() != null && s.isItemStackDamageable() && s.getHasSubtypes()) { + meta = s.getItemDamage(); + } + + if (isShared(tagCompound)) { + return tagCompound; + } + + final SharedSearchObject sso = new SharedSearchObject(item, meta, tagCompound); + + final WeakReference c = SHARED_TAG_COMPOUND.get(sso); + if (c != null) { + final SharedSearchObject cg = c.get(); + if (cg != null) { + return cg.getShared(); // I don't think I really need to check this + } + // as its already certain to exist.. + } + + final AESharedNBT clone = AESharedNBT.createFromCompound(item, meta, tagCompound); + sso.setCompound((NBTTagCompound) sso.getCompound().copy()); // prevent + // modification + // of data based + // on original + // item. + sso.setShared(clone); + clone.sso = sso; + + SHARED_TAG_COMPOUND.put(sso, new WeakReference(sso)); + return clone; + } + + /* + * returns true if the compound is part of the shared compound system ( and can thus be compared directly ). + */ + public static boolean isShared(final NBTTagCompound ta) { + return ta instanceof AESharedNBT; + } + + private static AESharedNBT createFromCompound(final Item itemID, final int damageValue, final NBTTagCompound c) { + final AESharedNBT x = new AESharedNBT(itemID, damageValue); + + // c.getTags() + for (final Object o : c.func_150296_c()) { + final String name = (String) o; + x.setTag(name, c.getTag(name).copy()); + } + + x.hash = Platform.NBTOrderlessHash(c); + + final ItemStack isc = new ItemStack(itemID, 1, damageValue); + isc.setTagCompound(c); + x.comp = AEApi.instance().registries().specialComparison().getSpecialComparison(isc); + + return x; + } + + int getHash() { + return this.hash; + } + + @Override + public NBTTagCompound getNBTTagCompoundCopy() { + return (NBTTagCompound) this.copy(); + } + + @Override + public IItemComparison getSpecialComparison() { + return this.comp; + } + + @Override + public boolean equals(final Object par1Obj) { + if (par1Obj instanceof AESharedNBT) { + return this == par1Obj; + } + return super.equals(par1Obj); + } + + public boolean matches(final Item item, final int meta, final int orderlessHash) { + return item == this.item && this.meta == meta && this.hash == orderlessHash; + } + + public boolean comparePreciseWithRegistry(final AESharedNBT tagCompound) { + if (this == tagCompound) { + return true; + } + + if (this.comp != null && tagCompound.comp != null) { + return this.comp.sameAsPrecise(tagCompound.comp); + } + + return false; + } + + public boolean compareFuzzyWithRegistry(final AESharedNBT tagCompound) { + if (this == tagCompound) { + return true; + } + if (tagCompound == null) { + return false; + } + + if (this.comp == tagCompound.comp) { + return true; + } + + if (this.comp != null) { + return this.comp.sameAsFuzzy(tagCompound.comp); + } + + return false; + } } diff --git a/src/main/java/appeng/util/item/AEStack.java b/src/main/java/appeng/util/item/AEStack.java index 1bdfe896e13..6d40c46881c 100644 --- a/src/main/java/appeng/util/item/AEStack.java +++ b/src/main/java/appeng/util/item/AEStack.java @@ -18,181 +18,146 @@ package appeng.util.item; - import appeng.api.storage.data.IAEStack; import io.netty.buffer.ByteBuf; - import java.io.IOException; - -public abstract class AEStack implements IAEStack -{ - - private boolean isCraftable; - private long stackSize; - private long countRequestable; - - static long getPacketValue( final byte type, final ByteBuf tag ) - { - if( type == 0 ) - { - long l = tag.readByte(); - l -= Byte.MIN_VALUE; - return l; - } - else if( type == 1 ) - { - long l = tag.readShort(); - l -= Short.MIN_VALUE; - return l; - } - else if( type == 2 ) - { - long l = tag.readInt(); - l -= Integer.MIN_VALUE; - return l; - } - - return tag.readLong(); - } - - @Override - public long getStackSize() - { - return this.stackSize; - } - - @Override - public StackType setStackSize( final long ss ) - { - this.stackSize = ss; - return (StackType) this; - } - - @Override - public long getCountRequestable() - { - return this.countRequestable; - } - - @Override - public StackType setCountRequestable( final long countRequestable ) - { - this.countRequestable = countRequestable; - return (StackType) this; - } - - @Override - public boolean isCraftable() - { - return this.isCraftable; - } - - @Override - public StackType setCraftable( final boolean isCraftable ) - { - this.isCraftable = isCraftable; - return (StackType) this; - } - - @Override - public StackType reset() - { - this.stackSize = 0; - // priority = Integer.MIN_VALUE; - this.setCountRequestable( 0 ); - this.setCraftable( false ); - return (StackType) this; - } - - @Override - public boolean isMeaningful() - { - return this.stackSize != 0 || this.countRequestable > 0 || this.isCraftable; - } - - @Override - public void incStackSize( final long i ) - { - this.stackSize += i; - } - - @Override - public void decStackSize( final long i ) - { - this.stackSize -= i; - } - - @Override - public void incCountRequestable( final long i ) - { - this.countRequestable += i; - } - - @Override - public void decCountRequestable( final long i ) - { - this.countRequestable -= i; - } - - @Override - public void writeToPacket( final ByteBuf i ) throws IOException - { - final byte mask = (byte) ( this.getType( 0 ) | ( this.getType( this.stackSize ) << 2 ) | ( this.getType( this.countRequestable ) << 4 ) | ( (byte) ( this.isCraftable ? 1 : 0 ) << 6 ) | ( this.hasTagCompound() ? 1 : 0 ) << 7 ); - - i.writeByte( mask ); - this.writeIdentity( i ); - - this.readNBT( i ); - - // putPacketValue( i, priority ); - this.putPacketValue( i, this.stackSize ); - this.putPacketValue( i, this.countRequestable ); - } - - private byte getType( final long num ) - { - if( num <= 255 ) - { - return 0; - } - else if( num <= 65535 ) - { - return 1; - } - else if( num <= 4294967295L ) - { - return 2; - } - else - { - return 3; - } - } - - abstract boolean hasTagCompound(); - - abstract void writeIdentity( ByteBuf i ) throws IOException; - - abstract void readNBT( ByteBuf i ) throws IOException; - - private void putPacketValue( final ByteBuf tag, final long num ) - { - if( num <= 255 ) - { - tag.writeByte( (byte) ( num + Byte.MIN_VALUE ) ); - } - else if( num <= 65535 ) - { - tag.writeShort( (short) ( num + Short.MIN_VALUE ) ); - } - else if( num <= 4294967295L ) - { - tag.writeInt( (int) ( num + Integer.MIN_VALUE ) ); - } - else - { - tag.writeLong( num ); - } - } +public abstract class AEStack implements IAEStack { + + private boolean isCraftable; + private long stackSize; + private long countRequestable; + + static long getPacketValue(final byte type, final ByteBuf tag) { + if (type == 0) { + long l = tag.readByte(); + l -= Byte.MIN_VALUE; + return l; + } else if (type == 1) { + long l = tag.readShort(); + l -= Short.MIN_VALUE; + return l; + } else if (type == 2) { + long l = tag.readInt(); + l -= Integer.MIN_VALUE; + return l; + } + + return tag.readLong(); + } + + @Override + public long getStackSize() { + return this.stackSize; + } + + @Override + public StackType setStackSize(final long ss) { + this.stackSize = ss; + return (StackType) this; + } + + @Override + public long getCountRequestable() { + return this.countRequestable; + } + + @Override + public StackType setCountRequestable(final long countRequestable) { + this.countRequestable = countRequestable; + return (StackType) this; + } + + @Override + public boolean isCraftable() { + return this.isCraftable; + } + + @Override + public StackType setCraftable(final boolean isCraftable) { + this.isCraftable = isCraftable; + return (StackType) this; + } + + @Override + public StackType reset() { + this.stackSize = 0; + // priority = Integer.MIN_VALUE; + this.setCountRequestable(0); + this.setCraftable(false); + return (StackType) this; + } + + @Override + public boolean isMeaningful() { + return this.stackSize != 0 || this.countRequestable > 0 || this.isCraftable; + } + + @Override + public void incStackSize(final long i) { + this.stackSize += i; + } + + @Override + public void decStackSize(final long i) { + this.stackSize -= i; + } + + @Override + public void incCountRequestable(final long i) { + this.countRequestable += i; + } + + @Override + public void decCountRequestable(final long i) { + this.countRequestable -= i; + } + + @Override + public void writeToPacket(final ByteBuf i) throws IOException { + final byte mask = (byte) (this.getType(0) + | (this.getType(this.stackSize) << 2) + | (this.getType(this.countRequestable) << 4) + | ((byte) (this.isCraftable ? 1 : 0) << 6) + | (this.hasTagCompound() ? 1 : 0) << 7); + + i.writeByte(mask); + this.writeIdentity(i); + + this.readNBT(i); + + // putPacketValue( i, priority ); + this.putPacketValue(i, this.stackSize); + this.putPacketValue(i, this.countRequestable); + } + + private byte getType(final long num) { + if (num <= 255) { + return 0; + } else if (num <= 65535) { + return 1; + } else if (num <= 4294967295L) { + return 2; + } else { + return 3; + } + } + + abstract boolean hasTagCompound(); + + abstract void writeIdentity(ByteBuf i) throws IOException; + + abstract void readNBT(ByteBuf i) throws IOException; + + private void putPacketValue(final ByteBuf tag, final long num) { + if (num <= 255) { + tag.writeByte((byte) (num + Byte.MIN_VALUE)); + } else if (num <= 65535) { + tag.writeShort((short) (num + Short.MIN_VALUE)); + } else if (num <= 4294967295L) { + tag.writeInt((int) (num + Integer.MIN_VALUE)); + } else { + tag.writeLong(num); + } + } } diff --git a/src/main/java/appeng/util/item/FluidList.java b/src/main/java/appeng/util/item/FluidList.java index 03810867f99..0e8cae4b584 100644 --- a/src/main/java/appeng/util/item/FluidList.java +++ b/src/main/java/appeng/util/item/FluidList.java @@ -18,180 +18,151 @@ package appeng.util.item; - import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; - import java.util.*; +public final class FluidList implements IItemList { + + private final Map records = new HashMap(); + + @Override + public void add(final IAEFluidStack option) { + if (option == null) { + return; + } + + final IAEFluidStack st = this.getFluidRecord(option); + + if (st != null) { + st.add(option); + return; + } + + final IAEFluidStack opt = option.copy(); + + this.putFluidRecord(opt); + } + + @Override + public IAEFluidStack findPrecise(final IAEFluidStack fluidStack) { + if (fluidStack == null) { + return null; + } + + return this.getFluidRecord(fluidStack); + } + + @Override + public Collection findFuzzy(final IAEFluidStack filter, final FuzzyMode fuzzy) { + if (filter == null) { + return Collections.emptyList(); + } + + return Collections.singletonList(this.findPrecise(filter)); + } + + @Override + public boolean isEmpty() { + return !this.iterator().hasNext(); + } + + @Override + public void addStorage(final IAEFluidStack option) { + if (option == null) { + return; + } + + final IAEFluidStack st = this.getFluidRecord(option); + + if (st != null) { + st.incStackSize(option.getStackSize()); + return; + } + + final IAEFluidStack opt = option.copy(); + + this.putFluidRecord(opt); + } + + /* + * public synchronized void clean() { Iterator i = iterator(); while (i.hasNext()) { StackType AEI = + * i.next(); if ( !AEI.isMeaningful() ) i.remove(); } } + */ + + @Override + public void addCrafting(final IAEFluidStack option) { + if (option == null) { + return; + } + + final IAEFluidStack st = this.getFluidRecord(option); + + if (st != null) { + st.setCraftable(true); + return; + } + + final IAEFluidStack opt = option.copy(); + opt.setStackSize(0); + opt.setCraftable(true); + + this.putFluidRecord(opt); + } + + @Override + public void addRequestable(final IAEFluidStack option) { + if (option == null) { + return; + } + + final IAEFluidStack st = this.getFluidRecord(option); -public final class FluidList implements IItemList -{ - - private final Map records = new HashMap(); - - @Override - public void add( final IAEFluidStack option ) - { - if( option == null ) - { - return; - } - - final IAEFluidStack st = this.getFluidRecord( option ); - - if( st != null ) - { - st.add( option ); - return; - } - - final IAEFluidStack opt = option.copy(); - - this.putFluidRecord( opt ); - } - - @Override - public IAEFluidStack findPrecise( final IAEFluidStack fluidStack ) - { - if( fluidStack == null ) - { - return null; - } - - return this.getFluidRecord( fluidStack ); - } - - @Override - public Collection findFuzzy( final IAEFluidStack filter, final FuzzyMode fuzzy ) - { - if( filter == null ) - { - return Collections.emptyList(); - } - - return Collections.singletonList( this.findPrecise( filter ) ); - } - - @Override - public boolean isEmpty() - { - return !this.iterator().hasNext(); - } - - @Override - public void addStorage( final IAEFluidStack option ) - { - if( option == null ) - { - return; - } - - final IAEFluidStack st = this.getFluidRecord( option ); - - if( st != null ) - { - st.incStackSize( option.getStackSize() ); - return; - } - - final IAEFluidStack opt = option.copy(); - - this.putFluidRecord( opt ); - } - - /* - * public synchronized void clean() { Iterator i = iterator(); while (i.hasNext()) { StackType AEI = - * i.next(); if ( !AEI.isMeaningful() ) i.remove(); } } - */ - - @Override - public void addCrafting( final IAEFluidStack option ) - { - if( option == null ) - { - return; - } - - final IAEFluidStack st = this.getFluidRecord( option ); - - if( st != null ) - { - st.setCraftable( true ); - return; - } - - final IAEFluidStack opt = option.copy(); - opt.setStackSize( 0 ); - opt.setCraftable( true ); - - this.putFluidRecord( opt ); - } - - @Override - public void addRequestable( final IAEFluidStack option ) - { - if( option == null ) - { - return; - } - - final IAEFluidStack st = this.getFluidRecord( option ); - - if( st != null ) - { - st.setCountRequestable( st.getCountRequestable() + option.getCountRequestable() ); - return; - } - - final IAEFluidStack opt = option.copy(); - opt.setStackSize( 0 ); - opt.setCraftable( false ); - opt.setCountRequestable( option.getCountRequestable() ); - - this.putFluidRecord( opt ); - } - - @Override - public IAEFluidStack getFirstItem() - { - for( final IAEFluidStack stackType : this ) - { - return stackType; - } - - return null; - } - - @Override - public int size() - { - return this.records.values().size(); - } - - @Override - public Iterator iterator() - { - return new MeaningfulFluidIterator( this.records.values().iterator() ); - } - - @Override - public void resetStatus() - { - for( final IAEFluidStack i : this ) - { - i.reset(); - } - } - - private IAEFluidStack getFluidRecord( final IAEFluidStack fluid ) - { - return this.records.get( fluid ); - } - - private IAEFluidStack putFluidRecord( final IAEFluidStack fluid ) - { - return this.records.put( fluid, fluid ); - } + if (st != null) { + st.setCountRequestable(st.getCountRequestable() + option.getCountRequestable()); + return; + } + + final IAEFluidStack opt = option.copy(); + opt.setStackSize(0); + opt.setCraftable(false); + opt.setCountRequestable(option.getCountRequestable()); + + this.putFluidRecord(opt); + } + + @Override + public IAEFluidStack getFirstItem() { + for (final IAEFluidStack stackType : this) { + return stackType; + } + + return null; + } + + @Override + public int size() { + return this.records.values().size(); + } + + @Override + public Iterator iterator() { + return new MeaningfulFluidIterator(this.records.values().iterator()); + } + + @Override + public void resetStatus() { + for (final IAEFluidStack i : this) { + i.reset(); + } + } + + private IAEFluidStack getFluidRecord(final IAEFluidStack fluid) { + return this.records.get(fluid); + } + + private IAEFluidStack putFluidRecord(final IAEFluidStack fluid) { + return this.records.put(fluid, fluid); + } } diff --git a/src/main/java/appeng/util/item/HashBasedItemList.java b/src/main/java/appeng/util/item/HashBasedItemList.java index 15bcc7efccb..5e711b49955 100644 --- a/src/main/java/appeng/util/item/HashBasedItemList.java +++ b/src/main/java/appeng/util/item/HashBasedItemList.java @@ -18,170 +18,143 @@ package appeng.util.item; - import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; - import java.util.*; +public final class HashBasedItemList implements IItemList { + + private final Map records = new LinkedHashMap<>(); + + @Override + public void add(final IAEItemStack option) { + if (option == null) { + return; + } + + final IAEItemStack st = this.records.get(option); + + if (st != null) { + st.add(option); + return; + } + + final IAEItemStack opt = option.copy(); + + this.putItemRecord(opt); + } + + @Override + public IAEItemStack findPrecise(final IAEItemStack itemStack) { + if (itemStack == null) { + return null; + } + + return this.records.get(itemStack); + } + + @Override + public Collection findFuzzy(final IAEItemStack filter, final FuzzyMode fuzzy) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean isEmpty() { + return !this.iterator().hasNext(); + } + + @Override + public void addStorage(final IAEItemStack option) { + if (option == null) { + return; + } + + final IAEItemStack st = this.records.get(option); + + if (st != null) { + st.incStackSize(option.getStackSize()); + return; + } + + final IAEItemStack opt = option.copy(); + + this.putItemRecord(opt); + } + + /* + * public void clean() { Iterator i = iterator(); while (i.hasNext()) { StackType AEI = + * i.next(); if ( !AEI.isMeaningful() ) i.remove(); } } + */ + + @Override + public void addCrafting(final IAEItemStack option) { + if (option == null) { + return; + } + + final IAEItemStack st = this.records.get(option); + + if (st != null) { + st.setCraftable(true); + return; + } + + final IAEItemStack opt = option.copy(); + opt.setStackSize(0); + opt.setCraftable(true); + + this.putItemRecord(opt); + } + + @Override + public void addRequestable(final IAEItemStack option) { + if (option == null) { + return; + } + + final IAEItemStack st = this.records.get(option); + + if (st != null) { + st.setCountRequestable(st.getCountRequestable() + option.getCountRequestable()); + return; + } -public final class HashBasedItemList implements IItemList -{ - - private final Map records = new LinkedHashMap<>(); - - @Override - public void add( final IAEItemStack option ) - { - if( option == null ) - { - return; - } - - final IAEItemStack st = this.records.get( option ); - - if( st != null ) - { - st.add( option ); - return; - } - - final IAEItemStack opt = option.copy(); - - this.putItemRecord( opt ); - } - - @Override - public IAEItemStack findPrecise( final IAEItemStack itemStack ) - { - if( itemStack == null ) - { - return null; - } - - return this.records.get( itemStack ); - } - - @Override - public Collection findFuzzy( final IAEItemStack filter, final FuzzyMode fuzzy ) - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isEmpty() - { - return !this.iterator().hasNext(); - } - - @Override - public void addStorage( final IAEItemStack option ) - { - if( option == null ) - { - return; - } - - final IAEItemStack st = this.records.get( option ); - - if( st != null ) - { - st.incStackSize( option.getStackSize() ); - return; - } - - final IAEItemStack opt = option.copy(); - - this.putItemRecord( opt ); - } - - /* - * public void clean() { Iterator i = iterator(); while (i.hasNext()) { StackType AEI = - * i.next(); if ( !AEI.isMeaningful() ) i.remove(); } } - */ - - @Override - public void addCrafting( final IAEItemStack option ) - { - if( option == null ) - { - return; - } - - final IAEItemStack st = this.records.get( option ); - - if( st != null ) - { - st.setCraftable( true ); - return; - } - - final IAEItemStack opt = option.copy(); - opt.setStackSize( 0 ); - opt.setCraftable( true ); - - this.putItemRecord( opt ); - } - - @Override - public void addRequestable( final IAEItemStack option ) - { - if( option == null ) - { - return; - } - - final IAEItemStack st = this.records.get( option ); - - if( st != null ) - { - st.setCountRequestable( st.getCountRequestable() + option.getCountRequestable() ); - return; - } - - final IAEItemStack opt = option.copy(); - opt.setStackSize( 0 ); - opt.setCraftable( false ); - opt.setCountRequestable( option.getCountRequestable() ); - - this.putItemRecord( opt ); - } - - @Override - public IAEItemStack getFirstItem() - { - for( final IAEItemStack stackType : this ) - { - return stackType; - } - - return null; - } - - @Override - public int size() - { - return this.records.size(); - } - - @Override - public Iterator iterator() - { - return new MeaningfulItemIterator<>(this.records.values().iterator()); - } - - @Override - public void resetStatus() - { - for( final IAEItemStack i : this ) - { - i.reset(); - } - } - - private void putItemRecord( final IAEItemStack itemStack ) - { - this.records.put( itemStack, itemStack ); - } + final IAEItemStack opt = option.copy(); + opt.setStackSize(0); + opt.setCraftable(false); + opt.setCountRequestable(option.getCountRequestable()); + + this.putItemRecord(opt); + } + + @Override + public IAEItemStack getFirstItem() { + for (final IAEItemStack stackType : this) { + return stackType; + } + + return null; + } + + @Override + public int size() { + return this.records.size(); + } + + @Override + public Iterator iterator() { + return new MeaningfulItemIterator<>(this.records.values().iterator()); + } + + @Override + public void resetStatus() { + for (final IAEItemStack i : this) { + i.reset(); + } + } + + private void putItemRecord(final IAEItemStack itemStack) { + this.records.put(itemStack, itemStack); + } } diff --git a/src/main/java/appeng/util/item/ItemList.java b/src/main/java/appeng/util/item/ItemList.java index 6a8c7e084b9..94b0899baa3 100644 --- a/src/main/java/appeng/util/item/ItemList.java +++ b/src/main/java/appeng/util/item/ItemList.java @@ -18,210 +18,180 @@ package appeng.util.item; - import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; -import net.minecraftforge.oredict.OreDictionary; - import java.util.*; import java.util.concurrent.ConcurrentSkipListMap; +import net.minecraftforge.oredict.OreDictionary; + +public final class ItemList implements IItemList { + + private final NavigableMap records = + new ConcurrentSkipListMap(); + + @Override + public void add(final IAEItemStack option) { + if (option == null) { + return; + } + + final IAEItemStack st = this.records.get(option); + + if (st != null) { + st.add(option); + return; + } + + final IAEItemStack opt = option.copy(); + + this.putItemRecord(opt); + } + + @Override + public IAEItemStack findPrecise(final IAEItemStack itemStack) { + if (itemStack == null) { + return null; + } + + return this.records.get(itemStack); + } + + @Override + public Collection findFuzzy(final IAEItemStack filter, final FuzzyMode fuzzy) { + if (filter == null) { + return Collections.emptyList(); + } + + final AEItemStack ais = (AEItemStack) filter; + + if (ais.isOre()) { + final OreReference or = ais.getDefinition().getIsOre(); + + if (or.getAEEquivalents().size() == 1) { + final IAEItemStack is = or.getAEEquivalents().get(0); + + return this.findFuzzyDamage( + (AEItemStack) is, fuzzy, is.getItemDamage() == OreDictionary.WILDCARD_VALUE); + } else { + final Collection output = new LinkedList(); + + for (final IAEItemStack is : or.getAEEquivalents()) { + output.addAll(this.findFuzzyDamage( + (AEItemStack) is, fuzzy, is.getItemDamage() == OreDictionary.WILDCARD_VALUE)); + } + + return output; + } + } + + return this.findFuzzyDamage(ais, fuzzy, false); + } + + @Override + public boolean isEmpty() { + return !this.iterator().hasNext(); + } + + @Override + public void addStorage(final IAEItemStack option) { + if (option == null) { + return; + } + + final IAEItemStack st = this.records.get(option); + + if (st != null) { + st.incStackSize(option.getStackSize()); + return; + } + + final IAEItemStack opt = option.copy(); + + this.putItemRecord(opt); + } + + /* + * public void clean() { Iterator i = iterator(); while (i.hasNext()) { StackType AEI = + * i.next(); if ( !AEI.isMeaningful() ) i.remove(); } } + */ + + @Override + public void addCrafting(final IAEItemStack option) { + if (option == null) { + return; + } + final IAEItemStack st = this.records.get(option); -public final class ItemList implements IItemList -{ - - private final NavigableMap records = new ConcurrentSkipListMap(); + if (st != null) { + st.setCraftable(true); + return; + } + + final IAEItemStack opt = option.copy(); + opt.setStackSize(0); + opt.setCraftable(true); + + this.putItemRecord(opt); + } - @Override - public void add( final IAEItemStack option ) - { - if( option == null ) - { - return; - } - - final IAEItemStack st = this.records.get( option ); - - if( st != null ) - { - st.add( option ); - return; - } - - final IAEItemStack opt = option.copy(); - - this.putItemRecord( opt ); - } - - @Override - public IAEItemStack findPrecise( final IAEItemStack itemStack ) - { - if( itemStack == null ) - { - return null; - } - - return this.records.get( itemStack ); - } - - @Override - public Collection findFuzzy( final IAEItemStack filter, final FuzzyMode fuzzy ) - { - if( filter == null ) - { - return Collections.emptyList(); - } - - final AEItemStack ais = (AEItemStack) filter; - - if( ais.isOre() ) - { - final OreReference or = ais.getDefinition().getIsOre(); - - if( or.getAEEquivalents().size() == 1 ) - { - final IAEItemStack is = or.getAEEquivalents().get( 0 ); - - return this.findFuzzyDamage( (AEItemStack) is, fuzzy, is.getItemDamage() == OreDictionary.WILDCARD_VALUE ); - } - else - { - final Collection output = new LinkedList(); - - for( final IAEItemStack is : or.getAEEquivalents() ) - { - output.addAll( this.findFuzzyDamage( (AEItemStack) is, fuzzy, is.getItemDamage() == OreDictionary.WILDCARD_VALUE ) ); - } - - return output; - } - } - - return this.findFuzzyDamage( ais, fuzzy, false ); - } - - @Override - public boolean isEmpty() - { - return !this.iterator().hasNext(); - } - - @Override - public void addStorage( final IAEItemStack option ) - { - if( option == null ) - { - return; - } - - final IAEItemStack st = this.records.get( option ); - - if( st != null ) - { - st.incStackSize( option.getStackSize() ); - return; - } - - final IAEItemStack opt = option.copy(); - - this.putItemRecord( opt ); - } - - /* - * public void clean() { Iterator i = iterator(); while (i.hasNext()) { StackType AEI = - * i.next(); if ( !AEI.isMeaningful() ) i.remove(); } } - */ - - @Override - public void addCrafting( final IAEItemStack option ) - { - if( option == null ) - { - return; - } - - final IAEItemStack st = this.records.get( option ); - - if( st != null ) - { - st.setCraftable( true ); - return; - } - - final IAEItemStack opt = option.copy(); - opt.setStackSize( 0 ); - opt.setCraftable( true ); - - this.putItemRecord( opt ); - } - - @Override - public void addRequestable( final IAEItemStack option ) - { - if( option == null ) - { - return; - } - - final IAEItemStack st = this.records.get( option ); - - if( st != null ) - { - st.setCountRequestable( st.getCountRequestable() + option.getCountRequestable() ); - return; - } - - final IAEItemStack opt = option.copy(); - opt.setStackSize( 0 ); - opt.setCraftable( false ); - opt.setCountRequestable( option.getCountRequestable() ); - - this.putItemRecord( opt ); - } - - @Override - public IAEItemStack getFirstItem() - { - for( final IAEItemStack stackType : this ) - { - return stackType; - } - - return null; - } - - @Override - public int size() - { - return this.records.size(); - } - - @Override - public Iterator iterator() - { - return new MeaningfulItemIterator( this.records.values().iterator() ); - } - - @Override - public void resetStatus() - { - for( final IAEItemStack i : this ) - { - i.reset(); - } - } - - private IAEItemStack putItemRecord( final IAEItemStack itemStack ) - { - return this.records.put( itemStack, itemStack ); - } - - private Collection findFuzzyDamage( final AEItemStack filter, final FuzzyMode fuzzy, final boolean ignoreMeta ) - { - final IAEItemStack low = filter.getLow( fuzzy, ignoreMeta ); - final IAEItemStack high = filter.getHigh( fuzzy, ignoreMeta ); - - return this.records.subMap( low, true, high, true ).descendingMap().values(); - } + @Override + public void addRequestable(final IAEItemStack option) { + if (option == null) { + return; + } + + final IAEItemStack st = this.records.get(option); + + if (st != null) { + st.setCountRequestable(st.getCountRequestable() + option.getCountRequestable()); + return; + } + + final IAEItemStack opt = option.copy(); + opt.setStackSize(0); + opt.setCraftable(false); + opt.setCountRequestable(option.getCountRequestable()); + + this.putItemRecord(opt); + } + + @Override + public IAEItemStack getFirstItem() { + for (final IAEItemStack stackType : this) { + return stackType; + } + + return null; + } + + @Override + public int size() { + return this.records.size(); + } + + @Override + public Iterator iterator() { + return new MeaningfulItemIterator(this.records.values().iterator()); + } + + @Override + public void resetStatus() { + for (final IAEItemStack i : this) { + i.reset(); + } + } + + private IAEItemStack putItemRecord(final IAEItemStack itemStack) { + return this.records.put(itemStack, itemStack); + } + + private Collection findFuzzyDamage( + final AEItemStack filter, final FuzzyMode fuzzy, final boolean ignoreMeta) { + final IAEItemStack low = filter.getLow(fuzzy, ignoreMeta); + final IAEItemStack high = filter.getHigh(fuzzy, ignoreMeta); + + return this.records.subMap(low, true, high, true).descendingMap().values(); + } } diff --git a/src/main/java/appeng/util/item/ItemModList.java b/src/main/java/appeng/util/item/ItemModList.java index e05303ef2a4..a94bbc5ee09 100644 --- a/src/main/java/appeng/util/item/ItemModList.java +++ b/src/main/java/appeng/util/item/ItemModList.java @@ -18,69 +18,54 @@ package appeng.util.item; - import appeng.api.AEApi; import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemContainer; - import java.util.Collection; +public class ItemModList implements IItemContainer { -public class ItemModList implements IItemContainer -{ - - private final IItemContainer backingStore; - private final IItemContainer overrides = AEApi.instance().storage().createItemList(); + private final IItemContainer backingStore; + private final IItemContainer overrides = + AEApi.instance().storage().createItemList(); - public ItemModList( final IItemContainer backend ) - { - this.backingStore = backend; - } + public ItemModList(final IItemContainer backend) { + this.backingStore = backend; + } - @Override - public void add( final IAEItemStack option ) - { - IAEItemStack over = this.overrides.findPrecise( option ); - if( over == null ) - { - over = this.backingStore.findPrecise( option ); - if( over == null ) - { - this.overrides.add( option ); - } - else - { - option.add( over ); - this.overrides.add( option ); - } - } - else - { - this.overrides.add( option ); - } - } + @Override + public void add(final IAEItemStack option) { + IAEItemStack over = this.overrides.findPrecise(option); + if (over == null) { + over = this.backingStore.findPrecise(option); + if (over == null) { + this.overrides.add(option); + } else { + option.add(over); + this.overrides.add(option); + } + } else { + this.overrides.add(option); + } + } - @Override - public IAEItemStack findPrecise( final IAEItemStack i ) - { - final IAEItemStack over = this.overrides.findPrecise( i ); - if( over == null ) - { - return this.backingStore.findPrecise( i ); - } - return over; - } + @Override + public IAEItemStack findPrecise(final IAEItemStack i) { + final IAEItemStack over = this.overrides.findPrecise(i); + if (over == null) { + return this.backingStore.findPrecise(i); + } + return over; + } - @Override - public Collection findFuzzy( final IAEItemStack input, final FuzzyMode fuzzy ) - { - return this.overrides.findFuzzy( input, fuzzy ); - } + @Override + public Collection findFuzzy(final IAEItemStack input, final FuzzyMode fuzzy) { + return this.overrides.findFuzzy(input, fuzzy); + } - @Override - public boolean isEmpty() - { - return this.overrides.isEmpty() && this.backingStore.isEmpty(); - } + @Override + public boolean isEmpty() { + return this.overrides.isEmpty() && this.backingStore.isEmpty(); + } } diff --git a/src/main/java/appeng/util/item/MeaningfulFluidIterator.java b/src/main/java/appeng/util/item/MeaningfulFluidIterator.java index cc3e667849d..0d4ee6b2280 100644 --- a/src/main/java/appeng/util/item/MeaningfulFluidIterator.java +++ b/src/main/java/appeng/util/item/MeaningfulFluidIterator.java @@ -18,58 +18,45 @@ package appeng.util.item; - import appeng.api.storage.data.IAEStack; - import java.util.Iterator; import java.util.NoSuchElementException; - -public class MeaningfulFluidIterator implements Iterator -{ - - private final Iterator parent; - private T next; - - public MeaningfulFluidIterator( final Iterator iterator ) - { - this.parent = iterator; - } - - @Override - public boolean hasNext() - { - while( this.parent.hasNext() ) - { - this.next = this.parent.next(); - if( this.next.isMeaningful() ) - { - return true; - } - else - { - this.parent.remove(); // self cleaning :3 - } - } - - this.next = null; - return false; - } - - @Override - public T next() - { - if( this.next == null ) - { - throw new NoSuchElementException(); - } - - return this.next; - } - - @Override - public void remove() - { - this.parent.remove(); - } +public class MeaningfulFluidIterator implements Iterator { + + private final Iterator parent; + private T next; + + public MeaningfulFluidIterator(final Iterator iterator) { + this.parent = iterator; + } + + @Override + public boolean hasNext() { + while (this.parent.hasNext()) { + this.next = this.parent.next(); + if (this.next.isMeaningful()) { + return true; + } else { + this.parent.remove(); // self cleaning :3 + } + } + + this.next = null; + return false; + } + + @Override + public T next() { + if (this.next == null) { + throw new NoSuchElementException(); + } + + return this.next; + } + + @Override + public void remove() { + this.parent.remove(); + } } diff --git a/src/main/java/appeng/util/item/MeaningfulItemIterator.java b/src/main/java/appeng/util/item/MeaningfulItemIterator.java index d87d90391b5..bc060b77442 100644 --- a/src/main/java/appeng/util/item/MeaningfulItemIterator.java +++ b/src/main/java/appeng/util/item/MeaningfulItemIterator.java @@ -18,59 +18,46 @@ package appeng.util.item; - import appeng.api.storage.data.IAEItemStack; - import java.util.Iterator; import java.util.NoSuchElementException; +public class MeaningfulItemIterator implements Iterator { -public class MeaningfulItemIterator implements Iterator -{ - - private final Iterator parent; - private T next; + private final Iterator parent; + private T next; - public MeaningfulItemIterator( final Iterator iterator ) - { - this.parent = iterator; - } + public MeaningfulItemIterator(final Iterator iterator) { + this.parent = iterator; + } - @Override - public boolean hasNext() - { - while( this.parent.hasNext() ) - { - this.next = this.parent.next(); + @Override + public boolean hasNext() { + while (this.parent.hasNext()) { + this.next = this.parent.next(); - if( this.next.isMeaningful() ) - { - return true; - } - else - { - this.parent.remove(); // self cleaning :3 - } - } + if (this.next.isMeaningful()) { + return true; + } else { + this.parent.remove(); // self cleaning :3 + } + } - this.next = null; - return false; - } + this.next = null; + return false; + } - @Override - public T next() - { - if( this.next == null ) - { - throw new NoSuchElementException(); - } + @Override + public T next() { + if (this.next == null) { + throw new NoSuchElementException(); + } - return this.next; - } + return this.next; + } - @Override - public void remove() - { - this.parent.remove(); - } + @Override + public void remove() { + this.parent.remove(); + } } diff --git a/src/main/java/appeng/util/item/OreHelper.java b/src/main/java/appeng/util/item/OreHelper.java index 723ef5a0ba0..3718a8adc68 100644 --- a/src/main/java/appeng/util/item/OreHelper.java +++ b/src/main/java/appeng/util/item/OreHelper.java @@ -18,164 +18,138 @@ package appeng.util.item; - import appeng.api.storage.data.IAEItemStack; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.Sets; +import java.util.*; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; -import java.util.*; - - -public class OreHelper -{ - - public static final OreHelper INSTANCE = new OreHelper(); - - /** - * A local cache to speed up OreDictionary lookups. - */ - private final LoadingCache> oreDictCache = CacheBuilder.newBuilder().build( new CacheLoader>() - { - @Override - public List load( final String oreName ) - { - return OreDictionary.getOres( oreName ); - } - } ); - - private final Map references = new HashMap(); - - /** - * Test if the passed {@link ItemStack} is an ore. - * - * @param itemStack the itemstack to test - * @return true if an ore entry exists, false otherwise - */ - public OreReference isOre( final ItemStack itemStack ) - { - final ItemRef ir = new ItemRef( itemStack ); - - if( !this.references.containsKey( ir ) ) - { - final OreReference ref = new OreReference(); - final Collection ores = ref.getOres(); - final Collection set = ref.getEquivalents(); - - for( final int id : OreDictionary.getOreIDs(itemStack) ) - { - ores.add(id); - set.add(OreDictionary.getOreName(id)); - } - - if( !set.isEmpty() ) - { - this.references.put( ir, ref ); - } - else - { - this.references.put( ir, null ); - } - } - - return this.references.get( ir ); - } - - boolean sameOre( final AEItemStack aeItemStack, final IAEItemStack is ) - { - if( is instanceof AEItemStack ) - { - return this.sameOre(aeItemStack.getDefinition().getIsOre(), ((AEItemStack) is).getDefinition().getIsOre()); - } - - return this.sameOre( aeItemStack, is.getItemStack() ); - } - - public boolean sameOre( final OreReference a, final OreReference b ) - { - if( a == null || b == null ) - { - return false; - } - - if( a == b ) - { - return true; - } - - return !Sets.intersection(a.getOres(), b.getOres()).isEmpty(); - } - - boolean sameOre( final AEItemStack aeItemStack, final ItemStack o ) - { - final OreReference a = aeItemStack.getDefinition().getIsOre(); - - HashSet set = new HashSet<>(); - for( final int id : OreDictionary.getOreIDs(o) ) - { - set.add(id); - } - - return !Sets.intersection(a.getOres(), set).isEmpty(); - } - - List getCachedOres( final String oreName ) - { - return this.oreDictCache.getUnchecked( oreName ); - } - - private static class ItemRef - { - - private final Item ref; - private final int damage; - private final int hash; - - ItemRef( final ItemStack stack ) - { - this.ref = stack.getItem(); - - if( stack.getItem().isDamageable() ) - { - this.damage = 0; // IGNORED - } - else - { - this.damage = stack.getItemDamage(); // might be important... - } - - this.hash = this.ref.hashCode() ^ this.damage; - } - - @Override - public int hashCode() - { - return this.hash; - } - - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - final ItemRef other = (ItemRef) obj; - return this.damage == other.damage && this.ref == other.ref; - } - - @Override - public String toString() - { - return "ItemRef [ref=" + this.ref.getUnlocalizedName() + ", damage=" + this.damage + ", hash=" + this.hash + ']'; - } - } -} \ No newline at end of file +public class OreHelper { + + public static final OreHelper INSTANCE = new OreHelper(); + + /** + * A local cache to speed up OreDictionary lookups. + */ + private final LoadingCache> oreDictCache = CacheBuilder.newBuilder() + .build(new CacheLoader>() { + @Override + public List load(final String oreName) { + return OreDictionary.getOres(oreName); + } + }); + + private final Map references = new HashMap(); + + /** + * Test if the passed {@link ItemStack} is an ore. + * + * @param itemStack the itemstack to test + * @return true if an ore entry exists, false otherwise + */ + public OreReference isOre(final ItemStack itemStack) { + final ItemRef ir = new ItemRef(itemStack); + + if (!this.references.containsKey(ir)) { + final OreReference ref = new OreReference(); + final Collection ores = ref.getOres(); + final Collection set = ref.getEquivalents(); + + for (final int id : OreDictionary.getOreIDs(itemStack)) { + ores.add(id); + set.add(OreDictionary.getOreName(id)); + } + + if (!set.isEmpty()) { + this.references.put(ir, ref); + } else { + this.references.put(ir, null); + } + } + + return this.references.get(ir); + } + + boolean sameOre(final AEItemStack aeItemStack, final IAEItemStack is) { + if (is instanceof AEItemStack) { + return this.sameOre( + aeItemStack.getDefinition().getIsOre(), + ((AEItemStack) is).getDefinition().getIsOre()); + } + + return this.sameOre(aeItemStack, is.getItemStack()); + } + + public boolean sameOre(final OreReference a, final OreReference b) { + if (a == null || b == null) { + return false; + } + + if (a == b) { + return true; + } + + return !Sets.intersection(a.getOres(), b.getOres()).isEmpty(); + } + + boolean sameOre(final AEItemStack aeItemStack, final ItemStack o) { + final OreReference a = aeItemStack.getDefinition().getIsOre(); + + HashSet set = new HashSet<>(); + for (final int id : OreDictionary.getOreIDs(o)) { + set.add(id); + } + + return !Sets.intersection(a.getOres(), set).isEmpty(); + } + + List getCachedOres(final String oreName) { + return this.oreDictCache.getUnchecked(oreName); + } + + private static class ItemRef { + + private final Item ref; + private final int damage; + private final int hash; + + ItemRef(final ItemStack stack) { + this.ref = stack.getItem(); + + if (stack.getItem().isDamageable()) { + this.damage = 0; // IGNORED + } else { + this.damage = stack.getItemDamage(); // might be important... + } + + this.hash = this.ref.hashCode() ^ this.damage; + } + + @Override + public int hashCode() { + return this.hash; + } + + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final ItemRef other = (ItemRef) obj; + return this.damage == other.damage && this.ref == other.ref; + } + + @Override + public String toString() { + return "ItemRef [ref=" + this.ref.getUnlocalizedName() + ", damage=" + this.damage + ", hash=" + this.hash + + ']'; + } + } +} diff --git a/src/main/java/appeng/util/item/OreReference.java b/src/main/java/appeng/util/item/OreReference.java index 19e1a2cfde1..6ba1b9efcd5 100644 --- a/src/main/java/appeng/util/item/OreReference.java +++ b/src/main/java/appeng/util/item/OreReference.java @@ -18,49 +18,38 @@ package appeng.util.item; - import appeng.api.storage.data.IAEItemStack; -import net.minecraft.item.ItemStack; - import java.util.*; +import net.minecraft.item.ItemStack; +public class OreReference { -public class OreReference -{ - - private final List otherOptions = new LinkedList(); - private final Set ores = new HashSet(); - private List aeOtherOptions = null; + private final List otherOptions = new LinkedList(); + private final Set ores = new HashSet(); + private List aeOtherOptions = null; - Collection getEquivalents() - { - return this.otherOptions; - } + Collection getEquivalents() { + return this.otherOptions; + } - List getAEEquivalents() - { - if( this.aeOtherOptions == null ) - { - this.aeOtherOptions = new ArrayList( this.otherOptions.size() ); + List getAEEquivalents() { + if (this.aeOtherOptions == null) { + this.aeOtherOptions = new ArrayList(this.otherOptions.size()); - // SUMMON AE STACKS! - for( final String oreName : this.otherOptions ) - { - for( final ItemStack is : OreHelper.INSTANCE.getCachedOres( oreName ) ) - { - if( is.getItem() != null ) - { - this.aeOtherOptions.add( AEItemStack.create( is ) ); - } - } - } - } + // SUMMON AE STACKS! + for (final String oreName : this.otherOptions) { + for (final ItemStack is : OreHelper.INSTANCE.getCachedOres(oreName)) { + if (is.getItem() != null) { + this.aeOtherOptions.add(AEItemStack.create(is)); + } + } + } + } - return this.aeOtherOptions; - } + return this.aeOtherOptions; + } - Set getOres() - { - return this.ores; - } + Set getOres() { + return this.ores; + } } diff --git a/src/main/java/appeng/util/item/SharedSearchObject.java b/src/main/java/appeng/util/item/SharedSearchObject.java index 26610d8f96c..25154dc37e8 100644 --- a/src/main/java/appeng/util/item/SharedSearchObject.java +++ b/src/main/java/appeng/util/item/SharedSearchObject.java @@ -18,69 +18,56 @@ package appeng.util.item; - import appeng.util.Platform; import net.minecraft.item.Item; import net.minecraft.nbt.NBTTagCompound; +public class SharedSearchObject { -public class SharedSearchObject -{ - - private final int def; - private final int hash; - private AESharedNBT shared; - private NBTTagCompound compound; + private final int def; + private final int hash; + private AESharedNBT shared; + private NBTTagCompound compound; - public SharedSearchObject( final Item itemID, final int damageValue, final NBTTagCompound tagCompound ) - { - this.def = ( damageValue << Platform.DEF_OFFSET ) | Item.itemRegistry.getIDForObject( itemID ); - this.hash = Platform.NBTOrderlessHash( tagCompound ); - this.setCompound( tagCompound ); - } + public SharedSearchObject(final Item itemID, final int damageValue, final NBTTagCompound tagCompound) { + this.def = (damageValue << Platform.DEF_OFFSET) | Item.itemRegistry.getIDForObject(itemID); + this.hash = Platform.NBTOrderlessHash(tagCompound); + this.setCompound(tagCompound); + } - @Override - public int hashCode() - { - return this.def ^ this.hash; - } + @Override + public int hashCode() { + return this.def ^ this.hash; + } - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - final SharedSearchObject other = (SharedSearchObject) obj; - if( this.def == other.def && this.hash == other.hash ) - { - return Platform.NBTEqualityTest( this.getCompound(), other.getCompound() ); - } - return false; - } + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final SharedSearchObject other = (SharedSearchObject) obj; + if (this.def == other.def && this.hash == other.hash) { + return Platform.NBTEqualityTest(this.getCompound(), other.getCompound()); + } + return false; + } - AESharedNBT getShared() - { - return this.shared; - } + AESharedNBT getShared() { + return this.shared; + } - void setShared( final AESharedNBT shared ) - { - this.shared = shared; - } + void setShared(final AESharedNBT shared) { + this.shared = shared; + } - NBTTagCompound getCompound() - { - return this.compound; - } + NBTTagCompound getCompound() { + return this.compound; + } - void setCompound( final NBTTagCompound compound ) - { - this.compound = compound; - } + void setCompound(final NBTTagCompound compound) { + this.compound = compound; + } } diff --git a/src/main/java/appeng/util/iterators/AEInvIterator.java b/src/main/java/appeng/util/iterators/AEInvIterator.java index 6bd1c96c5e6..36abb1a9054 100644 --- a/src/main/java/appeng/util/iterators/AEInvIterator.java +++ b/src/main/java/appeng/util/iterators/AEInvIterator.java @@ -18,45 +18,37 @@ package appeng.util.iterators; - import appeng.api.storage.data.IAEItemStack; import appeng.tile.inventory.AppEngInternalAEInventory; - import java.util.Iterator; +public final class AEInvIterator implements Iterator { + private final AppEngInternalAEInventory inventory; + private final int size; -public final class AEInvIterator implements Iterator -{ - private final AppEngInternalAEInventory inventory; - private final int size; - - private int counter = 0; + private int counter = 0; - public AEInvIterator( final AppEngInternalAEInventory inventory ) - { - this.inventory = inventory; - this.size = this.inventory.getSizeInventory(); - } + public AEInvIterator(final AppEngInternalAEInventory inventory) { + this.inventory = inventory; + this.size = this.inventory.getSizeInventory(); + } - @Override - public boolean hasNext() - { - return this.counter < this.size; - } + @Override + public boolean hasNext() { + return this.counter < this.size; + } - @Override - public IAEItemStack next() - { - final IAEItemStack result = this.inventory.getAEStackInSlot( this.counter ); + @Override + public IAEItemStack next() { + final IAEItemStack result = this.inventory.getAEStackInSlot(this.counter); - this.counter++; + this.counter++; - return result; - } + return result; + } - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/iterators/ChainedIterator.java b/src/main/java/appeng/util/iterators/ChainedIterator.java index 93f3769f7b7..b2934def32a 100644 --- a/src/main/java/appeng/util/iterators/ChainedIterator.java +++ b/src/main/java/appeng/util/iterators/ChainedIterator.java @@ -18,38 +18,31 @@ package appeng.util.iterators; - import java.util.Iterator; +public final class ChainedIterator implements Iterator { + private final T[] list; + + private int offset = 0; + + public ChainedIterator(final T... list) { + this.list = list; + } + + @Override + public boolean hasNext() { + return this.offset < this.list.length; + } + + @Override + public T next() { + final T result = this.list[this.offset]; + this.offset++; + return result; + } -public final class ChainedIterator implements Iterator -{ - private final T[] list; - - private int offset = 0; - - public ChainedIterator( final T... list ) - { - this.list = list; - } - - @Override - public boolean hasNext() - { - return this.offset < this.list.length; - } - - @Override - public T next() - { - final T result = this.list[this.offset]; - this.offset++; - return result; - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/iterators/InvIterator.java b/src/main/java/appeng/util/iterators/InvIterator.java index 10d246ef62b..59762e072f0 100644 --- a/src/main/java/appeng/util/iterators/InvIterator.java +++ b/src/main/java/appeng/util/iterators/InvIterator.java @@ -18,44 +18,36 @@ package appeng.util.iterators; - +import java.util.Iterator; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.util.Iterator; - - -public final class InvIterator implements Iterator -{ - private final IInventory inventory; - private final int size; +public final class InvIterator implements Iterator { + private final IInventory inventory; + private final int size; - private int counter = 0; + private int counter = 0; - public InvIterator( final IInventory inventory ) - { - this.inventory = inventory; - this.size = this.inventory.getSizeInventory(); - } + public InvIterator(final IInventory inventory) { + this.inventory = inventory; + this.size = this.inventory.getSizeInventory(); + } - @Override - public boolean hasNext() - { - return this.counter < this.size; - } + @Override + public boolean hasNext() { + return this.counter < this.size; + } - @Override - public ItemStack next() - { - final ItemStack result = this.inventory.getStackInSlot( this.counter ); - this.counter++; + @Override + public ItemStack next() { + final ItemStack result = this.inventory.getStackInSlot(this.counter); + this.counter++; - return result; - } + return result; + } - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/iterators/NullIterator.java b/src/main/java/appeng/util/iterators/NullIterator.java index 3ce3edcc500..6705057de6f 100644 --- a/src/main/java/appeng/util/iterators/NullIterator.java +++ b/src/main/java/appeng/util/iterators/NullIterator.java @@ -18,28 +18,20 @@ package appeng.util.iterators; - import java.util.Iterator; +public class NullIterator implements Iterator { -public class NullIterator implements Iterator -{ - - @Override - public boolean hasNext() - { - return false; - } - - @Override - public T next() - { - return null; - } + @Override + public boolean hasNext() { + return false; + } - @Override - public void remove() - { + @Override + public T next() { + return null; + } - } + @Override + public void remove() {} } diff --git a/src/main/java/appeng/util/iterators/ProxyNodeIterator.java b/src/main/java/appeng/util/iterators/ProxyNodeIterator.java index 8d2f0a6c3f0..1ba0cb16d19 100644 --- a/src/main/java/appeng/util/iterators/ProxyNodeIterator.java +++ b/src/main/java/appeng/util/iterators/ProxyNodeIterator.java @@ -18,39 +18,31 @@ package appeng.util.iterators; - import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; -import net.minecraftforge.common.util.ForgeDirection; - import java.util.Iterator; +import net.minecraftforge.common.util.ForgeDirection; +public final class ProxyNodeIterator implements Iterator { + private final Iterator hosts; -public final class ProxyNodeIterator implements Iterator -{ - private final Iterator hosts; - - public ProxyNodeIterator( final Iterator hosts ) - { - this.hosts = hosts; - } + public ProxyNodeIterator(final Iterator hosts) { + this.hosts = hosts; + } - @Override - public boolean hasNext() - { - return this.hosts.hasNext(); - } + @Override + public boolean hasNext() { + return this.hosts.hasNext(); + } - @Override - public IGridNode next() - { - final IGridHost host = this.hosts.next(); - return host.getGridNode( ForgeDirection.UNKNOWN ); - } + @Override + public IGridNode next() { + final IGridHost host = this.hosts.next(); + return host.getGridNode(ForgeDirection.UNKNOWN); + } - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/iterators/StackToSlotIterator.java b/src/main/java/appeng/util/iterators/StackToSlotIterator.java index b44e143dbb1..06a563eb770 100644 --- a/src/main/java/appeng/util/iterators/StackToSlotIterator.java +++ b/src/main/java/appeng/util/iterators/StackToSlotIterator.java @@ -18,43 +18,35 @@ package appeng.util.iterators; - import appeng.util.inv.ItemSlot; -import net.minecraft.item.ItemStack; - import java.util.Iterator; +import net.minecraft.item.ItemStack; - -public class StackToSlotIterator implements Iterator -{ - - private final ItemSlot iss = new ItemSlot(); - private final Iterator is; - private int x = 0; - - public StackToSlotIterator( final Iterator is ) - { - this.is = is; - } - - @Override - public boolean hasNext() - { - return this.is.hasNext(); - } - - @Override - public ItemSlot next() - { - this.iss.setSlot( this.x ); - this.x++; - this.iss.setItemStack( this.is.next() ); - return this.iss; - } - - @Override - public void remove() - { - // uhh no. - } +public class StackToSlotIterator implements Iterator { + + private final ItemSlot iss = new ItemSlot(); + private final Iterator is; + private int x = 0; + + public StackToSlotIterator(final Iterator is) { + this.is = is; + } + + @Override + public boolean hasNext() { + return this.is.hasNext(); + } + + @Override + public ItemSlot next() { + this.iss.setSlot(this.x); + this.x++; + this.iss.setItemStack(this.is.next()); + return this.iss; + } + + @Override + public void remove() { + // uhh no. + } } diff --git a/src/main/java/appeng/util/prioitylist/DefaultPriorityList.java b/src/main/java/appeng/util/prioitylist/DefaultPriorityList.java index 24598fad616..335223f69cf 100644 --- a/src/main/java/appeng/util/prioitylist/DefaultPriorityList.java +++ b/src/main/java/appeng/util/prioitylist/DefaultPriorityList.java @@ -18,33 +18,26 @@ package appeng.util.prioitylist; - import appeng.api.storage.data.IAEStack; - import java.util.ArrayList; import java.util.List; +public class DefaultPriorityList> implements IPartitionList { -public class DefaultPriorityList> implements IPartitionList -{ - - private static final List NULL_LIST = new ArrayList(); + private static final List NULL_LIST = new ArrayList(); - @Override - public boolean isListed( final T input ) - { - return false; - } + @Override + public boolean isListed(final T input) { + return false; + } - @Override - public boolean isEmpty() - { - return true; - } + @Override + public boolean isEmpty() { + return true; + } - @Override - public Iterable getItems() - { - return NULL_LIST; - } + @Override + public Iterable getItems() { + return NULL_LIST; + } } diff --git a/src/main/java/appeng/util/prioitylist/FuzzyPriorityList.java b/src/main/java/appeng/util/prioitylist/FuzzyPriorityList.java index a2191a36028..976018ccef6 100644 --- a/src/main/java/appeng/util/prioitylist/FuzzyPriorityList.java +++ b/src/main/java/appeng/util/prioitylist/FuzzyPriorityList.java @@ -18,42 +18,34 @@ package appeng.util.prioitylist; - import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; - import java.util.Collection; +public class FuzzyPriorityList> implements IPartitionList { + + private final IItemList list; + private final FuzzyMode mode; + + public FuzzyPriorityList(final IItemList in, final FuzzyMode mode) { + this.list = in; + this.mode = mode; + } + + @Override + public boolean isListed(final T input) { + final Collection out = this.list.findFuzzy(input, this.mode); + return out != null && !out.isEmpty(); + } + + @Override + public boolean isEmpty() { + return this.list.isEmpty(); + } -public class FuzzyPriorityList> implements IPartitionList -{ - - private final IItemList list; - private final FuzzyMode mode; - - public FuzzyPriorityList( final IItemList in, final FuzzyMode mode ) - { - this.list = in; - this.mode = mode; - } - - @Override - public boolean isListed( final T input ) - { - final Collection out = this.list.findFuzzy( input, this.mode ); - return out != null && !out.isEmpty(); - } - - @Override - public boolean isEmpty() - { - return this.list.isEmpty(); - } - - @Override - public Iterable getItems() - { - return this.list; - } + @Override + public Iterable getItems() { + return this.list; + } } diff --git a/src/main/java/appeng/util/prioitylist/IPartitionList.java b/src/main/java/appeng/util/prioitylist/IPartitionList.java index 95b27d4a19f..d9bc1952093 100644 --- a/src/main/java/appeng/util/prioitylist/IPartitionList.java +++ b/src/main/java/appeng/util/prioitylist/IPartitionList.java @@ -18,15 +18,12 @@ package appeng.util.prioitylist; - import appeng.api.storage.data.IAEStack; +public interface IPartitionList> { + boolean isListed(T input); -public interface IPartitionList> -{ - boolean isListed( T input ); - - boolean isEmpty(); + boolean isEmpty(); - Iterable getItems(); + Iterable getItems(); } diff --git a/src/main/java/appeng/util/prioitylist/MergedPriorityList.java b/src/main/java/appeng/util/prioitylist/MergedPriorityList.java index 0c59bbd27d1..45a45451b04 100644 --- a/src/main/java/appeng/util/prioitylist/MergedPriorityList.java +++ b/src/main/java/appeng/util/prioitylist/MergedPriorityList.java @@ -18,67 +18,51 @@ package appeng.util.prioitylist; - import appeng.api.storage.data.IAEStack; - import java.util.ArrayList; import java.util.Collection; +public final class MergedPriorityList> implements IPartitionList { -public final class MergedPriorityList> implements IPartitionList -{ - - private final Collection> positive = new ArrayList>(); - private final Collection> negative = new ArrayList>(); + private final Collection> positive = new ArrayList>(); + private final Collection> negative = new ArrayList>(); - public void addNewList( final IPartitionList list, final boolean isWhitelist ) - { - if( isWhitelist ) - { - this.positive.add( list ); - } - else - { - this.negative.add( list ); - } - } + public void addNewList(final IPartitionList list, final boolean isWhitelist) { + if (isWhitelist) { + this.positive.add(list); + } else { + this.negative.add(list); + } + } - @Override - public boolean isListed( final T input ) - { - for( final IPartitionList l : this.negative ) - { - if( l.isListed( input ) ) - { - return false; - } - } + @Override + public boolean isListed(final T input) { + for (final IPartitionList l : this.negative) { + if (l.isListed(input)) { + return false; + } + } - if( !this.positive.isEmpty() ) - { - for( final IPartitionList l : this.positive ) - { - if( l.isListed( input ) ) - { - return true; - } - } + if (!this.positive.isEmpty()) { + for (final IPartitionList l : this.positive) { + if (l.isListed(input)) { + return true; + } + } - return false; - } + return false; + } - return true; - } + return true; + } - @Override - public boolean isEmpty() - { - return this.positive.isEmpty() && this.negative.isEmpty(); - } + @Override + public boolean isEmpty() { + return this.positive.isEmpty() && this.negative.isEmpty(); + } - @Override - public Iterable getItems() - { - throw new UnsupportedOperationException(); - } + @Override + public Iterable getItems() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/prioitylist/OreFilteredList.java b/src/main/java/appeng/util/prioitylist/OreFilteredList.java index 96c6574f352..d4d65a4c04d 100644 --- a/src/main/java/appeng/util/prioitylist/OreFilteredList.java +++ b/src/main/java/appeng/util/prioitylist/OreFilteredList.java @@ -2,48 +2,43 @@ import appeng.api.storage.data.IAEItemStack; import appeng.core.AELog; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraftforge.oredict.OreDictionary; -import org.apache.commons.lang3.StringUtils; - import java.util.HashMap; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.IntStream; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; +import org.apache.commons.lang3.StringUtils; -public class OreFilteredList implements IPartitionList{ +public class OreFilteredList implements IPartitionList { private final Predicate filterPredicate; - public OreFilteredList(String filter){ + + public OreFilteredList(String filter) { filterPredicate = makeFilter(filter.trim()); } @Override - public boolean isListed( final IAEItemStack input ) { + public boolean isListed(final IAEItemStack input) { return filterPredicate != null && filterPredicate.test(input); } @Override - public boolean isEmpty() - { + public boolean isEmpty() { return this.filterPredicate == null; } @Override - public Iterable getItems() - { + public Iterable getItems() { return null; } public static Predicate makeFilter(String f) { try { Predicate matcher = makeMatcher(f); - if (matcher == null) - return null; + if (matcher == null) return null; return new OreListMatcher(matcher); - } - catch (Exception ex) - { + } catch (Exception ex) { AELog.debug(ex); return null; } @@ -53,27 +48,23 @@ private static Predicate makeMatcher(String f) { Predicate matcher = null; if (notAWildcard(f)) { final Predicate test = Pattern.compile(f).asPredicate(); - matcher = (is) -> is != null && - IntStream.of(OreDictionary.getOreIDs(is)) + matcher = (is) -> is != null + && IntStream.of(OreDictionary.getOreIDs(is)) .mapToObj(OreDictionary::getOreName) .anyMatch(test); - } - else if (!f.isEmpty()) { + } else if (!f.isEmpty()) { String[] filters = f.split("[&|]"); String lastFilter = null; for (String filter : filters) { filter = filter.trim(); - if (filter.isEmpty()) - continue; + if (filter.isEmpty()) continue; boolean negated = filter.startsWith("!"); - if (negated) - filter = filter.substring(1); + if (negated) filter = filter.substring(1); Predicate test = filterToItemStackPredicate(filter); - if (negated) - test = test.negate(); + if (negated) test = test.negate(); if (matcher == null) { matcher = test; @@ -82,8 +73,7 @@ else if (!f.isEmpty()) { int endLast = f.indexOf(lastFilter) + lastFilter.length(); int startThis = f.indexOf(filter); lastFilter = filter; - if (startThis <= endLast) - continue; + if (startThis <= endLast) continue; boolean or = f.substring(endLast, startThis).contains("|"); matcher = or ? matcher.or(test) : matcher.and(test); } @@ -92,17 +82,17 @@ else if (!f.isEmpty()) { return matcher; } - private static class OreListMatcher implements Predicate { + private static class OreListMatcher implements Predicate { final HashMap cache = new HashMap<>(); final Predicate matcher; - public OreListMatcher(Predicate matcher){ + + public OreListMatcher(Predicate matcher) { this.matcher = matcher; } + public boolean test(IAEItemStack t) { - if (t == null) - return false; - return cache.compute(new ItemRef(t), - (k, v) -> (v != null) ? v : matcher.test(t.getItemStack())); + if (t == null) return false; + return cache.compute(new ItemRef(t), (k, v) -> (v != null) ? v : matcher.test(t.getItemStack())); } } @@ -116,48 +106,45 @@ private static boolean notAWildcard(String f) { || f.contains("[") || f.contains("]"); } - private static class ItemRef - { + + private static class ItemRef { private final Item ref; private final int damage; private final int hash; - ItemRef( final IAEItemStack stack ) - { + ItemRef(final IAEItemStack stack) { this.ref = stack.getItem(); this.damage = stack.getItem().isDamageable() ? 0 : stack.getItemDamage(); this.hash = this.ref.hashCode() ^ this.damage; } @Override - public int hashCode() - { + public int hashCode() { return this.hash; } @Override - public boolean equals( final Object obj ) - { - if( obj == null || this.getClass() != obj.getClass()) - return false; + public boolean equals(final Object obj) { + if (obj == null || this.getClass() != obj.getClass()) return false; final ItemRef other = (ItemRef) obj; return this.damage == other.damage && this.ref == other.ref; } @Override - public String toString() - { - return "ItemRef [ref=" + this.ref.getUnlocalizedName() + ", damage=" + this.damage + ", hash=" + this.hash + ']'; + public String toString() { + return "ItemRef [ref=" + this.ref.getUnlocalizedName() + ", damage=" + this.damage + ", hash=" + this.hash + + ']'; } } private static Predicate filterToItemStackPredicate(String filter) { final Predicate test = filterToPredicate(filter); - return (is) -> is != null && - IntStream.of(OreDictionary.getOreIDs(is)) + return (is) -> is != null + && IntStream.of(OreDictionary.getOreIDs(is)) .mapToObj(OreDictionary::getOreName) .anyMatch(test); } + private static Predicate filterToPredicate(String filter) { int numStars = StringUtils.countMatches(filter, "*"); if (numStars == filter.length()) { diff --git a/src/main/java/appeng/util/prioitylist/PrecisePriorityList.java b/src/main/java/appeng/util/prioitylist/PrecisePriorityList.java index 796fcd9dac8..0f732d57705 100644 --- a/src/main/java/appeng/util/prioitylist/PrecisePriorityList.java +++ b/src/main/java/appeng/util/prioitylist/PrecisePriorityList.java @@ -18,36 +18,29 @@ package appeng.util.prioitylist; - import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; +public class PrecisePriorityList> implements IPartitionList { -public class PrecisePriorityList> implements IPartitionList -{ - - private final IItemList list; + private final IItemList list; - public PrecisePriorityList( final IItemList in ) - { - this.list = in; - } + public PrecisePriorityList(final IItemList in) { + this.list = in; + } - @Override - public boolean isListed( final T input ) - { - return this.list.findPrecise( input ) != null; - } + @Override + public boolean isListed(final T input) { + return this.list.findPrecise(input) != null; + } - @Override - public boolean isEmpty() - { - return this.list.isEmpty(); - } + @Override + public boolean isEmpty() { + return this.list.isEmpty(); + } - @Override - public Iterable getItems() - { - return this.list; - } + @Override + public Iterable getItems() { + return this.list; + } } diff --git a/src/main/java/appeng/worldgen/MeteoritePlacer.java b/src/main/java/appeng/worldgen/MeteoritePlacer.java index 86d6a0f1296..29c8450b98a 100644 --- a/src/main/java/appeng/worldgen/MeteoritePlacer.java +++ b/src/main/java/appeng/worldgen/MeteoritePlacer.java @@ -18,7 +18,6 @@ package appeng.worldgen; - import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IBlocks; @@ -29,6 +28,10 @@ import appeng.util.InventoryAdaptor; import appeng.util.Platform; import appeng.worldgen.meteorite.*; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; @@ -41,540 +44,461 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.oredict.OreDictionary; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; - - -public final class MeteoritePlacer -{ - private static final double PRESSES_SPAWN_CHANCE = 0.7; - private static final int SKYSTONE_SPAWN_LIMIT = 12; - private final Collection validSpawn = new HashSet(); - private final Collection invalidSpawn = new HashSet(); - private final IBlockDefinition skyChestDefinition; - private final IBlockDefinition skyStoneDefinition; - private final MeteoriteBlockPutter putter = new MeteoriteBlockPutter(); - private double meteoriteSize = ( Math.random() * 6.0 ) + 2; - private double realCrater = this.meteoriteSize * 2 + 5; - private double squaredMeteoriteSize = this.meteoriteSize * this.meteoriteSize; - private double crater = this.realCrater * this.realCrater; - private NBTTagCompound settings; - private Fallout type; - - public MeteoritePlacer() - { - final IBlocks blocks = AEApi.instance().definitions().blocks(); - - this.skyChestDefinition = blocks.skyChest(); - this.skyStoneDefinition = blocks.skyStone(); - - this.validSpawn.add( Blocks.stone ); - this.validSpawn.add( Blocks.cobblestone ); - this.validSpawn.add( Blocks.grass ); - this.validSpawn.add( Blocks.sand ); - this.validSpawn.add( Blocks.dirt ); - this.validSpawn.add( Blocks.gravel ); - this.validSpawn.add( Blocks.netherrack ); - this.validSpawn.add( Blocks.iron_ore ); - this.validSpawn.add( Blocks.gold_ore ); - this.validSpawn.add( Blocks.diamond_ore ); - this.validSpawn.add( Blocks.redstone_ore ); - this.validSpawn.add( Blocks.hardened_clay ); - this.validSpawn.add( Blocks.ice ); - this.validSpawn.add( Blocks.snow ); - this.validSpawn.add( Blocks.stained_hardened_clay ); - - for( final Block skyStoneBlock : this.skyStoneDefinition.maybeBlock().asSet() ) - { - this.invalidSpawn.add( skyStoneBlock ); - } - this.invalidSpawn.add( Blocks.planks ); - this.invalidSpawn.add( Blocks.iron_door ); - this.invalidSpawn.add( Blocks.iron_bars ); - this.invalidSpawn.add( Blocks.wooden_door ); - this.invalidSpawn.add( Blocks.brick_block ); - this.invalidSpawn.add( Blocks.clay ); - this.invalidSpawn.add( Blocks.water ); - this.invalidSpawn.add( Blocks.log ); - this.invalidSpawn.add( Blocks.log2 ); - - this.type = new Fallout( this.putter, this.skyStoneDefinition ); - } - - boolean spawnMeteorite( final IMeteoriteWorld w, final NBTTagCompound meteoriteBlob ) - { - this.settings = meteoriteBlob; - - final int x = this.settings.getInteger( "x" ); - final int y = this.settings.getInteger( "y" ); - final int z = this.settings.getInteger( "z" ); - - this.meteoriteSize = this.settings.getDouble( "real_sizeOfMeteorite" ); - this.realCrater = this.settings.getDouble( "realCrater" ); - this.squaredMeteoriteSize = this.settings.getDouble( "sizeOfMeteorite" ); - this.crater = this.settings.getDouble( "crater" ); - - final Block blk = Block.getBlockById( this.settings.getInteger( "blk" ) ); - - if( blk == Blocks.sand ) - { - this.type = new FalloutSand( w, x, y, z, this.putter, this.skyStoneDefinition ); - } - else if( blk == Blocks.hardened_clay ) - { - this.type = new FalloutCopy( w, x, y, z, this.putter, this.skyStoneDefinition ); - } - else if( blk == Blocks.ice || blk == Blocks.snow ) - { - this.type = new FalloutSnow( w, x, y, z, this.putter, this.skyStoneDefinition ); - } - - final int skyMode = this.settings.getInteger( "skyMode" ); - - // creator - if( skyMode > 10 ) - { - this.placeCrater( w, x, y, z ); - } - - this.placeMeteorite( w, x, y, z ); - - // collapse blocks... - if( skyMode > 3 ) - { - this.decay( w, x, y, z ); - } - - w.done(); - return true; - } - - private void placeCrater( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final boolean lava = this.settings.getBoolean( "lava" ); - - final int maxY = 255; - final int minX = w.minX( x - 200 ); - final int maxX = w.maxX( x + 200 ); - final int minZ = w.minZ( z - 200 ); - final int maxZ = w.maxZ( z + 200 ); - - for( int j = y - 5; j < maxY; j++ ) - { - boolean changed = false; - - for( int i = minX; i < maxX; i++ ) - { - for( int k = minZ; k < maxZ; k++ ) - { - final double dx = i - x; - final double dz = k - z; - final double h = y - this.meteoriteSize + 1 + this.type.adjustCrater(); - - final double distanceFrom = dx * dx + dz * dz; - - if( j > h + distanceFrom * 0.02 ) - { - if( lava && j < y && w.getBlock( x, y - 1, z ).isBlockSolid( w.getWorld(), i, j, k, 0 ) ) - { - if( j > h + distanceFrom * 0.02 ) - { - this.putter.put( w, i, j, k, Blocks.lava ); - } - } - else - { - changed = this.putter.put( w, i, j, k, Platform.AIR_BLOCK ) || changed; - } - } - } - } - } - - for( final Object o : w.getWorld().getEntitiesWithinAABB( EntityItem.class, AxisAlignedBB.getBoundingBox( w.minX( x - 30 ), y - 5, w.minZ( z - 30 ), w.maxX( x + 30 ), y + 30, w.maxZ( z + 30 ) ) ) ) - { - final Entity e = (Entity) o; - e.setDead(); - } - } - - private void placeMeteorite( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final int meteorXLength = w.minX( x - 8 ); - final int meteorXHeight = w.maxX( x + 8 ); - final int meteorZLength = w.minZ( z - 8 ); - final int meteorZHeight = w.maxZ( z + 8 ); - - // spawn meteor - for( int i = meteorXLength; i < meteorXHeight; i++ ) - { - for( int j = y - 8; j < y + 8; j++ ) - { - for( int k = meteorZLength; k < meteorZHeight; k++ ) - { - final double dx = i - x; - final double dy = j - y; - final double dz = k - z; - - if( dx * dx * 0.7 + dy * dy * ( j > y ? 1.4 : 0.8 ) + dz * dz * 0.7 < this.squaredMeteoriteSize ) - { - for( final Block skyStoneBlock : this.skyStoneDefinition.maybeBlock().asSet() ) - { - this.putter.put( w, i, j, k, skyStoneBlock ); - } - } - } - } - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.SpawnPressesInMeteorites ) ) - { - for( final Block skyChestBlock : this.skyChestDefinition.maybeBlock().asSet() ) - { - this.putter.put( w, x, y, z, skyChestBlock ); - } - - final TileEntity te = w.getTileEntity( x, y, z ); - if( te instanceof IInventory ) - { - final InventoryAdaptor ap = InventoryAdaptor.getAdaptor( te, ForgeDirection.UP ); - - int primary = Math.max( 1, (int) ( Math.random() * 4 ) ); - - if( primary > 3 ) // in case math breaks... - { - primary = 3; - } - - for( int zz = 0; zz < primary; zz++ ) - { - int r = 0; - boolean duplicate = false; - - do - { - duplicate = false; - - if( Math.random() > PRESSES_SPAWN_CHANCE ) - { - r = WorldData.instance().storageData().getNextOrderedValue( "presses" ); - } - else - { - r = (int) ( Math.random() * 1000 ); - } - - ItemStack toAdd = null; - final IMaterials materials = AEApi.instance().definitions().materials(); - - switch( r % 4 ) - { - case 0: - for( final ItemStack calc : materials.calcProcessorPress().maybeStack( 1 ).asSet() ) - { - toAdd = calc; - } - break; - case 1: - for( final ItemStack calc : materials.engProcessorPress().maybeStack( 1 ).asSet() ) - { - toAdd = calc; - } - break; - case 2: - for( final ItemStack calc : materials.logicProcessorPress().maybeStack( 1 ).asSet() ) - { - toAdd = calc; - } - break; - case 3: - for( final ItemStack calc : materials.siliconPress().maybeStack( 1 ).asSet() ) - { - toAdd = calc; - } - break; - default: - } - - if( toAdd != null ) - { - if( ap.simulateRemove( 1, toAdd, null ) == null ) - { - ap.addItems( toAdd ); - } - else - { - duplicate = true; - } - } - } - while( duplicate ); - } - - final int secondary = Math.max( 1, (int) ( Math.random() * 3 ) ); - for( int zz = 0; zz < secondary; zz++ ) - { - switch( (int) ( Math.random() * 1000 ) % 3 ) - { - case 0: - final int amount = (int) ( ( Math.random() * SKYSTONE_SPAWN_LIMIT ) + 1 ); - for( final ItemStack skyStoneStack : this.skyStoneDefinition.maybeStack( amount ).asSet() ) - { - ap.addItems( skyStoneStack ); - } - break; - case 1: - final List possibles = new LinkedList(); - possibles.addAll( OreDictionary.getOres( "nuggetIron" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetCopper" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetTin" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetSilver" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetLead" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetPlatinum" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetNickel" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetAluminium" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetElectrum" ) ); - possibles.add( new ItemStack( net.minecraft.init.Items.gold_nugget ) ); - - ItemStack nugget = Platform.pickRandom( possibles ); - if( nugget != null ) - { - nugget = nugget.copy(); - nugget.stackSize = (int) ( Math.random() * 12 ) + 1; - ap.addItems( nugget ); - } - break; - } - } - } - } - } - - private void decay( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - double randomShit = 0; - - final int meteorXLength = w.minX( x - 30 ); - final int meteorXHeight = w.maxX( x + 30 ); - final int meteorZLength = w.minZ( z - 30 ); - final int meteorZHeight = w.maxZ( z + 30 ); - - for( int i = meteorXLength; i < meteorXHeight; i++ ) - { - for( int k = meteorZLength; k < meteorZHeight; k++ ) - { - for( int j = y - 9; j < y + 30; j++ ) - { - Block blk = w.getBlock( i, j, k ); - if( blk == Blocks.lava ) - { - continue; - } - - if( blk.isReplaceable( w.getWorld(), i, j, k ) ) - { - blk = Platform.AIR_BLOCK; - final Block blk_b = w.getBlock( i, j + 1, k ); - - if( blk_b != blk ) - { - final int meta_b = w.getBlockMetadata( i, j + 1, k ); - - w.setBlock( i, j, k, blk_b, meta_b, 3 ); - w.setBlock( i, j + 1, k, blk ); - } - else if( randomShit < 100 * this.crater ) - { - final double dx = i - x; - final double dy = j - y; - final double dz = k - z; - final double dist = dx * dx + dy * dy + dz * dz; - - final Block xf = w.getBlock( i, j - 1, k ); - if( !xf.isReplaceable( w.getWorld(), i, j - 1, k ) ) - { - final double extraRange = Math.random() * 0.6; - final double height = this.crater * ( extraRange + 0.2 ) - Math.abs( dist - this.crater * 1.7 ); - - if( xf != blk && height > 0 && Math.random() > 0.6 ) - { - randomShit++; - this.type.getRandomFall( w, i, j, k ); - } - } - } - } - else - { - // decay. - final Block blk_b = w.getBlock( i, j + 1, k ); - if( blk_b == Platform.AIR_BLOCK ) - { - if( Math.random() > 0.4 ) - { - final double dx = i - x; - final double dy = j - y; - final double dz = k - z; - - if( dx * dx + dy * dy + dz * dz < this.crater * 1.6 ) - { - this.type.getRandomInset( w, i, j, k ); - } - } - } - } - } - } - } - } - - double getSqDistance( final int x, final int z ) - { - final int chunkX = this.settings.getInteger( "x" ) - x; - final int chunkZ = this.settings.getInteger( "z" ) - z; - - return chunkX * chunkX + chunkZ * chunkZ; - } - - public boolean spawnMeteorite( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - - if( !w.hasNoSky() ) - { - return false; - } - - Block blk = w.getBlock( x, y, z ); - if( !this.validSpawn.contains( blk ) ) - { - return false; // must spawn on a valid block.. - } - - this.settings = new NBTTagCompound(); - this.settings.setInteger( "x", x ); - this.settings.setInteger( "y", y ); - this.settings.setInteger( "z", z ); - this.settings.setInteger( "blk", Block.getIdFromBlock( blk ) ); - - this.settings.setDouble( "real_sizeOfMeteorite", this.meteoriteSize ); - this.settings.setDouble( "realCrater", this.realCrater ); - this.settings.setDouble( "sizeOfMeteorite", this.squaredMeteoriteSize ); - this.settings.setDouble( "crater", this.crater ); - - this.settings.setBoolean( "lava", Math.random() > 0.9 ); - - if( blk == Blocks.sand ) - { - this.type = new FalloutSand( w, x, y, z, this.putter, this.skyStoneDefinition ); - } - else if( blk == Blocks.hardened_clay ) - { - this.type = new FalloutCopy( w, x, y, z, this.putter, this.skyStoneDefinition ); - } - else if( blk == Blocks.ice || blk == Blocks.snow ) - { - this.type = new FalloutSnow( w, x, y, z, this.putter, this.skyStoneDefinition ); - } - - int realValidBlocks = 0; - - for( int i = x - 6; i < x + 6; i++ ) - { - for( int j = y - 6; j < y + 6; j++ ) - { - for( int k = z - 6; k < z + 6; k++ ) - { - blk = w.getBlock( i, j, k ); - if( this.validSpawn.contains( blk ) ) - { - realValidBlocks++; - } - } - } - } - - int validBlocks = 0; - for( int i = x - 15; i < x + 15; i++ ) - { - for( int j = y - 15; j < y + 15; j++ ) - { - for( int k = z - 15; k < z + 15; k++ ) - { - blk = w.getBlock( i, j, k ); - if( this.invalidSpawn.contains( blk ) ) - { - return false; - } - if( this.validSpawn.contains( blk ) ) - { - validBlocks++; - } - } - } - } - - final int minBLocks = 200; - if( validBlocks > minBLocks && realValidBlocks > 80 ) - { - // we can spawn here! - - int skyMode = 0; - - for( int i = x - 15; i < x + 15; i++ ) - { - for( int j = y - 15; j < y + 11; j++ ) - { - for( int k = z - 15; k < z + 15; k++ ) - { - if( w.canBlockSeeTheSky( i, j, k ) ) - { - skyMode++; - } - } - } - } - - boolean solid = true; - for( int j = y - 15; j < y - 1; j++ ) - { - if( w.getBlock( x, j, z ) == Platform.AIR_BLOCK ) - { - solid = false; - } - } - - if( !solid ) - { - skyMode = 0; - } - - // creator - if( skyMode > 10 ) - { - this.placeCrater( w, x, y, z ); - } - - this.placeMeteorite( w, x, y, z ); - - // collapse blocks... - if( skyMode > 3 ) - { - this.decay( w, x, y, z ); - } - - this.settings.setInteger( "skyMode", skyMode ); - w.done(); - - WorldData.instance().spawnData().addNearByMeteorites( w.getWorld().provider.dimensionId, x >> 4, z >> 4, this.settings ); - return true; - } - return false; - } - - NBTTagCompound getSettings() - { - return this.settings; - } +public final class MeteoritePlacer { + private static final double PRESSES_SPAWN_CHANCE = 0.7; + private static final int SKYSTONE_SPAWN_LIMIT = 12; + private final Collection validSpawn = new HashSet(); + private final Collection invalidSpawn = new HashSet(); + private final IBlockDefinition skyChestDefinition; + private final IBlockDefinition skyStoneDefinition; + private final MeteoriteBlockPutter putter = new MeteoriteBlockPutter(); + private double meteoriteSize = (Math.random() * 6.0) + 2; + private double realCrater = this.meteoriteSize * 2 + 5; + private double squaredMeteoriteSize = this.meteoriteSize * this.meteoriteSize; + private double crater = this.realCrater * this.realCrater; + private NBTTagCompound settings; + private Fallout type; + + public MeteoritePlacer() { + final IBlocks blocks = AEApi.instance().definitions().blocks(); + + this.skyChestDefinition = blocks.skyChest(); + this.skyStoneDefinition = blocks.skyStone(); + + this.validSpawn.add(Blocks.stone); + this.validSpawn.add(Blocks.cobblestone); + this.validSpawn.add(Blocks.grass); + this.validSpawn.add(Blocks.sand); + this.validSpawn.add(Blocks.dirt); + this.validSpawn.add(Blocks.gravel); + this.validSpawn.add(Blocks.netherrack); + this.validSpawn.add(Blocks.iron_ore); + this.validSpawn.add(Blocks.gold_ore); + this.validSpawn.add(Blocks.diamond_ore); + this.validSpawn.add(Blocks.redstone_ore); + this.validSpawn.add(Blocks.hardened_clay); + this.validSpawn.add(Blocks.ice); + this.validSpawn.add(Blocks.snow); + this.validSpawn.add(Blocks.stained_hardened_clay); + + for (final Block skyStoneBlock : this.skyStoneDefinition.maybeBlock().asSet()) { + this.invalidSpawn.add(skyStoneBlock); + } + this.invalidSpawn.add(Blocks.planks); + this.invalidSpawn.add(Blocks.iron_door); + this.invalidSpawn.add(Blocks.iron_bars); + this.invalidSpawn.add(Blocks.wooden_door); + this.invalidSpawn.add(Blocks.brick_block); + this.invalidSpawn.add(Blocks.clay); + this.invalidSpawn.add(Blocks.water); + this.invalidSpawn.add(Blocks.log); + this.invalidSpawn.add(Blocks.log2); + + this.type = new Fallout(this.putter, this.skyStoneDefinition); + } + + boolean spawnMeteorite(final IMeteoriteWorld w, final NBTTagCompound meteoriteBlob) { + this.settings = meteoriteBlob; + + final int x = this.settings.getInteger("x"); + final int y = this.settings.getInteger("y"); + final int z = this.settings.getInteger("z"); + + this.meteoriteSize = this.settings.getDouble("real_sizeOfMeteorite"); + this.realCrater = this.settings.getDouble("realCrater"); + this.squaredMeteoriteSize = this.settings.getDouble("sizeOfMeteorite"); + this.crater = this.settings.getDouble("crater"); + + final Block blk = Block.getBlockById(this.settings.getInteger("blk")); + + if (blk == Blocks.sand) { + this.type = new FalloutSand(w, x, y, z, this.putter, this.skyStoneDefinition); + } else if (blk == Blocks.hardened_clay) { + this.type = new FalloutCopy(w, x, y, z, this.putter, this.skyStoneDefinition); + } else if (blk == Blocks.ice || blk == Blocks.snow) { + this.type = new FalloutSnow(w, x, y, z, this.putter, this.skyStoneDefinition); + } + + final int skyMode = this.settings.getInteger("skyMode"); + + // creator + if (skyMode > 10) { + this.placeCrater(w, x, y, z); + } + + this.placeMeteorite(w, x, y, z); + + // collapse blocks... + if (skyMode > 3) { + this.decay(w, x, y, z); + } + + w.done(); + return true; + } + + private void placeCrater(final IMeteoriteWorld w, final int x, final int y, final int z) { + final boolean lava = this.settings.getBoolean("lava"); + + final int maxY = 255; + final int minX = w.minX(x - 200); + final int maxX = w.maxX(x + 200); + final int minZ = w.minZ(z - 200); + final int maxZ = w.maxZ(z + 200); + + for (int j = y - 5; j < maxY; j++) { + boolean changed = false; + + for (int i = minX; i < maxX; i++) { + for (int k = minZ; k < maxZ; k++) { + final double dx = i - x; + final double dz = k - z; + final double h = y - this.meteoriteSize + 1 + this.type.adjustCrater(); + + final double distanceFrom = dx * dx + dz * dz; + + if (j > h + distanceFrom * 0.02) { + if (lava && j < y && w.getBlock(x, y - 1, z).isBlockSolid(w.getWorld(), i, j, k, 0)) { + if (j > h + distanceFrom * 0.02) { + this.putter.put(w, i, j, k, Blocks.lava); + } + } else { + changed = this.putter.put(w, i, j, k, Platform.AIR_BLOCK) || changed; + } + } + } + } + } + + for (final Object o : w.getWorld() + .getEntitiesWithinAABB( + EntityItem.class, + AxisAlignedBB.getBoundingBox( + w.minX(x - 30), y - 5, w.minZ(z - 30), w.maxX(x + 30), y + 30, w.maxZ(z + 30)))) { + final Entity e = (Entity) o; + e.setDead(); + } + } + + private void placeMeteorite(final IMeteoriteWorld w, final int x, final int y, final int z) { + final int meteorXLength = w.minX(x - 8); + final int meteorXHeight = w.maxX(x + 8); + final int meteorZLength = w.minZ(z - 8); + final int meteorZHeight = w.maxZ(z + 8); + + // spawn meteor + for (int i = meteorXLength; i < meteorXHeight; i++) { + for (int j = y - 8; j < y + 8; j++) { + for (int k = meteorZLength; k < meteorZHeight; k++) { + final double dx = i - x; + final double dy = j - y; + final double dz = k - z; + + if (dx * dx * 0.7 + dy * dy * (j > y ? 1.4 : 0.8) + dz * dz * 0.7 < this.squaredMeteoriteSize) { + for (final Block skyStoneBlock : + this.skyStoneDefinition.maybeBlock().asSet()) { + this.putter.put(w, i, j, k, skyStoneBlock); + } + } + } + } + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.SpawnPressesInMeteorites)) { + for (final Block skyChestBlock : + this.skyChestDefinition.maybeBlock().asSet()) { + this.putter.put(w, x, y, z, skyChestBlock); + } + + final TileEntity te = w.getTileEntity(x, y, z); + if (te instanceof IInventory) { + final InventoryAdaptor ap = InventoryAdaptor.getAdaptor(te, ForgeDirection.UP); + + int primary = Math.max(1, (int) (Math.random() * 4)); + + if (primary > 3) // in case math breaks... + { + primary = 3; + } + + for (int zz = 0; zz < primary; zz++) { + int r = 0; + boolean duplicate = false; + + do { + duplicate = false; + + if (Math.random() > PRESSES_SPAWN_CHANCE) { + r = WorldData.instance().storageData().getNextOrderedValue("presses"); + } else { + r = (int) (Math.random() * 1000); + } + + ItemStack toAdd = null; + final IMaterials materials = + AEApi.instance().definitions().materials(); + + switch (r % 4) { + case 0: + for (final ItemStack calc : materials + .calcProcessorPress() + .maybeStack(1) + .asSet()) { + toAdd = calc; + } + break; + case 1: + for (final ItemStack calc : materials + .engProcessorPress() + .maybeStack(1) + .asSet()) { + toAdd = calc; + } + break; + case 2: + for (final ItemStack calc : materials + .logicProcessorPress() + .maybeStack(1) + .asSet()) { + toAdd = calc; + } + break; + case 3: + for (final ItemStack calc : + materials.siliconPress().maybeStack(1).asSet()) { + toAdd = calc; + } + break; + default: + } + + if (toAdd != null) { + if (ap.simulateRemove(1, toAdd, null) == null) { + ap.addItems(toAdd); + } else { + duplicate = true; + } + } + } while (duplicate); + } + + final int secondary = Math.max(1, (int) (Math.random() * 3)); + for (int zz = 0; zz < secondary; zz++) { + switch ((int) (Math.random() * 1000) % 3) { + case 0: + final int amount = (int) ((Math.random() * SKYSTONE_SPAWN_LIMIT) + 1); + for (final ItemStack skyStoneStack : + this.skyStoneDefinition.maybeStack(amount).asSet()) { + ap.addItems(skyStoneStack); + } + break; + case 1: + final List possibles = new LinkedList(); + possibles.addAll(OreDictionary.getOres("nuggetIron")); + possibles.addAll(OreDictionary.getOres("nuggetCopper")); + possibles.addAll(OreDictionary.getOres("nuggetTin")); + possibles.addAll(OreDictionary.getOres("nuggetSilver")); + possibles.addAll(OreDictionary.getOres("nuggetLead")); + possibles.addAll(OreDictionary.getOres("nuggetPlatinum")); + possibles.addAll(OreDictionary.getOres("nuggetNickel")); + possibles.addAll(OreDictionary.getOres("nuggetAluminium")); + possibles.addAll(OreDictionary.getOres("nuggetElectrum")); + possibles.add(new ItemStack(net.minecraft.init.Items.gold_nugget)); + + ItemStack nugget = Platform.pickRandom(possibles); + if (nugget != null) { + nugget = nugget.copy(); + nugget.stackSize = (int) (Math.random() * 12) + 1; + ap.addItems(nugget); + } + break; + } + } + } + } + } + + private void decay(final IMeteoriteWorld w, final int x, final int y, final int z) { + double randomShit = 0; + + final int meteorXLength = w.minX(x - 30); + final int meteorXHeight = w.maxX(x + 30); + final int meteorZLength = w.minZ(z - 30); + final int meteorZHeight = w.maxZ(z + 30); + + for (int i = meteorXLength; i < meteorXHeight; i++) { + for (int k = meteorZLength; k < meteorZHeight; k++) { + for (int j = y - 9; j < y + 30; j++) { + Block blk = w.getBlock(i, j, k); + if (blk == Blocks.lava) { + continue; + } + + if (blk.isReplaceable(w.getWorld(), i, j, k)) { + blk = Platform.AIR_BLOCK; + final Block blk_b = w.getBlock(i, j + 1, k); + + if (blk_b != blk) { + final int meta_b = w.getBlockMetadata(i, j + 1, k); + + w.setBlock(i, j, k, blk_b, meta_b, 3); + w.setBlock(i, j + 1, k, blk); + } else if (randomShit < 100 * this.crater) { + final double dx = i - x; + final double dy = j - y; + final double dz = k - z; + final double dist = dx * dx + dy * dy + dz * dz; + + final Block xf = w.getBlock(i, j - 1, k); + if (!xf.isReplaceable(w.getWorld(), i, j - 1, k)) { + final double extraRange = Math.random() * 0.6; + final double height = + this.crater * (extraRange + 0.2) - Math.abs(dist - this.crater * 1.7); + + if (xf != blk && height > 0 && Math.random() > 0.6) { + randomShit++; + this.type.getRandomFall(w, i, j, k); + } + } + } + } else { + // decay. + final Block blk_b = w.getBlock(i, j + 1, k); + if (blk_b == Platform.AIR_BLOCK) { + if (Math.random() > 0.4) { + final double dx = i - x; + final double dy = j - y; + final double dz = k - z; + + if (dx * dx + dy * dy + dz * dz < this.crater * 1.6) { + this.type.getRandomInset(w, i, j, k); + } + } + } + } + } + } + } + } + + double getSqDistance(final int x, final int z) { + final int chunkX = this.settings.getInteger("x") - x; + final int chunkZ = this.settings.getInteger("z") - z; + + return chunkX * chunkX + chunkZ * chunkZ; + } + + public boolean spawnMeteorite(final IMeteoriteWorld w, final int x, final int y, final int z) { + + if (!w.hasNoSky()) { + return false; + } + + Block blk = w.getBlock(x, y, z); + if (!this.validSpawn.contains(blk)) { + return false; // must spawn on a valid block.. + } + + this.settings = new NBTTagCompound(); + this.settings.setInteger("x", x); + this.settings.setInteger("y", y); + this.settings.setInteger("z", z); + this.settings.setInteger("blk", Block.getIdFromBlock(blk)); + + this.settings.setDouble("real_sizeOfMeteorite", this.meteoriteSize); + this.settings.setDouble("realCrater", this.realCrater); + this.settings.setDouble("sizeOfMeteorite", this.squaredMeteoriteSize); + this.settings.setDouble("crater", this.crater); + + this.settings.setBoolean("lava", Math.random() > 0.9); + + if (blk == Blocks.sand) { + this.type = new FalloutSand(w, x, y, z, this.putter, this.skyStoneDefinition); + } else if (blk == Blocks.hardened_clay) { + this.type = new FalloutCopy(w, x, y, z, this.putter, this.skyStoneDefinition); + } else if (blk == Blocks.ice || blk == Blocks.snow) { + this.type = new FalloutSnow(w, x, y, z, this.putter, this.skyStoneDefinition); + } + + int realValidBlocks = 0; + + for (int i = x - 6; i < x + 6; i++) { + for (int j = y - 6; j < y + 6; j++) { + for (int k = z - 6; k < z + 6; k++) { + blk = w.getBlock(i, j, k); + if (this.validSpawn.contains(blk)) { + realValidBlocks++; + } + } + } + } + + int validBlocks = 0; + for (int i = x - 15; i < x + 15; i++) { + for (int j = y - 15; j < y + 15; j++) { + for (int k = z - 15; k < z + 15; k++) { + blk = w.getBlock(i, j, k); + if (this.invalidSpawn.contains(blk)) { + return false; + } + if (this.validSpawn.contains(blk)) { + validBlocks++; + } + } + } + } + + final int minBLocks = 200; + if (validBlocks > minBLocks && realValidBlocks > 80) { + // we can spawn here! + + int skyMode = 0; + + for (int i = x - 15; i < x + 15; i++) { + for (int j = y - 15; j < y + 11; j++) { + for (int k = z - 15; k < z + 15; k++) { + if (w.canBlockSeeTheSky(i, j, k)) { + skyMode++; + } + } + } + } + + boolean solid = true; + for (int j = y - 15; j < y - 1; j++) { + if (w.getBlock(x, j, z) == Platform.AIR_BLOCK) { + solid = false; + } + } + + if (!solid) { + skyMode = 0; + } + + // creator + if (skyMode > 10) { + this.placeCrater(w, x, y, z); + } + + this.placeMeteorite(w, x, y, z); + + // collapse blocks... + if (skyMode > 3) { + this.decay(w, x, y, z); + } + + this.settings.setInteger("skyMode", skyMode); + w.done(); + + WorldData.instance() + .spawnData() + .addNearByMeteorites(w.getWorld().provider.dimensionId, x >> 4, z >> 4, this.settings); + return true; + } + return false; + } + + NBTTagCompound getSettings() { + return this.settings; + } } diff --git a/src/main/java/appeng/worldgen/MeteoriteWorldGen.java b/src/main/java/appeng/worldgen/MeteoriteWorldGen.java index ee2901af265..8d8b8556cf8 100644 --- a/src/main/java/appeng/worldgen/MeteoriteWorldGen.java +++ b/src/main/java/appeng/worldgen/MeteoriteWorldGen.java @@ -18,7 +18,6 @@ package appeng.worldgen; - import appeng.api.features.IWorldGen.WorldGenType; import appeng.core.AEConfig; import appeng.core.features.registries.WorldGenRegistry; @@ -28,131 +27,113 @@ import appeng.util.Platform; import appeng.worldgen.meteorite.ChunkOnly; import cpw.mods.fml.common.IWorldGenerator; +import java.util.Random; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; -import java.util.Random; - - -public final class MeteoriteWorldGen implements IWorldGenerator -{ - @Override - public void generate( final Random r, final int chunkX, final int chunkZ, final World w, final IChunkProvider chunkGenerator, final IChunkProvider chunkProvider ) - { - if( WorldGenRegistry.INSTANCE.isWorldGenEnabled( WorldGenType.Meteorites, w ) ) - { - // add new meteorites? - if( r.nextFloat() < AEConfig.instance.meteoriteSpawnChance ) - { - final int x = r.nextInt( 16 ) + ( chunkX << 4 ); - final int z = r.nextInt( 16 ) + ( chunkZ << 4 ); - - final int depth = 180 + r.nextInt( 20 ); - TickHandler.INSTANCE.addCallable( w, new MeteoriteSpawn( x, depth, z ) ); - } - else - { - TickHandler.INSTANCE.addCallable( w, new MeteoriteSpawn( chunkX << 4, 128, chunkZ << 4 ) ); - } - } - else - { - WorldData.instance().compassData().service().updateArea( w, chunkX, chunkZ ); - } - } - - private boolean tryMeteorite( final World w, int depth, final int x, final int z ) - { - for( int tries = 0; tries < 20; tries++ ) - { - final MeteoritePlacer mp = new MeteoritePlacer(); - - if( mp.spawnMeteorite( new ChunkOnly( w, x >> 4, z >> 4 ), x, depth, z ) ) - { - final int px = x >> 4; - final int pz = z >> 4; - - for( int cx = px - 6; cx < px + 6; cx++ ) - { - for( int cz = pz - 6; cz < pz + 6; cz++ ) - { - if( w.getChunkProvider().chunkExists( cx, cz ) ) - { - if( px == cx && pz == cz ) - { - continue; - } - - if( WorldData.instance().spawnData().hasGenerated( w.provider.dimensionId, cx, cz ) ) - { - final MeteoritePlacer mp2 = new MeteoritePlacer(); - mp2.spawnMeteorite( new ChunkOnly( w, cx, cz ), mp.getSettings() ); - } - } - } - } - - return true; - } - - depth -= 15; - if( depth < 40 ) - { - return false; - } - } - - return false; - } - - private Iterable getNearByMeteorites( final World w, final int chunkX, final int chunkZ ) - { - return WorldData.instance().spawnData().getNearByMeteorites( w.provider.dimensionId, chunkX, chunkZ ); - } - - private class MeteoriteSpawn implements IWorldCallable - { - - private final int x; - private final int z; - private final int depth; - - public MeteoriteSpawn( final int x, final int depth, final int z ) - { - this.x = x; - this.z = z; - this.depth = depth; - } - - @Override - public Object call( final World world ) throws Exception - { - final int chunkX = this.x >> 4; - final int chunkZ = this.z >> 4; - - double minSqDist = Double.MAX_VALUE; - - // near by meteorites! - for( final NBTTagCompound data : MeteoriteWorldGen.this.getNearByMeteorites( world, chunkX, chunkZ ) ) - { - final MeteoritePlacer mp = new MeteoritePlacer(); - mp.spawnMeteorite( new ChunkOnly( world, chunkX, chunkZ ), data ); - - minSqDist = Math.min( minSqDist, mp.getSqDistance( this.x, this.z ) ); - } - - final boolean isCluster = ( minSqDist < 30 * 30 ) && Platform.getRandomFloat() < AEConfig.instance.meteoriteClusterChance; - - if( minSqDist > AEConfig.instance.minMeteoriteDistanceSq || isCluster ) - { - MeteoriteWorldGen.this.tryMeteorite( world, this.depth, this.x, this.z ); - } - - WorldData.instance().spawnData().setGenerated( world.provider.dimensionId, chunkX, chunkZ ); - WorldData.instance().compassData().service().updateArea( world, chunkX, chunkZ ); - - return null; - } - } +public final class MeteoriteWorldGen implements IWorldGenerator { + @Override + public void generate( + final Random r, + final int chunkX, + final int chunkZ, + final World w, + final IChunkProvider chunkGenerator, + final IChunkProvider chunkProvider) { + if (WorldGenRegistry.INSTANCE.isWorldGenEnabled(WorldGenType.Meteorites, w)) { + // add new meteorites? + if (r.nextFloat() < AEConfig.instance.meteoriteSpawnChance) { + final int x = r.nextInt(16) + (chunkX << 4); + final int z = r.nextInt(16) + (chunkZ << 4); + + final int depth = 180 + r.nextInt(20); + TickHandler.INSTANCE.addCallable(w, new MeteoriteSpawn(x, depth, z)); + } else { + TickHandler.INSTANCE.addCallable(w, new MeteoriteSpawn(chunkX << 4, 128, chunkZ << 4)); + } + } else { + WorldData.instance().compassData().service().updateArea(w, chunkX, chunkZ); + } + } + + private boolean tryMeteorite(final World w, int depth, final int x, final int z) { + for (int tries = 0; tries < 20; tries++) { + final MeteoritePlacer mp = new MeteoritePlacer(); + + if (mp.spawnMeteorite(new ChunkOnly(w, x >> 4, z >> 4), x, depth, z)) { + final int px = x >> 4; + final int pz = z >> 4; + + for (int cx = px - 6; cx < px + 6; cx++) { + for (int cz = pz - 6; cz < pz + 6; cz++) { + if (w.getChunkProvider().chunkExists(cx, cz)) { + if (px == cx && pz == cz) { + continue; + } + + if (WorldData.instance().spawnData().hasGenerated(w.provider.dimensionId, cx, cz)) { + final MeteoritePlacer mp2 = new MeteoritePlacer(); + mp2.spawnMeteorite(new ChunkOnly(w, cx, cz), mp.getSettings()); + } + } + } + } + + return true; + } + + depth -= 15; + if (depth < 40) { + return false; + } + } + + return false; + } + + private Iterable getNearByMeteorites(final World w, final int chunkX, final int chunkZ) { + return WorldData.instance().spawnData().getNearByMeteorites(w.provider.dimensionId, chunkX, chunkZ); + } + + private class MeteoriteSpawn implements IWorldCallable { + + private final int x; + private final int z; + private final int depth; + + public MeteoriteSpawn(final int x, final int depth, final int z) { + this.x = x; + this.z = z; + this.depth = depth; + } + + @Override + public Object call(final World world) throws Exception { + final int chunkX = this.x >> 4; + final int chunkZ = this.z >> 4; + + double minSqDist = Double.MAX_VALUE; + + // near by meteorites! + for (final NBTTagCompound data : MeteoriteWorldGen.this.getNearByMeteorites(world, chunkX, chunkZ)) { + final MeteoritePlacer mp = new MeteoritePlacer(); + mp.spawnMeteorite(new ChunkOnly(world, chunkX, chunkZ), data); + + minSqDist = Math.min(minSqDist, mp.getSqDistance(this.x, this.z)); + } + + final boolean isCluster = + (minSqDist < 30 * 30) && Platform.getRandomFloat() < AEConfig.instance.meteoriteClusterChance; + + if (minSqDist > AEConfig.instance.minMeteoriteDistanceSq || isCluster) { + MeteoriteWorldGen.this.tryMeteorite(world, this.depth, this.x, this.z); + } + + WorldData.instance().spawnData().setGenerated(world.provider.dimensionId, chunkX, chunkZ); + WorldData.instance().compassData().service().updateArea(world, chunkX, chunkZ); + + return null; + } + } } diff --git a/src/main/java/appeng/worldgen/QuartzWorldGen.java b/src/main/java/appeng/worldgen/QuartzWorldGen.java index 5dbde893261..757ada89b68 100644 --- a/src/main/java/appeng/worldgen/QuartzWorldGen.java +++ b/src/main/java/appeng/worldgen/QuartzWorldGen.java @@ -18,7 +18,6 @@ package appeng.worldgen; - import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IBlocks; @@ -26,65 +25,63 @@ import appeng.core.AEConfig; import appeng.core.features.registries.WorldGenRegistry; import cpw.mods.fml.common.IWorldGenerator; +import java.util.Random; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.feature.WorldGenMinable; -import java.util.Random; - - -public final class QuartzWorldGen implements IWorldGenerator -{ - private final WorldGenMinable oreNormal; - private final WorldGenMinable oreCharged; +public final class QuartzWorldGen implements IWorldGenerator { + private final WorldGenMinable oreNormal; + private final WorldGenMinable oreCharged; - public QuartzWorldGen() - { - final IBlocks blocks = AEApi.instance().definitions().blocks(); - final IBlockDefinition oreDefinition = blocks.quartzOre(); - final IBlockDefinition chargedDefinition = blocks.quartzOreCharged(); + public QuartzWorldGen() { + final IBlocks blocks = AEApi.instance().definitions().blocks(); + final IBlockDefinition oreDefinition = blocks.quartzOre(); + final IBlockDefinition chargedDefinition = blocks.quartzOreCharged(); - final Block ore = oreDefinition.maybeBlock().orNull(); - final Block charged = chargedDefinition.maybeBlock().orNull(); + final Block ore = oreDefinition.maybeBlock().orNull(); + final Block charged = chargedDefinition.maybeBlock().orNull(); - this.oreNormal = new WorldGenMinable( ore, 0, AEConfig.instance.quartzOresPerCluster, Blocks.stone ); - this.oreCharged = new WorldGenMinable( charged, 0, AEConfig.instance.quartzOresPerCluster, Blocks.stone ); - } + this.oreNormal = new WorldGenMinable(ore, 0, AEConfig.instance.quartzOresPerCluster, Blocks.stone); + this.oreCharged = new WorldGenMinable(charged, 0, AEConfig.instance.quartzOresPerCluster, Blocks.stone); + } - @Override - public void generate( final Random r, final int chunkX, final int chunkZ, final World w, final IChunkProvider chunkGenerator, final IChunkProvider chunkProvider ) - { - int seaLevel = w.provider.getAverageGroundLevel() + 1; + @Override + public void generate( + final Random r, + final int chunkX, + final int chunkZ, + final World w, + final IChunkProvider chunkGenerator, + final IChunkProvider chunkProvider) { + int seaLevel = w.provider.getAverageGroundLevel() + 1; - if( seaLevel < 20 ) - { - final int x = ( chunkX << 4 ) + 8; - final int z = ( chunkZ << 4 ) + 8; - seaLevel = w.getHeightValue( x, z ); - } + if (seaLevel < 20) { + final int x = (chunkX << 4) + 8; + final int z = (chunkZ << 4) + 8; + seaLevel = w.getHeightValue(x, z); + } - if( this.oreNormal == null || this.oreCharged == null ) - { - return; - } + if (this.oreNormal == null || this.oreCharged == null) { + return; + } - final double oreDepthMultiplier = AEConfig.instance.quartzOresClusterAmount * seaLevel / 64; - final int scale = (int) Math.round( r.nextGaussian() * Math.sqrt( oreDepthMultiplier ) + oreDepthMultiplier ); + final double oreDepthMultiplier = AEConfig.instance.quartzOresClusterAmount * seaLevel / 64; + final int scale = (int) Math.round(r.nextGaussian() * Math.sqrt(oreDepthMultiplier) + oreDepthMultiplier); - for( int x = 0; x < ( r.nextBoolean() ? scale * 2 : scale ) / 2; ++x ) - { - final boolean isCharged = r.nextFloat() > AEConfig.instance.spawnChargedChance; - final WorldGenMinable whichOre = isCharged ? this.oreCharged : this.oreNormal; + for (int x = 0; x < (r.nextBoolean() ? scale * 2 : scale) / 2; ++x) { + final boolean isCharged = r.nextFloat() > AEConfig.instance.spawnChargedChance; + final WorldGenMinable whichOre = isCharged ? this.oreCharged : this.oreNormal; - if( WorldGenRegistry.INSTANCE.isWorldGenEnabled( isCharged ? WorldGenType.ChargedCertusQuartz : WorldGenType.CertusQuartz, w ) ) - { - final int cx = chunkX * 16 + r.nextInt( 22 ); - final int cy = r.nextInt( 40 * seaLevel / 64 ) + r.nextInt( 22 * seaLevel / 64 ) + 12 * seaLevel / 64; - final int cz = chunkZ * 16 + r.nextInt( 22 ); - whichOre.generate( w, r, cx, cy, cz ); - } - } - } + if (WorldGenRegistry.INSTANCE.isWorldGenEnabled( + isCharged ? WorldGenType.ChargedCertusQuartz : WorldGenType.CertusQuartz, w)) { + final int cx = chunkX * 16 + r.nextInt(22); + final int cy = r.nextInt(40 * seaLevel / 64) + r.nextInt(22 * seaLevel / 64) + 12 * seaLevel / 64; + final int cz = chunkZ * 16 + r.nextInt(22); + whichOre.generate(w, r, cx, cy, cz); + } + } + } } diff --git a/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java b/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java index f3229e1cafa..89ccad1f8b5 100644 --- a/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java +++ b/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java @@ -1,104 +1,85 @@ package appeng.worldgen.meteorite; - import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; - -public class ChunkOnly extends StandardWorld -{ - - private final Chunk target; - private final int cx; - private final int cz; - private int verticalBits = 0; - - public ChunkOnly( final World w, final int cx, final int cz ) - { - super( w ); - this.target = w.getChunkFromChunkCoords( cx, cz ); - this.cx = cx; - this.cz = cz; - } - - @Override - public int minX( final int in ) - { - return Math.max( in, this.cx << 4 ); - } - - @Override - public int minZ( final int in ) - { - return Math.max( in, this.cz << 4 ); - } - - @Override - public int maxX( final int in ) - { - return Math.min( in, ( this.cx + 1 ) << 4 ); - } - - @Override - public int maxZ( final int in ) - { - return Math.min( in, ( this.cz + 1 ) << 4 ); - } - - @Override - public int getBlockMetadata( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.target.getBlockMetadata( x & 0xF, y, z & 0xF ); - } - return 0; - } - - @Override - public Block getBlock( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.target.getBlock( x & 0xF, y, z & 0xF ); - } - return Platform.AIR_BLOCK; - } - - @Override - public void setBlock( final int x, final int y, final int z, final Block blk ) - { - if( this.range( x, y, z ) ) - { - this.verticalBits |= 1 << ( y >> 4 ); - this.getWorld().setBlock( x, y, z, blk, 0, 1 ); - } - } - - @Override - public void setBlock( final int x, final int y, final int z, final Block block, final int meta, final int flags ) - { - if( this.range( x, y, z ) ) - { - this.verticalBits |= 1 << ( y >> 4 ); - this.getWorld().setBlock( x, y, z, block, meta, flags & ( ~2 ) ); - } - } - - @Override - public void done() - { - if( this.verticalBits != 0 ) - { - Platform.sendChunk( this.target, this.verticalBits ); - } - } - - @Override - public boolean range( final int x, final int y, final int z ) - { - return this.cx == ( x >> 4 ) && this.cz == ( z >> 4 ); - } +public class ChunkOnly extends StandardWorld { + + private final Chunk target; + private final int cx; + private final int cz; + private int verticalBits = 0; + + public ChunkOnly(final World w, final int cx, final int cz) { + super(w); + this.target = w.getChunkFromChunkCoords(cx, cz); + this.cx = cx; + this.cz = cz; + } + + @Override + public int minX(final int in) { + return Math.max(in, this.cx << 4); + } + + @Override + public int minZ(final int in) { + return Math.max(in, this.cz << 4); + } + + @Override + public int maxX(final int in) { + return Math.min(in, (this.cx + 1) << 4); + } + + @Override + public int maxZ(final int in) { + return Math.min(in, (this.cz + 1) << 4); + } + + @Override + public int getBlockMetadata(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.target.getBlockMetadata(x & 0xF, y, z & 0xF); + } + return 0; + } + + @Override + public Block getBlock(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.target.getBlock(x & 0xF, y, z & 0xF); + } + return Platform.AIR_BLOCK; + } + + @Override + public void setBlock(final int x, final int y, final int z, final Block blk) { + if (this.range(x, y, z)) { + this.verticalBits |= 1 << (y >> 4); + this.getWorld().setBlock(x, y, z, blk, 0, 1); + } + } + + @Override + public void setBlock(final int x, final int y, final int z, final Block block, final int meta, final int flags) { + if (this.range(x, y, z)) { + this.verticalBits |= 1 << (y >> 4); + this.getWorld().setBlock(x, y, z, block, meta, flags & (~2)); + } + } + + @Override + public void done() { + if (this.verticalBits != 0) { + Platform.sendChunk(this.target, this.verticalBits); + } + } + + @Override + public boolean range(final int x, final int y, final int z) { + return this.cx == (x >> 4) && this.cz == (z >> 4); + } } diff --git a/src/main/java/appeng/worldgen/meteorite/Fallout.java b/src/main/java/appeng/worldgen/meteorite/Fallout.java index e0be26abd13..55a98173337 100644 --- a/src/main/java/appeng/worldgen/meteorite/Fallout.java +++ b/src/main/java/appeng/worldgen/meteorite/Fallout.java @@ -1,78 +1,53 @@ package appeng.worldgen.meteorite; - import appeng.api.definitions.IBlockDefinition; import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.init.Blocks; - -public class Fallout -{ - private final MeteoriteBlockPutter putter; - private final IBlockDefinition skyStoneDefinition; - - public Fallout( final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition ) - { - this.putter = putter; - this.skyStoneDefinition = skyStoneDefinition; - } - - public int adjustCrater() - { - return 0; - } - - public void getRandomFall( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final double a = Math.random(); - if( a > 0.9 ) - { - this.putter.put( w, x, y, z, Blocks.stone ); - } - else if( a > 0.8 ) - { - this.putter.put( w, x, y, z, Blocks.cobblestone ); - } - else if( a > 0.7 ) - { - this.putter.put( w, x, y, z, Blocks.dirt ); - } - else - { - this.putter.put( w, x, y, z, Blocks.gravel ); - } - } - - public void getRandomInset( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final double a = Math.random(); - if( a > 0.9 ) - { - this.putter.put( w, x, y, z, Blocks.cobblestone ); - } - else if( a > 0.8 ) - { - this.putter.put( w, x, y, z, Blocks.stone ); - } - else if( a > 0.7 ) - { - this.putter.put( w, x, y, z, Blocks.grass ); - } - else if( a > 0.6 ) - { - for( final Block skyStoneBlock : this.skyStoneDefinition.maybeBlock().asSet() ) - { - this.putter.put( w, x, y, z, skyStoneBlock ); - } - } - else if( a > 0.5 ) - { - this.putter.put( w, x, y, z, Blocks.gravel ); - } - else - { - this.putter.put( w, x, y, z, Platform.AIR_BLOCK ); - } - } +public class Fallout { + private final MeteoriteBlockPutter putter; + private final IBlockDefinition skyStoneDefinition; + + public Fallout(final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition) { + this.putter = putter; + this.skyStoneDefinition = skyStoneDefinition; + } + + public int adjustCrater() { + return 0; + } + + public void getRandomFall(final IMeteoriteWorld w, final int x, final int y, final int z) { + final double a = Math.random(); + if (a > 0.9) { + this.putter.put(w, x, y, z, Blocks.stone); + } else if (a > 0.8) { + this.putter.put(w, x, y, z, Blocks.cobblestone); + } else if (a > 0.7) { + this.putter.put(w, x, y, z, Blocks.dirt); + } else { + this.putter.put(w, x, y, z, Blocks.gravel); + } + } + + public void getRandomInset(final IMeteoriteWorld w, final int x, final int y, final int z) { + final double a = Math.random(); + if (a > 0.9) { + this.putter.put(w, x, y, z, Blocks.cobblestone); + } else if (a > 0.8) { + this.putter.put(w, x, y, z, Blocks.stone); + } else if (a > 0.7) { + this.putter.put(w, x, y, z, Blocks.grass); + } else if (a > 0.6) { + for (final Block skyStoneBlock : + this.skyStoneDefinition.maybeBlock().asSet()) { + this.putter.put(w, x, y, z, skyStoneBlock); + } + } else if (a > 0.5) { + this.putter.put(w, x, y, z, Blocks.gravel); + } else { + this.putter.put(w, x, y, z, Platform.AIR_BLOCK); + } + } } diff --git a/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java b/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java index e3660c20ace..79dd17b03cb 100644 --- a/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java +++ b/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java @@ -1,63 +1,52 @@ package appeng.worldgen.meteorite; - import appeng.api.definitions.IBlockDefinition; import appeng.util.Platform; import net.minecraft.block.Block; - -public class FalloutCopy extends Fallout -{ - private static final double SPECIFIED_BLOCK_THRESHOLD = 0.9; - private static final double AIR_BLOCK_THRESHOLD = 0.8; - private static final double BLOCK_THRESHOLD_STEP = 0.1; - - private final Block block; - private final int meta; - private final MeteoriteBlockPutter putter; - - public FalloutCopy( final IMeteoriteWorld w, final int x, final int y, final int z, final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition ) - { - super( putter, skyStoneDefinition ); - this.putter = putter; - this.block = w.getBlock( x, y, z ); - this.meta = w.getBlockMetadata( x, y, z ); - } - - @Override - public void getRandomFall( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final double a = Math.random(); - if( a > SPECIFIED_BLOCK_THRESHOLD ) - { - this.putter.put( w, x, y, z, this.block, this.meta ); - } - else - { - this.getOther( w, x, y, z, a ); - } - } - - public void getOther( final IMeteoriteWorld w, final int x, final int y, final int z, final double a ) - { - - } - - @Override - public void getRandomInset( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final double a = Math.random(); - if( a > SPECIFIED_BLOCK_THRESHOLD ) - { - this.putter.put( w, x, y, z, this.block, this.meta ); - } - else if( a > AIR_BLOCK_THRESHOLD ) - { - this.putter.put( w, x, y, z, Platform.AIR_BLOCK ); - } - else - { - this.getOther( w, x, y, z, a - BLOCK_THRESHOLD_STEP ); - } - } -} \ No newline at end of file +public class FalloutCopy extends Fallout { + private static final double SPECIFIED_BLOCK_THRESHOLD = 0.9; + private static final double AIR_BLOCK_THRESHOLD = 0.8; + private static final double BLOCK_THRESHOLD_STEP = 0.1; + + private final Block block; + private final int meta; + private final MeteoriteBlockPutter putter; + + public FalloutCopy( + final IMeteoriteWorld w, + final int x, + final int y, + final int z, + final MeteoriteBlockPutter putter, + final IBlockDefinition skyStoneDefinition) { + super(putter, skyStoneDefinition); + this.putter = putter; + this.block = w.getBlock(x, y, z); + this.meta = w.getBlockMetadata(x, y, z); + } + + @Override + public void getRandomFall(final IMeteoriteWorld w, final int x, final int y, final int z) { + final double a = Math.random(); + if (a > SPECIFIED_BLOCK_THRESHOLD) { + this.putter.put(w, x, y, z, this.block, this.meta); + } else { + this.getOther(w, x, y, z, a); + } + } + + public void getOther(final IMeteoriteWorld w, final int x, final int y, final int z, final double a) {} + + @Override + public void getRandomInset(final IMeteoriteWorld w, final int x, final int y, final int z) { + final double a = Math.random(); + if (a > SPECIFIED_BLOCK_THRESHOLD) { + this.putter.put(w, x, y, z, this.block, this.meta); + } else if (a > AIR_BLOCK_THRESHOLD) { + this.putter.put(w, x, y, z, Platform.AIR_BLOCK); + } else { + this.getOther(w, x, y, z, a - BLOCK_THRESHOLD_STEP); + } + } +} diff --git a/src/main/java/appeng/worldgen/meteorite/FalloutSand.java b/src/main/java/appeng/worldgen/meteorite/FalloutSand.java index fe1ad5dd0f3..d4eb8cebc8c 100644 --- a/src/main/java/appeng/worldgen/meteorite/FalloutSand.java +++ b/src/main/java/appeng/worldgen/meteorite/FalloutSand.java @@ -1,33 +1,32 @@ package appeng.worldgen.meteorite; - import appeng.api.definitions.IBlockDefinition; import net.minecraft.init.Blocks; +public class FalloutSand extends FalloutCopy { + private static final double GLASS_THRESHOLD = 0.66; + private final MeteoriteBlockPutter putter; -public class FalloutSand extends FalloutCopy -{ - private static final double GLASS_THRESHOLD = 0.66; - private final MeteoriteBlockPutter putter; - - public FalloutSand( final IMeteoriteWorld w, final int x, final int y, final int z, final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition ) - { - super( w, x, y, z, putter, skyStoneDefinition ); - this.putter = putter; - } + public FalloutSand( + final IMeteoriteWorld w, + final int x, + final int y, + final int z, + final MeteoriteBlockPutter putter, + final IBlockDefinition skyStoneDefinition) { + super(w, x, y, z, putter, skyStoneDefinition); + this.putter = putter; + } - @Override - public int adjustCrater() - { - return 2; - } + @Override + public int adjustCrater() { + return 2; + } - @Override - public void getOther( final IMeteoriteWorld w, final int x, final int y, final int z, final double a ) - { - if( a > GLASS_THRESHOLD ) - { - this.putter.put( w, x, y, z, Blocks.glass ); - } - } -} \ No newline at end of file + @Override + public void getOther(final IMeteoriteWorld w, final int x, final int y, final int z, final double a) { + if (a > GLASS_THRESHOLD) { + this.putter.put(w, x, y, z, Blocks.glass); + } + } +} diff --git a/src/main/java/appeng/worldgen/meteorite/FalloutSnow.java b/src/main/java/appeng/worldgen/meteorite/FalloutSnow.java index 7030a568c34..0445fdd0c5a 100644 --- a/src/main/java/appeng/worldgen/meteorite/FalloutSnow.java +++ b/src/main/java/appeng/worldgen/meteorite/FalloutSnow.java @@ -1,38 +1,35 @@ package appeng.worldgen.meteorite; - import appeng.api.definitions.IBlockDefinition; import net.minecraft.init.Blocks; +public class FalloutSnow extends FalloutCopy { + private static final double SNOW_THRESHOLD = 0.7; + private static final double ICE_THRESHOLD = 0.5; + private final MeteoriteBlockPutter putter; -public class FalloutSnow extends FalloutCopy -{ - private static final double SNOW_THRESHOLD = 0.7; - private static final double ICE_THRESHOLD = 0.5; - private final MeteoriteBlockPutter putter; - - public FalloutSnow( final IMeteoriteWorld w, final int x, final int y, final int z, final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition ) - { - super( w, x, y, z, putter, skyStoneDefinition ); - this.putter = putter; - } + public FalloutSnow( + final IMeteoriteWorld w, + final int x, + final int y, + final int z, + final MeteoriteBlockPutter putter, + final IBlockDefinition skyStoneDefinition) { + super(w, x, y, z, putter, skyStoneDefinition); + this.putter = putter; + } - @Override - public int adjustCrater() - { - return 2; - } + @Override + public int adjustCrater() { + return 2; + } - @Override - public void getOther( final IMeteoriteWorld w, final int x, final int y, final int z, final double a ) - { - if( a > SNOW_THRESHOLD ) - { - this.putter.put( w, x, y, z, Blocks.snow ); - } - else if( a > ICE_THRESHOLD ) - { - this.putter.put( w, x, y, z, Blocks.ice ); - } - } -} \ No newline at end of file + @Override + public void getOther(final IMeteoriteWorld w, final int x, final int y, final int z, final double a) { + if (a > SNOW_THRESHOLD) { + this.putter.put(w, x, y, z, Blocks.snow); + } else if (a > ICE_THRESHOLD) { + this.putter.put(w, x, y, z, Blocks.ice); + } + } +} diff --git a/src/main/java/appeng/worldgen/meteorite/IMeteoriteWorld.java b/src/main/java/appeng/worldgen/meteorite/IMeteoriteWorld.java index 34eda3de2dc..48ff8451a4e 100644 --- a/src/main/java/appeng/worldgen/meteorite/IMeteoriteWorld.java +++ b/src/main/java/appeng/worldgen/meteorite/IMeteoriteWorld.java @@ -1,36 +1,33 @@ package appeng.worldgen.meteorite; - import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; +public interface IMeteoriteWorld { + int minX(int in); -public interface IMeteoriteWorld -{ - int minX( int in ); - - int minZ( int in ); + int minZ(int in); - int maxX( int in ); + int maxX(int in); - int maxZ( int in ); + int maxZ(int in); - boolean hasNoSky(); + boolean hasNoSky(); - int getBlockMetadata( int x, int y, int z ); + int getBlockMetadata(int x, int y, int z); - Block getBlock( int x, int y, int z ); + Block getBlock(int x, int y, int z); - boolean canBlockSeeTheSky( int i, int j, int k ); + boolean canBlockSeeTheSky(int i, int j, int k); - TileEntity getTileEntity( int x, int y, int z ); + TileEntity getTileEntity(int x, int y, int z); - World getWorld(); + World getWorld(); - void setBlock( int i, int j, int k, Block blk ); + void setBlock(int i, int j, int k, Block blk); - void setBlock( int i, int j, int k, Block block, int meta, int l ); + void setBlock(int i, int j, int k, Block block, int meta, int l); - void done(); -} \ No newline at end of file + void done(); +} diff --git a/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java b/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java index e27aa48e1c2..5f77f120991 100644 --- a/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java +++ b/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java @@ -1,32 +1,25 @@ package appeng.worldgen.meteorite; - import net.minecraft.block.Block; import net.minecraft.init.Blocks; +public class MeteoriteBlockPutter { + public boolean put(final IMeteoriteWorld w, final int i, final int j, final int k, final Block blk) { + final Block original = w.getBlock(i, j, k); -public class MeteoriteBlockPutter -{ - public boolean put( final IMeteoriteWorld w, final int i, final int j, final int k, final Block blk ) - { - final Block original = w.getBlock( i, j, k ); - - if( original == Blocks.bedrock || original == blk ) - { - return false; - } + if (original == Blocks.bedrock || original == blk) { + return false; + } - w.setBlock( i, j, k, blk ); - return true; - } + w.setBlock(i, j, k, blk); + return true; + } - void put( final IMeteoriteWorld w, final int i, final int j, final int k, final Block blk, final int meta ) - { - if( w.getBlock( i, j, k ) == Blocks.bedrock ) - { - return; - } + void put(final IMeteoriteWorld w, final int i, final int j, final int k, final Block blk, final int meta) { + if (w.getBlock(i, j, k) == Blocks.bedrock) { + return; + } - w.setBlock( i, j, k, blk, meta, 3 ); - } + w.setBlock(i, j, k, blk, meta, 3); + } } diff --git a/src/main/java/appeng/worldgen/meteorite/StandardWorld.java b/src/main/java/appeng/worldgen/meteorite/StandardWorld.java index 7425ba12d1c..e5c8a3ac339 100644 --- a/src/main/java/appeng/worldgen/meteorite/StandardWorld.java +++ b/src/main/java/appeng/worldgen/meteorite/StandardWorld.java @@ -1,124 +1,98 @@ package appeng.worldgen.meteorite; - import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; - -public class StandardWorld implements IMeteoriteWorld -{ - - private final World w; - - public StandardWorld( final World w ) - { - this.w = w; - } - - @Override - public int minX( final int in ) - { - return in; - } - - @Override - public int minZ( final int in ) - { - return in; - } - - @Override - public int maxX( final int in ) - { - return in; - } - - @Override - public int maxZ( final int in ) - { - return in; - } - - @Override - public boolean hasNoSky() - { - return !this.getWorld().provider.hasNoSky; - } - - @Override - public int getBlockMetadata( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.getWorld().getBlockMetadata( x, y, z ); - } - return 0; - } - - @Override - public Block getBlock( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.getWorld().getBlock( x, y, z ); - } - return Platform.AIR_BLOCK; - } - - @Override - public boolean canBlockSeeTheSky( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.getWorld().canBlockSeeTheSky( x, y, z ); - } - return false; - } - - @Override - public TileEntity getTileEntity( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.getWorld().getTileEntity( x, y, z ); - } - return null; - } - - @Override - public World getWorld() - { - return this.w; - } - - @Override - public void setBlock( final int x, final int y, final int z, final Block blk ) - { - if( this.range( x, y, z ) ) - { - this.getWorld().setBlock( x, y, z, blk ); - } - } - - @Override - public void setBlock( final int x, final int y, final int z, final Block block, final int meta, final int flags ) - { - if( this.range( x, y, z ) ) - { - this.getWorld().setBlock( x, y, z, block, meta, flags ); - } - } - - @Override - public void done() - { - - } - - public boolean range( final int x, final int y, final int z ) - { - return true; - } +public class StandardWorld implements IMeteoriteWorld { + + private final World w; + + public StandardWorld(final World w) { + this.w = w; + } + + @Override + public int minX(final int in) { + return in; + } + + @Override + public int minZ(final int in) { + return in; + } + + @Override + public int maxX(final int in) { + return in; + } + + @Override + public int maxZ(final int in) { + return in; + } + + @Override + public boolean hasNoSky() { + return !this.getWorld().provider.hasNoSky; + } + + @Override + public int getBlockMetadata(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.getWorld().getBlockMetadata(x, y, z); + } + return 0; + } + + @Override + public Block getBlock(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.getWorld().getBlock(x, y, z); + } + return Platform.AIR_BLOCK; + } + + @Override + public boolean canBlockSeeTheSky(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.getWorld().canBlockSeeTheSky(x, y, z); + } + return false; + } + + @Override + public TileEntity getTileEntity(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.getWorld().getTileEntity(x, y, z); + } + return null; + } + + @Override + public World getWorld() { + return this.w; + } + + @Override + public void setBlock(final int x, final int y, final int z, final Block blk) { + if (this.range(x, y, z)) { + this.getWorld().setBlock(x, y, z, blk); + } + } + + @Override + public void setBlock(final int x, final int y, final int z, final Block block, final int meta, final int flags) { + if (this.range(x, y, z)) { + this.getWorld().setBlock(x, y, z, block, meta, flags); + } + } + + @Override + public void done() {} + + public boolean range(final int x, final int y, final int z) { + return true; + } } diff --git a/src/test/java/appeng/core/worlddata/MeteorDataNameEncoderTest.java b/src/test/java/appeng/core/worlddata/MeteorDataNameEncoderTest.java index f66575b07d5..c6cf652c4a4 100644 --- a/src/test/java/appeng/core/worlddata/MeteorDataNameEncoderTest.java +++ b/src/test/java/appeng/core/worlddata/MeteorDataNameEncoderTest.java @@ -18,11 +18,9 @@ package appeng.core.worlddata; - import org.junit.Assert; import org.junit.Test; - /** * Tests for {@link MeteorDataNameEncoder} * @@ -30,36 +28,33 @@ * @version rv3 - 06.06.2015 * @since rv3 06.06.2015 */ -public class MeteorDataNameEncoderTest -{ - private static final int WITHOUT_DIMENSION = -5; - private static final int WITHOUT_CHUNK_X = 0; - private static final int WITHOUT_CHUNK_Z = 13; - private static final String WITHOUT_EXPECTED = "-5_0_13.dat"; - - private static final int WITH_DIMENSION = 3; - private static final int WITH_CHUNK_X = 32; - private static final int WITH_CHUNK_Z = -64; - private static final String WITH_EXPECTED = "3_2_-4.dat"; - - private final MeteorDataNameEncoder encoderWithZeroShifting = new MeteorDataNameEncoder( 0 ); - private final MeteorDataNameEncoder encoderWithFourShifting = new MeteorDataNameEncoder( 4 ); - - @Test - public void testEncoderWithoutShifting() - { - final String expected = WITHOUT_EXPECTED; - final String actual = this.encoderWithZeroShifting.encode( WITHOUT_DIMENSION, WITHOUT_CHUNK_X, WITHOUT_CHUNK_Z ); - - Assert.assertEquals( expected, actual ); - } - - @Test - public void testEncoderWithShifting() - { - final String expected = WITH_EXPECTED; - final String actual = this.encoderWithFourShifting.encode( WITH_DIMENSION, WITH_CHUNK_X, WITH_CHUNK_Z ); - - Assert.assertEquals( expected, actual ); - } +public class MeteorDataNameEncoderTest { + private static final int WITHOUT_DIMENSION = -5; + private static final int WITHOUT_CHUNK_X = 0; + private static final int WITHOUT_CHUNK_Z = 13; + private static final String WITHOUT_EXPECTED = "-5_0_13.dat"; + + private static final int WITH_DIMENSION = 3; + private static final int WITH_CHUNK_X = 32; + private static final int WITH_CHUNK_Z = -64; + private static final String WITH_EXPECTED = "3_2_-4.dat"; + + private final MeteorDataNameEncoder encoderWithZeroShifting = new MeteorDataNameEncoder(0); + private final MeteorDataNameEncoder encoderWithFourShifting = new MeteorDataNameEncoder(4); + + @Test + public void testEncoderWithoutShifting() { + final String expected = WITHOUT_EXPECTED; + final String actual = this.encoderWithZeroShifting.encode(WITHOUT_DIMENSION, WITHOUT_CHUNK_X, WITHOUT_CHUNK_Z); + + Assert.assertEquals(expected, actual); + } + + @Test + public void testEncoderWithShifting() { + final String expected = WITH_EXPECTED; + final String actual = this.encoderWithFourShifting.encode(WITH_DIMENSION, WITH_CHUNK_X, WITH_CHUNK_Z); + + Assert.assertEquals(expected, actual); + } } diff --git a/src/test/java/appeng/services/version/ModVersionFetcherTest.java b/src/test/java/appeng/services/version/ModVersionFetcherTest.java index c6f20e1e417..ffd88c62fd3 100644 --- a/src/test/java/appeng/services/version/ModVersionFetcherTest.java +++ b/src/test/java/appeng/services/version/ModVersionFetcherTest.java @@ -18,48 +18,41 @@ package appeng.services.version; - import org.junit.Assert; import org.junit.Test; - /** * @author thatsIch * @version rv3 - 16.05.2015 * @since rv3 16.05.2015 */ -public class ModVersionFetcherTest -{ - // private static final ModVersionFetcher FETCHER = new ModVersionFetcher( ) - - private final ModVersionFetcher indev; - private final ModVersionFetcher pullRequest; - private final ModVersionFetcher working; - - public ModVersionFetcherTest() - { - final VersionParser parser = new VersionParser(); - - this.indev = new ModVersionFetcher( "@version@", parser ); - this.pullRequest = new ModVersionFetcher( "pr", parser ); - this.working = new ModVersionFetcher( "rv2-beta-8", parser ); - } - - @Test - public void testInDev() throws Exception - { - Assert.assertEquals( this.indev.get(), new DoNotCheckVersion() ); - } - - @Test - public void testPR() throws Exception - { - Assert.assertEquals( this.pullRequest.get(), new DoNotCheckVersion() ); - } - - @Test - public void testWorking() throws Exception - { - Assert.assertEquals( this.working.get(), new DefaultVersion( 2, Channel.Beta, 8 ) ); - } +public class ModVersionFetcherTest { + // private static final ModVersionFetcher FETCHER = new ModVersionFetcher( ) + + private final ModVersionFetcher indev; + private final ModVersionFetcher pullRequest; + private final ModVersionFetcher working; + + public ModVersionFetcherTest() { + final VersionParser parser = new VersionParser(); + + this.indev = new ModVersionFetcher("@version@", parser); + this.pullRequest = new ModVersionFetcher("pr", parser); + this.working = new ModVersionFetcher("rv2-beta-8", parser); + } + + @Test + public void testInDev() throws Exception { + Assert.assertEquals(this.indev.get(), new DoNotCheckVersion()); + } + + @Test + public void testPR() throws Exception { + Assert.assertEquals(this.pullRequest.get(), new DoNotCheckVersion()); + } + + @Test + public void testWorking() throws Exception { + Assert.assertEquals(this.working.get(), new DefaultVersion(2, Channel.Beta, 8)); + } } diff --git a/src/test/java/appeng/services/version/VersionParserTest.java b/src/test/java/appeng/services/version/VersionParserTest.java index 3590a2973ab..55b440cc15e 100644 --- a/src/test/java/appeng/services/version/VersionParserTest.java +++ b/src/test/java/appeng/services/version/VersionParserTest.java @@ -1,102 +1,87 @@ package appeng.services.version; +import static org.junit.Assert.*; import appeng.services.version.exceptions.*; import org.junit.Test; -import static org.junit.Assert.*; - - /** * Tests for {@link VersionParser} */ -public final class VersionParserTest -{ - private static final String GITHUB_VERSION = "rv2.beta.8"; - private static final String GITHUB_INVALID_REVISION = "2.beta.8"; - private static final String GITHUB_INVALID_CHANNEL = "rv2.gamma.8"; - private static final String GITHUB_INVALID_BUILD = "rv2.beta.b8"; - private static final String MOD_VERSION = "rv2-beta-8"; - private static final String MOD_INVALID_REVISION = "2-beta-8"; - private static final String MOD_INVALID_CHANNEL = "rv2-gamma-8"; - private static final String MOD_INVALID_BUILD = "rv2-beta-b8"; - private static final String GENERIC_MISSING_SEPARATOR = "foobar"; - private static final String GENERIC_INVALID_VERSION = "foo-bar"; - - private static final DefaultVersion VERSION = new DefaultVersion( 2, Channel.Beta, 8 ); - - private final VersionParser parser; - - public VersionParserTest() - { - this.parser = new VersionParser(); - } - - @Test - public void testSameParsedGitHub() throws VersionCheckerException - { - final Version version = this.parser.parse( GITHUB_VERSION ); - - assertEquals( version, version ); - } - - @Test - public void testParseGitHub() throws VersionCheckerException - { - assertTrue( this.parser.parse( GITHUB_VERSION ).equals( VERSION ) ); - } - - @Test( expected = InvalidRevisionException.class ) - public void parseGH_InvalidRevision() throws VersionCheckerException - { - assertFalse( this.parser.parse( GITHUB_INVALID_REVISION ).equals( VERSION ) ); - } - - @Test( expected = InvalidChannelException.class ) - public void parseGH_InvalidChannel() throws VersionCheckerException - { - assertFalse( this.parser.parse( GITHUB_INVALID_CHANNEL ).equals( VERSION ) ); - } - - @Test( expected = InvalidBuildException.class ) - public void parseGH_InvalidBuild() throws VersionCheckerException - { - assertFalse( this.parser.parse( GITHUB_INVALID_BUILD ).equals( VERSION ) ); - } - - @Test - public void testParseMod() throws VersionCheckerException - { - assertTrue( this.parser.parse( MOD_VERSION ).equals( VERSION ) ); - } - - @Test( expected = InvalidRevisionException.class ) - public void parseMod_InvalidRevision() throws VersionCheckerException - { - assertFalse( this.parser.parse( MOD_INVALID_REVISION ).equals( VERSION ) ); - } - - @Test( expected = InvalidChannelException.class ) - public void parseMod_InvalidChannel() throws VersionCheckerException - { - assertFalse( this.parser.parse( MOD_INVALID_CHANNEL ).equals( VERSION ) ); - } - - @Test( expected = InvalidBuildException.class ) - public void parseMod_InvalidBuild() throws VersionCheckerException - { - assertFalse( this.parser.parse( MOD_INVALID_BUILD ).equals( VERSION ) ); - } - - @Test( expected = MissingSeparatorException.class ) - public void parseGeneric_MissingSeparator() throws VersionCheckerException - { - assertFalse( this.parser.parse( GENERIC_MISSING_SEPARATOR ).equals( VERSION ) ); - } - - @Test( expected = InvalidVersionException.class ) - public void parseGeneric_InvalidVersion() throws VersionCheckerException - { - assertFalse( this.parser.parse( GENERIC_INVALID_VERSION ).equals( VERSION ) ); - } +public final class VersionParserTest { + private static final String GITHUB_VERSION = "rv2.beta.8"; + private static final String GITHUB_INVALID_REVISION = "2.beta.8"; + private static final String GITHUB_INVALID_CHANNEL = "rv2.gamma.8"; + private static final String GITHUB_INVALID_BUILD = "rv2.beta.b8"; + private static final String MOD_VERSION = "rv2-beta-8"; + private static final String MOD_INVALID_REVISION = "2-beta-8"; + private static final String MOD_INVALID_CHANNEL = "rv2-gamma-8"; + private static final String MOD_INVALID_BUILD = "rv2-beta-b8"; + private static final String GENERIC_MISSING_SEPARATOR = "foobar"; + private static final String GENERIC_INVALID_VERSION = "foo-bar"; + + private static final DefaultVersion VERSION = new DefaultVersion(2, Channel.Beta, 8); + + private final VersionParser parser; + + public VersionParserTest() { + this.parser = new VersionParser(); + } + + @Test + public void testSameParsedGitHub() throws VersionCheckerException { + final Version version = this.parser.parse(GITHUB_VERSION); + + assertEquals(version, version); + } + + @Test + public void testParseGitHub() throws VersionCheckerException { + assertTrue(this.parser.parse(GITHUB_VERSION).equals(VERSION)); + } + + @Test(expected = InvalidRevisionException.class) + public void parseGH_InvalidRevision() throws VersionCheckerException { + assertFalse(this.parser.parse(GITHUB_INVALID_REVISION).equals(VERSION)); + } + + @Test(expected = InvalidChannelException.class) + public void parseGH_InvalidChannel() throws VersionCheckerException { + assertFalse(this.parser.parse(GITHUB_INVALID_CHANNEL).equals(VERSION)); + } + + @Test(expected = InvalidBuildException.class) + public void parseGH_InvalidBuild() throws VersionCheckerException { + assertFalse(this.parser.parse(GITHUB_INVALID_BUILD).equals(VERSION)); + } + + @Test + public void testParseMod() throws VersionCheckerException { + assertTrue(this.parser.parse(MOD_VERSION).equals(VERSION)); + } + + @Test(expected = InvalidRevisionException.class) + public void parseMod_InvalidRevision() throws VersionCheckerException { + assertFalse(this.parser.parse(MOD_INVALID_REVISION).equals(VERSION)); + } + + @Test(expected = InvalidChannelException.class) + public void parseMod_InvalidChannel() throws VersionCheckerException { + assertFalse(this.parser.parse(MOD_INVALID_CHANNEL).equals(VERSION)); + } + + @Test(expected = InvalidBuildException.class) + public void parseMod_InvalidBuild() throws VersionCheckerException { + assertFalse(this.parser.parse(MOD_INVALID_BUILD).equals(VERSION)); + } + + @Test(expected = MissingSeparatorException.class) + public void parseGeneric_MissingSeparator() throws VersionCheckerException { + assertFalse(this.parser.parse(GENERIC_MISSING_SEPARATOR).equals(VERSION)); + } + + @Test(expected = InvalidVersionException.class) + public void parseGeneric_InvalidVersion() throws VersionCheckerException { + assertFalse(this.parser.parse(GENERIC_INVALID_VERSION).equals(VERSION)); + } } diff --git a/src/test/java/appeng/services/version/VersionTest.java b/src/test/java/appeng/services/version/VersionTest.java index 9f89fef5aa5..28627218f32 100644 --- a/src/test/java/appeng/services/version/VersionTest.java +++ b/src/test/java/appeng/services/version/VersionTest.java @@ -18,11 +18,9 @@ package appeng.services.version; - import org.junit.Assert; import org.junit.Test; - /** * Tests for {@link Version} * @@ -30,87 +28,73 @@ * @version rv3 - 16.05.2015 * @since rv3 16.05.2015 */ -public final class VersionTest -{ - private static final Version DEFAULT_VERSION_RV2_BETA_8 = new DefaultVersion( 2, Channel.Beta, 8 ); - private static final Version DEFAULT_VERSION_RV2_BETA_9 = new DefaultVersion( 2, Channel.Beta, 9 ); - private static final Version DEFAULT_VERSION_RV3_BETA_8 = new DefaultVersion( 3, Channel.Beta, 8 ); - private static final Version DEFAULT_VERSION_RV2_ALPHA_8 = new DefaultVersion( 2, Channel.Alpha, 8 ); - private static final Version DO_NOT_CHECK_VERSION = new DoNotCheckVersion(); - private static final Version MISSING_VERSION = new MissingVersion(); - - @Test - public void testDevBuild() - { - Assert.assertEquals( DO_NOT_CHECK_VERSION.formatted(), "dev build" ); - } - - @Test - public void testMissingBuild() - { - Assert.assertEquals( MISSING_VERSION.formatted(), "missing" ); - } - - @Test - public void compareVersionToDoNotCheck() - { - Assert.assertFalse( DEFAULT_VERSION_RV2_ALPHA_8.isNewerAs( DO_NOT_CHECK_VERSION ) ); - Assert.assertTrue( DO_NOT_CHECK_VERSION.isNewerAs( DEFAULT_VERSION_RV2_ALPHA_8 ) ); - } - - @Test - public void compareVersionToMissingVersion() - { - Assert.assertTrue( DEFAULT_VERSION_RV2_ALPHA_8.isNewerAs( MISSING_VERSION ) ); - Assert.assertFalse( MISSING_VERSION.isNewerAs( DEFAULT_VERSION_RV2_ALPHA_8 ) ); - } - - @Test - public void compareTwoDefaultVersions() - { - Assert.assertTrue( DEFAULT_VERSION_RV2_BETA_8.isNewerAs( DEFAULT_VERSION_RV2_ALPHA_8 ) ); - } - - @Test - public void testEqualsNonVersion() - { - Assert.assertFalse( DEFAULT_VERSION_RV2_ALPHA_8.equals( new Object() ) ); - } - - @Test - public void testEqualsUnequalBuild() - { - Assert.assertFalse( DEFAULT_VERSION_RV2_BETA_8.equals( DEFAULT_VERSION_RV2_BETA_9 ) ); - } - - @Test - public void testEqualsUnequalChannel() - { - Assert.assertFalse( DEFAULT_VERSION_RV2_BETA_8.equals( DEFAULT_VERSION_RV2_ALPHA_8 ) ); - } - - @Test - public void testEqualsUnequalRevision() - { - Assert.assertFalse( DEFAULT_VERSION_RV2_BETA_8.equals( DEFAULT_VERSION_RV3_BETA_8 ) ); - } - - @Test - public void testUnequalHash() - { - Assert.assertNotEquals( DEFAULT_VERSION_RV2_BETA_8.hashCode(), DEFAULT_VERSION_RV2_ALPHA_8.hashCode() ); - } - - @Test - public void testToString() - { - Assert.assertEquals( DEFAULT_VERSION_RV2_BETA_8.toString(), "Version{revision=2, channel=Beta, build=8}" ); - } - - @Test - public void testFormatted() - { - Assert.assertEquals( DEFAULT_VERSION_RV2_BETA_8.formatted(), "rv2-beta-8" ); - } - +public final class VersionTest { + private static final Version DEFAULT_VERSION_RV2_BETA_8 = new DefaultVersion(2, Channel.Beta, 8); + private static final Version DEFAULT_VERSION_RV2_BETA_9 = new DefaultVersion(2, Channel.Beta, 9); + private static final Version DEFAULT_VERSION_RV3_BETA_8 = new DefaultVersion(3, Channel.Beta, 8); + private static final Version DEFAULT_VERSION_RV2_ALPHA_8 = new DefaultVersion(2, Channel.Alpha, 8); + private static final Version DO_NOT_CHECK_VERSION = new DoNotCheckVersion(); + private static final Version MISSING_VERSION = new MissingVersion(); + + @Test + public void testDevBuild() { + Assert.assertEquals(DO_NOT_CHECK_VERSION.formatted(), "dev build"); + } + + @Test + public void testMissingBuild() { + Assert.assertEquals(MISSING_VERSION.formatted(), "missing"); + } + + @Test + public void compareVersionToDoNotCheck() { + Assert.assertFalse(DEFAULT_VERSION_RV2_ALPHA_8.isNewerAs(DO_NOT_CHECK_VERSION)); + Assert.assertTrue(DO_NOT_CHECK_VERSION.isNewerAs(DEFAULT_VERSION_RV2_ALPHA_8)); + } + + @Test + public void compareVersionToMissingVersion() { + Assert.assertTrue(DEFAULT_VERSION_RV2_ALPHA_8.isNewerAs(MISSING_VERSION)); + Assert.assertFalse(MISSING_VERSION.isNewerAs(DEFAULT_VERSION_RV2_ALPHA_8)); + } + + @Test + public void compareTwoDefaultVersions() { + Assert.assertTrue(DEFAULT_VERSION_RV2_BETA_8.isNewerAs(DEFAULT_VERSION_RV2_ALPHA_8)); + } + + @Test + public void testEqualsNonVersion() { + Assert.assertFalse(DEFAULT_VERSION_RV2_ALPHA_8.equals(new Object())); + } + + @Test + public void testEqualsUnequalBuild() { + Assert.assertFalse(DEFAULT_VERSION_RV2_BETA_8.equals(DEFAULT_VERSION_RV2_BETA_9)); + } + + @Test + public void testEqualsUnequalChannel() { + Assert.assertFalse(DEFAULT_VERSION_RV2_BETA_8.equals(DEFAULT_VERSION_RV2_ALPHA_8)); + } + + @Test + public void testEqualsUnequalRevision() { + Assert.assertFalse(DEFAULT_VERSION_RV2_BETA_8.equals(DEFAULT_VERSION_RV3_BETA_8)); + } + + @Test + public void testUnequalHash() { + Assert.assertNotEquals(DEFAULT_VERSION_RV2_BETA_8.hashCode(), DEFAULT_VERSION_RV2_ALPHA_8.hashCode()); + } + + @Test + public void testToString() { + Assert.assertEquals(DEFAULT_VERSION_RV2_BETA_8.toString(), "Version{revision=2, channel=Beta, build=8}"); + } + + @Test + public void testFormatted() { + Assert.assertEquals(DEFAULT_VERSION_RV2_BETA_8.formatted(), "rv2-beta-8"); + } } diff --git a/src/test/java/appeng/util/SlimReadableNumberConverterTest.java b/src/test/java/appeng/util/SlimReadableNumberConverterTest.java index 16413a319fc..25c06db124f 100644 --- a/src/test/java/appeng/util/SlimReadableNumberConverterTest.java +++ b/src/test/java/appeng/util/SlimReadableNumberConverterTest.java @@ -1,10 +1,8 @@ package appeng.util; - -import org.junit.Test; - import static org.junit.Assert.assertEquals; +import org.junit.Test; /** * Test for {@link ISlimReadableNumberConverter} @@ -13,115 +11,102 @@ * @version rv2 * @since rv2 */ -public final class SlimReadableNumberConverterTest -{ - private static final long NUMBER_NEG_999999 = -999999L; - private static final String RESULT_NEG_999999 = "-0M"; - - private static final long NUMBER_NEG_9999 = -9999L; - private static final String RESULT_NEG_9999 = "-9K"; - - private static final long NUMBER_NEG_999 = -999L; - private static final String RESULT_NEG_999 = "-0K"; - - private static final long NUMBER_0 = 0L; - private static final String RESULT_0 = "0"; - - private static final long NUMBER_999 = 999L; - private static final String RESULT_999 = "999"; - - private static final long NUMBER_9999 = 9999L; - private static final String RESULT_9999 = "9K"; - - private static final long NUMBER_10000 = 10000L; - private static final String RESULT_10000 = "10K"; - - private static final long NUMBER_10500 = 10500L; - private static final String RESULT_10500 = "10K"; - - private static final long NUMBER_155555 = 155555L; - private static final String RESULT_155555 = ".1M"; - - private static final long NUMBER_9999999 = 9999999L; - private static final String RESULT_9999999 = "9M"; - - private static final long NUMBER_10000000 = 10000000L; - private static final String RESULT_10000000 = "10M"; - - private static final long NUMBER_155555555 = 155555555L; - private static final String RESULT_155555555 = ".1G"; - - private final ISlimReadableNumberConverter converter = ReadableNumberConverter.INSTANCE; - - @Test( expected = AssertionError.class ) - public void testConvertNeg999999() - { - assertEquals( RESULT_NEG_999999, this.converter.toSlimReadableForm( NUMBER_NEG_999999 ) ); - } - - @Test( expected = AssertionError.class ) - public void testConvertNeg9999() - { - assertEquals( RESULT_NEG_9999, this.converter.toSlimReadableForm( NUMBER_NEG_9999 ) ); - } - - @Test( expected = AssertionError.class ) - public void testConvertNeg999() - { - assertEquals( RESULT_NEG_999, this.converter.toSlimReadableForm( NUMBER_NEG_999 ) ); - } - - @Test - public void testConvert0() - { - assertEquals( RESULT_0, this.converter.toSlimReadableForm( NUMBER_0 ) ); - } - - @Test - public void testConvert999() - { - assertEquals( RESULT_999, this.converter.toSlimReadableForm( NUMBER_999 ) ); - } - - @Test - public void testConvert9999() - { - assertEquals( RESULT_9999, this.converter.toSlimReadableForm( NUMBER_9999 ) ); - } - - @Test - public void testConvert10000() - { - assertEquals( RESULT_10000, this.converter.toSlimReadableForm( NUMBER_10000 ) ); - } - - @Test - public void testConvert10500() - { - assertEquals( RESULT_10500, this.converter.toSlimReadableForm( NUMBER_10500 ) ); - } - - @Test - public void testConvert155555() - { - assertEquals( RESULT_155555, this.converter.toSlimReadableForm( NUMBER_155555 ) ); - } - - @Test - public void testConvert9999999() - { - assertEquals( RESULT_9999999, this.converter.toSlimReadableForm( NUMBER_9999999 ) ); - } - - @Test - public void testConvert10000000() - { - assertEquals( RESULT_10000000, this.converter.toSlimReadableForm( NUMBER_10000000 ) ); - } - - @Test - public void testConvert155555555() - { - assertEquals( RESULT_155555555, this.converter.toSlimReadableForm( NUMBER_155555555 ) ); - } +public final class SlimReadableNumberConverterTest { + private static final long NUMBER_NEG_999999 = -999999L; + private static final String RESULT_NEG_999999 = "-0M"; + + private static final long NUMBER_NEG_9999 = -9999L; + private static final String RESULT_NEG_9999 = "-9K"; + + private static final long NUMBER_NEG_999 = -999L; + private static final String RESULT_NEG_999 = "-0K"; + + private static final long NUMBER_0 = 0L; + private static final String RESULT_0 = "0"; + + private static final long NUMBER_999 = 999L; + private static final String RESULT_999 = "999"; + + private static final long NUMBER_9999 = 9999L; + private static final String RESULT_9999 = "9K"; + + private static final long NUMBER_10000 = 10000L; + private static final String RESULT_10000 = "10K"; + + private static final long NUMBER_10500 = 10500L; + private static final String RESULT_10500 = "10K"; + + private static final long NUMBER_155555 = 155555L; + private static final String RESULT_155555 = ".1M"; + + private static final long NUMBER_9999999 = 9999999L; + private static final String RESULT_9999999 = "9M"; + + private static final long NUMBER_10000000 = 10000000L; + private static final String RESULT_10000000 = "10M"; + + private static final long NUMBER_155555555 = 155555555L; + private static final String RESULT_155555555 = ".1G"; + + private final ISlimReadableNumberConverter converter = ReadableNumberConverter.INSTANCE; + + @Test(expected = AssertionError.class) + public void testConvertNeg999999() { + assertEquals(RESULT_NEG_999999, this.converter.toSlimReadableForm(NUMBER_NEG_999999)); + } + + @Test(expected = AssertionError.class) + public void testConvertNeg9999() { + assertEquals(RESULT_NEG_9999, this.converter.toSlimReadableForm(NUMBER_NEG_9999)); + } + + @Test(expected = AssertionError.class) + public void testConvertNeg999() { + assertEquals(RESULT_NEG_999, this.converter.toSlimReadableForm(NUMBER_NEG_999)); + } + + @Test + public void testConvert0() { + assertEquals(RESULT_0, this.converter.toSlimReadableForm(NUMBER_0)); + } + + @Test + public void testConvert999() { + assertEquals(RESULT_999, this.converter.toSlimReadableForm(NUMBER_999)); + } + + @Test + public void testConvert9999() { + assertEquals(RESULT_9999, this.converter.toSlimReadableForm(NUMBER_9999)); + } + + @Test + public void testConvert10000() { + assertEquals(RESULT_10000, this.converter.toSlimReadableForm(NUMBER_10000)); + } + + @Test + public void testConvert10500() { + assertEquals(RESULT_10500, this.converter.toSlimReadableForm(NUMBER_10500)); + } + + @Test + public void testConvert155555() { + assertEquals(RESULT_155555, this.converter.toSlimReadableForm(NUMBER_155555)); + } + + @Test + public void testConvert9999999() { + assertEquals(RESULT_9999999, this.converter.toSlimReadableForm(NUMBER_9999999)); + } + + @Test + public void testConvert10000000() { + assertEquals(RESULT_10000000, this.converter.toSlimReadableForm(NUMBER_10000000)); + } + + @Test + public void testConvert155555555() { + assertEquals(RESULT_155555555, this.converter.toSlimReadableForm(NUMBER_155555555)); + } } diff --git a/src/test/java/appeng/util/UUIDMatcherTest.java b/src/test/java/appeng/util/UUIDMatcherTest.java index 54e52c18f0c..16cc1da5bfa 100644 --- a/src/test/java/appeng/util/UUIDMatcherTest.java +++ b/src/test/java/appeng/util/UUIDMatcherTest.java @@ -18,44 +18,37 @@ package appeng.util; - -import org.junit.Test; - import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import org.junit.Test; /** * Tests for {@link UUIDMatcher} */ -public final class UUIDMatcherTest -{ - private static final String IS_UUID = "03ba29a1-d6bd-32ba-90b2-375e4d65abc9"; - private static final String NO_UUID = "no"; - private static final String INVALID_UUID = "g3ba29a1-d6bd-32ba-90b2-375e4d65abc9"; - - private final UUIDMatcher matcher; - - public UUIDMatcherTest() - { - this.matcher = new UUIDMatcher(); - } - - @Test - public void testUUID_shouldPass() - { - assertTrue( this.matcher.isUUID( IS_UUID ) ); - } - - @Test - public void testNoUUD_shouldPass() - { - assertFalse( this.matcher.isUUID( NO_UUID ) ); - } - - @Test - public void testInvalidUUID_shouldPass() - { - assertFalse( this.matcher.isUUID( INVALID_UUID ) ); - } +public final class UUIDMatcherTest { + private static final String IS_UUID = "03ba29a1-d6bd-32ba-90b2-375e4d65abc9"; + private static final String NO_UUID = "no"; + private static final String INVALID_UUID = "g3ba29a1-d6bd-32ba-90b2-375e4d65abc9"; + + private final UUIDMatcher matcher; + + public UUIDMatcherTest() { + this.matcher = new UUIDMatcher(); + } + + @Test + public void testUUID_shouldPass() { + assertTrue(this.matcher.isUUID(IS_UUID)); + } + + @Test + public void testNoUUD_shouldPass() { + assertFalse(this.matcher.isUUID(NO_UUID)); + } + + @Test + public void testInvalidUUID_shouldPass() { + assertFalse(this.matcher.isUUID(INVALID_UUID)); + } } diff --git a/src/test/java/appeng/util/WideReadableNumberConverterTest.java b/src/test/java/appeng/util/WideReadableNumberConverterTest.java index 6b047af55a5..00b0b3ec328 100644 --- a/src/test/java/appeng/util/WideReadableNumberConverterTest.java +++ b/src/test/java/appeng/util/WideReadableNumberConverterTest.java @@ -1,10 +1,8 @@ package appeng.util; - -import org.junit.Test; - import static org.junit.Assert.assertEquals; +import org.junit.Test; /** * Test for {@link IWideReadableNumberConverter} @@ -13,115 +11,102 @@ * @version rv2 * @since rv2 */ -public final class WideReadableNumberConverterTest -{ - private static final long NUMBER_NEG_999999 = -999999L; - private static final String RESULT_NEG_999999 = "-0M"; - - private static final long NUMBER_NEG_9999 = -9999L; - private static final String RESULT_NEG_9999 = "-9K"; - - private static final long NUMBER_NEG_999 = -999L; - private static final String RESULT_NEG_999 = "-999"; - - private static final long NUMBER_0 = 0L; - private static final String RESULT_0 = "0"; - - private static final long NUMBER_999 = 999L; - private static final String RESULT_999 = "999"; - - private static final long NUMBER_9999 = 9999L; - private static final String RESULT_9999 = "9999"; - - private static final long NUMBER_10000 = 10000L; - private static final String RESULT_10000 = "10K"; - - private static final long NUMBER_10500 = 10500L; - private static final String RESULT_10500 = "10K"; - - private static final long NUMBER_155555 = 155555L; - private static final String RESULT_155555 = "155K"; - - private static final long NUMBER_9999999 = 9999999L; - private static final String RESULT_9999999 = "9.9M"; - - private static final long NUMBER_10000000 = 10000000L; - private static final String RESULT_10000000 = "10M"; - - private static final long NUMBER_155555555 = 155555555L; - private static final String RESULT_155555555 = "155M"; - - private final IWideReadableNumberConverter converter = ReadableNumberConverter.INSTANCE; - - @Test( expected = AssertionError.class ) - public void testConvertNeg999999() - { - assertEquals( RESULT_NEG_999999, this.converter.toWideReadableForm( NUMBER_NEG_999999 ) ); - } - - @Test( expected = AssertionError.class ) - public void testConvertNeg9999() - { - assertEquals( RESULT_NEG_9999, this.converter.toWideReadableForm( NUMBER_NEG_9999 ) ); - } - - @Test( expected = AssertionError.class ) - public void testConvertNeg999() - { - assertEquals( RESULT_NEG_999, this.converter.toWideReadableForm( NUMBER_NEG_999 ) ); - } - - @Test - public void testConvert0() - { - assertEquals( RESULT_0, this.converter.toWideReadableForm( NUMBER_0 ) ); - } - - @Test - public void testConvert999() - { - assertEquals( RESULT_999, this.converter.toWideReadableForm( NUMBER_999 ) ); - } - - @Test - public void testConvert9999() - { - assertEquals( RESULT_9999, this.converter.toWideReadableForm( NUMBER_9999 ) ); - } - - @Test - public void testConvert10000() - { - assertEquals( RESULT_10000, this.converter.toWideReadableForm( NUMBER_10000 ) ); - } - - @Test - public void testConvert10500() - { - assertEquals( RESULT_10500, this.converter.toWideReadableForm( NUMBER_10500 ) ); - } - - @Test - public void testConvert155555() - { - assertEquals( RESULT_155555, this.converter.toWideReadableForm( NUMBER_155555 ) ); - } - - @Test - public void testConvert9999999() - { - assertEquals( RESULT_9999999, this.converter.toWideReadableForm( NUMBER_9999999 ) ); - } - - @Test - public void testConvert10000000() - { - assertEquals( RESULT_10000000, this.converter.toWideReadableForm( NUMBER_10000000 ) ); - } - - @Test - public void testConvert155555555() - { - assertEquals( RESULT_155555555, this.converter.toWideReadableForm( NUMBER_155555555 ) ); - } +public final class WideReadableNumberConverterTest { + private static final long NUMBER_NEG_999999 = -999999L; + private static final String RESULT_NEG_999999 = "-0M"; + + private static final long NUMBER_NEG_9999 = -9999L; + private static final String RESULT_NEG_9999 = "-9K"; + + private static final long NUMBER_NEG_999 = -999L; + private static final String RESULT_NEG_999 = "-999"; + + private static final long NUMBER_0 = 0L; + private static final String RESULT_0 = "0"; + + private static final long NUMBER_999 = 999L; + private static final String RESULT_999 = "999"; + + private static final long NUMBER_9999 = 9999L; + private static final String RESULT_9999 = "9999"; + + private static final long NUMBER_10000 = 10000L; + private static final String RESULT_10000 = "10K"; + + private static final long NUMBER_10500 = 10500L; + private static final String RESULT_10500 = "10K"; + + private static final long NUMBER_155555 = 155555L; + private static final String RESULT_155555 = "155K"; + + private static final long NUMBER_9999999 = 9999999L; + private static final String RESULT_9999999 = "9.9M"; + + private static final long NUMBER_10000000 = 10000000L; + private static final String RESULT_10000000 = "10M"; + + private static final long NUMBER_155555555 = 155555555L; + private static final String RESULT_155555555 = "155M"; + + private final IWideReadableNumberConverter converter = ReadableNumberConverter.INSTANCE; + + @Test(expected = AssertionError.class) + public void testConvertNeg999999() { + assertEquals(RESULT_NEG_999999, this.converter.toWideReadableForm(NUMBER_NEG_999999)); + } + + @Test(expected = AssertionError.class) + public void testConvertNeg9999() { + assertEquals(RESULT_NEG_9999, this.converter.toWideReadableForm(NUMBER_NEG_9999)); + } + + @Test(expected = AssertionError.class) + public void testConvertNeg999() { + assertEquals(RESULT_NEG_999, this.converter.toWideReadableForm(NUMBER_NEG_999)); + } + + @Test + public void testConvert0() { + assertEquals(RESULT_0, this.converter.toWideReadableForm(NUMBER_0)); + } + + @Test + public void testConvert999() { + assertEquals(RESULT_999, this.converter.toWideReadableForm(NUMBER_999)); + } + + @Test + public void testConvert9999() { + assertEquals(RESULT_9999, this.converter.toWideReadableForm(NUMBER_9999)); + } + + @Test + public void testConvert10000() { + assertEquals(RESULT_10000, this.converter.toWideReadableForm(NUMBER_10000)); + } + + @Test + public void testConvert10500() { + assertEquals(RESULT_10500, this.converter.toWideReadableForm(NUMBER_10500)); + } + + @Test + public void testConvert155555() { + assertEquals(RESULT_155555, this.converter.toWideReadableForm(NUMBER_155555)); + } + + @Test + public void testConvert9999999() { + assertEquals(RESULT_9999999, this.converter.toWideReadableForm(NUMBER_9999999)); + } + + @Test + public void testConvert10000000() { + assertEquals(RESULT_10000000, this.converter.toWideReadableForm(NUMBER_10000000)); + } + + @Test + public void testConvert155555555() { + assertEquals(RESULT_155555555, this.converter.toWideReadableForm(NUMBER_155555555)); + } }